diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 4317128869..7ebdcc514f 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -1123,10 +1123,11 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](moment/moment.d.ts) [Moment.js](https://github.com/timrwood/moment) by [Michael Lakerveld](https://github.com/Lakerfield), [Aaron King](https://github.com/kingdango), [Hiroki Horiuchi](https://github.com/horiuchi), [Dick van den Brink](https://github.com/DickvdBrink), [Adi Dahiya](https://github.com/adidahiya), [Matt Brooks](https://github.com/EnableSoftware) * [:link:](moment-range/moment-range.d.ts) [Moment.js](https://github.com/gf3/moment-range) by [Bart van den Burg](https://github.com/Burgov), [Wilgert Velinga](https://github.com/wilgert) * [:link:](mongodb/mongodb.d.ts) [MongoDB](https://github.com/mongodb/node-mongodb-native/tree/2.1) by [Federico Caselli](https://github.com/CaselIT) -* [:link:](mongoose/mongoose.d.ts) [Mongoose](http://mongoosejs.com) by [horiuchi](https://github.com/horiuchi) +* [:link:](mongoose/mongoose.d.ts) [Mongoose](http://mongoosejs.com) by [simonxca](https://github.com/simonxca), [horiuchi](https://github.com/horiuchi) * [:link:](mongoose-auto-increment/mongoose-auto-increment.d.ts) [mongoose-auto-increment](https://github.com/codetunnel/mongoose-auto-increment) by [Aya Morisawa](https://github.com/AyaMorisawa) * [:link:](mongoose-deep-populate/mongoose-deep-populate.d.ts) [mongoose-deep-populate](https://github.com/buunguyen/mongoose-deep-populate) by [Aya Morisawa](https://github.com/AyaMorisawa) * [:link:](mongoose-mock/mongoose-mock.d.ts) [mongoose-mock](https://github.com/JohanObrink/mongoose-mock) by [jt000](https://github.com/jt000) +* [:link:](mongoose-promise/mongoose-promise.d.ts) [mongoose-promise](http://mongoosejs.com/docs/api.html#promise-js) by [simonxca](https://github.com/simonxca) * [:link:](morgan/morgan.d.ts) [morgan](https://github.com/expressjs/morgan) by [James Roland Cabresos](https://github.com/staticfunction) * [:link:](mousetrap/mousetrap-global-bind.d.ts) [Mousetrap 1.4.6's global-bind extension](http://craig.is/killing/mice#extensions.global) by [Andrew Bradley](https://github.com/cspotcode) * [:link:](mousetrap/mousetrap.d.ts) [Mousetrap 1.5.x](http://craig.is/killing/mice) by [Dániel Tar](https://github.com/qcz) diff --git a/adal/adal-tests.ts b/adal/adal-tests.ts index 423ef60bad..32a6715222 100644 --- a/adal/adal-tests.ts +++ b/adal/adal-tests.ts @@ -20,4 +20,5 @@ Logging.level = 4; auth.info("Logging message"); -var userName: string = auth.getCachedUser().userName; \ No newline at end of file +var userName: string = auth.getCachedUser().userName;var postLogoutRedirectUrl = auth.config.postLogoutRedirectUri; +var isValidRequest = auth.getRequestInfo('hash').valid; \ No newline at end of file diff --git a/adal/index.d.ts b/adal/index.d.ts index 1c60cbf6ef..a896d687ec 100644 --- a/adal/index.d.ts +++ b/adal/index.d.ts @@ -13,29 +13,30 @@ declare module 'adal' { declare namespace adal { interface Config { - tenant?: string, - clientId: string, - redirectUri?: string, - cacheLocation?: string, - displayCall?: (urlNavigate: string) => any, - correlationId?: string, - loginResource?: string, - resource?: string - endpoints?: any // If you need to send CORS api requests. - extraQueryParameter?: string + tenant?: string; + clientId: string; + redirectUri?: string; + cacheLocation?: string; + displayCall?: (urlNavigate: string) => any; + correlationId?: string; + loginResource?: string; + resource?: string; + endpoints?: any; // If you need to send CORS api requests. + extraQueryParameter?: string; + postLogoutRedirectUri?: string; // redirect url after succesful logout operation } interface User { - userName: string, - profile: any + userName: string; + profile: any; } interface RequestInfo { - valid: boolean, - parameters: any, - stateMatch: boolean, - stateResponse: string, - requestType: string + valid: boolean; + parameters: any; + stateMatch: boolean; + stateResponse: string; + requestType: string; } interface Logging { @@ -64,6 +65,10 @@ declare namespace adal { * Saves the resulting Idtoken in localStorage. */ login(): void; + + /** + * Indicates whether login is in progress now or not. + */ loginInProgress(): boolean; /** @@ -147,6 +152,11 @@ declare namespace adal { */ getResourceForEndpoint(endpoint: string): string; + /** + * Handles redirection after login operation. + * Gets access token from url and saves token to the (local/session) storage + * or saves error in case unsuccessful login. + */ handleWindowCallback(): void; log(level: number, message: string, error: any): void; diff --git a/agenda/index.d.ts b/agenda/index.d.ts index 8bf309249f..e859de3188 100644 --- a/agenda/index.d.ts +++ b/agenda/index.d.ts @@ -18,8 +18,8 @@ interface ResultCallback { (err?: Error, result?: T): void; } -declare class Agenda extends EventEmitter { +declare class Agenda extends EventEmitter { /** * Constructs a new Agenda object. * @param config Optional configuration to initialize the Agenda. @@ -164,6 +164,7 @@ declare class Agenda extends EventEmitter { } declare namespace Agenda { + /** * Agenda Configuration. */ @@ -318,6 +319,11 @@ declare namespace Agenda { * The date/time the job last failed. */ failedAt: Date; + + /** + * Job's state + */ + disabled: boolean } /** @@ -408,6 +414,11 @@ declare namespace Agenda { * @param cb Called after the job has been saved to the database. */ touch(cb?: Callback): void; + + /** + * Calculates next time the job should run + */ + computeNextRunAt(): Job; } interface JobOptions { diff --git a/angular-animate/index.d.ts b/angular-animate/index.d.ts index 55f84227ef..624284be2c 100644 --- a/angular-animate/index.d.ts +++ b/angular-animate/index.d.ts @@ -71,7 +71,7 @@ declare module 'angular' { * @returns current animation state */ enabled(element: JQuery, value?: boolean): boolean; - enabled(value: boolean): boolean; + enabled(value?: boolean): boolean; /** * Cancels the provided animation. diff --git a/angular-environment/index.d.ts b/angular-environment/index.d.ts index 483474410c..94972d1383 100644 --- a/angular-environment/index.d.ts +++ b/angular-environment/index.d.ts @@ -14,6 +14,11 @@ declare namespace angular.environment { * loads the correct environment variables. */ check: () => void; + /** + * Retrieves the correct version of a + * variable for the current environment. + */ + read: (key: string) => any; } interface Service { /** diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts index d58ed30b22..de55f61b8f 100644 --- a/angular-material/angular-material-tests.ts +++ b/angular-material/angular-material-tests.ts @@ -30,7 +30,11 @@ myApp.config(( myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng.material.IBottomSheetService) => { $scope['openBottomSheet'] = () => { $mdBottomSheet.show({ - template: 'Hello!' + template: 'Hello!', + clickOutsideToClose: true, + disableBackdrop: true, + disableParentScroll: false, + parent: () => {} }); }; $scope['hideBottomSheet'] = $mdBottomSheet.hide.bind($mdBottomSheet, 'hide'); @@ -115,6 +119,14 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia $scope['close'] = () => $mdSidenav(componentId).close(); $scope['isOpen'] = $mdSidenav(componentId).isOpen(); $scope['isLockedOpen'] = $mdSidenav(componentId).isLockedOpen(); + + $scope['asyncLookup'] = $mdSidenav(componentId, true).then((instance) => { + instance.toggle(); + instance.open(); + instance.close(); + instance.isOpen(); + instance.isLockedOpen(); + }); }); myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => { diff --git a/angular-material/index.d.ts b/angular-material/index.d.ts index 14536f8b13..942ecebe5f 100644 --- a/angular-material/index.d.ts +++ b/angular-material/index.d.ts @@ -1,13 +1,12 @@ -// Type definitions for Angular Material 1.0.0-rc5+ (angular.material module) +// Type definitions for Angular Material 1.1.0-rc5+ (angular.material module) // Project: https://github.com/angular/material // Definitions by: Alex Staroselsky , Blake Bigelow , Peter Hajdu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as angular from 'angular'; - -declare module 'angular-material' { -} +declare var _: string; +export = _; declare module 'angular' { export namespace material { @@ -18,11 +17,12 @@ declare module 'angular' { preserveScope?: boolean; // default: false controller?: string | Function; locals?: { [index: string]: any }; - targetEvent?: MouseEvent; - resolve?: { [index: string]: angular.IPromise } + clickOutsideToClose?: boolean; + disableBackdrop?: boolean; + escapeToClose?: boolean; + resolve?: { [index: string]: angular.IPromise }; controllerAs?: string; - bindToController?: boolean; - parent?: string | Element | JQuery; // default: root node + parent?: Function | string | Object; // default: root node disableParentScroll?: boolean; // default: true } @@ -68,16 +68,7 @@ declare module 'angular' { interface IPromptDialog extends IPresetDialog { cancel(cancel: string): IPromptDialog; placeholder(placeholder: string): IPromptDialog; - } - - interface IPromptDialog extends IPresetDialog { - placeholder(placeholder: string): IPromptDialog; - } - - interface IPromptDialog extends IPresetDialog { - cancel(cancel: string): IPromptDialog; - placeholder(placeholder: string): IPromptDialog; - initialValue(value: string): IPromptDialog; + initialValue(initialValue: string): IPromptDialog; } interface IDialogOptions { @@ -104,8 +95,8 @@ declare module 'angular' { onShowing?: Function; onComplete?: Function; onRemoving?: Function; - fullscreen?: boolean; // default: false skipHide?: boolean; + fullscreen?: boolean; // default: false } interface IDialogService { @@ -142,6 +133,7 @@ declare module 'angular' { } interface ISidenavService { + (component: string, enableWait: boolean): angular.IPromise; (component: string): ISidenavObject; } @@ -307,13 +299,13 @@ declare module 'angular' { panelClass?: string; zIndex?: number; // default: 80 position?: IPanelPosition; - hasBackdrop?: boolean; // default: true clickOutsideToClose?: boolean; // default: false escapeToClose?: boolean; // default: false trapFocus?: boolean; // default: false focusOnOpen?: boolean; // default: true fullscreen?: boolean; // default: false animation?: IPanelAnimation; + hasBackdrop?: boolean; // default: false disableParentScroll?: boolean; // default: false onDomAdded?: Function; onOpenComplete?: Function; diff --git a/angular-translate/index.d.ts b/angular-translate/index.d.ts index 6c158026fe..a3b1fd5416 100644 --- a/angular-translate/index.d.ts +++ b/angular-translate/index.d.ts @@ -11,7 +11,7 @@ declare module 'angular' { export namespace translate { interface ITranslationTable { - [key: string]: any; + [key: string]: string | ITranslationTable; } interface ILanguageKeyAlias { @@ -94,7 +94,7 @@ declare module 'angular' { storageKey(): string; storageKey(key: string): void; // JeroMiya - the library should probably return ITranslateProvider but it doesn't here useUrlLoader(url: string): ITranslateProvider; - useStaticFilesLoader(options: IStaticFilesLoaderOptions): ITranslateProvider; + useStaticFilesLoader(options: IStaticFilesLoaderOptions | { files: IStaticFilesLoaderOptions[] }): ITranslateProvider; useLoader(loaderFactory: string, options?: any): ITranslateProvider; useLocalStorage(): ITranslateProvider; useCookieStorage(): ITranslateProvider; diff --git a/angular-ui-bootstrap/index.d.ts b/angular-ui-bootstrap/index.d.ts index 21e246f22f..89efa8fe36 100644 --- a/angular-ui-bootstrap/index.d.ts +++ b/angular-ui-bootstrap/index.d.ts @@ -379,12 +379,18 @@ declare module 'angular' { * @default 'model-open' */ openedClass?: string; - /** * CSS class(es) to be added to the top modal window. */ windowTopClass?: string; + + /** + * Appends the modal to a specific element. + * + * @default 'body' + */ + appendTo?: angular.IAugmentedJQuery; } interface IModalStackService { diff --git a/angular-ui-router/index.d.ts b/angular-ui-router/index.d.ts index 842fe7d1f6..55af591ac6 100644 --- a/angular-ui-router/index.d.ts +++ b/angular-ui-router/index.d.ts @@ -42,6 +42,10 @@ declare module 'angular' { * Function, returns HTML content string */ templateProvider?: Function | Array; + /** + * String, component name + */ + component?: string; /** * A controller paired to the state. Function, annotated array or name as String */ diff --git a/angular-xeditable/angular-xeditable.d.ts b/angular-xeditable/angular-xeditable.d.ts index eaa1296886..026fc5d2fb 100644 --- a/angular-xeditable/angular-xeditable.d.ts +++ b/angular-xeditable/angular-xeditable.d.ts @@ -53,4 +53,46 @@ declare namespace angular.xeditable { */ activationEvent: string; } + + interface IEditableFormController extends angular.IFormController { + + /** + * Shows form with editable controls. + */ + $show(): void; + + /** + * Hides form with editable controls without saving. + */ + $hide(): void; + + /** + * Sets focus on form field specified by `name`.
+ * When trying to set the focus on a form field of a new row in the editable table, the `$activate` call needs to be wrapped in a `$timeout` call so that the form is rendered before the `$activate` function is called. + * + * @param name name of field + */ + $activate(name: string): void; + + /** + * Triggers `oncancel` event and calls `$hide()`. + */ + $cancel(): void; + + $setWaiting(value: boolean): void; + + /** + * Shows error message for particular field. + * + * @param name name of field + * @param msg error message + */ + $setError(name: string, msg: string): void; + + $submit(): void; + + $save(): void; + + } + } diff --git a/angular/angular-tests.ts b/angular/angular-tests.ts index f92fd669c4..30422e1526 100644 --- a/angular/angular-tests.ts +++ b/angular/angular-tests.ts @@ -1097,6 +1097,12 @@ function parseTyping() { } } +function parseWithParams() { + var $parse: angular.IParseService; + var compiledExp = $parse('a.b.c', () => null); + var compiledExp = $parse('a.b.c', null, false); +} + function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjectorService { if (mode === 'debug') { return angular.bootstrap(element, ['main', function($provide: ng.auto.IProvideService) { @@ -1104,11 +1110,11 @@ function doBootstrap(element: Element | JQuery, mode: string): ng.auto.IInjector $delegate['debug'] = true; }); }, 'debug-helpers'], { - debugInfoEnabled: true + strictDi: true }); } return angular.bootstrap(element, ['main'], { - debugInfoEnabled: false + strictDi: false }); } diff --git a/angular/index.d.ts b/angular/index.d.ts index 5c48151a9f..0863a1d78c 100644 --- a/angular/index.d.ts +++ b/angular/index.d.ts @@ -43,7 +43,6 @@ declare namespace angular { interface IAngularBootstrapConfig { strictDi?: boolean; - debugInfoEnabled?: boolean; } /////////////////////////////////////////////////////////////////////////// @@ -876,7 +875,7 @@ declare namespace angular { // see http://docs.angularjs.org/api/ng.$parseProvider /////////////////////////////////////////////////////////////////////////// interface IParseService { - (expression: string): ICompiledExpression; + (expression: string, interceptorFn?: (value: any, scope: IScope, locals: any) => any, expensiveChecks?: boolean): ICompiledExpression; } interface IParseProvider { @@ -988,7 +987,10 @@ declare namespace angular { // DocumentService // see http://docs.angularjs.org/api/ng.$document /////////////////////////////////////////////////////////////////////////// - interface IDocumentService extends JQuery {} + interface IDocumentService extends JQuery { + // Must return intersection type for index signature compatibility with JQuery + [index: number]: HTMLElement & Document; + } /////////////////////////////////////////////////////////////////////////// // ExceptionHandlerService @@ -1718,6 +1720,12 @@ declare namespace angular { * Whether transclusion is enabled. Enabled by default. */ transclude?: boolean | string | {[slot: string]: string}; + /** + * Requires the controllers of other directives and binds them to this component's controller. + * The object keys specify the property names under which the required controllers (object values) will be bound. + * Note that the required controllers will not be available during the instantiation of the controller, + * but they are guaranteed to be available just before the $onInit method is executed! + */ require?: {[controller: string]: string}; } diff --git a/angular/legacy/angular-1.4.d.ts b/angular/legacy/angular-1.4.d.ts index da16c30920..61f4edad02 100644 --- a/angular/legacy/angular-1.4.d.ts +++ b/angular/legacy/angular-1.4.d.ts @@ -886,7 +886,7 @@ declare namespace angular { // see http://docs.angularjs.org/api/ng.$parseProvider /////////////////////////////////////////////////////////////////////////// interface IParseService { - (expression: string): ICompiledExpression; + (expression: string, interceptorFn?: (value: any, scope: IScope, locals: any) => any, expensiveChecks?: boolean): ICompiledExpression; } interface IParseProvider { diff --git a/aphrodite/aphrodite-tests.tsx b/aphrodite/aphrodite-tests.tsx new file mode 100644 index 0000000000..76d28ca43f --- /dev/null +++ b/aphrodite/aphrodite-tests.tsx @@ -0,0 +1,82 @@ +/// +/// + +import * as React from "react"; +import { StyleSheet, css, StyleSheetServer, StyleSheetTestUtils } from "aphrodite"; + +const styles = StyleSheet.create({ + red: { + backgroundColor: 'red' + }, + blue: { + backgroundColor: 'blue' + }, + hover: { + ':hover': { + backgroundColor: 'red' + } + }, + small: { + '@media (max-width: 600px)': { + backgroundColor: 'red', + } + } +}); + +const coolFont = { + fontFamily: "CoolFont", + fontStyle: "normal", + fontWeight: "normal", + src: "url('coolfont.woff2') format('woff2')" +}; + +const withFont = StyleSheet.create({ + headingText: { + fontFamily: coolFont, + fontSize: 20 + }, + bodyText: { + fontFamily: [coolFont, "sans-serif"], + fontSize: 12 + } +}); + + +class App extends React.Component<{}, {}> { + render() { + return
+ + This is red. + + + This turns red on hover. + + + This turns red when the browser is less than 600px width. + + + This is blue. + + + This is blue and turns red when the browser is less than + 600px width. + + + With font + +
; + } +} + +const output = StyleSheetServer.renderStatic(() => { + return "test"; +}); + +output.css.content; +output.css.renderedClassNames; +output.html; + +StyleSheet.rehydrate(output.css.renderedClassNames); + +StyleSheetTestUtils.suppressStyleInjection(); +StyleSheetTestUtils.clearBufferAndResumeStyleInjection(); diff --git a/aphrodite/aphrodite.d.ts b/aphrodite/aphrodite.d.ts new file mode 100644 index 0000000000..89d8646e54 --- /dev/null +++ b/aphrodite/aphrodite.d.ts @@ -0,0 +1,76 @@ +// Type definitions for Aphrodite 0.5.0 +// Project: https://github.com/Khan/aphrodite +// Definitions by: Alexey Svetliakov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "aphrodite" { + import * as React from "react"; + + /** + * Aphrodite style declaration + */ + export interface StyleDeclaration { + [key: string]: React.CSSProperties; + } + + interface StyleSheetStatic { + /** + * Create style sheet + */ + create(styles: T): T; + /** + * Rehydrate class names from server renderer + */ + rehydrate(renderedClassNames: string[]): void; + } + + export var StyleSheet: StyleSheetStatic; + /** + * Get class names from passed styles + */ + export function css(...styles: any[]): string; + + interface StaticRendererResult { + html: string; + css: { + content: string; + renderedClassNames: string[]; + } + } + + /** + * Utilities for using Aphrodite server-side. + */ + interface StyleSheetServerStatic { + renderStatic(renderFunc: () => string): StaticRendererResult; + } + + export var StyleSheetServer: StyleSheetServerStatic; + + interface StyleSheetTestUtilsStatic { + /** + * Prevent styles from being injected into the DOM. + * + * This is useful in situations where you'd like to test rendering UI + * components which use Aphrodite without any of the side-effects of + * Aphrodite happening. Particularly useful for testing the output of + * components when you have no DOM, e.g. testing in Node without a fake DOM. + * + * Should be paired with a subsequent call to + * clearBufferAndResumeStyleInjection. + */ + suppressStyleInjection(): void; + /** + * Opposite method of preventStyleInject. + */ + clearBufferAndResumeStyleInjection(): void; + } + + export var StyleSheetTestUtils: StyleSheetTestUtilsStatic; +} + +declare module "aphrodite/no-important" { + export * from "aphrodite"; +} diff --git a/app-root-path/app-root-path-tests.ts b/app-root-path/app-root-path-tests.ts new file mode 100644 index 0000000000..64d8cdab6b --- /dev/null +++ b/app-root-path/app-root-path-tests.ts @@ -0,0 +1,10 @@ +/// +import * as root from 'app-root-path'; + +let resolvedPath: string; +resolvedPath = root.resolve('../dir'); +resolvedPath = root.path; +resolvedPath = root.toString(); +let resolvedModule: any = root.require('app-root-path'); +root.setPath('C:\\app-root'); + diff --git a/app-root-path/app-root-path.d.ts b/app-root-path/app-root-path.d.ts new file mode 100644 index 0000000000..7cccc59e01 --- /dev/null +++ b/app-root-path/app-root-path.d.ts @@ -0,0 +1,39 @@ +// Type definitions for app-root-path 1.2.1 +// Project: https://github.com/inxilpro/node-app-root-path +// Definitions by: Shant Marouti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'app-root-path' { + interface RootPath { + + /** + * Application root directory absolute path + * @type {string} + */ + path: string; + + /** + * Resolves relative path from root to absolute path + * @param {string} pathToModule + * @returns {string} + */ + resolve(pathToModule: string): string; + + /** + * Resolve module by relative addressing from root + * @param {string} pathToModule + * @returns {*} + */ + require(pathToModule: string): any; + + /** + * Explicitly set root path + * @param {string} explicitlySetPath + */ + setPath(explicitlySetPath: string): void; + + toString(): string; + } + var RootPath: RootPath; + export = RootPath; +} \ No newline at end of file diff --git a/applicationinsights-js/applicationinsights-js.d.ts b/applicationinsights-js/applicationinsights-js.d.ts index d9ad3c1c9d..9047f44b9f 100644 --- a/applicationinsights-js/applicationinsights-js.d.ts +++ b/applicationinsights-js/applicationinsights-js.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ApplicationInsights-JS v0.22.14 +// Type definitions for ApplicationInsights-JS v0.23.2 // Project: https://github.com/Microsoft/ApplicationInsights-JS // Definitions by: Kamil Szostak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -788,3 +788,9 @@ declare module Microsoft.ApplicationInsights { _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error): any; } } + +declare module 'applicationinsights-js' { + export = appInsights; +} + +declare var appInsights: Microsoft.ApplicationInsights.IAppInsights; \ No newline at end of file diff --git a/arcgis-js-api/index.d.ts b/arcgis-js-api/index.d.ts index 01d8a02c12..65765fbb09 100644 --- a/arcgis-js-api/index.d.ts +++ b/arcgis-js-api/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ArcGIS API for JavaScript v3.16 +// Type definitions for ArcGIS API for JavaScript v3.17 // Project: http://js.arcgis.com // Definitions by: Esri // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -18,7 +18,6 @@ declare module "esri" { import BasemapLayer = require("esri/dijit/BasemapLayer"); import Symbol = require("esri/symbols/Symbol"); import BookmarkItem = require("esri/dijit/BookmarkItem"); - import Units = require("esri/units"); import Color = require("esri/Color"); import LocationProviderBase = require("esri/tasks/locationproviders/LocationProviderBase"); import PictureMarkerSymbol = require("esri/symbols/PictureMarkerSymbol"); @@ -45,6 +44,7 @@ declare module "esri" { import QueryTask = require("esri/tasks/QueryTask"); import TextSymbol = require("esri/symbols/TextSymbol"); import StandardGeographyQueryTask = require("esri/tasks/geoenrichment/StandardGeographyQueryTask"); + import WMSLayerInfo = require("esri/layers/WMSLayerInfo"); import WMTSLayerInfo = require("esri/layers/WMTSLayerInfo"); export interface AGSMouseEvent extends MouseEvent { @@ -354,7 +354,7 @@ declare module "esri" { /** Radius of the circle. */ radius?: number; /** Unit of the radius. */ - radiusUnit?: Units; + radiusUnit?: string; } export interface CircleOptions2 { /** The center point of the circle. */ @@ -366,7 +366,7 @@ declare module "esri" { /** The radius of the circle. */ radius?: number; /** Unit of the radius. */ - radiusUnit?: Units; + radiusUnit?: string; } export interface ClassedColorSliderOptions { /** Data map containing renderer information. */ @@ -643,6 +643,8 @@ declare module "esri" { minStops?: number; /** When true, stops on the route are re-ordered to provide an optimal route. */ optimalRoute?: boolean; + /** If specified, this specifies the portal where the produced route layers are going to be stored and accessed. */ + portalUrl?: string; /** URL link to a custom print page. */ printPage?: string; /** If available, this print task is used to display an overview map of the route on the directions print page (Added at v3.11). */ @@ -677,6 +679,8 @@ declare module "esri" { showReturnToStartOption?: boolean; /** Display the 'Show Reverse Stops' button. */ showReverseStopsButton?: boolean; + /** Applicable if the widget works with a Network Analyst Server federated with ArcGIS Online or Portal. */ + showSaveButton?: boolean; /** Highlight the route segment when a directions step is clicked. */ showSegmentHighlight?: boolean; /** Display a popup with segment details when a direction step is clicked. */ @@ -911,6 +915,8 @@ declare module "esri" { layer: FeatureLayer; } export interface FeatureTableOptions { + /** The number of features a service will try to fetch. */ + batchCount?: number; /** Object defining the date options specifically for formatting date and time editors. */ dateOptions?: any; /** Sets the editing state for the FeatureTable. */ @@ -931,12 +937,18 @@ declare module "esri" { menuFunctions?: any[]; /** Attribute fields to include in the FeatureTable. */ outFields?: string[]; + /** Displays or hides the attachment column. */ + showAttachments?: boolean; /** Displays the data type of the field right under the field label. */ showDataTypes?: boolean; + /** Displays or hides total number of features and selected number of features in the grid header. */ + showFeatureCount?: boolean; /** Displays or hides the FeatureTable header. */ showGridHeader?: boolean; /** Displays or hides 'Options' drop-down menu of the FeatureTable. */ showGridMenu?: boolean; + /** Displays or hides the 'Statistics' option in column menus for numeric fields. */ + showStatistics?: boolean; /** Enables an interaction between the map and the feature table. */ syncSelection?: boolean; /** Enables pan/zoom to selected features on the map when the table in 'sync selection' mode. */ @@ -1187,10 +1199,20 @@ declare module "esri" { gdbVersion?: string; } export interface ImageServiceMeasureOptions { + /** The angular unit in which directions of line segments will be calculated. */ + angularUnit?: string; + /** The area unit in which areas of polygons will be calculated. */ + areaUnit?: string; + /** Defines whether to show the widget result in a popup or in the widget's result area when the widget has 'toolbar' layout. */ + displayMeasureResultInPopup?: boolean; /** Symbol to be used when drawing a polygon or extent. */ fillSymbol?: SimpleFillSymbol; /** Image service layer with which the toolbar is associated. */ layer: ArcGISImageServiceLayer; + /** Defines the layout of the widget. */ + layout?: string; + /** The linear unit in which height, length, or perimeters will be calculated. */ + linearUnit?: string; /** Symbol to be used when drawing a line. */ lineSymbol?: SimpleLineSymbol; /** Map instance with which the toolbar is associate. */ @@ -1402,9 +1424,9 @@ declare module "esri" { /** Flag for showing full list of units in the Location tool. */ advancedLocationUnits?: boolean; /** The default area unit for the measure area tool. */ - defaultAreaUnit?: Units; + defaultAreaUnit?: string; /** The default length unit for the measure distance tool. */ - defaultLengthUnit?: Units; + defaultLengthUnit?: string; /** Allows the user to immediately measure previously-created geometry on dijit creation. */ geometry?: Point | Polyline | Polygon; /** Line symbol used to draw the lines for the measure line and measure distance tools. */ @@ -2190,6 +2212,28 @@ declare module "esri" { /** The well-known ID of the spatial reference used by the WFSLayer. */ wkid?: string; } + export interface WMSLayerInfoOptions { + /** All the bounding extents defined for this layer. */ + allExtents?: Extent[]; + /** A description of the WMS layer. */ + description?: string; + /** The extent of the WMS Layer. */ + extent?: Extent; + /** The URL to the legend image. */ + legendURL?: string; + /** The name of the WMS layer. */ + name: string; + /** Returns true if the layer can be queried and the service supports GetFeatureInfo with either text/html or text/plain formats. */ + queryable?: boolean; + /** Indicates if this layer should be included in the popup. */ + showPopup?: boolean; + /** All the spatial references defined for this layer. */ + spatialReferences?: SpatialReference[]; + /** WMSLayerInfos of the layer's sub layers. */ + subLayers?: WMSLayerInfo[]; + /** The title of the WMS layer. */ + title?: string; + } export interface WMSLayerOptions { /** Specify the map image format, valid options are png,jpg,bmp,gif,svg. */ format?: string; @@ -3732,6 +3776,8 @@ declare module "esri/dijit/Directions" { maxStopsReached: boolean; /** Read-only: The graphic for the calculated route. */ mergedRouteGraphic: Graphic; + /** If specified, this specifies the portal where the produced route layers are going to be stored and accessed. */ + portalUrl: string; /** Routing parameters for the widget. */ routeParams: RouteParameters; /** Routing task for the widget. */ @@ -3744,6 +3790,8 @@ declare module "esri/dijit/Directions" { showClearButton: boolean; /** If true, the toggle button group allowing user to choose between Miles and Kilometers is shown. */ showMilesKilometersOption: boolean; + /** Applicable if the widget works with a Network Analyst Server federated with ArcGIS Online or Portal. */ + showSaveButton: boolean; /** If true, and supported by the service, then two toggle button groups are shown: one to allow user to choose between driving a car, a truck, or walking, and one more group to choose between fastest or shortest routes. */ showTravelModesOption: boolean; /** An array of graphics that define the stop locations along the route. */ @@ -3792,6 +3840,11 @@ declare module "esri/dijit/Directions" { * @param index The index of the route segment to highlight. */ highlightSegment(index: number): void; + /** + * Loads a stored route layer from either ArcGIS Online or Portal + * @param itemId The itemId of the stored route layer from either ArcGIS Online or Portal. + */ + loadRoute(itemId: string): any; /** * Remove the stop at the specified index. * @param index The index of the stop to remove. @@ -3801,6 +3854,16 @@ declare module "esri/dijit/Directions" { removeStops(): any; /** Resets the directions widget removing any directions, stops and map graphics. */ reset(): any; + /** + * Specify the language used for the directions. + * @param locale The locale used for the directions. + */ + setDirectionsLanguage(locale: string): any; + /** + * Specify the length units used for the directions widget. + * @param units The length units used for the directions widget. + */ + setDirectionsLengthUnits(units: string): any; /** * If widget runs with Travel Modes enabled, call this method to switch to particular Travel mode programmatically. * @param travelModeName Travel mode. @@ -3843,10 +3906,16 @@ declare module "esri/dijit/Directions" { on(type: "directions-finish", listener: (event: { result: RouteResult; target: Directions }) => void): esri.Handle; /** Fires when the route services starts to calculate the route. */ on(type: "directions-start", listener: (event: { target: Directions }) => void): esri.Handle; + /** Fires after a user clicks the Save or Save as New button and subsequently does not have permission to create an item in ArcGIS Online or Portal. */ + on(type: "feature-collection-created", listener: (event: { target: Directions }) => void): esri.Handle; /** Fires when the directions widget has fully loaded. */ on(type: "load", listener: (event: { target: Directions }) => void): esri.Handle; /** Fires when the widget starts or stops listening for map clicks. */ on(type: "map-click-active", listener: (event: { mapClickActive: boolean; target: Directions }) => void): esri.Handle; + /** Fires after a user clicks the Save or Save as New button for the first time in order to store a new route in either ArcGIS Online or Portal. */ + on(type: "route-item-created", listener: (event: { target: Directions }) => void): esri.Handle; + /** Fires when a existing route layer item is successfully updated in ArcGIS Online or Portal after user clicks the Save button. */ + on(type: "route-item-updated", listener: (event: { target: Directions }) => void): esri.Handle; /** Fired when you hover over a route segment in the directions display. */ on(type: "segment-highlight", listener: (event: { graphic: Graphic; target: Directions }) => void): esri.Handle; /** Fires when a route segment is selected in the directions display. */ @@ -3901,6 +3970,8 @@ declare module "esri/dijit/FeatureTable" { /** Creates an instance of the FeatureTable widget within the provided DOM node. */ class FeatureTable { + /** The number of features a service will try to fetch. */ + batchCount: number; /** Read-only: A reference to the column objects and their parameters. */ columns: any[]; /** Read-only: Reference to the dataStore used by the dGrid. */ @@ -3909,6 +3980,8 @@ declare module "esri/dijit/FeatureTable" { dateOptions: any; /** Sets the editing state for the FeatureTable. */ editable: boolean; + /** Event trigger(s) used to display editing interface for an individual cell. */ + editOn: string | any; /** Read-only: Number of records displayed in FeatureTable. */ featureCount: number; /** The featureLayer that the table is associated with. */ @@ -3937,12 +4010,18 @@ declare module "esri/dijit/FeatureTable" { selectedRowIds: number[]; /** Read-only: Each element in the array is an object that contains name-value pair of fields and field values associated with the selected rows. */ selectedRows: any[]; - /** Displays the data type of the field right under the field label in the column header. */ + /** Displays or hides the attachment column. */ + showAttachments: boolean; + /** Displays or hides the data type of the field right under the field label in the column header. */ showDataTypes: boolean; + /** Displays or hides total number of features and selected number of features in the grid header. */ + showFeatureCount: boolean; /** Displays or hides the FeatureTable header. */ showGridHeader: boolean; /** Displays or hides 'Options' drop-down menu of the FeatureTable. */ showGridMenu: boolean; + /** Displays or hides the 'Statistics' option in column menus for numeric fields. */ + showStatistics: boolean; /** Enables an interaction between the map and the feature table. */ syncSelection: boolean; /** Enables pans to selected features on the map when the table in 'sync selection' mode. */ @@ -3953,6 +4032,29 @@ declare module "esri/dijit/FeatureTable" { * @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into. */ constructor(params: esri.FeatureTableOptions, srcNodeRef: Node | string); + /** Removes all current selections including subsets from filterSelectedRecords(). */ + clearSelection(): void; + /** Destroys the FeatureTable widget. */ + destroy(): void; + /** + * Allows users to see the sub-set of currently selected records (uses dGrid.query). + * @param toggle When true only a subset of currently selected features will be displayed in the FeatureTable. + */ + filterSelectedRecords(toggle: boolean): void; + /** + * Queries and gets selected features from the FeatureLayer instead of the store. + * @param id Array of row ids + */ + getFeatureDataById(id: number[]): any; + /** + * Gets row object by the row ID. + * @param id row ID + */ + getRowDataById(id: number): any; + /** Refreshes the data in the grid. */ + refresh(): void; + /** Resizes the grid's container. */ + resize(): void; /** Finalizes the creation of the widget. */ startup(): void; /** Fires when the grid column is resized. */ @@ -4286,8 +4388,13 @@ declare module "esri/dijit/ImageServiceMeasure" { /** * Creates an instance of the ImageServiceMeasure widget. * @param params An Object containing constructor options. + * @param srcNode Reference or id of the HTML element where the widget should be rendered. */ - constructor(params: esri.ImageServiceMeasureOptions); + constructor(params: esri.ImageServiceMeasureOptions, srcNode: Node | string); + /** Destroys the ImageServiceMeasure widget. */ + destroy(): void; + /** Finalizes the creation of the widget. */ + startup(): void; } export = ImageServiceMeasure; } @@ -4528,9 +4635,14 @@ declare module "esri/dijit/LayerSwipe" { declare module "esri/dijit/Legend" { import esri = require("esri"); + import Map = require("esri/map"); /** The legend dijit displays a label and symbol for some or all of the layers in the map. */ class Legend { + /** Specify a subset of the layers in the map to display in the legend. */ + layerInfos: any[]; + /** Reference to the map. */ + map: Map; /** * Creates a new Legend dijit. * @param params Parameters used to configure the dijit. @@ -4555,7 +4667,7 @@ declare module "esri/dijit/LocateButton" { import Symbol = require("esri/symbols/Symbol"); import Graphic = require("esri/graphic"); - /** LocateButton provides a simple button to locate and zoom to the users current location. */ + /** LocateButton provides a simple button to locate and zoom to the user's location. */ class LocateButton { /** Centers the map to the location when a new position is returned. */ centerAt: boolean; @@ -6767,7 +6879,7 @@ declare module "esri/dijit/editing/Add" { import esri = require("esri"); import OperationBase = require("esri/OperationBase"); - /** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */ + /** This class is used with the UndoManager to provide undo/redo functionality of Add operations when editing. */ class Add extends OperationBase { /** * Create a new Add operation. @@ -6810,7 +6922,7 @@ declare module "esri/dijit/editing/Cut" { import esri = require("esri"); import OperationBase = require("esri/OperationBase"); - /** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */ + /** This class is used with the UndoManager to provide undo/redo functionality of Cut operations when editing. */ class Cut extends OperationBase { /** * Create a new Cut operation. @@ -6829,7 +6941,7 @@ declare module "esri/dijit/editing/Delete" { import esri = require("esri"); import OperationBase = require("esri/OperationBase"); - /** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */ + /** This class is used with the UndoManager to provide undo/redo functionality of Delete operations when editing. */ class Delete extends OperationBase { /** * Create a new Delete operation. @@ -6929,7 +7041,7 @@ declare module "esri/dijit/editing/Union" { import esri = require("esri"); import OperationBase = require("esri/OperationBase"); - /** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */ + /** This class is used with the UndoManager to provide undo/redo functionality of Union operations when editing. */ class Union extends OperationBase { /** * Create a new Union operation. @@ -6948,7 +7060,7 @@ declare module "esri/dijit/editing/Update" { import esri = require("esri"); import OperationBase = require("esri/OperationBase"); - /** The esri/dijit/editing namespace contains editing related operations that inherit from OperationBase. */ + /** This class is used with the UndoManager to provide undo/redo functionality of Update operations when editing. */ class Update extends OperationBase { /** * Create a new Update operation. @@ -8353,8 +8465,9 @@ declare module "esri/geometry/webMercatorUtils" { /** * Converts geometry from Web Mercator units to geographic units. * @param geometry The geometry to convert. + * @param isLinear Indicates whether to work with linear values, i.e., do not normalize. */ - webMercatorToGeographic(geometry: Geometry): Geometry; + webMercatorToGeographic(geometry: Geometry, isLinear?: boolean): Geometry; /** * Translates the given Web Mercator coordinates to Longitude and Latitude. * @param x The x coordinate value to convert. @@ -10809,8 +10922,6 @@ declare module "esri/layers/VectorTileLayer" { initialExtent: Extent; /** The spatial reference of the layer. */ spatialReference: SpatialReference; - /** The style object of the service with fully qualified URLs for glyphs and sprite. */ - style: any; /** Contains information about the tiling scheme for the layer. */ tileInfo: TileInfo; /** The URL to the vector tile service or style JSON that will be used to draw the layer. */ @@ -10821,6 +10932,8 @@ declare module "esri/layers/VectorTileLayer" { * @param options Optional parameters. */ constructor(url: string | any, options?: esri.VectorTileLayerOptions); + /** Returns an object that contains the current style information for the layer. */ + getStyle(): any; /** * Changes the style properties used to render the layers. * @param styleUrl A url to a JSON file containing the stylesheet information to render the layer. @@ -10835,14 +10948,15 @@ declare module "esri/layers/VectorTileLayer" { declare module "esri/layers/WFSLayer" { import esri = require("esri"); + import GraphicsLayer = require("esri/layers/GraphicsLayer"); import Field = require("esri/layers/Field"); import Extent = require("esri/geometry/Extent"); import Graphic = require("esri/graphic"); import InfoTemplate = require("esri/InfoTemplate"); import Renderer = require("esri/renderers/Renderer"); - /** (Currently in beta) A layer for OGC Web Feature Services (WFS). */ - class WFSLayer { + /** (Currently in beta) A layer for OGC Web Feature Services (WFS). */ + class WFSLayer extends GraphicsLayer { /** An array of fields in the layer. */ fields: Field[]; /** The full extent of the layer. */ @@ -10864,17 +10978,11 @@ declare module "esri/layers/WFSLayer" { * @param options See options table below for full descriptions of the properties needed for this object. */ constructor(options: esri.WFSLayerOptions); - /** Creates the getFeature parameter based on the version, nsLayerName, nsGeometryFieldName, mode, wkid, inverseFilter, maxFeatures constructor parameters. */ - buildRequest(): string; /** - * Gets the WFS layer capabilities. - * @param callback An array of WFS layers in JSON format. + * Creates a WFSLayer using the provided JSON object. + * @param json The input JSON. */ - getCapabilities(callback?: Function): void; - /** Performs the getFeature request. */ - getFeature(): void; - /** Returns a JSON Object containing all of the WFS parameters. */ - getWFSParameters(): any; + fromJson(json: Object): void; /** Redraws all the graphics in the layer. */ redraw(): void; /** Refreshes the features in the WFS layer. */ @@ -10885,8 +10993,8 @@ declare module "esri/layers/WFSLayer" { setPointSymbol(): void; /** Sets the default polygon symbol to be used if no renderer is specified. */ setPolygonSymbol(): void; - /** Sets the WFS parameters using the provided JSON Object. */ - setWFSParameters(): void; + /** Converts the WFSLayer instance to a JSON object. */ + toJson(): any; } export = WFSLayer; } @@ -10952,6 +11060,7 @@ declare module "esri/layers/WMSLayer" { } declare module "esri/layers/WMSLayerInfo" { + import esri = require("esri"); import Extent = require("esri/geometry/Extent"); /** The WMSLayerInfo class defines and provides information about layers in a WMS service. */ @@ -10966,6 +11075,10 @@ declare module "esri/layers/WMSLayerInfo" { legendURL: string; /** The layer name. */ name: string; + /** Returns true if the layer can be queried and the service supports GetFeatureInfo with either text/html or text/plain formats */ + queryable: boolean; + /** Indicates if this layer should be included in the popup. */ + showPopup: boolean; /** An array of WKIDs of all spatial references defined for the layer. */ spatialReferences: number[]; /** WMSLayerInfos of the layer's sub layers. */ @@ -10974,9 +11087,9 @@ declare module "esri/layers/WMSLayerInfo" { title: string; /** * Creates a new WMSLayerInfo object. - * @param layer WMSLayerInfo layer object. + * @param options See options list for parameters. */ - constructor(layer: any); + constructor(options?: esri.WMSLayerInfoOptions); } export = WMSLayerInfo; } @@ -11584,7 +11697,7 @@ declare module "esri/opsdashboard/DataSourceProxy" { displayFieldName: string; /** Read-only: The collection of fields. */ fields: Field[]; - /** The geometry type. */ + /** Read-only: The geometry type. */ geometryType: string; /** Read-only: The id of the data source. */ id: string; @@ -11611,8 +11724,8 @@ declare module "esri/opsdashboard/DataSourceProxy" { executeQuery(query: Query): any; /** An object that contains service level metadata about whether or not the layer supports queries using statistics, order by fields, DISTINCT, pagination, query with distance, and returning queries with extents. */ getAdvancedQueryCapabilities(): any; - /** Retrieve the associated data source that supports selection. */ - getAssociatedSelectionDataSourceProxy(): any; + /** Retrieve the associated id of the data source that supports selection. */ + getAssociatedSelectionDataSourceId(): any; /** Get the associated popupInfo for the data source if any available. */ getPopupInfo(): any; /** Get the associated render object for the data source if any available. */ @@ -11666,12 +11779,17 @@ declare module "esri/opsdashboard/ExtensionBase" { static POLYLINE: any; /** Read-only: Indicates if the host application is the Windows Operations Dashboard. */ isNative: boolean; + /** Read Only: It will list all of the Portal helper services. */ + portalHelperServices: string; /** Read-only: The URL to the ArcGIS.com site or in-house portal that you are currently signed in to. */ portalUrl: string; /** Get the collection of data sources from the host application. */ getDataSourceProxies(): any; - /** Get the data source corresponding to the data source id from the host application. */ - getDataSourceProxy(): any; + /** + * Get the data source corresponding to the data source id from the host application. + * @param dataSourceId The data source id + */ + getDataSourceProxy(dataSourceId: string): any; /** Get the collection of map widgets from the host application. */ getMapWidgetProxies(): any; /** @@ -11791,7 +11909,7 @@ declare module "esri/opsdashboard/GraphicsLayerProxy" { minScale: number; /** Read-only: The current host graphics layer opacity ratio. */ opacity: number; - /** The current renderer used by the host graphics layer. */ + /** Read-only: The current renderer used by the host graphics layer. */ renderer: Renderer; /** Read-only: The current host graphics layer visibility. */ visible: boolean; @@ -11928,8 +12046,6 @@ declare module "esri/opsdashboard/MapWidgetProxy" { destroyGraphicsLayerProxy(graphicsLayerProxy: GraphicsLayerProxy): void; /** Gets the current host map extent. */ getMapExtent(): any; - /** Called by the host application when the extent of the host map has changed. */ - mapExtentChanged(): void; /** * Pans the map to a new location. * @param mapPoint A new location with the same spatial reference as the host map. @@ -14088,7 +14204,7 @@ declare module "esri/tasks/FindTask" { url: string; /** * Creates a new FindTask object. - * @param url URL to the ArcGIS Server REST resource that represents a layer in a service. + * @param url URL to the ArcGIS Server REST resource that represents a map service. * @param options Optional parameters. */ constructor(url: string, options?: esri.FindTaskOptions); @@ -15343,6 +15459,8 @@ declare module "esri/tasks/RouteParameters" { startTimeIsUTC: boolean; /** The set of stops loaded as network locations during analysis. */ stops: any; + /** If true , the TimeWindowStart and TimeWindowEnd attributes of a stop are in UTC time (milliseconds). */ + timeWindowsAreUTC: boolean; /** Travel modes define how a pedestrian, car, truck or other medium of transportation moves through the street network. */ travelMode: any; /** If true, the hierarchy attribute for the network should be used in analysis. */ @@ -16696,7 +16814,7 @@ declare module "esri/tasks/query" { static SPATIAL_REL_TOUCHES: any; /** The feature from feature class 1 is completely enclosed by the feature from feature class 2. */ static SPATIAL_REL_WITHIN: any; - /** Distance to buffer input geometry. */ + /** Buffer distance for input geometries. */ distance: number; /** The geometry to apply to the spatial filter. */ geometry: Geometry; @@ -16738,7 +16856,7 @@ declare module "esri/tasks/query" { text: string; /** Specify a time extent for the query. */ timeExtent: TimeExtent; - /** Distance unit. */ + /** The unit for calculating the buffer distance. */ units: string; /** A where clause for the query. */ where: string; @@ -17055,7 +17173,7 @@ declare module "esri/toolbars/navigation" { * @param symbol The SimpleFillSymbol used for the rubber band zoom. */ setZoomSymbol(symbol: Symbol): void; - /** Zoom to full extent of base layer. */ + /** Zoom to initial extent of base layer. */ zoomToFullExtent(): void; /** Zoom to next extent in extent history. */ zoomToNextExtent(): void; diff --git a/archiver/index.d.ts b/archiver/index.d.ts index 74a3351b99..df824c3915 100644 --- a/archiver/index.d.ts +++ b/archiver/index.d.ts @@ -24,7 +24,7 @@ interface nameInterface { interface Archiver extends STREAM.Transform { pipe(writeStream: FS.WriteStream): void; - append(readStream: FS.ReadStream, name: nameInterface): void; + append(source: FS.ReadStream | Buffer | string, name: nameInterface): void; finalize(): void; } diff --git a/autobahn/index.d.ts b/autobahn/index.d.ts index 4a91323a05..d59eaf6750 100644 --- a/autobahn/index.d.ts +++ b/autobahn/index.d.ts @@ -47,7 +47,7 @@ declare namespace autobahn { interface IInvocation { caller?: number; - progress?: boolean; + progress?: (args : any[], kwargs : any) => void; procedure: string; } diff --git a/avoscloud-sdk/avoscloud-sdk.d.ts b/avoscloud-sdk/avoscloud-sdk.d.ts index af904a6c8c..deb416290d 100644 --- a/avoscloud-sdk/avoscloud-sdk.d.ts +++ b/avoscloud-sdk/avoscloud-sdk.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "avoscloud-sdk" { - namespace AV{ + namespace AV { var applicationId: string; var applicationKey: string; @@ -301,6 +301,7 @@ declare module "avoscloud-sdk" { fetch(options?: Object.FetchOptions): Promise; get(attr: string): any; getACL(): ACL; + getObjectId(): string; has(attr: string): boolean; hasChanged(attr: string): boolean; increment(attr: string, amount?: number): any; @@ -529,6 +530,7 @@ declare module "avoscloud-sdk" { constructor(objectClass: any); + static and(...var_args: Query[]): Query; static or(...var_args: Query[]): Query; addAscending(key: string): Query; @@ -628,7 +630,7 @@ declare module "avoscloud-sdk" { signUp(attrs: any, options?: SuccessFailureOptions): Promise; logIn(options?: SuccessFailureOptions): Promise; fetch(options?: SuccessFailureOptions): Promise; - save(arg1: any, arg2: any, arg3: any): Promise; + save(arg1?: any, arg2?: any, arg3?: any): Promise; authenticated(): boolean; isCurrent(): boolean; diff --git a/aws-sdk/index.d.ts b/aws-sdk/index.d.ts index adc4b4196b..fa0c32df18 100644 --- a/aws-sdk/index.d.ts +++ b/aws-sdk/index.d.ts @@ -88,8 +88,6 @@ export interface Services { export interface ClientConfigPartial extends Services { credentials?: Credentials; region?: string; - accessKeyId: string; - secretAccessKey: string; computeChecksums?: boolean; convertResponseTypes?: boolean; logger?: Logger; @@ -152,17 +150,22 @@ export declare class SimpleWorkflow { export declare class S3 { constructor(options?: any); - putObject(params: s3.PutObjectRequest, callback: (err: any, data: any) => void): void; - getObject(params: s3.GetObjectRequest, callback: (err: any, data: any) => void): void; + getObject(params: s3.GetObjectRequest, callback: (err: Error, data: any) => void): void; + putObject(params: s3.PutObjectRequest, callback: (err: Error, data: any) => void): void; + deleteObject(params: s3.DeleteObjectRequest, callback: (err: Error, data: any) => void): void; + headObject(params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void; + getSignedUrl(operation: string, params: any): string; + getSignedUrl(operation: string, params: any, callback: (err: Error, url: string) => void): void; + upload(params?: s3.PutObjectRequest, options?: s3.UploadOptions, callback?: (err: Error, data: any) => void): void; } + export class STS { constructor(options?: any); /** * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that you can use to access AWS resources that you might not normally have access to. */ assumeRole(params: sts.AssumeRoleParams, callback: (err: any, data: any) => void): void; - /** * Returns a set of temporary security credentials for users who have been authenticated via a SAML authentication response. */ @@ -306,6 +309,7 @@ export declare module DynamoDB { ScanFilter?: _DDBDC_KeyComparison; TotalSegments?: number; } + interface GetParam extends _DDBDC_Reader { Key: _DDBDC_Keys; } @@ -394,7 +398,7 @@ export declare module SQS { } export interface SendMessageParams { - QueueUrl: string; + QueueUrl?: string; MessageBody: string; DelaySeconds?: number; MessageAttributes?: { [name: string]: MessageAttribute; } @@ -1272,6 +1276,33 @@ export declare module s3 { VersionId?: string; } + export interface DeleteObjectRequest { + Bucket: string; + Key: string; + MFA?: string; + RequestPayer?: string; + VersionId?: string; + } + + export interface HeadObjectRequest { + Bucket: string; + Key: string; + IfMatch?: string; + IfModifiedSince?: Date; + IfNoneMatch?: string; + IfUnmodifiedSince?: Date; + Range?: string; + RequestPayer?: string; + SSECustomerAlgorithm?: string; + SSECustomerKey?: Buffer | string; + SSECustomerKeyMD5?: string; + VersionId?: string; + } + + export interface UploadOptions { + partSize?: number; + queueSize?: number; + } } export declare module ecs { diff --git a/bazinga-translator/bazinga-translator-tests.ts b/bazinga-translator/bazinga-translator-tests.ts new file mode 100644 index 0000000000..2401641815 --- /dev/null +++ b/bazinga-translator/bazinga-translator-tests.ts @@ -0,0 +1,12 @@ +/// + +Translator.fallback = 'en'; +Translator.defaultDomain = 'messages'; + +Translator.add("test", "it work", "frontend", "en"); + +Translator.trans('key', {}, 'frontend'); +Translator.trans('key', {"foo": "bar"}, 'DOMAIN_NAME'); + +Translator.transChoice('key', 1, {}, 'frontend'); +Translator.transChoice('key', 123, {"foo": "bar"}, 'DOMAIN_NAME'); \ No newline at end of file diff --git a/bazinga-translator/bazinga-translator.d.ts b/bazinga-translator/bazinga-translator.d.ts new file mode 100644 index 0000000000..5467fbfd85 --- /dev/null +++ b/bazinga-translator/bazinga-translator.d.ts @@ -0,0 +1,99 @@ +// Type definitions for Translator +// Project: https://github.com/willdurand/BazingaJsTranslationBundle +// Definitions by: Alex +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface BazingaTranslator { + /** + * The current locale. + * + * @type {String} + */ + locale: string; + + /** + * Fallback locale. + * + * @type {String} + */ + fallback: string; + + /** + * Placeholder prefix. + * + * @type {String} + */ + placeHolderPrefix: string; + + /** + * Placeholder suffix. + * + * @type {String} + */ + placeHolderSuffix: string; + + /** + * Default domain. + * + * @type {String} + */ + defaultDomain: string; + + /** + * Plural separator. + * + * @type {String} + */ + pluralSeparator: string; + + /** + * Adds a translation entry. + * + * @param {String} id The message id + * @param {String} message The message to register for the given id + * @param {String} [domain] The domain for the message or null to use the default + * @param {String} [locale] The locale or null to use the default + * + * @return {Object} Translator + */ + add(id: string, message: string, domain: string, locale: string): BazingaTranslator; + + + /** + * Translates the given message. + * + * @param {String} id The message id + * @param {Object} [parameters] An array of parameters for the message + * @param {String} [domain] The domain for the message or null to guess it + * @param {String} [locale] The locale or null to use the default + * + * @return {String} The translated string + */ + trans(id: string, parameters: any, domain: string, locale?: string): string; + + /** + * Translates the given choice message by choosing a translation according to a number. + * + * @param {String} id The message id + * @param {Number} number The number to use to find the indice of the message + * @param {Object} [parameters] An array of parameters for the message + * @param {String} [domain] The domain for the message or null to guess it + * @param {String} [locale] The locale or null to use the default + * + * @return {String} The translated string + */ + transChoice(id: string, number: number, parameters: any, domain: string, locale?: string): string, + + /** + * Loads translations from JSON. + * + * @param {String} data A JSON string or object literal + * + * @return {Object} Translator + */ + fromJSON(data: string): BazingaTranslator; + + reset(): void; +} + +declare var Translator: BazingaTranslator; \ No newline at end of file diff --git a/bezier-js/bezier-js-tests.ts b/bezier-js/bezier-js-tests.ts index 54c629d11b..2f9f2685a2 100644 --- a/bezier-js/bezier-js-tests.ts +++ b/bezier-js/bezier-js-tests.ts @@ -1,27 +1,29 @@ /// function test() { - + var bezierjs: typeof BezierJs; - - var bezier = new bezierjs.Bezier([1,2,3,4]); + + var bezier = new bezierjs.Bezier([1, 2, 3, 4]); var cap = new bezierjs.BezierCap([]); var point: BezierJs.Point = { x: 0, y: 0 }; var utils = bezier.getUtils(); - var line: BezierJs.Line = { p1: { x:0, y: 0}, p2: {x:1, y: 1}}; + var line: BezierJs.Line = { p1: { x: 0, y: 0 }, p2: { x: 1, y: 1 } }; var abc: BezierJs.ABC = { A: null, B: null, C: null }; var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1 }; var bbox: BezierJs.BBox = bezier.bbox(); - var closest: BezierJs.Closest = { mdist: 1, mpos: 0 }; - var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z:[0] }; + var closest: BezierJs.Closest = { mdist: 1, mpos: 0 }; + var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z: [0] }; var minmax: BezierJs.MinMax = { min: 0, max: 0 }; var offset: BezierJs.Offset = { x: 0, y: 0, c: point, n: point }; var pair: BezierJs.Pair = { left: bezier, right: bezier }; var poly: BezierJs.PolyBezier = bezier.outline(1); var projection: BezierJs.Projection = { x: 0, y: 0, t: 9, d: 4 }; - var shape: BezierJs.Shape = { startcap: cap, endcap: cap, forward: bezier, back: bezier, bbox: bbox }; + var shape: BezierJs.Shape = { + startcap: cap, endcap: cap, forward: bezier, back: bezier, bbox: bbox, intersections: function (shape) { return [[0]]; } + }; var split: BezierJs.Split = { left: bezier, right: bezier, span: [point] }; - + bezier.arcs(); bezier.clockwise; bezier.compute(.5); @@ -36,10 +38,10 @@ function test() { bezier.length(); bezier.lineIntersects(line); bezier.normal(0); - bezier.offset(1,2); + bezier.offset(1, 2); bezier.on(point, 0); bezier.order = 5; - bezier.outlineshapes(1,3); + bezier.outlineshapes(1, 3); bezier.overlaps(bezier); bezier.point(9); bezier.project(point); @@ -52,9 +54,9 @@ function test() { bezier.split(0.5).left; bezier.toSVG(); bezier.update(); - + cap.virtual = true; - + poly.addCurve(bezier); poly.bbox(); poly.curve(7); @@ -62,12 +64,12 @@ function test() { poly.length(); poly.offset(9).points[0].y; poly.points[0]; - + utils.abcratio(0, 1); utils.align([point], line); utils.angle(point, point, point); utils.approximately(5, 7, .001); - utils.arcfn(1, function(){}); + utils.arcfn(1, function () { }); utils.bboxoverlap(bbox, bbox); utils.between(0, 0, 1); utils.closest([point], point); @@ -78,7 +80,7 @@ function test() { utils.findbbox([bezier]); utils.getccenter(point, point, point); utils.getminmax(bezier, 'x', [0]); - utils.length(function(){}); + utils.length(function () { }); utils.lerp(1, point, point); utils.lli(offset, offset); utils.lli4(point, point, point, point); @@ -92,5 +94,5 @@ function test() { utils.roots([point], line); utils.round(.999, .001); utils.shapeintersections(shape, bbox, shape, bbox); - + } \ No newline at end of file diff --git a/bezier-js/bezier-js.d.ts b/bezier-js/bezier-js.d.ts index 8256f4ce99..8ee85790b1 100644 --- a/bezier-js/bezier-js.d.ts +++ b/bezier-js/bezier-js.d.ts @@ -57,6 +57,7 @@ declare module BezierJs { back: Bezier; endcap: BezierCap; bbox: BBox; + intersections: (shape: Shape) => string[][] | number[][]; } interface ABC { A: Point; @@ -76,8 +77,8 @@ declare module BezierJs { * */ class Bezier { - clockwise: boolean; private _linear; + clockwise: boolean; _3d: boolean; _t1: number; _t2: number; @@ -124,16 +125,16 @@ declare module BezierJs { overlaps(curve: Bezier): boolean; offset(t: number, d?: number): Offset | Bezier[]; simple(): boolean; - reduce(): any[]; + reduce(): Bezier[]; scale(d: Function): Bezier; scale(d: number): Bezier; outline(d1: number, d2?: number, d3?: number, d4?: number): PolyBezier; - outlineshapes(d1: number, d2: number): Shape[]; - intersects(curve: Bezier): string[] | number[]; + outlineshapes(d1: number, d2: number, curveIntersectionThreshold?: number): Shape[]; + intersects(curve: Bezier, curveIntersectionThreshold?: number): string[] | number[]; intersects(curve: Line): string[] | number[]; lineIntersects(line: Line): number[]; - selfintersects(): string[]; - curveintersects(c1: Bezier[], c2: Bezier[]): string[]; + selfintersects(curveIntersectionThreshold?: number): string[]; + curveintersects(c1: Bezier[], c2: Bezier[], curveIntersectionThreshold?: number): string[]; arcs(errorThreshold?: number): Arc[]; private _error(pc, np1, s, e); private _iterate(errorThreshold, circles); @@ -165,8 +166,8 @@ declare module BezierJs.utils { function lli(v1: Offset, v2: Offset): Point; function makeline(p1: Point, p2: Point): Bezier; function findbbox(sections: Bezier[]): BBox; - function shapeintersections(s1: Shape, bbox1: BBox, s2: Shape, bbox2: BBox): string[][] | number[][]; - function makeshape(forward: Bezier, back: Bezier): Shape; + function shapeintersections(s1: Shape, bbox1: BBox, s2: Shape, bbox2: BBox, curveIntersectionThreshold?: number): string[][] | number[][]; + function makeshape(forward: Bezier, back: Bezier, curveIntersectionThreshold?: number): Shape; function getminmax(curve: Bezier, d: string, list: number[]): MinMax; function align(points: Point[], line: Line): Point[]; function roots(points: Point[], line: Line): number[]; @@ -174,7 +175,7 @@ declare module BezierJs.utils { function inflections(points: Point[]): number[]; function bboxoverlap(b1: BBox, b2: BBox): boolean; function expandbox(bbox: BBox, _bbox: BBox): void; - function pairiteration(c1: Bezier, c2: Bezier): string[]; + function pairiteration(c1: Bezier, c2: Bezier, curveIntersectionThreshold?: number): string[]; function getccenter(p1: Point, p2: Point, p3: Point): Arc; } declare module BezierJs { diff --git a/bootstrap-slider/index.d.ts b/bootstrap-slider/index.d.ts index 0d704c0dfc..9ed5c440c3 100644 --- a/bootstrap-slider/index.d.ts +++ b/bootstrap-slider/index.d.ts @@ -35,7 +35,7 @@ interface SliderOptions { * Default: 'horizontal' * set the orientation. Accepts 'vertical' or 'horizontal' */ - orientation?: number; + orientation?: string; /** * Default: 5 * initial value. Use array to have a range slider. diff --git a/chai-dom/chai-dom-tests.ts b/chai-dom/chai-dom-tests.ts new file mode 100644 index 0000000000..2fca54765e --- /dev/null +++ b/chai-dom/chai-dom-tests.ts @@ -0,0 +1,27 @@ +/// + +import * as chai from 'chai'; +import * as chaiDom from 'chai-dom'; + +chai.use(chaiDom); +var expect = chai.expect; + +function test() { + + var testElement = '
'; + expect(testElement).to.have.attribute('foo', 'bar'); + expect(testElement).to.have.attr('foo').match(/bar/); + expect(testElement).to.have.class('foo'); + expect(testElement).to.have.id('id'); + expect(testElement).to.have.html('foo'); + expect(testElement).to.have.text('foo'); + expect(testElement).to.have.text(['foo', 'bar']); + expect(testElement).to.have.value('foo'); + expect(testElement).to.be.empty; + expect(testElement).to.have.length(2); + expect(testElement).to.exist; + expect(testElement).to.match('foo'); + expect(testElement).to.contain('foo'); + expect(testElement).to.contain(document.body); + +} \ No newline at end of file diff --git a/chai-dom/chai-dom.d.ts b/chai-dom/chai-dom.d.ts new file mode 100644 index 0000000000..397bc17cb4 --- /dev/null +++ b/chai-dom/chai-dom.d.ts @@ -0,0 +1,38 @@ +// Type definitions for chai-dom +// Project: https://github.com/nathanboktae/chai-dom +// Definitions by: Matt Lewis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace Chai { + + interface Assertion { + + attr(name: string, value?: string): Assertion; + + attribute(name: string, value?: string): Assertion; + + class(className: string): Assertion; + + id(id: string): Assertion; + + html(html: string): Assertion; + + text(text: string|string[]): Assertion; + + value(text: string): Assertion; + + } + +} + +declare module "chai-dom" { + + function chaiDom(chai: any, utils: any): void; + + namespace chaiDom { + } + + export = chaiDom; +} diff --git a/chai-enzyme/chai-enzyme-tests.tsx b/chai-enzyme/chai-enzyme-tests.tsx new file mode 100644 index 0000000000..f85320cee0 --- /dev/null +++ b/chai-enzyme/chai-enzyme-tests.tsx @@ -0,0 +1,45 @@ +/// +/// +/// +/// + +import * as React from "react"; +import * as chaiEnzyme from "chai-enzyme"; +import { expect } from "chai"; +import { shallow } from "enzyme"; + +const Test = () =>
; + +class Test2 extends React.Component<{}, {}> { + render() { + return
; + } +} + +chai.use(chaiEnzyme()); + +const wrapper = shallow(); + +expect(wrapper).to.be.checked(); +expect(wrapper).to.have.className("test"); +expect(wrapper).to.have.descendants({ a: "b" }); +expect(wrapper).to.have.descendants(Test); +expect(wrapper).to.have.exactly(1).descendants(Test2); +expect(wrapper).to.have.descendants("div"); +expect(wrapper).to.be.disabled(); +expect(wrapper).to.be.blank(); +expect(wrapper).to.be.present(); +expect(wrapper).to.have.html("
"); +expect(wrapper).to.have.id("test"); +expect(wrapper).to.have.ref("test"); +expect(wrapper).to.be.selected(); +expect(wrapper).to.have.tagName("div"); +expect(wrapper).to.have.text(""); +expect(wrapper).to.have.value("test"); +expect(wrapper).to.have.attr("test", "test"); +expect(wrapper).to.have.data("test", "Test"); +expect(wrapper).to.have.style("background", "green"); +expect(wrapper).to.have.state("test", "test"); +expect(wrapper).to.have.prop("test", 5); +expect(wrapper).to.contain(); +expect(wrapper).to.match(); diff --git a/chai-enzyme/chai-enzyme.d.ts b/chai-enzyme/chai-enzyme.d.ts new file mode 100644 index 0000000000..21e463dac5 --- /dev/null +++ b/chai-enzyme/chai-enzyme.d.ts @@ -0,0 +1,153 @@ +// Type definitions for chai-enzyme 0.5.0 +// Project: https://github.com/producthunt/chai-enzyme +// Definitions by: Alexey Svetliakov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// +/// +/// + +declare namespace Chai { + type EnzymeSelector = string | __React.StatelessComponent | __React.ComponentClass | { [key: string]: any }; + + interface Match { + /** + * Assert that the wrapper matches given selector: + * @param selector + */ + (selector: EnzymeSelector): Assertion; + } + interface Include { + /** + * Assert that the wrapper contains a given node: + * @param code + */ + (selector: EnzymeSelector): Assertion; + } + interface Assertion { + /** + * Assert that the given wrapper is checked: + */ + checked(): Assertion; + + /** + * Assert that the wrapper has a given class: + * @param name + */ + className(name: string): Assertion; + + /** + * Assert that the wrapper contains a descendant matching the given selector: + * @param selector + */ + descendants(selector?: EnzymeSelector): Assertion; + + /** + * Assert that the wrapper contains an exact amount of descendants matching the given selector: + */ + exactly(count?: number): Assertion; + + /** + * Assert that the given wrapper is disabled: + */ + disabled(): Assertion; + + /** + * Assert that the given wrapper is empty: + */ + blank(): Assertion; + + /** + * Assert that the given wrapper exists: + */ + present(): Assertion; + + /** + * Assert that the wrapper has given html: + * @param str + */ + html(str?: string): Assertion; + + /** + * Assert that the wrapper has given ID attribute: + * @param str + */ + id(str: string): Assertion; + + /** + * Assert that the wrapper has a given ref + * @param key + */ + ref(key: string): Assertion; + + /** + * Assert that the given wrapper is selected: + */ + selected(): Assertion; + + /** + * Assert that the given wrapper has the tag name: + * @param str + */ + tagName(str: string): Assertion; + + /** + * Assert that the given wrapper has the supplied text: + * @param str + */ + text(str?: string): Assertion; + + /** + * Assert that the given wrapper has given value: + * @param str + */ + value(str: string): Assertion; + + /** + * Assert that the wrapper has given attribute [with value]: + * @param key + * @param val + */ + attr(key: string, val?: string): Assertion; + + /** + * Assert that the wrapper has a given data attribute [with value]: + * @param key + * @param val + */ + data(key: string, val?: string): Assertion; + + /** + * Assert that the wrapper has given style: + * @param key + * @param val + */ + style(key: string, val?: string): Assertion; + + /** + * Assert that the wrapper has given state [with value]: + * @param key + * @param val + */ + state(key: string, val?: any): Assertion; + + /** + * Assert that the wrapper has given prop [with value]: + * @param key + * @param val + */ + prop(key: string, val?: any): Assertion; + } +} + +declare module "chai-enzyme" { + import { ShallowWrapper, ReactWrapper, CheerioWrapper } from "enzyme"; + + type DebugWrapper = ShallowWrapper | CheerioWrapper | ReactWrapper; + function chaiEnzyMe(wrapper?: (debugWrapper: DebugWrapper) => string): (chai: any) => void; + + module chaiEnzyMe { + } + export = chaiEnzyMe; +} diff --git a/chai-jquery/index.d.ts b/chai-jquery/index.d.ts index 79774640f6..540928091c 100644 --- a/chai-jquery/index.d.ts +++ b/chai-jquery/index.d.ts @@ -17,7 +17,7 @@ declare namespace Chai { html(html: string): Assertion; text(text: string): Assertion; value(text: string): Assertion; - (selector: string): Assertion; + descendants(selector: string): Assertion; visible: Assertion; hidden: Assertion; selected: Assertion; diff --git a/chart.js/chart.js.d.ts b/chart.js/chart.js.d.ts new file mode 100644 index 0000000000..2d77f4c502 --- /dev/null +++ b/chart.js/chart.js.d.ts @@ -0,0 +1,381 @@ +// Type definitions for Chart.js +// Project: https://github.com/nnnick/Chart.js +// Definitions by: Alberto Nuti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare enum ChartType { + line, bar, radar, doughnut, polarArea, bubble +} +declare enum TimeUnit { + millisecond, second, minute, + hour, day, week, + month, quarter, year +} +interface ChartLegendItem { + text?: string; + fillStyle?: string; + hidden?: boolean; + lineCap?: string; + lineDash?: number[]; + lineDashOffset?: number; + lineJoin?: string; + lineWidth?: number; + strokeStyle?: string; +} +interface ChartTooltipItem { + xLabel?: string; + yLabel?: string; + datasetIndex?: number; + index?: number; +} +interface ChartTooltipCallback { + beforeTitle?: (item?: ChartTooltipItem[], data?: any) => void; + title?: (item?: ChartTooltipItem[], data?: any) => void; + afterTitle?: (item?: ChartTooltipItem[], data?: any) => void; + beforeBody?: (item?: ChartTooltipItem[], data?: any) => void; + beforeLabel?: (tooltipItem?: ChartTooltipItem, data?: any) => void; + label?: (tooltipItem?: ChartTooltipItem, data?: any) => void; + afterLabel?: (tooltipItem?: ChartTooltipItem, data?: any) => void; + afterBody?: (item?: ChartTooltipItem[], data?: any) => void; + beforeFooter?: (item?: ChartTooltipItem[], data?: any) => void; + footer?: (item?: ChartTooltipItem[], data?: any) => void; + afterfooter?: (item?: ChartTooltipItem[], data?: any) => void; +} +interface ChartAnimationParameter { + chartInstance?: any; + animationObject?: any; +} +interface ChartPoint { + x?: number; + y?: number; +} + +interface ChartConfiguration { + type?: string; + data?: ChartData; + options?: ChartOptions; +} + +interface ChartData { + +} + +interface LinearChartData extends ChartData { + labels?: string[]; + datasets?: ChartDataSets[]; +} + +interface ChartOptions { + responsive?: boolean; + responsiveAnimationDuration?: number; + maintainAspectRatio?: boolean; + events?: string[]; + onClick?: (any?: any) => any; + title?: ChartTitleOptions; + legend?: ChartLegendOptions; + tooltip?: ChartTooltipOptions; + hover?: ChartHoverOptions; + animation?: ChartAnimationOptions; + elements?: ChartElementsOptions; + scales?: ChartScales; +} + +interface ChartFontOptions { + defaultFontColor?: string; + defaultFontFamily?: string; + defaultFontSize?: number; + defaultFontStyle?: string; +} + +interface ChartTitleOptions { + display?: boolean; + position?: string; + fullWdith?: boolean; + fontSize?: number; + fontFamily?: string; + fontColor?: string; + fontStyle?: string; + padding?: number; + text?: string; +} + +interface ChartLegendOptions { + display?: boolean; + position?: string; + fullWidth?: boolean; + onClick?: (event: any, legendItem: any) => void; + labels?: ChartLegendLabelOptions; +} + +interface ChartLegendLabelOptions { + boxWidth?: number; + fontSize?: number; + fontStyle?: number; + fontColor?: string; + fontFamily?: string; + padding?: number; + generateLabels?: (chart: any) => any; +} + +interface ChartTooltipOptions { + enabled?: boolean; + custom?: (a: any) => void; + mode?: string; + backgroundColor?: string; + titleFontFamily?: string; + titleFontSize?: number; + titleFontStyle?: string; + titleFontColor?: string; + titleSpacing?: number; + titleMarginBottom?: number; + bodyFontFamily?: string; + bodyFontSize?: number; + bodyFontStyle?: string; + bodyFontColor?: string; + bodySpacing?: number; + footerFontFamily?: string; + footerFontSize?: number; + footerFontStyle?: string; + footerFontColor?: string; + footerSpacing?: number; + footerMarginTop?: number; + xPadding?: number; + yPadding?: number; + caretSize?: number; + cornerRadius?: number; + multiKeyBackground?: string; + callbacks?: ChartTooltipCallback; +} + +interface ChartHoverOptions { + mode?: string; + animationDuration?: number; + onHover?: (active: any) => void; +} + +interface ChartAnimationObject { + currentStep?: number; + numSteps?: number; + easing?: string; + render?: (arg: any) => void; + onAnimationProgress?: (arg: any) => void; + onAnimationComplete?: (arg: any) => void; +} + +interface ChartAnimationOptions { + duration?: number; + easing?: string; + onProgress?: (chart: any) => void; + onComplete?: (chart: any) => void; +} + +interface ChartElementsOptions { + point?: ChartPointOptions; + line?: ChartLineOptions; + arg?: ChartArcOtpions; + rectangle?: ChartRectangleOptions; +} + +interface ChartArcOtpions { + backgroundColor?: string; + borderColor?: string; + borderWidth?: number; +} + +interface ChartLineOptions { + tension?: number; + backgroundColor?: string; + borderWidth?: number; + borderColor?: string; + borderCapStyle?: string; + borderDash?: any[]; + borderDashOffset?: number; + borderJoinStyle?: string; +} + +interface ChartPointOptions { + radius?: number; + pointStyle?: string; + backgroundColor?: string; + borderWidth?: number; + borderColor?: string; + hitRadius?: number; + hoverRadius?: number; + hoverBorderWidth?: number; +} + +interface ChartRectangleOptions { + backgroundColor?: string; + borderWidth?: number; + borderColor?: string; + borderSkipped?: string; +} +interface GridLineOptions { + display?: boolean; + color?: string; + lineWidth?: number; + drawBorder?: boolean; + drawOnChartArea?: boolean; + drawticks?: boolean; + tickMarkLength?: number; + zeroLineWidth?: number; + zeroLineColor?: string; + offsetGridLines?: boolean; +} + +interface ScaleTitleOptions { + display?: boolean; + labelString?: string; + fontColor?: string; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; +} + +interface TickOptions { + autoSkip?: boolean; + callback?: (value: any, index: any, values: any) => string; + display?: boolean; + fontColor?: string; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; + labelOffset?: number; + maxRotation?: number; + minRotation?: number; + mirror?: boolean; + padding?: number; + reverse?: boolean; + min?: any; + max?: any; +} +interface AngleLineOptions { + display?: boolean; + color?: string; + lineWidth?: number; +} + +interface PointLabelOptions { + callback?: (arg: any) => any; + fontColor?: string; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; +} + +interface TickOptions { + backdropColor?: string; + backdropPaddingX?: number; + backdropPaddingY?: number; + maxTicksLimit?: number; + showLabelBackdrop?: boolean; +} +interface LinearTickOptions extends TickOptions { + beginAtZero?: boolean; + min?: number; + max?: number; + maxTicksLimit?: number; + stepSize?: number; + suggestedMin?: number; + suggestedMax?: number; +} + +interface LogarithmicTickOptions extends TickOptions { + min?: number; + max?: number; +} + +interface ChartDataSets { + backgroundColor?: string[]; + borderWidth?: number; + borderColor?: string[]; + borderCapStyle?: string; + borderDash?: number[]; + borderDashOffset?: number; + borderJoinStyle?: string; + data?: number[] | ChartPoint[]; + fill?: boolean; + label?: string; + lineTension?: number; + pointBorderColor?: string | string[]; + pointBackgroundColor?: string | string[]; + pointBorderWidth?: number | number[]; + pointRadius?: number | number[]; + pointHoverRadius?: number | number[]; + pointHitRadius?: number | number[]; + pointHoverBackgroundColor?: string | string[]; + pointHoverBorderColor?: string | string[]; + pointHoverBorderWidth?: number | number[]; + pointStyle?: string | string[] | HTMLImageElement | HTMLImageElement[]; + xAxisID?: string; + yAxisID?: string; +} + +interface ChartScales { + type?: string; + display?: boolean; + position?: string; + beforeUpdate?: (scale?: any) => void; + beforeSetDimension?: (scale?: any) => void; + beforeDataLimits?: (scale?: any) => void; + beforeBuildTicks?: (scale?: any) => void; + beforeTickToLabelConversion?: (scale?: any) => void; + beforeCalculateTickRotation?: (scale?: any) => void; + beforeFit?: (scale?: any) => void; + afterUpdate?: (scale?: any) => void; + afterSetDimension?: (scale?: any) => void; + afterDataLimits?: (scale?: any) => void; + afterBuildTicks?: (scale?: any) => void; + afterTickToLabelConversion?: (scale?: any) => void; + afterCalculateTickRotation?: (scale?: any) => void; + afterFit?: (scale?: any) => void; + gridLines?: GridLineOptions; + scaleLabel?: ScaleTitleOptions; + ticks?: TickOptions; +} + +interface LinearScale extends ChartScales { + ticks?: LinearTickOptions; +} + +interface LogarithmicScale extends ChartScales { + ticks?: LogarithmicTickOptions; +} + +interface TimeScale extends ChartScales { + displayFormats?: string; + isoWeekday?: boolean; + max?: string; + min?: string; + parser?: string | ((arg: any) => any); + round?: string; + tooltipFormat?: string; + unit?: TimeUnit; + unitStepSize?: number; +} + +interface RadialLinearScale { + lineArc?: boolean; + angleLines?: AngleLineOptions; + pointLabels?: PointLabelOptions; + ticks?: TickOptions; +} + +declare var Chart: { + new (context: CanvasRenderingContext2D, options: ChartConfiguration): {}; + destroy: () => {}; + update: (duration: any, lazy: any) => {}; + render: (duration: any, lazy: any) => {}; + stop: () => {}; + resize: () => {}; + clear: () => {}; + toBase64: () => string; + generateLegend: () => {}; + getElementAtEvent: (e: any) => {}; + getElementsAtEvent: (e: any) => {}[]; + getDatasetAtEvent: (e: any) => {}[]; + + defaults: { + global: ChartOptions; + } +}; diff --git a/chosen/chosen-tests.ts b/chosen/chosen-tests.ts index e5a97b0b59..575b7503ea 100644 --- a/chosen/chosen-tests.ts +++ b/chosen/chosen-tests.ts @@ -1,8 +1,26 @@ -$(".chzn-select").chosen({ no_results_text: "No results matched" }); -$("#form_field").chosen().change(); -$("#form_field").trigger("liszt:updated"); +// Options +$(".my_select_box").chosen(); -$(".chzn-select").chosen(); -$(".chzn-select-deselect").chosen({ allow_single_deselect: true }); \ No newline at end of file +$(".my_select_box").chosen({}); + +$(".my_select_box").chosen({ + disable_search_threshold: 10, + max_selected_options: 5, + no_results_text: "Oops, nothing found!", + width: "95%" +}); + +// Destroy +$(".my_select_box").chosen("destroy"); + +// Triggered Events +$(".my_select_box").on("change", function(evt, params) { + evt.preventDefault(); + let s = params.selected; + console.log(s); +}); + +// Triggerable Events +$(".my_select_box").trigger("chosen:updated"); diff --git a/chosen/index.d.ts b/chosen/index.d.ts index 836e64e19d..4f413a39de 100644 --- a/chosen/index.d.ts +++ b/chosen/index.d.ts @@ -1,30 +1,98 @@ -// Type definitions for Chosen.JQuery 1.4.2 +// Type definitions for Chosen.JQuery 1.6.1 // Project: http://harvesthq.github.com/chosen/ -// Definitions by: Boris Yankov +// Definitions by: Boris Yankov , denis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - /// -interface ChosenOptions { - allow_single_deselect?: boolean; - disable_search?: boolean; - disable_search_threshold?: number; - enable_split_word_search?: boolean; - inherit_select_classes?: boolean; - max_selected_options?: number; - no_results_text?: string; - placeholder_text_multiple?: string; - placeholder_text_single?: string; - search_contains?: boolean; - single_backstroke_delete?: boolean; - width?: number|string; - display_disabled_options?: boolean; - display_selected_options?: boolean; - include_group_label_in_selected?: boolean; +declare namespace Chosen { + type OnEvent = "chosen:ready" | "chosen:maxselected" | "chosen:showing_dropdown" | "chosen:hiding_dropdown" | "chosen:no_results"; + type TriggerEvent = "chosen:updated" | "chosen:activate" | "chosen:open" | "chosen:close"; + + interface Options { + /**When set to true on a single select, Chosen adds a UI element which selects the first element (if it is blank). + * @default: false + */ + allow_single_deselect?: boolean; + /**By default Chosen's search is case-insensitive. Setting this option to true makes the search case-sensitive. + * @default: false + */ + case_sensitive_search?: boolean; + /**When set to true, Chosen will not display the search field (single selects only). + * @default: false + */ + disable_search?: boolean; + /**Hide the search input on single selects if there are n or fewer options. + * @default: 0 + */ + disable_search_threshold?: number; + /**By default, searching will match on any word within an option tag. Set this option to false if you want to only match on the entire text of an option tag. + * @default: true + */ + enable_split_word_search?: boolean; + /**When set to true, Chosen will grab any classes on the original select field and add them to Chosen’s container div. + * @default: false + */ + inherit_select_classes?: boolean; + /**Limits how many options the user can select. When the limit is reached, the chosen:maxselected event is triggered. + * @default: Infinity + */ + max_selected_options?: number; + /**The text to be displayed when no matching results are found. The current search is shown at the end of the text (e.g., No results match "Bad Search"). + * @default: "No results match" + */ + no_results_text?: string; + /**The text to be displayed as a placeholder when no options are selected for a multiple select. + * @default: "Select Some Options" + */ + placeholder_text_multiple?: string; + /**The text to be displayed as a placeholder when no options are selected for a single select. + * @default: "Select an Option" + */ + placeholder_text_single?: string; + /**By default, Chosen’s search matches starting at the beginning of a word. Setting this option to true allows matches starting from anywhere within a word. This is especially useful for options that include a lot of special characters or phrases in ()s and []s. + * @default: false + */ + search_contains?: boolean; + /**By default, pressing delete/backspace on multiple selects will remove a selected choice. When false, pressing delete/backspace will highlight the last choice, and a second press deselects it. + * @default: true + */ + single_backstroke_delete?: boolean; + /**The width of the Chosen select box. By default, Chosen attempts to match the width of the select box you are replacing. If your select is hidden when Chosen is instantiated, you must specify a width or the select will show up with a width of 0. */ + width?: string; + /**By default, Chosen includes disabled options in search results with a special styling. Setting this option to false will hide disabled results and exclude them from searches. + * @default: true + */ + display_disabled_options?: boolean; + /**By default, Chosen includes selected options in search results with a special styling. Setting this option to false will hide selected results and exclude them from searches. + * Note: this is for multiple selects only. In single selects, the selected result will always be displayed. + * @default: true + */ + display_selected_options?: boolean; + /**By default, Chosen only shows the text of a selected option. Setting this option to true will show the text and group (if any) of the selected option. + * @default: false + */ + include_group_label_in_selected?: boolean; + /**Only show the first (n) matching options in the results. This can be used to increase performance for selects with very many options. + * @default: Infinity + */ + max_shown_results?: number; + } + + interface SelectedData { + selected: string; + deselected: string; + } } interface JQuery { chosen(): JQuery; - chosen(options: ChosenOptions): JQuery; + chosen(options: Chosen.Options | "destroy"): JQuery; + + /**Chosen triggers the standard DOM event whenever a selection is made (it also sends a selected or deselected parameter that tells you which option was changed). */ + on(events: "change", handler: (eventObject: JQueryEventObject, args: Chosen.SelectedData) => any): JQuery; + + on(events: Chosen.OnEvent, handler: (eventObject: JQueryEventObject) => any): JQuery; + + trigger(eventType: Chosen.TriggerEvent): JQuery; } diff --git a/chroma-js/chroma-js-0.5.6-tests.ts b/chroma-js/chroma-js-0.5.6-tests.ts new file mode 100644 index 0000000000..cb8b593d26 --- /dev/null +++ b/chroma-js/chroma-js-0.5.6-tests.ts @@ -0,0 +1,120 @@ +/// + +function test_chroma() { + chroma("red"); + chroma("#ff0000"); + chroma("#f00"); + chroma("FF0000"); + chroma(255, 0, 0); + chroma([255, 0, 0]); + chroma(0, 1, 0.5, 'hsl'); + chroma([0, 1, 0.5], 'hsl'); + chroma(0, 1, 1, 'hsv'); + chroma("rgb(255,0,0)"); + chroma("rgb(100%,0%,0%)"); + chroma("hsl(0,100%,50%)"); + chroma(53.24, 80.09, 67.20, 'lab'); + chroma(53.24, 104.55, 40, 'lch'); + chroma(1, 0, 0, 'gl'); + + chroma.hex("#ff0000"); + chroma.hex("red"); + chroma.hex("rgb(255, 0, 0)"); + + chroma.rgb(255, 0, 0); + chroma.hsl(0, 1, 0.5); + chroma.hsv(120, 0.5, 0.5); + chroma.lab(53.24, 80.09, 67.20); + chroma.lch(53.24, 104.55, 40); + chroma.gl(1, 0, 0); + + chroma.interpolate('white', 'black', 0) // #ffffff + chroma.interpolate('white', 'black', 1) // #000000 + chroma.interpolate('white', 'black', 0.5) // #7f7f7f + chroma.interpolate('white', 'black', 0.5, 'hsv') // #808080 + chroma.interpolate('white', 'black', 0.5, 'lab') // #777777 + + chroma.interpolate('rgba(0,0,0,0)', 'rgba(255,0,0,1)', 0.5).css() //"rgba(127.5,0,0,0.5)" + + var bezInterpolator = chroma.interpolate.bezier(['white', 'yellow', 'red', 'black']); + bezInterpolator(0).hex() // #ffffff + bezInterpolator(0.33).hex() // #ffcc67 + bezInterpolator(0.66).hex() // #b65f1a + bezInterpolator(1).hex() // #000000 + + chroma.luminance('black') // 0 + chroma.luminance('white') // 1 + chroma.luminance('#ff0000') // 0.2126 + + chroma.contrast('white', 'navy') // 16.00 – ok + chroma.contrast('white', 'yellow') // 1.07 – not ok! +} + +function test_color() { + chroma('red').hex() // "#FF0000"" + chroma('red').rgb() // [255, 0, 0] + chroma('red').hsv() // [0, 1, 1] + chroma('red').hsl() // [0, 1, 0.5] + chroma('red').lab() // [53.2407, 80.0924, 67.2031] + chroma('red').lch() // [53.2407, 104.5517, 39.9990] + chroma('red').rgba() // [255, 0, 0, 1] + chroma('red').css() // "rgb(255,0,0)" + chroma('red').alpha(0.7).css() // "rgba(255,0,0,0.7)" + chroma('red').css('hsl') // "hsl(0,100%,50%)" + chroma('red').alpha(0.7).css('hsl') // "hsla(0,100%,50%,0.7)" + chroma('blue').css('hsla') // "hsla(240,100%,50%,1)" + + var red = chroma('red'); + red.alpha(0.5); + red.css(); // rgba(255,0,0,0.5); + + chroma('red').darken().hex() // #BC0000 + chroma('red').brighten().hex() // #FF603B + chroma('#eecc99').saturate().hex() // #fcc973 + chroma('red').desaturate().hex() // #ec3d23 + + chroma('black').luminance() // 0 + chroma('white').luminance() // 1 + chroma('red').luminance() // 0.2126 +} + +function test_scale() { + var scale = chroma.scale(['lightyellow', 'navy']); + scale(0.5); // #7F7FB0 + + chroma.scale('RdYlBu'); + + var col = scale(0.5); + col.hex(); // #7F7FB0 + col.rgb(); // [127.5, 127.5, 176] + + scale = chroma.scale(['lightyellow', 'navy']).out('hex'); + scale(0.5); // "#7F7FB0" + + var scale = chroma.scale(['lightyellow', 'navy']); + scale.mode('hsv')(0.5); // #54C08A + scale.mode('hsl')(0.5); // #31FF98 + scale.mode('lab')(0.5); // #967CB2 + scale.mode('lch')(0.5); // #D26662 + + var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 400]); + scale(200); // #7F7FB0 + + var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 100, 200, 300, 400]); + scale(98); // #7F7FB0 + scale(99); // #7F7FB0 + scale(100); // #AAAAC0 + scale(101); // #AAAAC0 + + chroma.scale(['#eee', '#900']).domain([0, 400], 7); + chroma.scale(['#eee', '#900']).domain([1, 1000000], 7, 'log'); + chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'quantiles'); + chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'k-means'); + chroma.scale(['white', 'red']).domain([0, 100], 4).domain() // [0, 25, 50, 75, 100] + + chroma.scale().range(['lightyellow', 'navy']); + + chroma.scale(['lightyellow', 'navy']).correctLightness(true); + + chroma.scale('RdYlGn').domain([0,1], 5).colors() +} diff --git a/chroma-js/chroma-js-0.5.6.d.ts b/chroma-js/chroma-js-0.5.6.d.ts new file mode 100644 index 0000000000..5d785eda27 --- /dev/null +++ b/chroma-js/chroma-js-0.5.6.d.ts @@ -0,0 +1,317 @@ +// Type definitions for Chroma.js v0.5.6 +// Project: https://github.com/gka/chroma.js +// Definitions by: Sebastian Brückner +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Chroma.js is a tiny library for all kinds of color conversions and color scales. + */ +declare namespace Chroma { + + export interface ChromaStatic { + /** + * Creates a color from a string representation (as supported in CSS). + * + * @param color The string to convert to a color. + * @return the color object. + */ + (color: string): Color; + + /** + * Create a color in the specified color space using a, b and c as values. + * + * @param a + * @param b + * @param c + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ + (a: number, b: number, c: number, colorSpace?: string): Color; + + /** + * Create a color in the specified color space using values. + * + * @param values An array of values (e.g. [r, g, b, a?]). + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ + (values: number[], colorSpace?: string): Color; + + /** + * Create a color in the specified color space using a, b and c as values. + * + * @param a + * @param b + * @param c + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ + color(a: number, b: number, c: number, colorSpace?: string): Color; + + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: Color, color2: Color): number; + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: Color, color2: string): number; + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: string, color2: Color): number; + /** + * Calculate the contrast ratio of two colors. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(color1: string, color2: string): number; + + /** + * Create a color from a hex or string representation (as supported in CSS). + * + * This is an alias of chroma.hex(). + * + * @param color The string to convert to a color. + * @return the color object. + */ + css(color: string): Color; + + /** + * Create a color from a hex or string representation (as supported in CSS). + * + * This is an alias of chroma.css(). + * + * @param color The string to convert to a color. + * @return the color object. + */ + hex(color: string): Color; + + rgb(red: number, green: number, blue: number, alpha?: number): Color; + hsl(hue: number, saturation: number, lightness: number, alpha?: number): Color; + hsv(hue: number, saturation: number, value: number, alpha?: number): Color; + lab(lightness: number, a: number, b: number, alpha?: number): Color; + lch(lightness: number, chroma: number, hue: number, alpha?: number): Color; + gl(red: number, green: number, blue: number, alpha?: number): Color; + + interpolate: InterpolateFunction; + mix: InterpolateFunction; + + luminance(color: Color): number; + luminance(color: string): number; + + /** + * Creates a color scale using a pre-defined color scale. + * + * @param name The name of the color scale. + * @return the resulting color scale. + */ + scale(name: string): Scale; + + /** + * Creates a color scale function from the given set of colors. + * + * @param colors An Array of at least two color names or hex values. + * @return the resulting color scale. + */ + scale(colors?: string[]): Scale; + + scales: PredefinedScales; + } + + interface InterpolateFunction { + (color1: Color, color2: Color, f: number, mode?: string): Color; + (color1: Color, color2: string, f: number, mode?: string): Color; + (color1: string, color2: Color, f: number, mode?: string): Color; + (color1: string, color2: string, f: number, mode?: string): Color; + + bezier(colors: any[]): (t: number) => Color; + } + + interface PredefinedScales { + [key: string]: Scale; + + cool: Scale; + hot: Scale; + } + + export interface Color { + /** + * Creates a color from a string representation (as supported in CSS). + * + * @param color The string to convert to a color. + */ + new(color: string): Color; + + /** + * Create a color in the specified color space using a, b and c as values. + * + * @param a + * @param b + * @param c + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + */ + new(a: number, b: number, c: number, colorSpace?: string): Color; + + /** + * Create a color in the specified color space using a, b and c as color values and alpha as the alpha value. + * + * @param a + * @param b + * @param c + * @param alpha The alpha value of the color. + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + */ + new(a: number, b: number, c: number, alpha: number, colorSpace?: string): Color; + + /** + * Create a color in the specified color space using values. + * + * @param values An array of values (e.g. [r, g, b, a?]). + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + */ + new(values: number[], colorSpace: string): Color; + + /** + * Convert this color to CSS hex representation. + * + * @return this color's hex representation. + */ + hex(): string; + + /** + * @return the relative luminance of the color, which is a value between 0 (black) and 1 (white). + */ + luminance(): number; + + /** + * @return the X11 name of this color or its hex value if it does not have a name. + */ + name(): string; + + /** + * @return the alpha value of the color. + */ + alpha(): number; + + /** + * Set the alpha value. + * + * @param alpha The alpha value. + * @return this + */ + alpha(alpha: number): Color; + + css(mode?: string): string; + + interpolate(color: Color, f: number, mode?: string): Color; + interpolate(color: string, f: number, mode?: string): Color; + + premultiply(): Color; + + rgb(): number[]; + rgba(): number[]; + hsl(): number[]; + hsv(): number[]; + lab(): number[]; + lch(): number[]; + hsi(): number[]; + gl(): number[]; + + darken(amount?: number): Color; + darker(amount: number): Color; + brighten(amount?: number): Color; + brighter(amount: number): Color; + saturate(amount?: number): Color; + desaturate(amount?: number): Color; + + toString(): string; + } + + export interface Scale { + /** + * Interpolate a color using the currently set range and domain. + * + * @param value The value to use for interpolation. + * @return the interpolated hex color OR a Color object (depending on the mode set on this Scale). + */ + (value: number): any; + + /** + * Retreive all possible colors generated by this scale if it has distinct classes. + * + * @param mode The output mode to use. Must be one of Color's getters. Defaults to "hex". + * @return an array of colors in the type specified by mode. + */ + colors(mode?: string): any[]; + + correctLightness(): boolean; + + /** + * Enable or disable automatic lightness correction of this scale. + * + * @param Whether to enable or disable automatic lightness correction. + * @return this + */ + correctLightness(enable: boolean): Scale; + + /** + * Get the current domain. + * + * @return The current domain. + */ + domain(): number[]; + + /** + * Set the domain. + * + * @param domain An Array of at least two numbers (min and max). + * @param classes The number of fixed classes to create between min and max. + * @param mode The scale to use. Examples: log, quantiles, k-means. + * @return this + */ + domain(domain: number[], classes?: number, mode?: string): Scale; + + /** + * Specify in which color space the colors should be interpolated. Defaults to "rgb". + * You can use any of the following spaces: rgb, hsv, hsl, lab, lch + * + * @param colorSpace The color space to use for interpolation. + * @return this + */ + mode(colorSpace: string): Scale; + + /** + * Set the output mode of this Scale. + * + * @param mode The output mode to use. Must be one of Color's getters. + * @return this + */ + out(mode: string): Scale; + + /** + * Set the color range after initialization. + * + * @param colors An Array of at least two color names or hex values. + * @return this + */ + range(colors: string[]): Scale; + } + +} + +declare var chroma: Chroma.ChromaStatic; diff --git a/chroma-js/chroma-js-tests.ts b/chroma-js/chroma-js-tests.ts index 4bb67004fb..82dea52002 100644 --- a/chroma-js/chroma-js-tests.ts +++ b/chroma-js/chroma-js-tests.ts @@ -1,120 +1,166 @@ function test_chroma() { - chroma("red"); - chroma("#ff0000"); - chroma("#f00"); - chroma("FF0000"); - chroma(255, 0, 0); - chroma([255, 0, 0]); - chroma(0, 1, 0.5, 'hsl'); - chroma([0, 1, 0.5], 'hsl'); - chroma(0, 1, 1, 'hsv'); - chroma("rgb(255,0,0)"); - chroma("rgb(100%,0%,0%)"); - chroma("hsl(0,100%,50%)"); - chroma(53.24, 80.09, 67.20, 'lab'); - chroma(53.24, 104.55, 40, 'lch'); - chroma(1, 0, 0, 'gl'); - - chroma.hex("#ff0000"); - chroma.hex("red"); - chroma.hex("rgb(255, 0, 0)"); - - chroma.rgb(255, 0, 0); - chroma.hsl(0, 1, 0.5); - chroma.hsv(120, 0.5, 0.5); - chroma.lab(53.24, 80.09, 67.20); - chroma.lch(53.24, 104.55, 40); - chroma.gl(1, 0, 0); - - chroma.interpolate('white', 'black', 0) // #ffffff - chroma.interpolate('white', 'black', 1) // #000000 - chroma.interpolate('white', 'black', 0.5) // #7f7f7f - chroma.interpolate('white', 'black', 0.5, 'hsv') // #808080 - chroma.interpolate('white', 'black', 0.5, 'lab') // #777777 - - chroma.interpolate('rgba(0,0,0,0)', 'rgba(255,0,0,1)', 0.5).css() //"rgba(127.5,0,0,0.5)" - - var bezInterpolator = chroma.interpolate.bezier(['white', 'yellow', 'red', 'black']); - bezInterpolator(0).hex() // #ffffff - bezInterpolator(0.33).hex() // #ffcc67 - bezInterpolator(0.66).hex() // #b65f1a - bezInterpolator(1).hex() // #000000 - - chroma.luminance('black') // 0 - chroma.luminance('white') // 1 - chroma.luminance('#ff0000') // 0.2126 - - chroma.contrast('white', 'navy') // 16.00 – ok - chroma.contrast('white', 'yellow') // 1.07 – not ok! + chroma('hotpink'); + chroma('#ff3399'); + chroma('F39'); + chroma.hex("#fff"); + + chroma(0xff3399); + chroma(0xff, 0x33, 0x99); + chroma(255, 51, 153); + chroma([255, 51, 153]); + chroma(330, 1, 0.6, 'hsl'); + chroma.hsl(330, 1, 0.6); + chroma.lch(80, 40, 130); + chroma(80, 40, 130, 'lch'); + chroma.cmyk(0.2, 0.8, 0, 0); + chroma(0.2, 0.8, 0, 0, 'cmyk'); + chroma.gl(0.6, 0, 0.8); + chroma.gl(0.6, 0, 0.8, 0.5); + chroma(0.6, 0, 0.8, 'gl'); + chroma.temperature(2000); + chroma.temperature(3500); + chroma.temperature(6000); + chroma.mix('red', 'blue'); + chroma.mix('red', 'blue', 0.25); + chroma.mix('red', 'blue', 0.5, 'rgb'); + chroma.mix('red', 'blue', 0.5, 'hsl'); + chroma.mix('red', 'blue', 0.5, 'lab'); + chroma.mix('red', 'blue', 0.5, 'lch'); + chroma.blend('4CBBFC', 'EEEE22', 'multiply'); + chroma.blend('4CBBFC', 'EEEE22', 'darken'); + chroma.blend('4CBBFC', 'EEEE22', 'lighten'); + chroma.random(); + chroma.contrast('pink', 'hotpink'); + chroma.contrast('pink', 'purple'); + chroma.brewer.OrRd; + var data = [3.0, 3.5, 3.6, 3.8, 3.8, 4.1, 4.3, 4.4, + 4.6, 4.9, 5.2, 5.3, 5.4, 5.7, 5.8, 5.9, + 6.2, 6.5, 6.8, 7.2, 9]; + chroma.limits(data, 'e', 5); + chroma.limits(data, 'q', 5); + chroma.limits(data, 'k', 5); } function test_color() { - chroma('red').hex() // "#FF0000"" - chroma('red').rgb() // [255, 0, 0] - chroma('red').hsv() // [0, 1, 1] - chroma('red').hsl() // [0, 1, 0.5] - chroma('red').lab() // [53.2407, 80.0924, 67.2031] - chroma('red').lch() // [53.2407, 104.5517, 39.9990] - chroma('red').rgba() // [255, 0, 0, 1] - chroma('red').css() // "rgb(255,0,0)" - chroma('red').alpha(0.7).css() // "rgba(255,0,0,0.7)" - chroma('red').css('hsl') // "hsl(0,100%,50%)" - chroma('red').alpha(0.7).css('hsl') // "hsla(0,100%,50%,0.7)" - chroma('blue').css('hsla') // "hsla(240,100%,50%,1)" - - var red = chroma('red'); - red.alpha(0.5); - red.css(); // rgba(255,0,0,0.5); - - chroma('red').darken().hex() // #BC0000 - chroma('red').brighten().hex() // #FF603B - chroma('#eecc99').saturate().hex() // #fcc973 - chroma('red').desaturate().hex() // #ec3d23 - - chroma('black').luminance() // 0 - chroma('white').luminance() // 1 - chroma('red').luminance() // 0.2126 + chroma('red').alpha(0.5); + chroma('rgba(255,0,0,0.35)').alpha(); + chroma('hotpink').darken(); + chroma('hotpink').darken(2); + chroma('hotpink').brighten(); + chroma('slategray').saturate(); + chroma('slategray').saturate(2); + chroma('hotpink').desaturate(); + chroma('hotpink').desaturate(2); + chroma('hotpink').desaturate(3); + // change hue to 0 deg (=red) + chroma('skyblue').set('hsl.h', 0); + // set chromacity to 30 + chroma('hotpink').set('lch.c', 30); + // half Lab lightness + chroma('orangered').set('lab.l', '*0.5'); + // double Lch saturation + chroma('darkseagreen').set('lch.c', '*2'); + chroma('orangered').get('lab.l'); + chroma('orangered').get('hsl.l'); + chroma('orangered').get('rgb.g'); + chroma('white').luminance(); + chroma('aquamarine').luminance(); + chroma('hotpink').luminance(); + chroma('darkslateblue').luminance(); + chroma('black').luminance(); + chroma('white').luminance(0.5); + chroma('aquamarine').luminance(0.5); + chroma('hotpink').luminance(0.5); + chroma('darkslateblue').luminance(0.5); + chroma('aquamarine').luminance(0.5); + chroma('aquamarine').luminance(0.5, 'lab'); + chroma('aquamarine').luminance(0.5, 'hsl'); + chroma('orange').hex(); + chroma('#ffa500').name(); + chroma('#ffa505').name(); + chroma('teal').css(); + chroma('teal').alpha(0.5).css(); + chroma('teal').css('hsl'); + chroma('orange').rgb(); + chroma('orange').hsl(); + chroma('white').hsl(); + chroma('orange').hsv(); + chroma('white').hsv(); + chroma('orange').hsi(); + chroma('white').hsi(); + chroma('orange').lab(); + chroma('skyblue').lch(); + chroma('skyblue').hcl(); + chroma('#ff3300').temperature(); + chroma('#ff8a13').temperature(); + chroma('#ffe3cd').temperature(); + chroma('#cbdbff').temperature(); + chroma('#b3ccff').temperature(); + chroma('33cc00').gl(); } function test_scale() { - var scale = chroma.scale(['lightyellow', 'navy']); - scale(0.5); // #7F7FB0 + var f = chroma.scale(); + f(0.25); + f(0.5); + f(0.75); + chroma.scale(['yellow', '008ae5']); + chroma.scale(['yellow', 'red', 'black']); + // default domain is [0,1] + chroma.scale(['yellow', '008ae5']); + // set domain to [0,100] + chroma.scale(['yellow', '008ae5']).domain([0, 100]); + // default domain is [0,1] + chroma.scale(['yellow', 'lightgreen', '008ae5']) + .domain([0, 0.25, 1]); + chroma.scale(['yellow', '008ae5']); + chroma.scale(['yellow', 'navy']); + chroma.scale(['yellow', 'navy']).mode('lab'); + chroma.scale(['yellow', 'navy']).mode('lab'); + chroma.scale(['yellow', 'navy']).mode('hsl'); + chroma.scale(['yellow', 'navy']).mode('lch'); + chroma.scale('YlGnBu'); + chroma.scale('Spectral'); + chroma.scale('Spectral').domain([1, 0]); + chroma.brewer.OrRd; + chroma.scale(['yellow', '008ae5']).mode('lch'); + + chroma.scale(['yellow', '008ae5']) + .mode('lch') + .correctLightness(); + // linear interpolation + chroma.scale(['yellow', 'red', 'black']); + // bezier interpolation + chroma.bezier(['yellow', 'red', 'black']); + // convert bezier interpolator into chroma.scale + chroma.bezier(['yellow', 'red', 'black']) + .scale().colors(5); + // use the default helix... + chroma.cubehelix(); + // or customize it + chroma.cubehelix() + .start(200) + .rotations(-0.5) + .gamma(0.8) + .lightness([0.3, 0.8]); + + chroma.cubehelix() + .start(200) + .rotations(-0.35) + .gamma(0.7) + .lightness([0.3, 0.8]) + .scale() // convert to chroma.scale + .correctLightness() + .colors(5); chroma.scale('RdYlBu'); + chroma.scale('RdYlBu').padding(0.15); - var col = scale(0.5); - col.hex(); // #7F7FB0 - col.rgb(); // [127.5, 127.5, 176] + chroma.scale('OrRd'); + chroma.scale('OrRd').padding([0.2, 0]); - scale = chroma.scale(['lightyellow', 'navy']).out('hex'); - scale(0.5); // "#7F7FB0" - - var scale = chroma.scale(['lightyellow', 'navy']); - scale.mode('hsv')(0.5); // #54C08A - scale.mode('hsl')(0.5); // #31FF98 - scale.mode('lab')(0.5); // #967CB2 - scale.mode('lch')(0.5); // #D26662 - - var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 400]); - scale(200); // #7F7FB0 - - var scale = chroma.scale(['lightyellow', 'navy']).domain([0, 100, 200, 300, 400]); - scale(98); // #7F7FB0 - scale(99); // #7F7FB0 - scale(100); // #AAAAC0 - scale(101); // #AAAAC0 - - chroma.scale(['#eee', '#900']).domain([0, 400], 7); - chroma.scale(['#eee', '#900']).domain([1, 1000000], 7, 'log'); - chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'quantiles'); - chroma.scale(['#eee', '#900']).domain([1, 1000000], 5, 'k-means'); - chroma.scale(['white', 'red']).domain([0, 100], 4).domain() // [0, 25, 50, 75, 100] - - chroma.scale().range(['lightyellow', 'navy']); - - chroma.scale(['lightyellow', 'navy']).correctLightness(true); - - chroma.scale('RdYlGn').domain([0,1], 5).colors() + chroma.scale('OrRd').classes(5); + chroma.scale('OrRd').classes(8); } diff --git a/chroma-js/index.d.ts b/chroma-js/index.d.ts index 5d785eda27..654c4d8cef 100644 --- a/chroma-js/index.d.ts +++ b/chroma-js/index.d.ts @@ -1,14 +1,14 @@ -// Type definitions for Chroma.js v0.5.6 +// Type definitions for Chroma.js v1.1.1 // Project: https://github.com/gka/chroma.js -// Definitions by: Sebastian Brückner +// Definitions by: Sebastian Brückner , Marcin Pacholec // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** * Chroma.js is a tiny library for all kinds of color conversions and color scales. */ declare namespace Chroma { - export interface ChromaStatic { + /** * Creates a color from a string representation (as supported in CSS). * @@ -17,6 +17,14 @@ declare namespace Chroma { */ (color: string): Color; + /** + * Creates a color from a number representation [0; 16777215] + * + * @param color The number to convert to a color. + * @return the color object. + */ + (number: number): Color; + /** * Create a color in the specified color space using a, b and c as values. * @@ -25,72 +33,20 @@ declare namespace Chroma { * @param c * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". * @return the color object. - */ + */ (a: number, b: number, c: number, colorSpace?: string): Color; + (a: number, b: number, c: number, d: number, colorSpace?: string): Color; + /** - * Create a color in the specified color space using values. - * - * @param values An array of values (e.g. [r, g, b, a?]). - * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". - * @return the color object. - */ + * Create a color in the specified color space using values. + * + * @param values An array of values (e.g. [r, g, b, a?]). + * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". + * @return the color object. + */ (values: number[], colorSpace?: string): Color; - /** - * Create a color in the specified color space using a, b and c as values. - * - * @param a - * @param b - * @param c - * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". - * @return the color object. - */ - color(a: number, b: number, c: number, colorSpace?: string): Color; - - /** - * Calculate the contrast ratio of two colors. - * - * @param color1 The first color. - * @param color2 The second color. - * @return the contrast ratio. - */ - contrast(color1: Color, color2: Color): number; - /** - * Calculate the contrast ratio of two colors. - * - * @param color1 The first color. - * @param color2 The second color. - * @return the contrast ratio. - */ - contrast(color1: Color, color2: string): number; - /** - * Calculate the contrast ratio of two colors. - * - * @param color1 The first color. - * @param color2 The second color. - * @return the contrast ratio. - */ - contrast(color1: string, color2: Color): number; - /** - * Calculate the contrast ratio of two colors. - * - * @param color1 The first color. - * @param color2 The second color. - * @return the contrast ratio. - */ - contrast(color1: string, color2: string): number; - - /** - * Create a color from a hex or string representation (as supported in CSS). - * - * This is an alias of chroma.hex(). - * - * @param color The string to convert to a color. - * @return the color object. - */ - css(color: string): Color; - /** * Create a color from a hex or string representation (as supported in CSS). * @@ -101,217 +57,209 @@ declare namespace Chroma { */ hex(color: string): Color; - rgb(red: number, green: number, blue: number, alpha?: number): Color; - hsl(hue: number, saturation: number, lightness: number, alpha?: number): Color; - hsv(hue: number, saturation: number, value: number, alpha?: number): Color; + hsl(h: number, s: number, l: number): Color; + + hsv(h: number, s: number, v: number): Color; + lab(lightness: number, a: number, b: number, alpha?: number): Color; - lch(lightness: number, chroma: number, hue: number, alpha?: number): Color; + + lch(l: number, c: number, h: number): Color; + + rgb(r: number, g: number, b: number): Color; + + /** + * GL is a variant of RGB(A), with the only difference that the components are normalized to the range of 0..1. + */ gl(red: number, green: number, blue: number, alpha?: number): Color; - interpolate: InterpolateFunction; - mix: InterpolateFunction; + /** + * light 2000K, bright sunlight 6000K. Based on Neil Bartlett's implementation. + * https://github.com/neilbartlett/color-temperature + */ + temperature(t: number): Color; - luminance(color: Color): number; - luminance(color: string): number; + mix(col1: string | Color, col2: string | Color, f?: number, colorSpace?: string): Color; + + interpolate(col1: string | Color, col2: string | Color, f?: number, colorSpace?: string): Color; /** - * Creates a color scale using a pre-defined color scale. - * - * @param name The name of the color scale. - * @return the resulting color scale. + * Blends two colors using RGB channel-wise blend functions. Valid blend modes are multiply, darken, lighten, screen, overlay, burn, and dogde. */ + blend(col1: string, col2: string, blendMode: string): Color; + + /** + * Returns a random color. + */ + random(): Color; + + /** + * Computes the WCAG contrast ratio between two colors. + * A minimum contrast of 4.5:1 is recommended to ensure that text is still readable against a background color. + * + * @param color1 The first color. + * @param color2 The second color. + * @return the contrast ratio. + */ + contrast(col1: string | Color, col2: string | Color): number; + + bezier(colors: string[]): Scale; + + /** + * chroma.brewer is an map of ColorBrewer scales that are included in chroma.js for convenience. + * chroma.scale uses the colors to construct. + */ + brewer: { + OrRd: string[]; + PuBu: string[]; + BuPu: string[]; + Oranges: string[]; + BuGn: string[]; + YlOrBr: string[]; + YlGn: string[]; + Reds: string[]; + RdPu: string[]; + Greens: string[]; + YlGnBu: string[]; + Purples: string[]; + GnBu: string[]; + Greys: string[]; + YlOrRd: string[]; + PuRd: string[]; + Blues: string[]; + PuBuGn: string[]; + Spectral: string[]; + RdYlGn: string[]; + RdBu: string[]; + PiYG: string[]; + PRGn: string[]; + RdYlBu: string[]; + BrBG: string[]; + RdGy: string[]; + PuOr: string[]; + Set2: string[]; + Accent: string[]; + Set1: string[]; + Set3: string[]; + Dark2: string[]; + Paired: string[]; + Pastel2: string[]; + Pastel1: string[]; + }; + + /** + * Helper function that computes class breaks for you, based on actual data. + * Supports three different modes: equidistant breaks, quantiles breaks and breaks based on k-means clusting. + */ + limits(data: number[], mode: string, c: number): number[]; + scale(name: string): Scale; - /** - * Creates a color scale function from the given set of colors. - * - * @param colors An Array of at least two color names or hex values. - * @return the resulting color scale. - */ scale(colors?: string[]): Scale; - scales: PredefinedScales; - } + cubehelix(): Cubehelix; - interface InterpolateFunction { - (color1: Color, color2: Color, f: number, mode?: string): Color; - (color1: Color, color2: string, f: number, mode?: string): Color; - (color1: string, color2: Color, f: number, mode?: string): Color; - (color1: string, color2: string, f: number, mode?: string): Color; - - bezier(colors: any[]): (t: number) => Color; - } - - interface PredefinedScales { - [key: string]: Scale; - - cool: Scale; - hot: Scale; + cmyk(c: number, m: number, y: number, k: number): Color; + + /** + * Create a color from a hex or string representation (as supported in CSS). + * + * This is an alias of chroma.hex(). + * + * @param color The string to convert to a color. + * @return the color object. + */ + css(col: string, mode?: string): string; } export interface Color { - /** - * Creates a color from a string representation (as supported in CSS). - * - * @param color The string to convert to a color. - */ - new(color: string): Color; + alpha(a?: number): Color; - /** - * Create a color in the specified color space using a, b and c as values. - * - * @param a - * @param b - * @param c - * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". - */ - new(a: number, b: number, c: number, colorSpace?: string): Color; + darken(f?: number): Color; - /** - * Create a color in the specified color space using a, b and c as color values and alpha as the alpha value. - * - * @param a - * @param b - * @param c - * @param alpha The alpha value of the color. - * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". - */ - new(a: number, b: number, c: number, alpha: number, colorSpace?: string): Color; + brighten(f?: number): Color; - /** - * Create a color in the specified color space using values. - * - * @param values An array of values (e.g. [r, g, b, a?]). - * @param colorSpace The color space to use (one of "rgb", "hsl", "hsv", "lab", "lch", "gl"). Defaults to "rgb". - */ - new(values: number[], colorSpace: string): Color; + saturate(s?: number): Color; - /** - * Convert this color to CSS hex representation. - * - * @return this color's hex representation. - */ - hex(): string; + desaturate(s?: number): Color; + + set(modechan: string, v: number | string): Color; + + get(modechan: string): number; - /** - * @return the relative luminance of the color, which is a value between 0 (black) and 1 (white). - */ luminance(): number; - /** - * @return the X11 name of this color or its hex value if it does not have a name. - */ + luminance(l: number, mode?: string): Color; + + hex(): string; + name(): string; /** - * @return the alpha value of the color. - */ - alpha(): number; - - /** - * Set the alpha value. + * Create a color from a hex or string representation (as supported in CSS). * - * @param alpha The alpha value. - * @return this + * This is an alias of chroma.hex(). + * + * @param color The string to convert to a color. + * @return the color object. */ - alpha(alpha: number): Color; - css(mode?: string): string; - interpolate(color: Color, f: number, mode?: string): Color; - interpolate(color: string, f: number, mode?: string): Color; - - premultiply(): Color; - rgb(): number[]; + rgba(): number[]; + hsl(): number[]; + hsv(): number[]; - lab(): number[]; - lch(): number[]; + hsi(): number[]; + + lab(): number[]; + + lch(): number[]; + + hcl(): number[]; + + temperature(): number; + gl(): number[]; - - darken(amount?: number): Color; - darker(amount: number): Color; - brighten(amount?: number): Color; - brighter(amount: number): Color; - saturate(amount?: number): Color; - desaturate(amount?: number): Color; - - toString(): string; } export interface Scale { - /** - * Interpolate a color using the currently set range and domain. - * - * @param value The value to use for interpolation. - * @return the interpolated hex color OR a Color object (depending on the mode set on this Scale). - */ + (c: string[]): Scale; + (value: number): any; - /** - * Retreive all possible colors generated by this scale if it has distinct classes. - * - * @param mode The output mode to use. Must be one of Color's getters. Defaults to "hex". - * @return an array of colors in the type specified by mode. - */ - colors(mode?: string): any[]; + domain(d?: number[], n?: number, mode?: string): Scale; - correctLightness(): boolean; + mode(mode: string): Scale; - /** - * Enable or disable automatic lightness correction of this scale. - * - * @param Whether to enable or disable automatic lightness correction. - * @return this - */ - correctLightness(enable: boolean): Scale; + correctLightness(enable?: boolean): Scale; - /** - * Get the current domain. - * - * @return The current domain. - */ - domain(): number[]; + bezier(colors: string[]): Scale; - /** - * Set the domain. - * - * @param domain An Array of at least two numbers (min and max). - * @param classes The number of fixed classes to create between min and max. - * @param mode The scale to use. Examples: log, quantiles, k-means. - * @return this - */ - domain(domain: number[], classes?: number, mode?: string): Scale; + padding(p: number | number[]): Scale; - /** - * Specify in which color space the colors should be interpolated. Defaults to "rgb". - * You can use any of the following spaces: rgb, hsv, hsl, lab, lch - * - * @param colorSpace The color space to use for interpolation. - * @return this - */ - mode(colorSpace: string): Scale; + colors(c?: number): string[]; + + classes(c: number | number[]): (t: number) => Color; + + range(arg: string[]): Scale; + + scale(): Scale; - /** - * Set the output mode of this Scale. - * - * @param mode The output mode to use. Must be one of Color's getters. - * @return this - */ out(mode: string): Scale; - - /** - * Set the color range after initialization. - * - * @param colors An Array of at least two color names or hex values. - * @return this - */ - range(colors: string[]): Scale; } + export interface Cubehelix extends Scale { + start(s: number): Cubehelix; + + rotations(r: number): Cubehelix; + + gamma(g: number): Cubehelix; + + lightness(l: number[]): Cubehelix; + } } declare var chroma: Chroma.ChromaStatic; diff --git a/chrome/chrome-app.d.ts b/chrome/chrome-app.d.ts index f6812fd7d7..e3cf256c2b 100644 --- a/chrome/chrome-app.d.ts +++ b/chrome/chrome-app.d.ts @@ -6,6 +6,17 @@ /// /// +//////////////////// +// App +//////////////////// +declare namespace chrome.app { + interface AppDetails extends chrome.runtime.Manifest { + id: string; + } + + export function getDetails(): AppDetails; +} + //////////////////// // App Runtime //////////////////// diff --git a/chrome/index.d.ts b/chrome/index.d.ts index 5f60533959..936616e118 100644 --- a/chrome/index.d.ts +++ b/chrome/index.d.ts @@ -7219,7 +7219,7 @@ declare namespace chrome.webRequest { * Optional. * If the request method is POST and the body is a sequence of key-value pairs encoded in UTF8, encoded as either multipart/form-data, or application/x-www-form-urlencoded, this dictionary is present and for each key contains the list of all values for that key. If the data is of another media type, or if it is malformed, the dictionary is not present. An example value of this dictionary is {'key': ['value1', 'value2']}. */ - formData?: Object; + formData?: { [key: string]: string[] }; /** * Optional. * If the request method is PUT or POST, and the body is not already parsed in formData, then the unparsed request body elements are contained in this array. @@ -7233,6 +7233,7 @@ declare namespace chrome.webRequest { } interface ResourceRequest { + url: string; /** The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request. */ requestId: string; /** The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. */ @@ -7251,7 +7252,6 @@ declare namespace chrome.webRequest { } interface WebRequestDetails extends ResourceRequest { - url: string; /** Standard HTTP method. */ method: string; } @@ -7304,7 +7304,7 @@ declare namespace chrome.webRequest { interface WebAuthenticationChallengeDetails extends WebResponseHeadersDetails { /** The authentication scheme, e.g. Basic or Digest. */ - schema: string; + scheme: string; /** The authentication realm provided by the server, if there is one. */ realm?: string; /** The server requesting authentication. */ @@ -7336,7 +7336,9 @@ declare namespace chrome.webRequest { interface WebRedirectionResponseEvent extends _WebResponseHeadersEvent {} - interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void> {} + interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void> { + addListener(callback: (details: WebAuthenticationChallengeDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + } interface WebResponseErrorEvent extends _WebResponseHeadersEvent {} diff --git a/cors/index.d.ts b/cors/index.d.ts index 06d8d6d618..74761eb7d6 100644 --- a/cors/index.d.ts +++ b/cors/index.d.ts @@ -16,6 +16,7 @@ declare namespace e { exposedHeaders?: any; credentials?: boolean; maxAge?: number; + preflightContinue?: boolean; } } diff --git a/countdown/countdown-tests.ts b/countdown/countdown-tests.ts new file mode 100644 index 0000000000..c803f1acc2 --- /dev/null +++ b/countdown/countdown-tests.ts @@ -0,0 +1,42 @@ +/// + +import { countdown, Timespan, CountdownStatic, Format } from 'countdown'; + +let ts: Timespan; +let interval: number; + +ts = countdown(new Date()); +ts = countdown(150); + +interval = countdown(new Date(), + function (ts: Timespan) { + document.getElementById('pageTimer').innerHTML = ts.toHTML('strong'); + }, + countdown.HOURS | countdown.MINUTES | countdown.SECONDS, + 2, + 2 +); + +clearInterval(interval); + +ts.toString('foo'); +ts.toHTML('em', 'foo'); + +countdown.resetFormat(); +countdown.setLabels('a', 'b', 'c', 'd', 'e'); + +countdown.setLabels('a', 'b', 'c', 'd', 'e', function (value: number): string { + return 'ok'; +}, function (value: number, unit: number): string { + return 'ok'; +}); + +countdown.setLabels(null, null, null, null, 'Now.'); + +countdown.setLabels( + ' millisecond| second| minute| hour| day| week| month| year| decade| century| millennium', + ' milliseconds| seconds| minutes| hours| days| weeks| months| years| decades| centuries| millennia', + ' and ', + ', ', + '', + n => n.toString()); diff --git a/countdown/countdown.d.ts b/countdown/countdown.d.ts new file mode 100644 index 0000000000..5b40541dd0 --- /dev/null +++ b/countdown/countdown.d.ts @@ -0,0 +1,69 @@ +// Type definitions for countdown.js +// Project: http://countdownjs.org/ +// Definitions by: Gabriel Juchault +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'countdown' { + export type DateFunction = (timespan: Timespan) => void; + export type DateTime = number | Date | DateFunction; + + export interface Timespan { + start?: Date; + end?: Date; + units?: number; + value?: number; + millennia?: number; + centuries?: number; + decades?: number; + years?: number; + months?: number; + days?: number; + hours?: number; + minutes?: number; + seconds?: number; + milliseconds?: number; + toString(label?: string): string; + toHTML(tagName?: string, label?: string): string; + } + + export interface Format { + singular?: string | Array; + plural?: string | Array; + last?: string; + delim?: string; + empty?: string; + formatNumber?(value: number): string; + formatter?(value: number, unit: number): string; + } + + export interface CountdownStatic { + (start: DateTime, end?: DateTime, units?: number, max?: number, digits?: number): Timespan | number; + MILLENNIA: number; + CENTURIES: number; + DECADES: number; + YEARS: number; + MONTHS: number; + WEEKS: number; + DAYS: number; + HOURS: number; + MINUTES: number; + SECONDS: number; + MILLISECONDS: number; + ALL: number; + DEFAULTS: number; + resetLabels(): void; + setLabels( + singular?: string, + plural?: string, + last?: string, + delim?: string, + empty?: string, + formatNumber?: (value: number) => string, + formatter?: (value: number, unit: number) => string + ): void; + resetFormat(): void; + setFormat(format: Format): void; + } + + export let countdown: CountdownStatic; +} diff --git a/cropperjs/cropperjs-tests.ts b/cropperjs/cropperjs-tests.ts index 9fb8556118..2c57656b78 100644 --- a/cropperjs/cropperjs-tests.ts +++ b/cropperjs/cropperjs-tests.ts @@ -1 +1,15 @@ import * as Cropper from 'cropperjs'; + +var image = document.getElementById('image'); +var cropper = new Cropper(image, { + aspectRatio: 16 / 9, + crop: function(e) { + console.log(e.detail.x); + console.log(e.detail.y); + console.log(e.detail.width); + console.log(e.detail.height); + console.log(e.detail.rotate); + console.log(e.detail.scaleX); + console.log(e.detail.scaleY); + } +}); diff --git a/cropperjs/index.d.ts b/cropperjs/index.d.ts index e0d08f9571..92fe782ab3 100644 --- a/cropperjs/index.d.ts +++ b/cropperjs/index.d.ts @@ -10,7 +10,26 @@ declare namespace cropperjs { CanvasShouldNotBeWithInTheContainer = 2, ContainerSshouldBeWithInTheCanvas = 3 } + export interface CropperCustomEvent extends CustomEvent { + detail: Data; + } export interface CropperOptions { + /** + * Function called when crop box is moved or resized + */ + crop?: (event: CropperCustomEvent) => void; + /** + * Function called at start of crop box being moved or resized + */ + cropstart?: (event: CropperCustomEvent) => void; + /** + * Function called when crop box is moved + */ + cropmove?: (event: CropperCustomEvent) => void; + /** + * Function called when crop box is finished being moved or resized + */ + cropend?: (event: CropperCustomEvent) => void; /** * Define the view mode of the cropper. * @default 0 diff --git a/crypto-js/index.d.ts b/crypto-js/index.d.ts index 964febab2b..5fdf193254 100644 --- a/crypto-js/index.d.ts +++ b/crypto-js/index.d.ts @@ -97,6 +97,7 @@ declare namespace CryptoJS { Base64: Encoder; }; mode: { + CBC: Mode; CFB: Mode; CTR: Mode; CTRGladman: Mode; diff --git a/csurf/index.d.ts b/csurf/index.d.ts index badf1f747a..e8d0d22f0b 100644 --- a/csurf/index.d.ts +++ b/csurf/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for csurf +// Type definitions for csurf 1.9.0 // Project: https://www.npmjs.org/package/csurf // Definitions by: Hiroki Horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -17,6 +17,8 @@ declare module "csurf" { function csurf(options?: { value?: (req: express.Request) => string; cookie?: csurf.CookieOptions | boolean; + ignoreMethods?: string[]; + sessionKey?: string; }): express.RequestHandler; namespace csurf { diff --git a/dojo/dijit.d.ts b/dojo/dijit.d.ts index 742881cc90..48961e5e48 100644 --- a/dojo/dijit.d.ts +++ b/dojo/dijit.d.ts @@ -1606,7 +1606,7 @@ declare module dijit { * already removed/destroyed manually. * */ - own(): any; + own(...args: any[]): any[]; /** * Place this widget somewhere in the DOM based * on standard domConstruct.place() conventions. diff --git a/dojo/index.d.ts b/dojo/index.d.ts index 1a045145db..88471ca098 100644 --- a/dojo/index.d.ts +++ b/dojo/index.d.ts @@ -5617,7 +5617,7 @@ declare namespace dojo { * @param scope The scope to use when method executes. If method is a string,scope is also the object containing method. * @param method A function to be hitched to scope, or the name of the method inscope to be hitched. */ - hitch(scope: Object, method: Function): any; + hitch(scope: Object, method: (...args: any[]) => any, ...args: any[]): any; /** * Returns a function that will only ever execute in the a given scope. * This allows for easy use of object member functions @@ -5631,7 +5631,7 @@ declare namespace dojo { * @param scope The scope to use when method executes. If method is a string,scope is also the object containing method. * @param method A function to be hitched to scope, or the name of the method inscope to be hitched. */ - hitch(scope: Object, method: String[]): any; + hitch(scope: Object, method: string, ...args: any[]): any; /** * Returns true if it is a built-in function or some other kind of * oddball that should report as a function but doesn't diff --git a/draft-js/draft-js-0.2.2.d.ts b/draft-js/draft-js-0.2.2.d.ts new file mode 100644 index 0000000000..ac5eb21f33 --- /dev/null +++ b/draft-js/draft-js-0.2.2.d.ts @@ -0,0 +1,277 @@ +// Type definitions for draft-js 0.2.2 +// Project: https://github.com/facebook/draft-js +// Definitions by: Pavel Evsegneev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module "draft-js" { + namespace Draft { + interface IEditor { + new(): Editor + } + + interface EditorState { + getCurrentContent(): ContentState, + getSelection(): SelectionState, + getCurrentInlineStyle(): any, + getBlockTree(): any, + + createEmpty(decorator?: any): EditorState, + createWithContent(contentState: ContentState, decorator?: any): EditorState, + create(config: any): EditorState, + push(editorState: EditorState, contentState: ContentState, actionType: string): EditorState, + undo(editorState: EditorState): EditorState, + redo(editorState: EditorState): EditorState, + acceptSelection(editorState: EditorState, selectionState: SelectionState): EditorState, + forceSelection(editorState: EditorState, selectionState: SelectionState): EditorState, + + moveFocusToEnd(editorState: EditorState): EditorState + } + + interface CompositeDecorator { + getDecorations(): Array, + getComponentForKey(): any, + getPropsForKey(): any + } + + interface Entity { + create(type: string, mutability: string, data?: Object): EntityInstance, + add(instance: EntityInstance): string, + get(key: string): EntityInstance, + mergeData(key: string, toMerge: any): EntityInstance, + replaceData(key: string, newData: any): EntityInstance + } + + interface EntityInstance { + getData(): any, + getKey(): string, + getMutability(): string + } + + interface BlockMapBuilder { + createFromArray(blocks: Array): BlockMap + } + + interface CharacterMetadata { + create(config?: any): CharacterMetadata, + + applyStyle(record: CharacterMetadata, + style: string): CharacterMetadata, + + removeStyle(record: CharacterMetadata, + style: string): CharacterMetadata, + + applyEntity(record: CharacterMetadata, + entityKey?: string): CharacterMetadata, + + getStyle(): any, + hasStyle(style: string): boolean, + + getEntity(): string + } + + interface IContentBlock { + new(draftContentBlock: any): ContentBlock; + } + interface ContentBlock { + key: string, + type: string, + text: string, + characterList: any, + depth: number, + + getKey(): string, + getType(): string, + getText(): string, + getCharacterList(): any, + getLength(): number, + getDepth(): number, + getInlineStyleAt(offset: number): any, + getEntityAt(offset: number): string, + findStyleRanges(filterFn: Function, callback: Function): void, + findEntityRanges(filterFn: Function, callback: Function): void + + } + + interface ContentState { + createFromText(text: string): ContentState, + createFromBlockArray(blocks: Array): ContentState, + + getBlockMap(): BlockMap, + getSelectionBefore(): SelectionState, + getSelectionAfter(): SelectionState, + + getBlockForKey(key: string): ContentBlock, + getKeyBefore(key: string): string, + getKeyAfter(key: string): string, + + getBlockBefore(key: string): ContentBlock, + getBlockAfter(key: string): ContentBlock, + + getBlocksAsArray(): Array, + + getPlainText(): string, + hasText(): boolean, + + set(key: string, value: any): ContentState, + toJS(): any + } + + interface ISelectionState { + new(draftSelectionState: any): SelectionState; + createEmpty(blockKey: string): SelectionState; + } + + interface SelectionState { + getStartKey(): string, + getStartOffset(): number, + getEndKey(): string, + getEndOffset(): number, + getAnchorKey(): string, + getAnchorOffset(): number, + getFocusKey(): string, + getFocusOffset(): number, + + getIsBackward(): boolean, + getHasFocus(): boolean, + isCollapsed(): boolean, + + hasEdgeWithin(blockKey: string, start: number, end: number): boolean, + serialize(): string, + + get(key: string): any, + set(key: string, value: any): SelectionState + } + + interface BlockMap { + get(key: string): ContentBlock, + set(key: string, value: any): BlockMap, + delete(key: string): BlockMap, + find(cb: any): ContentBlock + } + + interface Modifier { + replaceText(contentState: ContentState, + rangeToReplace: SelectionState, + text: string, + inlineStyle?: any, + entityKey?: string): ContentState, + + insertText(contentState: ContentState, + targetRange: SelectionState, + text: string, + inlineStyle?: any, + entityKey?: string): ContentState, + + moveText(contentState: ContentState, + removalRange: SelectionState, + targetRange: SelectionState): ContentState, + + replaceWithFragment(contentState: ContentState, + targetRange: SelectionState, + fragment: BlockMap): ContentState, + + removeRange(contentState: ContentState, + rangeToRemove: SelectionState, + removalDirection: string): ContentState, + + splitBlock(contentState: ContentState, + selectionState: SelectionState): ContentState, + + applyInlineStyle(contentState: ContentState, + selectionState: SelectionState, + inlineStyle: string): ContentState, + + removeInlineStyle(contentState: ContentState, + selectionState: SelectionState, + inlineStyle: string): ContentState, + + setBlockType(contentState: ContentState, + selectionState: SelectionState, + blockType: string): ContentState, + + applyEntity(contentState: ContentState, + selectionState: SelectionState, + entityKey: string): ContentState + } + + interface RichUtils { + currentBlockContainsLink(editorState: EditorState): boolean, + getCurrentBlockType(editor: EditorState): string, + handleKeyCommand(editorState: EditorState, command: string): any, + insertSoftNewline(editorState: EditorState): EditorState, + onBackspace(editorState: EditorState): EditorState, + onDelete(editorState: EditorState): EditorState, + onTab(event: Event, editorState: EditorState, maxDepth: number): EditorState, + toggleBlockType(editorState: EditorState, blockType: string): EditorState, + toggleCode(editorState: EditorState): EditorState, + toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState, + tryToRemoveBlockStyle(editorState: EditorState): EditorState + } + + interface EditorProps { + editorState: EditorState, + onChange(editorState: EditorState): void, + + placeholder?: string, + textAlignment?: any, + blockRendererFn?: (ContentBlock: ContentBlock) => any, + blockStyleFn?: (ContentBlock: ContentBlock) => string, + customStyleMap?: any, + + readOnly?: boolean, + spellCheck?: boolean, + stripPastedStyles?: boolean, + + handleReturn?: (e: any) => boolean, + handleKeyCommand?: (command: string) => boolean, + handleBeforeInput?: (chars: string) => boolean, + handlePastedFiles?: (files: Array) => boolean, + handleDroppedFiles?: (selection: SelectionState, files: Array) => boolean, + handleDrop?: (selection: SelectionState, dataTransfer: any, isInternal: any) => boolean, + + onEscape?: (e: any) => void, + onTab?: (e: any) => void, + onUpArrow?: (e: any) => void, + onDownArrow?: (e: any) => void, + + suppressContentEditableWarning?: any, + + onBlur?: (e: any) => void, + onFocus?: (e: any) => void + } + + interface Editor { + props: EditorProps + state: any, + refs: any, + context: any, + setState(): any, + render(): any, + forceUpdate(): any + } + + var Editor: IEditor; + var EditorState: EditorState; + + var CompositeDecorator: CompositeDecorator; + var Entity: Entity; + var EntityInstance: EntityInstance; + + var BlockMapBuilder: BlockMapBuilder; + var CharacterMetadata: CharacterMetadata; + var ContentBlock: IContentBlock; + var ContentState: ContentState; + var SelectionState: ISelectionState; + + var Modifier: Modifier; + var RichUtils: RichUtils; + + function convertFromRaw(rawState: any): Array; + + function convertToRaw(contentState: ContentState): any; + + function genKey(): string + } + + export = Draft; + +} diff --git a/draft-js/draft-js-tests-0.2.2.tsx b/draft-js/draft-js-tests-0.2.2.tsx new file mode 100644 index 0000000000..88271465f5 --- /dev/null +++ b/draft-js/draft-js-tests-0.2.2.tsx @@ -0,0 +1,183 @@ +/// +/// +/// + +import * as React from "react"; + +import { + Editor, + EditorState, + Entity, + CharacterMetadata, + ContentBlock, + Modifier, + SelectionState, + genKey +} from "draft-js"; + +export class Tag extends React.Component { + constructor(props: any) { + super(props); + } + + remove = (): void => { + this.props.blockProps.removeBlock(this.props.block.getKey()); + } + + render () { + const {block} = this.props; + if (block.getEntityAt(0)) { + const data = Entity.get(block.getEntityAt(0)).getData(); + + return ( +
+ {data.content.name} + + clear + +
+ ); + } + } +} + +export class Hint extends React.Component { + constructor(props: any) { + super(props); + } + + render () { + const {block} = this.props; + if (block.getEntityAt(0)) { + const data = Entity.get(block.getEntityAt(0)).getData(); + + return ( +
+ {this.props.blockProps.autocomplete} + {data.content.text} +
+ ); + } + } +} + +export function removeBlock(editorState: EditorState, blockKey: string) { + const content = editorState.getCurrentContent(); + + const targetRange = new SelectionState({ + anchorKey: blockKey, + anchorOffset: 0, + focusKey: blockKey, + focusOffset: 1 + }); + + const withoutTag = Modifier.removeRange(content, targetRange, "backward"); + const resetBlock = Modifier.setBlockType( + withoutTag, + withoutTag.getSelectionAfter(), + "unstyled" + ); + + const newState = EditorState.push(editorState, resetBlock, "remove-range"); + return EditorState.forceSelection(newState, resetBlock.getSelectionAfter()); +} + +export function applyEntity(editorState: EditorState, blockKey: string, entityKey: string) { + const content = editorState.getCurrentContent(); + + const targetRange = new SelectionState({ + anchorKey: blockKey, + anchorOffset: 0, + focusKey: blockKey, + focusOffset: 1 + }); + + const withNewEntity = Modifier.applyEntity( + content, + targetRange, + entityKey + ) + + const newState = EditorState.push(editorState, withNewEntity, "change-entity"); + return EditorState.forceSelection(newState, withNewEntity.getSelectionAfter()); +} + +export function addTagBlock(content: any, editorState: EditorState): any { + const contentState = editorState.getCurrentContent(); + + const entityKey = Entity.create( + "TOKEN", + "IMMUTABLE", + {content} + ); + + const charData = CharacterMetadata.create({entity: entityKey}); + const tag = new ContentBlock({ + key: genKey(), + type: "tag", + text: "", + characterList: [], + }); + + const withTag = contentState.set("blockMap", contentState.getBlockMap().set(tag.key, tag)); + + const withRemovedPreviousBlock = withTag.set("blockMap", withTag.getBlockMap().delete(contentState.getSelectionBefore().getAnchorKey())) + + const withTagBlock = EditorState.push(editorState, withRemovedPreviousBlock, "insert-fragment"); + + return withTagBlock; +} + +export function addHintBlock(content: any, editorState: EditorState): any { + const contentState = editorState.getCurrentContent(); + const selectionState = editorState.getSelection(); + + const entityKey = Entity.create( + "TOKEN", + "IMMUTABLE", + {content} + ); + + const charData = CharacterMetadata.create({entity: entityKey}); + const hint = new ContentBlock({ + key: genKey(), + type: "hint", + text: "", + characterList: [], + }); + const empty = new ContentBlock({ + key: genKey(), + type: "unstyled", + text: "", + characterList: [], + }); + + const withEmpty = contentState.set("blockMap", contentState.getBlockMap().set(empty.key, empty)); + const withHint = withEmpty.set("blockMap", withEmpty.getBlockMap().set(hint.key, hint)); + return { + editorState: EditorState.forceSelection(EditorState.push(editorState, withHint, "insert-fragment"), selectionState), + blockKey: hint.key + } + +} + +export class SearchField extends React.Component { + public onChange: any; + + constructor(props: any) { + super(props); + this.onChange = (editorState: EditorState) => { + this.setState({editorState}) + }; + } + + render() { + const {editorState} = this.state; + return ( + + ) + } +} diff --git a/draft-js/draft-js-tests.tsx b/draft-js/draft-js-tests.tsx index a04b5fe35e..eef542a266 100644 --- a/draft-js/draft-js-tests.tsx +++ b/draft-js/draft-js-tests.tsx @@ -1,182 +1,178 @@ -/// -/// - import * as React from "react"; +import * as ReactDOM from "react-dom"; +import {Map} from "immutable"; -import { -Editor, - EditorState, - Entity, - CharacterMetadata, - ContentBlock, - Modifier, - SelectionState, - genKey -} from "draft-js"; +import {Editor, EditorState, RichUtils, DefaultDraftBlockRenderMap, ContentBlock} from 'draft-js'; -export class Tag extends React.Component { - constructor(props: any) { - super(props); +class RichEditorExample extends React.Component<{}, { editorState: EditorState }> { + constructor() { + super(); + + this.state = { editorState: EditorState.createEmpty() }; } - remove = (): void => { - this.props.blockProps.removeBlock(this.props.block.getKey()); + onChange: (editorState: EditorState) => void = (editorState: EditorState) => this.setState({ editorState }); + + handleKeyCommand: (command: string) => boolean = (command: string) => { + const {editorState} = this.state; + const newState = RichUtils.handleKeyCommand(editorState, command); + if (newState) { + this.onChange(newState); + return true; + } + + return false; } - render () { - const {block} = this.props; - if (block.getEntityAt(0)) { - const data = Entity.get(block.getEntityAt(0)).getData(); + toggleBlockType: (blockType: string) => void = (blockType: string) => { + this.onChange(RichUtils.toggleBlockType(this.state.editorState, blockType)); + } + + toggleInlineStyle: (inlineStyle: string) => void = (inlineStyle: string) => { + this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, inlineStyle)); + } + + render(): React.ReactElement<{}> { + // If the user changes block type before entering any text, we can + // either style the placeholder or hide it. Let's just hide it now. + let className = 'RichEditor-editor'; + var contentState = this.state.editorState.getCurrentContent(); + if (!contentState.hasText()) { + if (contentState.getBlockMap().first().getType() !== 'unstyled') { + className += ' RichEditor-hidePlaceholder'; + } + } return ( -
- {data.content.name} - - clear - +
+ + +
+ +
); } - } } -export class Hint extends React.Component { - constructor(props: any) { - super(props); - } +// Custom overrides for "code" style. +const styleMap = { + CODE: { + backgroundColor: 'rgba(0, 0, 0, 0.05)', + fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace', + fontSize: 16, + padding: 2, + }, +}; - render () { - const {block} = this.props; - if (block.getEntityAt(0)) { - const data = Entity.get(block.getEntityAt(0)).getData(); - - return ( -
- {this.props.blockProps.autocomplete} - {data.content.text} -
- ); - } - } +function getBlockStyle(block: ContentBlock) { + switch (block.getType()) { + case 'blockquote': return 'RichEditor-blockquote'; + default: return null; + } } -export function removeBlock(editorState: EditorState, blockKey: string) { - const content = editorState.getCurrentContent(); +class StyleButton extends React.Component<{key: string, active: boolean, label: string, onToggle: (blockType: string) => void, style: string}, {}> { + constructor() { + super(); + } - const targetRange = new SelectionState({ - anchorKey: blockKey, - anchorOffset: 0, - focusKey: blockKey, - focusOffset: 1 - }); + onToggle: (event: Event) => void = (event: Event) => { + event.preventDefault(); + this.props.onToggle(this.props.style); + }; - const withoutTag = Modifier.removeRange(content, targetRange, "backward"); - const resetBlock = Modifier.setBlockType( - withoutTag, - withoutTag.getSelectionAfter(), - "unstyled" + render(): React.ReactElement<{}> { + let className = 'RichEditor-styleButton'; + + if (this.props.active) { + className += ' RichEditor-activeButton'; + } + + return ( + + {this.props.label} + ); - - const newState = EditorState.push(editorState, resetBlock, "remove-range"); - return EditorState.forceSelection(newState, resetBlock.getSelectionAfter()); + } } -export function applyEntity(editorState: EditorState, blockKey: string, entityKey: string) { - const content = editorState.getCurrentContent(); +const BLOCK_TYPES = [ + { label: 'H1', style: 'header-one' }, + { label: 'H2', style: 'header-two' }, + { label: 'H3', style: 'header-three' }, + { label: 'H4', style: 'header-four' }, + { label: 'H5', style: 'header-five' }, + { label: 'H6', style: 'header-six' }, + { label: 'Blockquote', style: 'blockquote' }, + { label: 'UL', style: 'unordered-list-item' }, + { label: 'OL', style: 'ordered-list-item' }, + { label: 'Code Block', style: 'code-block' }, +]; - const targetRange = new SelectionState({ - anchorKey: blockKey, - anchorOffset: 0, - focusKey: blockKey, - focusOffset: 1 - }); +const BlockStyleControls = (props: {editorState: EditorState, onToggle: (blockType: string) => void}) => { + const {editorState} = props; + const selection = editorState.getSelection(); + const blockType = editorState + .getCurrentContent() + .getBlockForKey(selection.getStartKey()) + .getType(); - const withNewEntity = Modifier.applyEntity( - content, - targetRange, - entityKey - ) - - const newState = EditorState.push(editorState, withNewEntity, "change-entity"); - return EditorState.forceSelection(newState, withNewEntity.getSelectionAfter()); -} - -export function addTagBlock(content: any, editorState: EditorState): any { - const contentState = editorState.getCurrentContent(); - - const entityKey = Entity.create( - "TOKEN", - "IMMUTABLE", - {content} + return ( +
+ {BLOCK_TYPES.map((type) => + + ) } +
); +}; - const charData = CharacterMetadata.create({entity: entityKey}); - const tag = new ContentBlock({ - key: genKey(), - type: "tag", - text: "", - characterList: [], - }); +var INLINE_STYLES = [ + { label: 'Bold', style: 'BOLD' }, + { label: 'Italic', style: 'ITALIC' }, + { label: 'Underline', style: 'UNDERLINE' }, + { label: 'Monospace', style: 'CODE' }, +]; - const withTag = contentState.set("blockMap", contentState.getBlockMap().set(tag.key, tag)); - - const withRemovedPreviousBlock = withTag.set("blockMap", withTag.getBlockMap().delete(contentState.getSelectionBefore().getAnchorKey())) - - const withTagBlock = EditorState.push(editorState, withRemovedPreviousBlock, "insert-fragment"); - - return withTagBlock; -} - -export function addHintBlock(content: any, editorState: EditorState): any { - const contentState = editorState.getCurrentContent(); - const selectionState = editorState.getSelection(); - - const entityKey = Entity.create( - "TOKEN", - "IMMUTABLE", - {content} - ); - - const charData = CharacterMetadata.create({entity: entityKey}); - const hint = new ContentBlock({ - key: genKey(), - type: "hint", - text: "", - characterList: [], - }); - const empty = new ContentBlock({ - key: genKey(), - type: "unstyled", - text: "", - characterList: [], - }); - - const withEmpty = contentState.set("blockMap", contentState.getBlockMap().set(empty.key, empty)); - const withHint = withEmpty.set("blockMap", withEmpty.getBlockMap().set(hint.key, hint)); - return { - editorState: EditorState.forceSelection(EditorState.push(editorState, withHint, "insert-fragment"), selectionState), - blockKey: hint.key - } - -} - -export class SearchField extends React.Component { - public onChange: any; - - constructor(props: any) { - super(props); - this.onChange = (editorState: EditorState) => { - this.setState({editorState}) - }; - } - - render() { - const {editorState} = this.state; +const InlineStyleControls = (props: {editorState: EditorState, onToggle: (blockType: string) => void}) => { + var currentStyle = props.editorState.getCurrentInlineStyle(); return ( - + {INLINE_STYLES.map(type => + - ) - } -} + ) } +
+ ); +}; + +ReactDOM.render( + , + document.getElementById('target') +); \ No newline at end of file diff --git a/draft-js/index.d.ts b/draft-js/index.d.ts index 7ab650acde..82753284a7 100644 --- a/draft-js/index.d.ts +++ b/draft-js/index.d.ts @@ -1,275 +1,935 @@ -// Type definitions for draft-js 0.2.2 -// Project: https://github.com/facebook/draft-js -// Definitions by: Pavel Evsegneev +// Type definitions for Draft.js v0.7.0 +// Project: https://facebook.github.io/draft-js/ +// Definitions by: Dmitry Rogozhny // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import * as React from 'react'; +import * as Immutable from 'immutable'; + +type SyntheticKeyboardEvent = React.KeyboardEvent<{}>; +type SyntheticEvent = React.SyntheticEvent<{}>; + declare namespace Draft { - interface IEditor { - new (): Editor + namespace Component { + namespace Base { + import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + import DraftDragType = Draft.Model.Constants.DraftDragType; + + import EditorState = Draft.Model.ImmutableData.EditorState; + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; + import SelectionState = Draft.Model.ImmutableData.SelectionState; + + import DraftBlockRenderConfig = Draft.Model.ImmutableData.DraftBlockRenderConfig; + + type DraftBlockRenderMap = Immutable.Map; + + /** + * `DraftEditor` is the root editor component. It composes a `contentEditable` + * div, and provides a wide variety of useful function props for managing the + * state of the editor. See `DraftEditorProps` for details. + */ + class DraftEditor extends React.Component { + // Force focus back onto the editor node. + focus(): void; + // Remove focus from the editor node. + blur(): void; + } + + /** + * The two most critical props are `editorState` and `onChange`. + * + * The `editorState` prop defines the entire state of the editor, while the + * `onChange` prop is the method in which all state changes are propagated + * upward to higher-level components. + * + * These props are analagous to `value` and `onChange` in controlled React + * text inputs. + */ + interface DraftEditorProps { + editorState: EditorState; + onChange(editorState: EditorState): void; + + placeholder?: string; + + // Specify whether text alignment should be forced in a direction + // regardless of input characters. + textAlignment?: DraftTextAlignment; + + // For a given `ContentBlock` object, return an object that specifies + // a custom block component and/or props. If no object is returned, + // the default `TextEditorBlock` is used. + blockRendererFn?(block: ContentBlock): any; + + // Function that allows to define class names to apply to the given block when it is rendered. + blockStyleFn?(block: ContentBlock): string; + + // Provide a map of inline style names corresponding to CSS style objects + // that will be rendered for matching ranges. + customStyleMap?: any, + + // A function that accepts a synthetic key event and returns + // the matching DraftEditorCommand constant, or null if no command should + // be invoked. + keyBindingFn?(e: SyntheticKeyboardEvent): DraftEditorCommand; + keyBindingFn?(e: SyntheticKeyboardEvent): string; + + // Set whether the `DraftEditor` component should be editable. Useful for + // temporarily disabling edit behavior or allowing `DraftEditor` rendering + // to be used for consumption purposes. + readOnly?: boolean, + + // Note: spellcheck is always disabled for IE. If enabled in Safari, OSX + // autocorrect is enabled as well. + spellCheck?: boolean, + + // Set whether to remove all style information from pasted content. If your + // use case should not have any block or inline styles, it is recommended + // that you set this to `true`. + stripPastedStyles?: boolean, + + tabIndex?: number, + + ariaActiveDescendantID?: string, + ariaAutoComplete?: string, + ariaDescribedBy?: string, + ariaExpanded?: boolean, + ariaHasPopup?: boolean, + ariaLabel?: string, + ariaOwneeID?: string, + + webDriverTestID?: string, + + /** + * Cancelable event handlers, handled from the top level down. A handler + * that returns true will be the last handler to execute for that event. + */ + + // Useful for managing special behavior for pressing the `Return` key. E.g. + // removing the style from an empty list item. + handleReturn?(e: SyntheticKeyboardEvent): boolean, + + // Map a key command string provided by your key binding function to a + // specified behavior. + handleKeyCommand?(command: DraftEditorCommand): boolean, + handleKeyCommand?(command: string): boolean, + + + // Handle intended text insertion before the insertion occurs. This may be + // useful in cases where the user has entered characters that you would like + // to trigger some special behavior. E.g. immediately converting `:)` to an + // emoji Unicode character, or replacing ASCII quote characters with smart + // quotes. + handleBeforeInput?(chars: string): boolean, + + handlePastedText?(text: string, html?: string): boolean, + + handlePastedFiles?(files: Array): boolean, + + // Handle dropped files + handleDroppedFiles?(selection: SelectionState, files: Array): boolean, + + // Handle other drops to prevent default text movement/insertion behaviour + handleDrop?(selection: SelectionState, dataTransfer: Object, isInternal: DraftDragType): boolean, + + /** + * Non-cancelable event triggers. + */ + onEscape?(e: SyntheticKeyboardEvent): void, + onTab?(e: SyntheticKeyboardEvent): void, + onUpArrow?(e: SyntheticKeyboardEvent): void, + onDownArrow?(e: SyntheticKeyboardEvent): void, + + onBlur?(e: SyntheticEvent): void, + onFocus?(e: SyntheticEvent): void, + + // Provide a map of block rendering configurations. Each block type maps to + // an element tag and an optional react element wrapper. This configuration + // is used for both rendering and paste processing. + blockRenderMap?: DraftBlockRenderMap + } + + type DraftTextAlignment = "left" | "center" | "right"; + } + + namespace Components { + class DraftEditorBlock extends React.Component { + } + } + + namespace Selection { + interface FakeClientRect { + left: number, + width: number, + right: number, + top: number, + bottom: number, + height: number, + } + + /** + * Return the bounding ClientRect for the visible DOM selection, if any. + * In cases where there are no selected ranges or the bounding rect is + * temporarily invalid, return null. + */ + function getVisibleSelectionRect(global: any): FakeClientRect; + } + + namespace Utils { + import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; + + interface KeyBindingUtil { + /** + * Check whether the ctrlKey modifier is *not* being used in conjunction with + * the altKey modifier. If they are combined, the result is an `altGraph` + * key modifier, which should not be handled by this set of key bindings. + */ + isCtrlKeyCommand(e: SyntheticKeyboardEvent): boolean; + + isOptionKeyCommand(e: SyntheticKeyboardEvent): boolean; + + hasCommandModifier(e: SyntheticKeyboardEvent): boolean; + } + + /** + * Retrieve a bound key command for the given event. + */ + function getDefaultKeyBinding(e: SyntheticKeyboardEvent): DraftEditorCommand; + function getDefaultKeyBinding(e: SyntheticKeyboardEvent): string; + } } - interface EditorState { - getCurrentContent(): ContentState, - getSelection(): SelectionState, - getCurrentInlineStyle(): any, - getBlockTree(): any, + namespace Model { + namespace Constants { + /** + * A set of editor commands that may be invoked by keyboard commands or UI + * controls. These commands should map to operations that modify content or + * selection state and update the editor state accordingly. + */ + type DraftEditorCommand = ( + /** + * Self-explanatory. + */ + "undo" | + "redo" | - createEmpty(decorator?: any): EditorState, - createWithContent(contentState: ContentState, decorator?: any): EditorState, - create(config: any): EditorState, - push(editorState: EditorState, contentState: ContentState, actionType: string): EditorState, - undo(editorState: EditorState): EditorState, - redo(editorState: EditorState): EditorState, - acceptSelection(editorState: EditorState, selectionState: SelectionState): EditorState, - forceSelection(editorState: EditorState, selectionState: SelectionState): EditorState, + /** + * Perform a forward deletion. + */ + "delete" | - moveFocusToEnd(editorState: EditorState): EditorState + /** + * Perform a forward deletion to the next word boundary after the selection. + */ + "delete-word" | + + /** + * Perform a backward deletion. + */ + "backspace" | + + /** + * Perform a backward deletion to the previous word boundary before the + * selection. + */ + "backspace-word" | + + /** + * Perform a backward deletion to the beginning of the current line. + */ + "backspace-to-start-of-line" | + + /** + * Toggle styles. Commands may be intepreted to modify inline text ranges + * or block types. + */ + "bold" | + "italic" | + "underline" | + "code" | + + /** + * Split a block in two. + */ + "split-block" | + + /** + * Self-explanatory. + */ + "transpose-characters" | + "move-selection-to-start-of-block" | + "move-selection-to-end-of-block" | + + /** + * Commands to support the "secondary" clipboard provided by certain + * browsers and operating systems. + */ + "secondary-cut" | + "secondary-paste" + ); + + /** + * A type that allows us to avoid passing boolean arguments + * around to indicate whether a drag type is internal or external. + */ + type DraftDragType = "internal" | "external"; + + /** + * The list of default valid block types. + */ + type DraftBlockType = ( + "unstyled" | + "paragraph" | + "header-one" | + "header-two" | + "header-three" | + "header-four" | + "header-five" | + "header-six" | + "unordered-list-item" | + "ordered-list-item" | + "blockquote" | + "code-block" | + "atomic" + ); + + /** + * A type that allows us to avoid passing boolean arguments + * around to indicate whether a deletion is forward or backward. + */ + type DraftRemovalDirection = "backward" | "forward"; + } + + namespace Decorators { + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; + + /** + * An interface for document decorator classes, allowing the creation of + * custom decorator classes. + * + * See `CompositeDraftDecorator` for the most common use case. + */ + interface DraftDecoratorType { + /** + * Given a `ContentBlock`, return an immutable List of decorator keys. + */ + getDecorations(block: ContentBlock): Immutable.List; + + /** + * Given a decorator key, return the component to use when rendering + * this decorated range. + */ + getComponentForKey(key: string): Function; + + /** + * Given a decorator key, optionally return the props to use when rendering + * this decorated range. + */ + getPropsForKey(key: string): any; + } + + /** + * A DraftDecorator is a strategy-component pair intended for use when + * rendering content. + * + * - A "strategy": A function that accepts a ContentBlock object and + * continuously executes a callback with start/end values corresponding to + * relevant matches in the document text. For example, getHashtagMatches + * uses a hashtag regex to find hashtag strings in the block, and + * for each hashtag match, executes the callback with start/end pairs. + * + * - A "component": A React component that will be used to render the + * "decorated" section of text. + * + * - "props": Props to be passed into the React component that will be used. + */ + interface DraftDecorator { + strategy: (block: ContentBlock, callback: (start: number, end: number) => void) => void; + component: Function; + props?: Object; + } + + /** + * A CompositeDraftDecorator traverses through a list of DraftDecorator + * instances to identify sections of a ContentBlock that should be rendered + * in a "decorated" manner. For example, hashtags, mentions, and links may + * be intended to stand out visually, be rendered as anchors, etc. + * + * The list of decorators supplied to the constructor will be used in the + * order they are provided. This allows the caller to specify a priority for + * string matching, in case of match collisions among decorators. + * + * For instance, I may have a link with a `#` in its text. Though this section + * of text may match our hashtag decorator, it should not be treated as a + * hashtag. I should therefore list my link DraftDecorator + * before my hashtag DraftDecorator when constructing this composite + * decorator instance. + * + * Thus, when a collision like this is encountered, the earlier match is + * preserved and the new match is discarded. + */ + class CompositeDraftDecorator { + constructor(decorators: Array); + + getDecorations(block: ContentBlock): Immutable.List; + getComponentForKey(key: string): Function; + getPropsForKey(key: string): Object; + } + } + + namespace Encoding { + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; + import ContentState = Draft.Model.ImmutableData.ContentState; + + import DraftBlockRenderMap = Draft.Component.Base.DraftBlockRenderMap; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + + import DraftEntityType = Draft.Model.Entity.DraftEntityType; + import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + + /** + * A plain object representation of an entity attribution. + * + * The `key` value corresponds to the key of the entity in the `entityMap` of + * a `ComposedText` object, not for use with `DraftEntity.get()`. + */ + interface EntityRange { + key: number, + offset: number, + length: number, + } + + /** + * A plain object representation of an inline style range. + */ + interface InlineStyleRange { + style: string; + offset: number; + length: number; + } + + /** + * A plain object representation of an EntityInstance. + */ + interface RawDraftEntity { + type: DraftEntityType; + mutability: DraftEntityMutability; + data: { [key: string]: any }; + } + + /** + * A plain object representation of a ContentBlock, with all style and entity + * attribution repackaged as range objects. + */ + interface RawDraftContentBlock { + key: string; + type: DraftBlockType; + text: string; + depth: number; + inlineStyleRanges: Array; + entityRanges: Array; + data?: Object; + } + + /** + * A type that represents a composed document as vanilla JavaScript objects, + * with all styles and entities represented as ranges. Corresponding entity + * objects are packaged as objects as well. + * + * This object is especially useful when sending the document state to the + * server for storage, as its representation is more concise than our + * immutable objects. + */ + interface RawDraftContentState { + blocks: Array; + entityMap: { [key: string]: RawDraftEntity }; + } + + function convertFromHTMLtoContentBlocks(html: string, DOMBuilder: Function, blockRenderMap?: DraftBlockRenderMap): Array; + function convertFromRawToDraftState(rawState: RawDraftContentState): ContentState; + function convertFromDraftStateToRaw(contentState: ContentState): RawDraftContentState; + } + + namespace Entity { + type ComposedEntityType = "LINK" | "TOKEN" | "PHOTO"; + type DraftEntityType = string | ComposedEntityType; + + /** + * An enum representing the possible "mutability" options for an entity. + * This refers to the behavior that should occur when inserting or removing + * characters in a text range with an entity applied to it. + * + * `MUTABLE`: + * The text range can be modified freely. Generally used in cases where + * the text content and the entity do not necessarily have a direct + * relationship. For instance, the text and URI for a link may be completely + * different. The user is allowed to edit the text as needed, and the entity + * is preserved and applied to any characters added within the range. + * + * `IMMUTABLE`: + * Not to be confused with immutable data structures used to represent the + * state of the editor. Immutable entity ranges cannot be modified in any + * way. Adding characters within the range will remove the entity from the + * entire range. Deleting characters will delete the entire range. Example: + * Facebook Page mentions. + * + * `SEGMENTED`: + * Segmented entities allow the removal of partial ranges of text, as + * separated by a delimiter. Adding characters wihin the range will remove + * the entity from the entire range. Deleting characters within a segmented + * entity will delete only the segments affected by the deletion. Example: + * Facebook User mentions. + */ + type DraftEntityMutability = "MUTABLE" | "IMMUTABLE" | "SEGMENTED"; + + /** + * A "document entity" is an object containing metadata associated with a + * piece of text in a ContentBlock. + * + * For example, a `link` entity might include a `uri` property. When a + * ContentBlock is rendered in the browser, text that refers to that link + * entity may be rendered as an anchor, with the `uri` as the href value. + * + * In a ContentBlock, every position in the text may correspond to zero + * or one entities. This correspondence is tracked using a key string, + * generated via DraftEntity.create() and used to obtain entity metadata + * via DraftEntity.get(). + */ + class DraftEntity { + /** + * Create a DraftEntityInstance and store it for later retrieval. + * + * A random key string will be generated and returned. This key may + * be used to track the entity's usage in a ContentBlock, and for + * retrieving data about the entity at render time. + */ + static create(type: DraftEntityType, mutability: DraftEntityMutability, data?: Object): string; + + /** + * Add an existing DraftEntityInstance to the DraftEntity map. This is + * useful when restoring instances from the server. + */ + static add(instance: DraftEntityInstance): string; + + /** + * Retrieve the entity corresponding to the supplied key string. + */ + static get(key: string): DraftEntityInstance; + + /** + * Entity instances are immutable. If you need to update the data for an + * instance, this method will merge your data updates and return a new + * instance. + */ + static mergeData(key: string, toMerge: { [key: string]: any }): DraftEntityInstance; + + /** + * Completely replace the data for a given instance. + */ + static replaceData(key: string, newData: { [key: string]: any }): DraftEntityInstance; + } + + /** + * An instance of a document entity, consisting of a `type` and relevant + * `data`, metadata about the entity. + * + * For instance, a "link" entity might provide a URI, and a "mention" + * entity might provide the mentioned user's ID. These pieces of data + * may be used when rendering the entity as part of a ContentBlock DOM + * representation. For a link, the data would be used as an href for + * the rendered anchor. For a mention, the ID could be used to retrieve + * a hovercard. + */ + interface DraftEntityInstance { + getType(): DraftEntityType; + getMutability(): DraftEntityMutability; + getData(): any; + } + } + + namespace ImmutableData { + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; + + type DraftInlineStyle = Immutable.OrderedSet; + type BlockMap = Immutable.OrderedMap; + + var Record: Immutable.Record.Class; + + interface DraftBlockRenderConfig { + element: string; + wrapper?: React.ReactElement; + } + + class EditorState extends Record { + static createEmpty(decorator?: DraftDecoratorType): EditorState; + static createWithContent(contentState: ContentState, decorator?: DraftDecoratorType): EditorState; + static create(config: Object): EditorState; + static set(editorState: EditorState, put: Object): EditorState; + + /** + * Incorporate native DOM selection changes into the EditorState. This + * method can be used when we simply want to accept whatever the DOM + * has given us to represent selection, and we do not need to re-render + * the editor. + * + * To forcibly move the DOM selection, see `EditorState.forceSelection`. + */ + static acceptSelection(editorState: EditorState, selection: SelectionState): EditorState; + + /** + * At times, we need to force the DOM selection to be where we + * need it to be. This can occur when the anchor or focus nodes + * are non-text nodes, for instance. In this case, we want to trigger + * a re-render of the editor, which in turn forces selection into + * the correct place in the DOM. The `forceSelection` method + * accomplishes this. + * + * This method should be used in cases where you need to explicitly + * move the DOM selection from one place to another without a change + * in ContentState. + */ + static forceSelection(editorState: EditorState, selection: SelectionState): EditorState; + + /** + * Move selection to the end of the editor without forcing focus. + */ + static moveSelectionToEnd(editorState: EditorState): EditorState; + + /** + * Force focus to the end of the editor. This is useful in scenarios + * where we want to programmatically focus the input and it makes sense + * to allow the user to continue working seamlessly. + */ + static moveFocusToEnd(editorState: EditorState): EditorState; + + /** + * Push the current ContentState onto the undo stack if it should be + * considered a boundary state, and set the provided ContentState as the + * new current content. + */ + static push(editorState: EditorState, contentState: ContentState, changeType: EditorChangeType): EditorState; + + /** + * Make the top ContentState in the undo stack the new current content and + * push the current content onto the redo stack. + */ + static undo(editorState: EditorState): EditorState; + + /** + * Make the top ContentState in the redo stack the new current content and + * push the current content onto the undo stack. + */ + static redo(editorState: EditorState): EditorState; + + toJS(): Object; + getAllowUndo(): boolean; + getCurrentContent(): ContentState; + getUndoStack(): Immutable.Stack; + getRedoStack(): Immutable.Stack; + getSelection(): SelectionState; + getDecorator(): DraftDecoratorType; + isInCompositionMode(): boolean; + mustForceSelection(): boolean; + getNativelyRenderedContent(): ContentState; + getLastChangeType(): EditorChangeType; + + /** + * While editing, the user may apply inline style commands with a collapsed + * cursor, intending to type text that adopts the specified style. In this + * case, we track the specified style as an "override" that takes precedence + * over the inline style of the text adjacent to the cursor. + * + * If null, there is no override in place. + */ + getInlineStyleOverride(): DraftInlineStyle; + + static setInlineStyleOverride(editorState: EditorState, inlineStyleOverride: DraftInlineStyle): EditorState; + + /** + * Get the appropriate inline style for the editor state. If an + * override is in place, use it. Otherwise, the current style is + * based on the location of the selection state. + */ + getCurrentInlineStyle(): DraftInlineStyle; + + getBlockTree(blockKey: string): Immutable.List; + isSelectionAtStartOfContent(): boolean; + isSelectionAtEndOfContent(): boolean; + getDirectionMap(): Immutable.OrderedMap; + } + + class ContentBlock extends Record { + getKey(): string; + + getType(): DraftBlockType; + getType(): string; + + getText(): string; + getCharacterList(): Immutable.List; + getLength(): number; + getDepth(): number; + getData(): Immutable.Map; + getInlineStyleAt(offset: number): DraftInlineStyle; + getEntityAt(offset: number): string; + + /** + * Execute a callback for every contiguous range of styles within the block. + */ + findStyleRanges(filterFn: (value: CharacterMetadata) => boolean, callback: (start: number, end: number) => void): void; + + /** + * Execute a callback for every contiguous range of entities within the block. + */ + findEntityRanges(filterFn: (value: CharacterMetadata) => boolean, callback: (start: number, end: number) => void): void; + } + + class ContentState extends Record { + static createFromBlockArray(blocks: Array): ContentState; + static createFromText(text: string, delimiter?: string): ContentState; + + getBlockMap(): BlockMap; + getSelectionBefore(): SelectionState; + getSelectionAfter(): SelectionState; + getBlockForKey(key: string): ContentBlock; + + getKeyBefore(key: string): string; + getKeyAfter(key: string): string; + getBlockAfter(key: string): ContentBlock; + getBlockBefore(key: string): ContentBlock; + + getBlocksAsArray(): Array; + getFirstBlock(): ContentBlock; + getLastBlock(): ContentBlock; + getPlainText(delimiter?: string): string; + hasText(): boolean; + } + + class SelectionState extends Record { + static createEmpty(key: string): SelectionState; + + serialize(): string; + getAnchorKey(): string; + getAnchorOffset(): number; + getFocusKey(): string; + getFocusOffset(): number; + getIsBackward(): boolean; + getHasFocus(): boolean; + /** + * Return whether the specified range overlaps with an edge of the + * SelectionState. + */ + hasEdgeWithin(blockKey: string, start: number, end: number): boolean; + isCollapsed(): boolean; + getStartKey(): string; + getStartOffset(): number; + getEndKey(): string; + getEndOffset(): number; + } + + class CharacterMetadata { + static applyStyle(record: CharacterMetadata, style: string): CharacterMetadata; + static removeStyle(record: CharacterMetadata, style: string): CharacterMetadata; + static applyEntity(record: CharacterMetadata, entityKey: string): CharacterMetadata; + static applyEntity(record: CharacterMetadata): CharacterMetadata; + /** + * Use this function instead of the `CharacterMetadata` constructor. + * Since most content generally uses only a very small number of + * style/entity permutations, we can reuse these objects as often as + * possible. + */ + static create(config?: CharacterMetadataConfig): CharacterMetadata; + static create(): CharacterMetadata; + + getStyle(): DraftInlineStyle; + getEntity(): string; + hasStyle(style: string): boolean; + } + + interface CharacterMetadataConfig { + style?: DraftInlineStyle; + entity?: string; + } + + type EditorChangeType = ( + "adjust-depth" | + "apply-entity" | + "backspace-character" | + "change-block-data" | + "change-block-type" | + "change-inline-style" | + "delete-character" | + "insert-characters" | + "insert-fragment" | + "redo" | + "remove-range" | + "spellcheck-change" | + "split-block" | + "undo" + ) + + interface BlockMapBuilder { + createFromArray(blocks: Array): BlockMap; + } + + const DefaultDraftBlockRenderMap: Immutable.Map; + const DefaultDraftInlineStyle: Immutable.Map; + } + + namespace Keys { + function generateRandomKey(): string; + } + + namespace Modifier { + import EditorState = Draft.Model.ImmutableData.EditorState; + import ContentState = Draft.Model.ImmutableData.ContentState; + import SelectionState = Draft.Model.ImmutableData.SelectionState; + + import BlockMap = Draft.Model.ImmutableData.BlockMap; + import DraftInlineStyle = Draft.Model.ImmutableData.DraftInlineStyle; + + import DraftRemovalDirection = Draft.Model.Constants.DraftRemovalDirection; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + + import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; + + type URI = any; + + interface AtomicBlockUtils { + insertAtomicBlock(editorState: EditorState, entityKey: string, character: string): EditorState; + } + + /** + * `DraftModifier` provides a set of convenience methods that apply + * modifications to a `ContentState` object based on a target `SelectionState`. + * + * Any change to a `ContentState` should be decomposable into a series of + * transaction functions that apply the required changes and return output + * `ContentState` objects. + * + * These functions encapsulate some of the most common transaction sequences. + */ + class DraftModifier { + static replaceText(contentState: ContentState, rangeToReplace: SelectionState, text: string, inlineStyle?: DraftInlineStyle, entityKey?: string): ContentState; + static insertText(contentState: ContentState, targetRange: SelectionState, text: string, inlineStyle?: DraftInlineStyle, entityKey?: string): ContentState; + static moveText(contentState: ContentState, removalRange: SelectionState, targetRange: SelectionState): ContentState; + static replaceWithFragment(contentState: ContentState, targetRange: SelectionState, fragment: BlockMap): ContentState; + + static removeRange(contentState: ContentState, rangeToRemove: SelectionState, removalDirection: DraftRemovalDirection): ContentState; + + static splitBlock(contentState: ContentState, selectionState: SelectionState): ContentState; + static applyInlineStyle(contentState: ContentState, selectionState: SelectionState, inlineStyle: string): ContentState; + static removeInlineStyle(contentState: ContentState, selectionState: SelectionState, inlineStyle: string): ContentState; + + static setBlockType(contentState: ContentState, selectionState: SelectionState, blockType: DraftBlockType): ContentState; + static setBlockType(contentState: ContentState, selectionState: SelectionState, blockType: string): ContentState; + + static setBlockData(contentState: ContentState, selectionState: SelectionState, blockData: Immutable.Map): ContentState; + static mergeBlockData(contentState: ContentState, selectionState: SelectionState, blockData: Immutable.Map): ContentState; + static applyEntity(contentState: ContentState, selectionState: SelectionState, entityKey: string): ContentState; + } + + class RichTextEditorUtil { + static currentBlockContainsLink(editorState: EditorState): boolean; + static getCurrentBlockType(editorState: EditorState): DraftBlockType; + static getCurrentBlockType(editorState: EditorState): string; + static getDataObjectForLinkURL(uri: URI): Object; + + static handleKeyCommand(editorState: EditorState, command: DraftEditorCommand): EditorState; + static handleKeyCommand(editorState: EditorState, command: string): EditorState; + + static insertSoftNewline(editorState: EditorState): EditorState; + + /** + * For collapsed selections at the start of styled blocks, backspace should + * just remove the existing style. + */ + static onBackspace(editorState: EditorState): EditorState; + static onDelete(editorState: EditorState): EditorState; + static onTab(event: SyntheticKeyboardEvent, editorState: EditorState, maxDepth: number): EditorState; + + static toggleBlockType(editorState: EditorState, blockType: DraftBlockType): EditorState; + static toggleBlockType(editorState: EditorState, blockType: string): EditorState; + + static toggleCode(editorState: EditorState): EditorState; + + /** + * Toggle the specified inline style for the selection. If the + * user's selection is collapsed, apply or remove the style for the + * internal state. If it is not collapsed, apply the change directly + * to the document state. + */ + static toggleInlineStyle(editorState: EditorState, inlineStyle: string): EditorState; + + static toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState; + + /** + * When a collapsed cursor is at the start of an empty styled block, allow + * certain key commands (newline, backspace) to simply change the + * style of the block instead of the default behavior. + */ + static tryToRemoveBlockStyle(editorState: EditorState): ContentState; + } + } } - - interface CompositeDecorator { - getDecorations(): Array, - getComponentForKey(): any, - getPropsForKey(): any - } - - interface Entity { - create(type: string, mutability: string, data?: Object): EntityInstance, - add(instance: EntityInstance): string, - get(key: string): EntityInstance, - mergeData(key: string, toMerge: any): EntityInstance, - replaceData(key: string, newData: any): EntityInstance - } - - interface EntityInstance { - getData(): any, - getKey(): string, - getMutability(): string - } - - interface BlockMapBuilder { - createFromArray(blocks: Array): BlockMap - } - - interface CharacterMetadata { - create(config?: any): CharacterMetadata, - - applyStyle(record: CharacterMetadata, - style: string): CharacterMetadata, - - removeStyle(record: CharacterMetadata, - style: string): CharacterMetadata, - - applyEntity(record: CharacterMetadata, - entityKey?: string): CharacterMetadata, - - getStyle(): any, - hasStyle(style: string): boolean, - - getEntity(): string - } - - interface IContentBlock { - new (draftContentBlock: any): ContentBlock; - } - interface ContentBlock { - key: string, - type: string, - text: string, - characterList: any, - depth: number, - - getKey(): string, - getType(): string, - getText(): string, - getCharacterList(): any, - getLength(): number, - getDepth(): number, - getInlineStyleAt(offset: number): any, - getEntityAt(offset: number): string, - findStyleRanges(filterFn: Function, callback: Function): void, - findEntityRanges(filterFn: Function, callback: Function): void - - } - - interface ContentState { - createFromText(text: string): ContentState, - createFromBlockArray(blocks: Array): ContentState, - - getBlockMap(): BlockMap, - getSelectionBefore(): SelectionState, - getSelectionAfter(): SelectionState, - - getBlockForKey(key: string): ContentBlock, - getKeyBefore(key: string): string, - getKeyAfter(key: string): string, - - getBlockBefore(key: string): ContentBlock, - getBlockAfter(key: string): ContentBlock, - - getBlocksAsArray(): Array, - - getPlainText(): string, - hasText(): boolean, - - set(key: string, value: any): ContentState, - toJS(): any - } - - interface ISelectionState { - new (draftSelectionState: any): SelectionState; - createEmpty(blockKey: string): SelectionState; - } - - interface SelectionState { - getStartKey(): string, - getStartOffset(): number, - getEndKey(): string, - getEndOffset(): number, - getAnchorKey(): string, - getAnchorOffset(): number, - getFocusKey(): string, - getFocusOffset(): number, - - getIsBackward(): boolean, - getHasFocus(): boolean, - isCollapsed(): boolean, - - hasEdgeWithin(blockKey: string, start: number, end: number): boolean, - serialize(): string, - - get(key: string): any, - set(key: string, value: any): SelectionState - } - - interface BlockMap { - get(key: string): ContentBlock, - set(key: string, value: any): BlockMap, - delete(key: string): BlockMap, - find(cb: any): ContentBlock - } - - interface Modifier { - replaceText(contentState: ContentState, - rangeToReplace: SelectionState, - text: string, - inlineStyle?: any, - entityKey?: string): ContentState, - - insertText(contentState: ContentState, - targetRange: SelectionState, - text: string, - inlineStyle?: any, - entityKey?: string): ContentState, - - moveText(contentState: ContentState, - removalRange: SelectionState, - targetRange: SelectionState): ContentState, - - replaceWithFragment(contentState: ContentState, - targetRange: SelectionState, - fragment: BlockMap): ContentState, - - removeRange(contentState: ContentState, - rangeToRemove: SelectionState, - removalDirection: string): ContentState, - - splitBlock(contentState: ContentState, - selectionState: SelectionState): ContentState, - - applyInlineStyle(contentState: ContentState, - selectionState: SelectionState, - inlineStyle: string): ContentState, - - removeInlineStyle(contentState: ContentState, - selectionState: SelectionState, - inlineStyle: string): ContentState, - - setBlockType(contentState: ContentState, - selectionState: SelectionState, - blockType: string): ContentState, - - applyEntity(contentState: ContentState, - selectionState: SelectionState, - entityKey: string): ContentState - } - - interface RichUtils { - currentBlockContainsLink(editorState: EditorState): boolean, - getCurrentBlockType(editor: EditorState): string, - handleKeyCommand(editorState: EditorState, command: string): any, - insertSoftNewline(editorState: EditorState): EditorState, - onBackspace(editorState: EditorState): EditorState, - onDelete(editorState: EditorState): EditorState, - onTab(event: Event, editorState: EditorState, maxDepth: number): EditorState, - toggleBlockType(editorState: EditorState, blockType: string): EditorState, - toggleCode(editorState: EditorState): EditorState, - toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState, - tryToRemoveBlockStyle(editorState: EditorState): EditorState - } - - interface EditorProps { - editorState: EditorState, - onChange(editorState: EditorState): void, - - placeholder?: string, - textAlignment?: any, - blockRendererFn?: (ContentBlock: ContentBlock) => any, - blockStyleFn?: (ContentBlock: ContentBlock) => string, - customStyleMap?: any, - - readOnly?: boolean, - spellCheck?: boolean, - stripPastedStyles?: boolean, - - handleReturn?: (e: any) => boolean, - handleKeyCommand?: (command: string) => boolean, - handleBeforeInput?: (chars: string) => boolean, - handlePastedFiles?: (files: Array) => boolean, - handleDroppedFiles?: (selection: SelectionState, files: Array) => boolean, - handleDrop?: (selection: SelectionState, dataTransfer: any, isInternal: any) => boolean, - - onEscape?: (e: any) => void, - onTab?: (e: any) => void, - onUpArrow?: (e: any) => void, - onDownArrow?: (e: any) => void, - - suppressContentEditableWarning?: any, - - onBlur?: (e: any) => void, - onFocus?: (e: any) => void - } - - interface Editor { - props: EditorProps - state: any, - refs: any, - context: any, - setState(): any, - render(): any, - forceUpdate(): any - } - - var Editor: IEditor; - var EditorState: EditorState; - - var CompositeDecorator: CompositeDecorator; - var Entity: Entity; - var EntityInstance: EntityInstance; - - var BlockMapBuilder: BlockMapBuilder; - var CharacterMetadata: CharacterMetadata; - var ContentBlock: IContentBlock; - var ContentState: ContentState; - var SelectionState: ISelectionState; - - var Modifier: Modifier; - var RichUtils: RichUtils; - - function convertFromRaw(rawState: any): Array; - - function convertToRaw(contentState: ContentState): any; - - function genKey(): string } -export = Draft; +import Editor = Draft.Component.Base.DraftEditor; +import EditorBlock = Draft.Component.Components.DraftEditorBlock; +import EditorState = Draft.Model.ImmutableData.EditorState; + +import CompositeDecorator = Draft.Model.Decorators.CompositeDraftDecorator; +import Entity = Draft.Model.Entity.DraftEntity; +import EntityInstance = Draft.Model.Entity.DraftEntityInstance; + +import BlockMapBuilder = Draft.Model.ImmutableData.BlockMapBuilder; +import CharacterMetadata = Draft.Model.ImmutableData.CharacterMetadata; +import ContentBlock = Draft.Model.ImmutableData.ContentBlock; +import ContentState = Draft.Model.ImmutableData.ContentState; +import SelectionState = Draft.Model.ImmutableData.SelectionState; + +import AtomicBlockUtils = Draft.Model.Modifier.AtomicBlockUtils; +import KeyBindingUtil = Draft.Component.Utils.KeyBindingUtil; +import Modifier = Draft.Model.Modifier.DraftModifier; +import RichUtils = Draft.Model.Modifier.RichTextEditorUtil; + +import DefaultDraftBlockRenderMap = Draft.Model.ImmutableData.DefaultDraftBlockRenderMap; +import DefaultDraftInlineStyle = Draft.Model.ImmutableData.DefaultDraftInlineStyle; + +import convertFromHTML = Draft.Model.Encoding.convertFromHTMLtoContentBlocks; +import convertFromRaw = Draft.Model.Encoding.convertFromRawToDraftState; +import convertToRaw = Draft.Model.Encoding.convertFromDraftStateToRaw; +import genKey = Draft.Model.Keys.generateRandomKey; +import getDefaultKeyBinding = Draft.Component.Utils.getDefaultKeyBinding; +import getVisibleSelectionRect = Draft.Component.Selection.getVisibleSelectionRect; + +export { + Editor, + EditorBlock, + EditorState, + + CompositeDecorator, + Entity, + EntityInstance, + + BlockMapBuilder, + CharacterMetadata, + ContentBlock, + ContentState, + SelectionState, + + AtomicBlockUtils, + KeyBindingUtil, + Modifier, + RichUtils, + + DefaultDraftBlockRenderMap, + DefaultDraftInlineStyle, + + convertFromHTML, + convertFromRaw, + convertToRaw, + genKey, + getDefaultKeyBinding, + getVisibleSelectionRect +}; diff --git a/durandal/index.d.ts b/durandal/index.d.ts index d85c155043..1ea8939608 100644 --- a/durandal/index.d.ts +++ b/durandal/index.d.ts @@ -693,6 +693,7 @@ declare module 'plugins/dialog' { } interface Dialog { + host: HTMLElement; owner: any; context: DialogContext; activator: DurandalActivator; diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index 5b7ba8055c..d32b2a8845 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -38,6 +38,8 @@ declare module Elasticsearch { create(params: IndicesCreateParams): PromiseLike; exists(params: IndicesIndexExitsParams, callback: (error: any, response: any, status: any) => void): void; exists(params: IndicesIndexExitsParams): PromiseLike; + existsType(params: IndicesIndexExitsParams & {type: string}, callback: (error: any, response: any, status: any) => void): void; + existsType(params: IndicesIndexExitsParams & {type: string}): PromiseLike; get(params: IndicesGetParams, callback: (error: any, response: any, status: any) => void): void; get(params: IndicesGetParams): PromiseLike; getAlias(params: IndicesGetAliasParams, callback: (error: any, response: any, status: any) => void): void; @@ -46,6 +48,8 @@ declare module Elasticsearch { putAlias(params: IndicesPutAliasParams): PromiseLike; putTemplate(params: IndicesPutTemplateParams, callback: (error: any, response: any) => void): void; putTemplate(params: IndicesPutTemplateParams): PromiseLike; + putMapping(params: IndicesPutMappingParams, callback: (error: any, response: any) => void): void; + putMapping(params: IndicesPutMappingParams): PromiseLike; refresh(params: IndicesRefreshParams, callback: (error: any, response: any) => void): void; refresh(params: IndicesRefreshParams): PromiseLike; } @@ -125,10 +129,21 @@ declare module Elasticsearch { body: string | any; } + export interface IndicesPutMappingParams extends GenericParams { + timeout?: Date | number; + masterTimeout?: Date | number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: "open" | "closed" | "none" | "all"; + updateAllTypes?: boolean; + index: string | string[] | boolean; + type: string; + } + export interface IndicesGetAliasParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; - expandWildcards?: string; + expandWildcards?: "open" | "closed" | "none" | "all"; local?: boolean; index?: string | string[] | boolean; name: string | string[] | boolean; @@ -260,7 +275,7 @@ declare module Elasticsearch { export interface SuggestParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; - expandWildcards?: string; + expandWildcards?: "open" | "closed" | "none" | "all"; preference?: string; routing?: string; source?: string; diff --git a/electron/github-electron-main-tests.ts b/electron/github-electron-main-tests.ts index b3990e817e..47833e6a50 100644 --- a/electron/github-electron-main-tests.ts +++ b/electron/github-electron-main-tests.ts @@ -96,6 +96,7 @@ app.on('ready', () => { mainWindow.webContents.executeJavaScript('return true;', true); mainWindow.webContents.executeJavaScript('return true;', true, (result: boolean) => console.log(result)); mainWindow.webContents.insertText('blah, blah, blah'); + mainWindow.webContents.startDrag({file: '/path/to/img.png', icon: nativeImage.createFromPath('/path/to/icon.png')}); mainWindow.webContents.findInPage('blah'); mainWindow.webContents.findInPage('blah', { forward: true, @@ -133,6 +134,12 @@ app.on('ready', () => { }); mainWindow.webContents.debugger.sendCommand("Network.enable"); + mainWindow.webContents.capturePage(image => { + console.log(image.toDataURL()); + }); + mainWindow.webContents.capturePage({width: 100, height: 200}, image => { + console.log(image.toPNG()); + }); }); app.commandLine.appendSwitch('enable-web-bluetooth'); @@ -220,6 +227,7 @@ app.dock.setBadge('foo'); var id = app.dock.bounce('informational'); app.dock.cancelBounce(id); app.dock.setIcon('/path/to/icon.png'); +app.dock.setBadgeCount(app.dock.getBadgeCount() + 1); app.setUserTasks([ { @@ -232,6 +240,12 @@ app.setUserTasks([ } ]); app.setUserTasks([]); +if (app.isUnityRunning()) { +} +if (app.isAccessibilitySupportEnabled()) { +} +app.setLoginItemSettings({openAtLogin: true, openAsHidden: false}); +console.log(app.getLoginItemSettings().wasOpenedAtLogin); var window = new BrowserWindow(); window.setProgressBar(0.5); @@ -247,6 +261,7 @@ app.on('ready', () => { onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false }); onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`); }); +app.on('accessibility-support-changed', (_, enabled) => console.log('accessibility: ' + enabled)); ipcMain.on('online-status-changed', (event: any, status: any) => { console.log(status); @@ -429,6 +444,14 @@ ipcMain.on('synchronous-message', (event: Electron.IpcMainEvent, arg: any) => { event.returnValue = 'pong'; }); +var winWindows = new BrowserWindow({ + width: 800, + height: 600, + show: false, + thickFrame: false, + type: 'toolbar', +}); + // menu-item // https://github.com/atom/electron/blob/master/docs/api/menu-item.md @@ -700,8 +723,11 @@ app.on('ready', () => { clipboard.writeText('Example String'); clipboard.writeText('Example String', 'selection'); +clipboard.writeBookmark('foo', 'http://example.com'); +clipboard.writeBookmark('foo', 'http://example.com', 'selection'); console.log(clipboard.readText('selection')); console.log(clipboard.availableFormats()); +console.log(clipboard.readBookmark().title); clipboard.clear(); clipboard.write({ diff --git a/electron/github-electron-renderer-tests.ts b/electron/github-electron-renderer-tests.ts index 6c001ede63..e70b660073 100644 --- a/electron/github-electron-renderer-tests.ts +++ b/electron/github-electron-renderer-tests.ts @@ -250,6 +250,7 @@ webview.addEventListener('ipc-message', function(event) { console.log(event.channel); // Prints "pong" }); webview.send('ping'); +webview.capturePage((image) => { console.log(image); }); // In guest page. ipcRenderer.on('ping', function() { diff --git a/electron/index.d.ts b/electron/index.d.ts index ce3e4a0520..7235de7fbb 100644 --- a/electron/index.d.ts +++ b/electron/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.2.5 +// Type definitions for Electron v1.2.7 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -160,6 +160,12 @@ declare namespace Electron { * Emitted when the gpu process crashes. */ on(event: 'gpu-process-crashed', listener: Function): this; + /** + * Emitted when Chrome's accessibility support changes. + * + * Note: This API is only available on macOS and Windows. + */ + on(event: 'accessibility-support-changed', listener: (event: Event, accessibilitySupportEnabled: boolean) => void): this; on(event: string, listener: Function): this; /** * Try to close all windows. The before-quit event will first be emitted. @@ -341,6 +347,33 @@ declare namespace Electron { * This method can only be called before app is ready. */ disableHardwareAcceleration(): void; + /** + * @returns whether current desktop environment is Unity launcher. (Linux) + * + * Note: This API is only available on Linux. + */ + isUnityRunning(): boolean; + /** + * Returns a Boolean, true if Chrome's accessibility support is enabled, false otherwise. + * This API will return true if the use of assistive technologies, such as screen readers, + * has been detected. + * See https://www.chromium.org/developers/design-documents/accessibility for more details. + * + * Note: This API is only available on macOS and Windows. + */ + isAccessibilitySupportEnabled(): boolean; + /** + * @returns an Object with the login item settings of the app. + * + * Note: This API is only available on macOS and Windows. + */ + getLoginItemSettings(): LoginItemSettings; + /** + * Set the app's login item settings. + * + * Note: This API is only available on macOS and Windows. + */ + setLoginItemSettings(settings: LoginItemSettings): void; commandLine: CommandLine; /** * Note: This API is only available on macOS. @@ -414,6 +447,20 @@ declare namespace Electron { * Note: This API is only available on macOS. */ getBadge(): string; + /** + * Sets the counter badge for current app. Setting the count to 0 will hide the badge. + * + * @returns True when the call succeeded, otherwise returns false. + * + * Note: This API is only available on macOS and Linux. + */ + setBadgeCount(count: number): boolean; + /** + * @returns The current value displayed in the counter badge. + * + * Note: This API is only available on macOS and Linux. + */ + getBadgeCount(): number; /** * Hides the dock icon. * @@ -472,6 +519,32 @@ declare namespace Electron { iconIndex?: number; } + interface LoginItemSettings { + /** + * True if the app is set to open at login. + */ + openAtLogin: boolean; + /** + * True if the app is set to open as hidden at login. This setting is only supported on macOS. + */ + openAsHidden: boolean; + /** + * True if the app was opened at login automatically. This setting is only supported on macOS. + */ + wasOpenedAtLogin?: boolean; + /** + * True if the app was opened as a hidden login item. This indicates that the app should not + * open any windows at startup. This setting is only supported on macOS. + */ + wasOpenedAsHidden?: boolean; + /** + * True if the app was opened as a login item that should restore the state from the previous session. + * This indicates that the app should restore the windows that were open the last time the app was closed. + * This setting is only supported on macOS. + */ + restoreState?: boolean; + } + // https://github.com/electron/electron/blob/master/docs/api/auto-updater.md /** @@ -968,6 +1041,13 @@ declare namespace Electron { * @param callback Supplies the image that stores data of the snapshot. */ capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; + /** + * Captures the snapshot of page within rect, upon completion the callback + * will be called. Omitting the rect would capture the whole visible page. + * Note: Be sure to read documents on remote buffer in remote if you are going + * to use this API in renderer process. + * @param callback Supplies the image that stores data of the snapshot. + */ capturePage(callback: (image: NativeImage) => void): void; /** * Same as webContents.loadURL(url). @@ -1458,15 +1538,20 @@ declare namespace Electron { * The style of window title bar. */ titleBarStyle?: 'default' | 'hidden' | 'hidden-inset'; + /** + * Use WS_THICKFRAME style for frameless windows on Windows + */ + thickFrame?: boolean; /** * Settings of web page’s features. */ webPreferences?: WebPreferences; } - type BrowserWindowType = BrowserWindowTypeLinux | BrowserWindowTypeMac; + type BrowserWindowType = BrowserWindowTypeLinux | BrowserWindowTypeMac | BrowserWindowTypeWindows; type BrowserWindowTypeLinux = 'desktop' | 'dock' | 'toolbar' | 'splash' | 'notification'; type BrowserWindowTypeMac = 'desktop' | 'textured'; + type BrowserWindowTypeWindows = 'toolbar'; interface Rectangle { x?: number; @@ -1541,10 +1626,27 @@ declare namespace Electron { html?: string; image?: NativeImage; }, type?: ClipboardType): void; + /** + * @returns An Object containing title and url keys representing the bookmark in the clipboard. + * + * Note: This API is available on macOS and Windows. + */ + readBookmark(): Bookmark; + /** + * Writes the title and url into the clipboard as a bookmark. + * + * Note: This API is available on macOS and Windows. + */ + writeBookmark(title: string, url: string, type?: ClipboardType): void; } type ClipboardType = '' | 'selection'; + interface Bookmark { + title: string; + url: string; + } + // https://github.com/electron/electron/blob/master/docs/api/content-tracing.md /** @@ -1836,7 +1938,7 @@ declare namespace Electron { /** * Contains which features the dialog should use. */ - properties?: ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory')[]; + properties?: ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory' | 'showHiddenFiles')[]; } interface SaveDialogOptions { @@ -3292,6 +3394,17 @@ declare namespace Electron { metaKey: boolean; } + interface DragItem { + /** + * The absolute path of the file to be dragged + */ + file: string; + /** + * The image showing under the cursor when dragging. + */ + icon: NativeImage; + } + // https://github.com/electron/electron/blob/master/docs/api/web-contents.md /** @@ -3739,16 +3852,12 @@ declare namespace Electron { * Begin subscribing for presentation events and captured frames, * The callback will be called when there is a presentation event. */ - beginFrameSubscription(callback: ( + beginFrameSubscription(onlyDirty: boolean, callback: BeginFrameSubscriptionCallback): void; /** - * The frameBuffer is a Buffer that contains raw pixel data. - * On most machines, the pixel data is effectively stored in 32bit BGRA format, - * but the actual representation depends on the endianness of the processor - * (most modern processors are little-endian, on machines with big-endian - * processors the data is in 32bit ARGB format). + * Begin subscribing for presentation events and captured frames, + * The callback will be called when there is a presentation event. */ - frameBuffer: Buffer - ) => void): void; + beginFrameSubscription(callback: BeginFrameSubscriptionCallback): void; /** * End subscribing for frame presentation events. */ @@ -3762,6 +3871,18 @@ declare namespace Electron { * Note: This API is available only on macOS. */ showDefinitionForSelection(): void; + /** + * Sets the item as dragging item for current drag-drop operation. + */ + startDrag(item: DragItem): void; + /** + * Captures a snapshot of the page within rect. + */ + capturePage(callback: (image: NativeImage) => void): void; + /** + * Captures a snapshot of the page within rect. + */ + capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; /** * @returns The unique ID of this WebContents. */ @@ -3786,6 +3907,24 @@ declare namespace Electron { debugger: Debugger; } + interface BeginFrameSubscriptionCallback { + ( + /** + * The frameBuffer is a Buffer that contains raw pixel data. + * On most machines, the pixel data is effectively stored in 32bit BGRA format, + * but the actual representation depends on the endianness of the processor + * (most modern processors are little-endian, on machines with big-endian + * processors the data is in 32bit ARGB format). + */ + frameBuffer: Buffer, + /** + * The dirtyRect is an object with x, y, width, height properties that describes which part of the page was repainted. + * If onlyDirty is set to true, frameBuffer will only contain the repainted area. onlyDirty defaults to false. + */ + dirtyRect?: Bounds + ): void + } + interface ContextMenuParams { /** * x coordinate @@ -3825,76 +3964,76 @@ declare namespace Electron { */ mediaFlags: { /** - * Wether the media element has crashed. + * Whether the media element has crashed. */ inError: boolean; /** - * Wether the media element is paused. + * Whether the media element is paused. */ isPaused: boolean; /** - * Wether the media element is muted. + * Whether the media element is muted. */ isMuted: boolean; /** - * Wether the media element has audio. + * Whether the media element has audio. */ hasAudio: boolean; /** - * Wether the media element is looping. + * Whether the media element is looping. */ isLooping: boolean; /** - * Wether the media element's controls are visible. + * Whether the media element's controls are visible. */ isControlsVisible: boolean; /** - * Wether the media element's controls are toggleable. + * Whether the media element's controls are toggleable. */ canToggleControls: boolean; /** - * Wether the media element can be rotated. + * Whether the media element can be rotated. */ canRotate: boolean; } /** - * Wether the context menu was invoked on an image which has non-empty contents. + * Whether the context menu was invoked on an image which has non-empty contents. */ hasImageContents: boolean; /** - * Wether the context is editable. + * Whether the context is editable. */ isEditable: boolean; /** - * These flags indicate wether the renderer believes it is able to perform the corresponding action. + * These flags indicate whether the renderer believes it is able to perform the corresponding action. */ editFlags: { /** - * Wether the renderer believes it can undo. + * Whether the renderer believes it can undo. */ canUndo: boolean; /** - * Wether the renderer believes it can redo. + * Whether the renderer believes it can redo. */ canRedo: boolean; /** - * Wether the renderer believes it can cut. + * Whether the renderer believes it can cut. */ canCut: boolean; /** - * Wether the renderer believes it can copy + * Whether the renderer believes it can copy */ canCopy: boolean; /** - * Wether the renderer believes it can paste. + * Whether the renderer believes it can paste. */ canPaste: boolean; /** - * Wether the renderer believes it can delete. + * Whether the renderer believes it can delete. */ canDelete: boolean; /** - * Wether the renderer believes it can select all. + * Whether the renderer believes it can select all. */ canSelectAll: boolean; } @@ -4556,6 +4695,14 @@ declare namespace Electron { * @returns The WebContents associated with this webview. */ getWebContents(): WebContents; + /** + * Captures a snapshot of the webview's page. Same as webContents.capturePage([rect, ]callback). + */ + capturePage(callback: (image: NativeImage) => void): void; + /** + * Captures a snapshot of the webview's page. Same as webContents.capturePage([rect, ]callback). + */ + capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; /** * Fired when a load has committed. This includes navigation within the current document * as well as subframe document-level loads, but does not include asynchronous resource loads. diff --git a/enzyme/enzyme-tests.tsx b/enzyme/enzyme-tests.tsx index fcab99ddf5..b8811d80b4 100644 --- a/enzyme/enzyme-tests.tsx +++ b/enzyme/enzyme-tests.tsx @@ -1,12 +1,9 @@ - -/// - +/* import { shallow, mount, render, describeWithDOM, spyLifecycle } from "enzyme"; import * as React from "react"; import {Component, ReactElement, HTMLAttributes} from "react"; import {ShallowWrapper, ReactWrapper, CheerioWrapper} from "enzyme"; - // Help classes/interfaces interface MyComponentProps { propsProperty: any; @@ -42,13 +39,23 @@ namespace ShallowWrapperTest { objectVal: Object, boolVal: Boolean, stringVal: String, - elementWrapper: ShallowWrapper, {}> + elementWrapper: ShallowWrapper + + function test_shallow_options() { + shallow(, { + context: { + test: "a", + }, + lifecycleExperimental: true + }); + } function test_find() { elementWrapper = shallowWrapper.find('.selector'); shallowWrapper = shallowWrapper.find(MyComponent); shallowWrapper.find(MyStatelessComponent).props().stateless; shallowWrapper.find(MyStatelessComponent).shallow(); + shallowWrapper.find({ prop: 'value' }); } function test_findWhere() { @@ -59,6 +66,7 @@ namespace ShallowWrapperTest { function test_filter() { elementWrapper = shallowWrapper.filter('.selector'); shallowWrapper = shallowWrapper.filter(MyComponent).shallow(); + shallowWrapper.filter({ prop: 'val' }); } function test_filterWhere() { @@ -108,6 +116,7 @@ namespace ShallowWrapperTest { function test_children() { shallowWrapper = shallowWrapper.children(); shallowWrapper.children(MyStatelessComponent).props().stateless; + shallowWrapper.children({ prop: 'myprop' }); } function test_childAt() { @@ -135,6 +144,7 @@ namespace ShallowWrapperTest { function test_closest() { elementWrapper = shallowWrapper.closest('.selector'); shallowWrapper = shallowWrapper.closest(MyComponent); + shallowWrapper = shallowWrapper.closest({ prop: 'myprop' }); } function test_shallow() { @@ -277,6 +287,10 @@ namespace ShallowWrapperTest { function test_everyWhere() { boolVal = shallowWrapper.everyWhere((aShallowWrapper: ShallowWrapper) => true); } + + function test_isEmptyRender() { + boolVal = shallowWrapper.isEmptyRender(); + } } @@ -289,7 +303,7 @@ namespace ReactWrapperTest { objectVal: Object, boolVal: Boolean, stringVal: String, - elementWrapper: ReactWrapper, {}> + elementWrapper: ReactWrapper function test_unmount() { reactWrapper = reactWrapper.unmount(); @@ -297,30 +311,38 @@ namespace ReactWrapperTest { function test_mount() { reactWrapper = reactWrapper.mount(); + + mount(, { + attachTo: document.getElementById('test'), + context: { + a: "b" + } + }); } function test_ref() { reactWrapper = reactWrapper.ref('refName'); - + interface TmpType1 { foo: string } - + interface TmpType2 { bar: string } - + const tmp: ReactWrapper = reactWrapper.ref('refName'); } - + function test_detach() { reactWrapper.detach(); } - + function test_find() { elementWrapper = reactWrapper.find('.selector'); reactWrapper = reactWrapper.find(MyComponent); reactWrapper.find(MyStatelessComponent).props().stateless; + reactWrapper.find({ prop: 'myprop' }); } function test_findWhere() { @@ -331,6 +353,7 @@ namespace ReactWrapperTest { function test_filter() { elementWrapper = reactWrapper.filter('.selector'); reactWrapper = reactWrapper.filter(MyComponent); + reactWrapper = reactWrapper.filter({ prop: 'myprop' }); } function test_filterWhere() { @@ -406,6 +429,7 @@ namespace ReactWrapperTest { function test_closest() { elementWrapper = reactWrapper.closest('.selector'); reactWrapper = reactWrapper.closest(MyComponent); + reactWrapper = reactWrapper.closest({ prop: 'myprop' }); } function test_text() { @@ -535,6 +559,9 @@ namespace ReactWrapperTest { function test_everyWhere() { boolVal = reactWrapper.everyWhere((aReactWrapper: ReactWrapper) => true); } + function test_isEmptyRender() { + boolVal = reactWrapper.isEmptyRender(); + } } // CheerioWrapper @@ -546,12 +573,13 @@ namespace CheerioWrapperTest { objectVal: Object, boolVal: Boolean, stringVal: String, - elementWrapper: CheerioWrapper, {}>; + elementWrapper: CheerioWrapper function test_find() { elementWrapper = cheerioWrapper.find('.selector'); cheerioWrapper = cheerioWrapper.find(MyComponent); cheerioWrapper.find(MyStatelessComponent).props().stateless; + cheerioWrapper.find({ prop: 'myprop' }); } function test_findWhere() { @@ -562,6 +590,7 @@ namespace CheerioWrapperTest { function test_filter() { elementWrapper = cheerioWrapper.filter('.selector'); cheerioWrapper = cheerioWrapper.filter(MyComponent); + cheerioWrapper = cheerioWrapper.filter({ prop: 'myprop' }); } function test_filterWhere() { @@ -637,6 +666,7 @@ namespace CheerioWrapperTest { function test_closest() { elementWrapper = cheerioWrapper.closest('.selector'); cheerioWrapper = cheerioWrapper.closest(MyComponent); + cheerioWrapper = cheerioWrapper.closest({ prop: 'myprop' }); } function test_text() { @@ -767,4 +797,4 @@ namespace CheerioWrapperTest { function test_everyWhere() { boolVal = cheerioWrapper.everyWhere((aCheerioWrapper: CheerioWrapper) => true); } -} +}*/ \ No newline at end of file diff --git a/enzyme/index.d.ts b/enzyme/index.d.ts index 1244686e4b..9de785196c 100644 --- a/enzyme/index.d.ts +++ b/enzyme/index.d.ts @@ -1,15 +1,11 @@ -// Type definitions for Enzyme v2.3.0 +// Type definitions for Enzyme v2.4.1 // Project: https://github.com/airbnb/enzyme // Definitions by: Marian Palkus , Cap3 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import { ReactElement, Component, StatelessComponent, ComponentClass, HTMLAttributes } from "react"; - - -import {ReactElement, Component, StatelessComponent, ComponentClass, HTMLAttributes} from "react"; - -export declare class ElementClass extends Component { +export class ElementClass extends Component { } /** @@ -19,8 +15,11 @@ export declare class ElementClass extends Component { * 1. A Valid CSS Selector * 2. A React Component Constructor * 3. A React Component's displayName + * 4. A React Stateless component + * 5. A React component property map */ -export type EnzymeSelector = String | typeof ElementClass; +export type EnzymeSelector = string | StatelessComponent | ComponentClass | { [key: string]: any }; +export type EnzymePropSelector = { [key: string]: any }; interface CommonWrapper { /** @@ -29,13 +28,14 @@ interface CommonWrapper { */ find(component: ComponentClass): CommonWrapper; find(statelessComponent: StatelessComponent): CommonWrapper; - find(selector: string): CommonWrapper, any>; + find(props: EnzymePropSelector): CommonWrapper; + find(selector: string): CommonWrapper, any>; /** * Finds every node in the render tree that returns true for the provided predicate function. * @param predicate */ - findWhere(predicate: (wrapper: CommonWrapper) => Boolean): CommonWrapper; + findWhere(predicate: (wrapper: CommonWrapper) => boolean): CommonWrapper; /** * Removes nodes in the current wrapper that do not match the provided selector. @@ -43,59 +43,60 @@ interface CommonWrapper { */ filter(component: ComponentClass): CommonWrapper; filter(statelessComponent: StatelessComponent): CommonWrapper; - filter(selector: string): CommonWrapper, any>; + filter(props: EnzymePropSelector): CommonWrapper; + filter(selector: string): CommonWrapper, any>; /** * Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true. * @param predicate */ - filterWhere(predicate: (wrapper: this) => Boolean): this; + filterWhere(predicate: (wrapper: this) => boolean): this; /** * Returns whether or not the current wrapper has a node anywhere in it's render tree that looks like the one passed in. * @param node */ - contains(node: ReactElement): Boolean; + contains(node: ReactElement): boolean; /** - * Returns whether or not a given react element exists in the shallow render tree. - * @param node - */ - containsMatchingElement(node: ReactElement): Boolean; + * Returns whether or not a given react element exists in the shallow render tree. + * @param node + */ + containsMatchingElement(node: ReactElement): boolean; - /** - * Returns whether or not all the given react elements exists in the shallow render tree - * @param nodes - */ - containsAllMatchingElements(nodes: ReactElement[]): Boolean; + /** + * Returns whether or not all the given react elements exists in the shallow render tree + * @param nodes + */ + containsAllMatchingElements(nodes: ReactElement[]): boolean; - /** - * Returns whether or not one of the given react elements exists in the shallow render tree. - * @param nodes - */ - containsAnyMatchingElements(nodes: ReactElement[]): Boolean; + /** + * Returns whether or not one of the given react elements exists in the shallow render tree. + * @param nodes + */ + containsAnyMatchingElements(nodes: ReactElement[]): boolean; - /** - * Returns whether or not the current render tree is equal to the given node, based on the expected value. - */ - equals(node: ReactElement): Boolean; + /** + * Returns whether or not the current render tree is equal to the given node, based on the expected value. + */ + equals(node: ReactElement): boolean; - /** - * Returns whether or not a given react element matches the shallow render tree. - */ - matchesElement(node: ReactElement): Boolean; + /** + * Returns whether or not a given react element matches the shallow render tree. + */ + matchesElement(node: ReactElement): boolean; - /** + /** * Returns whether or not the current node has a className prop including the passed in class name. * @param className */ - hasClass(className: String): Boolean; + hasClass(className: string): boolean; /** * Returns whether or not the current node matches a provided selector. * @param selector */ - is(selector: EnzymeSelector): Boolean; + is(selector: EnzymeSelector): boolean; /** * Returns a new wrapper with only the nodes of the current wrapper that don't match the provided selector. @@ -111,17 +112,18 @@ interface CommonWrapper { */ children(component: ComponentClass): CommonWrapper; children(statelessComponent: StatelessComponent): CommonWrapper; - children(selector: string): CommonWrapper, any>; + children(props: EnzymePropSelector): CommonWrapper; + children(selector: string): CommonWrapper, any>; children(): CommonWrapper; /** - * Returns a new wrapper with child at the specified index. - * @param index - */ - childAt(index: Number): CommonWrapper; - childAt(index: Number): CommonWrapper; + * Returns a new wrapper with child at the specified index. + * @param index + */ + childAt(index: number): CommonWrapper; + childAt(index: number): CommonWrapper; - /** + /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. * @@ -130,7 +132,8 @@ interface CommonWrapper { */ parents(component: ComponentClass): CommonWrapper; parents(statelessComponent: StatelessComponent): CommonWrapper; - parents(selector: string): CommonWrapper, any>; + parents(props: EnzymePropSelector): CommonWrapper; + parents(selector: string): CommonWrapper, any>; parents(): CommonWrapper; /** @@ -147,7 +150,8 @@ interface CommonWrapper { */ closest(component: ComponentClass): CommonWrapper; closest(statelessComponent: StatelessComponent): CommonWrapper; - closest(selector: string): CommonWrapper, any>; + closest(props: EnzymePropSelector): CommonWrapper; + closest(selector: string): CommonWrapper, any>; /** * Returns a string of the rendered text of the current render tree. This function should be looked at with @@ -156,14 +160,14 @@ interface CommonWrapper { * * Note: can only be called on a wrapper of a single node. */ - text(): String; + text(): string; /** * Returns a string of the rendered HTML markup of the current render tree. * * Note: can only be called on a wrapper of a single node. */ - html(): String; + html(): string; /** * Returns the node at a given index of the current wrapper. @@ -191,14 +195,14 @@ interface CommonWrapper { * 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] */ - state(key?: String): any; - state(key?: String): T; + state(key?: string): any; + state(key?: string): T; - /** - * Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. - */ - context(key?: String): any; - context(key?: String): T; + /** + * Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. + */ + context(key?: string): any; + context(key?: string): T; /** * Returns the props hash for the current node of the wrapper. @@ -213,14 +217,14 @@ interface CommonWrapper { * NOTE: can only be called on a wrapper of a single node. * @param key */ - prop(key: String): any; - prop(key: String): T; + prop(key: string): any; + prop(key: string): T; - /** - * Returns the key value for the node of the current wrapper. - * NOTE: can only be called on a wrapper of a single node. - */ - key(): String; + /** + * Returns the key value for the node of the current wrapper. + * NOTE: can only be called on a wrapper of a single node. + */ + key(): string; /** * Simulate events. @@ -286,7 +290,7 @@ interface CommonWrapper { * Returns an html-like string of the wrapper for debugging purposes. Useful to print out to the console when * tests are not passing when you expect them to. */ - debug(): String; + debug(): string; /** * Returns the type of the current node of this wrapper. If it's a composite component, this will be the @@ -294,14 +298,14 @@ interface CommonWrapper { * * Note: can only be called on a wrapper of a single node. */ - type(): String | Function; + type(): string | Function; /** - * Returns the name of the current node of the wrapper. - */ - name(): String; + * Returns the name of the current node of the wrapper. + */ + name(): string; - /** + /** * Iterates through each node of the current wrapper and executes the provided function with a wrapper around * the corresponding node passed in as the first argument. * @@ -341,25 +345,25 @@ interface CommonWrapper { * Returns whether or not any of the nodes in the wrapper match the provided selector. * @param selector */ - some(selector: EnzymeSelector): Boolean; + some(selector: EnzymeSelector): boolean; /** * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. * @param fn */ - someWhere(fn: (wrapper: this) => Boolean): Boolean; + someWhere(fn: (wrapper: this) => boolean): boolean; /** * Returns whether or not all of the nodes in the wrapper match the provided selector. * @param selector */ - every(selector: EnzymeSelector): Boolean; + every(selector: EnzymeSelector): boolean; /** * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. * @param fn */ - everyWhere(fn: (wrapper: this) => Boolean): Boolean; + everyWhere(fn: (wrapper: this) => boolean): boolean; length: number; } @@ -367,7 +371,7 @@ interface CommonWrapper { export interface ShallowWrapper extends CommonWrapper { shallow(): ShallowWrapper; render(): CheerioWrapper; - unmount(): ShallowWrapper; + unmount(): ShallowWrapper; /** * Find every node in the render tree that matches the provided selector. @@ -375,7 +379,8 @@ export interface ShallowWrapper extends CommonWrapper { */ find(component: ComponentClass): ShallowWrapper; find(statelessComponent: (props: P2) => JSX.Element): ShallowWrapper; - find(selector: string): ShallowWrapper, any>; + find(props: EnzymePropSelector): ShallowWrapper; + find(selector: string): ShallowWrapper, any>; /** * Removes nodes in the current wrapper that do not match the provided selector. @@ -383,13 +388,14 @@ export interface ShallowWrapper extends CommonWrapper { */ filter(component: ComponentClass): ShallowWrapper; filter(statelessComponent: StatelessComponent): ShallowWrapper; - filter(selector: string): ShallowWrapper, any>; + filter(props: EnzymePropSelector): ShallowWrapper; + filter(selector: string): ShallowWrapper, any>; /** * Finds every node in the render tree that returns true for the provided predicate function. * @param predicate */ - findWhere(predicate: (wrapper: CommonWrapper) => Boolean): ShallowWrapper; + findWhere(predicate: (wrapper: CommonWrapper) => boolean): ShallowWrapper; /** * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector @@ -398,17 +404,18 @@ export interface ShallowWrapper extends CommonWrapper { */ children(component: ComponentClass): ShallowWrapper; children(statelessComponent: StatelessComponent): ShallowWrapper; - children(selector: string): ShallowWrapper, any>; + children(props: EnzymePropSelector): ShallowWrapper; + children(selector: string): ShallowWrapper, any>; children(): ShallowWrapper; /** - * Returns a new wrapper with child at the specified index. - * @param index - */ - childAt(index: Number): ShallowWrapper; - childAt(index: Number): ShallowWrapper; + * Returns a new wrapper with child at the specified index. + * @param index + */ + childAt(index: number): ShallowWrapper; + childAt(index: number): ShallowWrapper; - /** + /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. * @@ -417,7 +424,8 @@ export interface ShallowWrapper extends CommonWrapper { */ parents(component: ComponentClass): ShallowWrapper; parents(statelessComponent: StatelessComponent): ShallowWrapper; - parents(selector: string): ShallowWrapper, any>; + parents(props: EnzymePropSelector): ShallowWrapper; + parents(selector: string): ShallowWrapper, any>; parents(): ShallowWrapper; /** @@ -429,131 +437,173 @@ export interface ShallowWrapper extends CommonWrapper { */ closest(component: ComponentClass): ShallowWrapper; closest(statelessComponent: StatelessComponent): ShallowWrapper; - closest(selector: string): ShallowWrapper, any>; + closest(props: EnzymePropSelector): ShallowWrapper; + closest(selector: string): ShallowWrapper, any>; /** * Returns a wrapper with the direct parent of the node in the current wrapper. */ parent(): ShallowWrapper; + + /** + * Returns true if renderer returned null + */ + isEmptyRender(): boolean; } export interface ReactWrapper extends CommonWrapper { - unmount(): ReactWrapper; - mount(): ReactWrapper; + unmount(): ReactWrapper; + mount(): ReactWrapper; - /** - * Returns a wrapper of the node that matches the provided reference name. - * - * NOTE: can only be called on a wrapper instance that is also the root instance. - */ - ref(refName: String): ReactWrapper; - ref(refName: String): ReactWrapper; + /** + * Returns a wrapper of the node that matches the provided reference name. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + */ + ref(refName: string): ReactWrapper; + ref(refName: string): ReactWrapper; - /** - * Detaches the react tree from the DOM. Runs ReactDOM.unmountComponentAtNode() under the hood. - * - * This method will most commonly be used as a "cleanup" method if you decide to use the attachTo option in mount(node, options). - * - * The method is intentionally not "fluent" (in that it doesn't return this) because you should not be doing anything with this wrapper after this method is called. - * - * Using the attachTo is not generally recommended unless it is absolutely necessary to test something. It is your responsibility to clean up after yourself at the end of the test if you do decide to use it, though. - */ - detach() : void; + /** + * Detaches the react tree from the DOM. Runs ReactDOM.unmountComponentAtNode() under the hood. + * + * This method will most commonly be used as a "cleanup" method if you decide to use the attachTo option in mount(node, options). + * + * The method is intentionally not "fluent" (in that it doesn't return this) because you should not be doing anything with this wrapper after this method is called. + * + * Using the attachTo is not generally recommended unless it is absolutely necessary to test something. It is your responsibility to clean up after yourself at the end of the test if you do decide to use it, though. + */ + detach(): void; - /** - * Find every node in the render tree that matches the provided selector. - * @param selector The selector to match. - */ - find(component: ComponentClass): ReactWrapper; - find(statelessComponent: (props: P2) => JSX.Element): ReactWrapper; - find(selector: string): ReactWrapper, any>; + /** + * Find every node in the render tree that matches the provided selector. + * @param selector The selector to match. + */ + find(component: ComponentClass): ReactWrapper; + find(statelessComponent: (props: P2) => JSX.Element): ReactWrapper; + find(props: EnzymePropSelector): ReactWrapper; + find(selector: string): ReactWrapper, any>; - /** - * Finds every node in the render tree that returns true for the provided predicate function. - * @param predicate - */ - findWhere(predicate: (wrapper: CommonWrapper) => Boolean): ReactWrapper; + /** + * Finds every node in the render tree that returns true for the provided predicate function. + * @param predicate + */ + findWhere(predicate: (wrapper: CommonWrapper) => boolean): ReactWrapper; - /** - * Removes nodes in the current wrapper that do not match the provided selector. - * @param selector The selector to match. - */ - filter(component: ComponentClass): ReactWrapper; - filter(statelessComponent: StatelessComponent): ReactWrapper; - filter(selector: string): ReactWrapper, any>; + /** + * Removes nodes in the current wrapper that do not match the provided selector. + * @param selector The selector to match. + */ + filter(component: ComponentClass): ReactWrapper; + filter(statelessComponent: StatelessComponent): ReactWrapper; + filter(props: EnzymePropSelector): ReactWrapper; + filter(selector: string): ReactWrapper, any>; - /** - * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector - * can be provided and it will filter the children by this selector. - * @param [selector] - */ - children(component: ComponentClass): ReactWrapper; - children(statelessComponent: StatelessComponent): ReactWrapper; - children(selector: string): ReactWrapper, any>; - children(): ReactWrapper; + /** + * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector + * can be provided and it will filter the children by this selector. + * @param [selector] + */ + children(component: ComponentClass): ReactWrapper; + children(statelessComponent: StatelessComponent): ReactWrapper; + children(props: EnzymePropSelector): ReactWrapper; + children(selector: string): ReactWrapper, any>; + children(): ReactWrapper; - /** - * Returns a new wrapper with child at the specified index. - * @param index - */ - childAt(index: Number): ReactWrapper; - childAt(index: Number): ReactWrapper; + /** + * Returns a new wrapper with child at the specified index. + * @param index + */ + childAt(index: number): ReactWrapper; + childAt(index: number): ReactWrapper; - /** - * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the - * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. - * - * Note: can only be called on a wrapper of a single node. - * @param [selector] - */ - parents(component: ComponentClass): ReactWrapper; - parents(statelessComponent: StatelessComponent): ReactWrapper; - parents(selector: string): ReactWrapper, any>; - parents(): ReactWrapper; + /** + * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the + * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. + * + * Note: can only be called on a wrapper of a single node. + * @param [selector] + */ + parents(component: ComponentClass): ReactWrapper; + parents(statelessComponent: StatelessComponent): ReactWrapper; + parents(props: EnzymePropSelector): ReactWrapper; + parents(selector: string): ReactWrapper, any>; + parents(): ReactWrapper; - /** - * Returns a wrapper of the first element that matches the selector by traversing up through the current node's - * ancestors in the tree, starting with itself. - * - * Note: can only be called on a wrapper of a single node. - * @param selector - */ - closest(component: ComponentClass): ReactWrapper; - closest(statelessComponent: StatelessComponent): ReactWrapper; - closest(selector: string): ReactWrapper, any>; + /** + * Returns a wrapper of the first element that matches the selector by traversing up through the current node's + * ancestors in the tree, starting with itself. + * + * Note: can only be called on a wrapper of a single node. + * @param selector + */ + closest(component: ComponentClass): ReactWrapper; + closest(statelessComponent: StatelessComponent): ReactWrapper; + closest(props: EnzymePropSelector): ReactWrapper; + closest(selector: string): ReactWrapper, any>; - /** - * Returns a wrapper with the direct parent of the node in the current wrapper. - */ - parent(): ReactWrapper; + /** + * Returns a wrapper with the direct parent of the node in the current wrapper. + */ + parent(): ReactWrapper; + + /** + * Returns true if renderer returned null + */ + isEmptyRender(): boolean; } export interface CheerioWrapper extends CommonWrapper { } +export interface ShallowRendererProps { + /** + * Enable experimental support for full react lifecycle methods + */ + lifecycleExperimental?: boolean; + /** + * Context to be passed into the component + */ + context?: {}; +} + +export interface MountRendererProps { + /** + * Context to be passed into the component + */ + context?: {}; + /** + * DOM Element to attach the component to + */ + attachTo?: HTMLElement; + /** + * Merged contextTypes for all children of the wrapper + */ + childContextTypes?: {}; +} + /** * Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that * your tests aren't indirectly asserting on behavior of child components. * @param node * @param [options] */ -export declare function shallow(node: ReactElement

, options?: any): ShallowWrapper; +export function shallow(node: ReactElement

, options?: ShallowRendererProps): ShallowWrapper; /** * Mounts and renders a react component into the document and provides a testing wrapper around it. * @param node * @param [options] */ -export declare function mount(node: ReactElement

, options?: any): ReactWrapper; +export function mount(node: ReactElement

, options?: MountRendererProps): ReactWrapper; /** * Render react components to static HTML and analyze the resulting HTML structure. * @param node * @param [options] */ -export declare function render(node: ReactElement

, options?: any): CheerioWrapper; +export function render(node: ReactElement

, options?: any): CheerioWrapper; -export declare function describeWithDOM(description: String, fn: Function): void; +export function describeWithDOM(description: string, fn: Function): void; -export declare function spyLifecycle(component: typeof Component): void; +export function spyLifecycle(component: typeof Component): void; diff --git a/express-jwt/index.d.ts b/express-jwt/index.d.ts index 960021c647..e721094edc 100644 --- a/express-jwt/index.d.ts +++ b/express-jwt/index.d.ts @@ -3,32 +3,37 @@ // Definitions by: Wonshik Kim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - import express = require('express'); import unless = require('express-unless'); +export = jwt; + declare function jwt(options: jwt.Options): jwt.RequestHandler; - -interface IDoneCallback { - (err: Error, result: T): void; -} - -type ICallback = (req: express.Request, payload: T, done: IDoneCallback) => void; - declare namespace jwt { + export type secretType = string | Buffer + export interface SecretCallback { + (req: express.Request, header: any, payload: any, done: (err: any, secret?: boolean) => void): void; + (req: express.Request, payload: any, done: (err: any, secret?: secretType) => void): void; + } + + export interface IsRevokedCallback { + (req: express.Request, payload: any, done: (err: any, revoked?: boolean) => void): void; + } + + export interface GetTokenCallback { + (req: express.Request): any; + } export interface Options { - secret: string | Buffer | ICallback; + secret: secretType | SecretCallback; userProperty?: string; skip?: string[]; credentialsRequired?: boolean; - isRevoked?: boolean; + isRevoked?: IsRevokedCallback; requestProperty?: string; - getToken?: ICallback; + getToken?: GetTokenCallback; [property: string]: any; } export interface RequestHandler extends express.RequestHandler { unless?: typeof unless; } } -export = jwt; diff --git a/express-serve-static-core/index.d.ts b/express-serve-static-core/index.d.ts index 50b62b6445..feb971291e 100644 --- a/express-serve-static-core/index.d.ts +++ b/express-serve-static-core/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Express 4.x (core shared with serve-static) +// Type definitions for Express 4.x (core shared with serve-static) // Project: http://expressjs.com // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -17,26 +17,33 @@ declare namespace Express { declare module "express-serve-static-core" { import * as http from "http"; - type RequestHandlerParams = RequestHandler | RequestHandler[]; - - interface IRoute { - path: string; - stack: any; - all(...handler: RequestHandlerParams[]): IRoute; - get(...handler: RequestHandlerParams[]): IRoute; - post(...handler: RequestHandlerParams[]): IRoute; - put(...handler: RequestHandlerParams[]): IRoute; - delete(...handler: RequestHandlerParams[]): IRoute; - patch(...handler: RequestHandlerParams[]): IRoute; - options(...handler: RequestHandlerParams[]): IRoute; - head(...handler: RequestHandlerParams[]): IRoute; + interface NextFunction { + (err?: any): void; } + interface RequestHandler { + (req: Request, res: Response, next: NextFunction): any; + } + + interface ErrorRequestHandler { + (err: any, req: Request, res: Response, next: NextFunction): any; + } + + type PathParams = string | RegExp | (string | RegExp)[]; + + type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[]; + interface IRouterMatcher { - (name: string | RegExp, ...handlers: RequestHandlerParams[]): T; + (path: PathParams, ...handlers: RequestHandler[]): T; + (path: PathParams, ...handlers: RequestHandlerParams[]): T; } - interface IRouter extends RequestHandler { + interface IRouterHandler { + (...handlers: RequestHandler[]): T; + (...handlers: RequestHandlerParams[]): T; + } + + interface IRouter extends RequestHandler { /** * Map the given param placeholder `name`(s) to the given callback(s). * @@ -66,11 +73,10 @@ declare module "express-serve-static-core" { * @param name * @param fn */ - param(name: string, handler: RequestParamHandler): T; - param(name: string, matcher: RegExp): T; - param(name: string, mapper: (param: any) => any): T; + param(name: string, handler: RequestParamHandler): this; // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): T; + // deprecated since express 4.11.0 + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; /** * Special-cased "all" method, applying the given route `path`, @@ -79,30 +85,34 @@ declare module "express-serve-static-core" { * @param path * @param fn */ - all: IRouterMatcher; - get: IRouterMatcher; - post: IRouterMatcher; - put: IRouterMatcher; - delete: IRouterMatcher; - patch: IRouterMatcher; - options: IRouterMatcher; - head: IRouterMatcher; + all: IRouterMatcher; + get: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + delete: IRouterMatcher; + patch: IRouterMatcher; + options: IRouterMatcher; + head: IRouterMatcher; - route(path: string | RegExp): IRoute; + use: IRouterHandler & IRouterMatcher; - use(...handler: RequestHandlerParams[]): T; - use(handler: ErrorRequestHandler | RequestHandlerParams): T; - use(path: string, ...handler: RequestHandlerParams[]): T; - use(path: string, handler: ErrorRequestHandler | RequestHandlerParams): T; - use(path: string[], ...handler: RequestHandlerParams[]): T; - use(path: string[], handler: ErrorRequestHandler): T; - use(path: RegExp, ...handler: RequestHandlerParams[]): T; - use(path: RegExp, handler: ErrorRequestHandler): T; - use(path: string, router: Router): T; + route(prefix: PathParams): IRoute; } + interface IRoute { + path: string; + stack: any; + all: IRouterHandler; + get: IRouterHandler; + post: IRouterHandler; + put: IRouterHandler; + delete: IRouterHandler; + patch: IRouterHandler; + options: IRouterHandler; + head: IRouterHandler; + } - export interface Router extends IRouter { } + export interface Router extends IRouter { } interface CookieOptions { maxAge?: number; @@ -243,6 +253,8 @@ declare module "express-serve-static-core" { accepted: MediaType[]; /** + * @deprecated Use either req.params, req.body or req.query, as applicable. + * * Return the value of param `name` when present or `defaultValue`. * * - Checks route placeholders, ex: _/user/:id_ @@ -374,10 +386,6 @@ declare module "express-serve-static-core" { params: any; - user: any; - - authenticatedUser: any; - /** * Clear cookie `name`. * @@ -793,22 +801,13 @@ declare module "express-serve-static-core" { vary(field: string): Response; } - interface NextFunction { - (err?: any): void; - } - - interface ErrorRequestHandler { - (err: any, req: Request, res: Response, next: NextFunction): any; - } - - interface Handler extends RequestHandler { } interface RequestParamHandler { - (req: Request, res: Response, next: NextFunction, param: any): any; + (req: Request, res: Response, next: NextFunction, value: any, name: string): any; } - interface Application extends IRouter, Express.Application { + interface Application extends IRouter, Express.Application { /** * Initialize the server. * @@ -869,10 +868,11 @@ declare module "express-serve-static-core" { * @param val */ set(setting: string, val: any): Application; - get: { - (name: string): any; // Getter - (name: string | RegExp, ...handlers: RequestHandlerParams[]): Application; - }; + get: {(name: string): any;} & IRouterMatcher; + + param(name: string | string[], handler: RequestParamHandler): this; + // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; /** * Return the app's absolute pathname @@ -1017,8 +1017,6 @@ declare module "express-serve-static-core" { listen(path: string, callback?: Function): http.Server; listen(handle: any, listeningListener?: Function): http.Server; - route(path: string | RegExp): IRoute; - router: string; settings: any; @@ -1066,8 +1064,4 @@ declare module "express-serve-static-core" { response: Response; } - - interface RequestHandler { - (req: Request, res: Response, next: NextFunction): any; - } } diff --git a/express/index.d.ts b/express/index.d.ts index 630e49301b..b1a618b79e 100644 --- a/express/index.d.ts +++ b/express/index.d.ts @@ -37,7 +37,7 @@ declare namespace e { interface Express extends core.Express { } interface Handler extends core.Handler { } interface IRoute extends core.IRoute { } - interface IRouter extends core.IRouter { } + interface IRouter extends core.IRouter { } interface IRouterMatcher extends core.IRouterMatcher { } interface MediaType extends core.MediaType { } interface NextFunction extends core.NextFunction { } diff --git a/fetch-mock/fetch-mock-tests.ts b/fetch-mock/fetch-mock-tests.ts new file mode 100644 index 0000000000..defefa25a1 --- /dev/null +++ b/fetch-mock/fetch-mock-tests.ts @@ -0,0 +1,32 @@ +/// + +import * as fetchMock from "fetch-mock"; + +fetchMock.mock("http://test.com", 200); +fetchMock.mock(/test\.com/, 200); +fetchMock.mock(() => true, 200); +fetchMock.mock((url, opts) => true, 200); + +fetchMock.mock(/test/, "test").mock(/test/, { a: "b" }); +fetchMock.mock(/test/, { + status: 200, + headers: { + "test": "test" + }, + body: { + a: "b" + } +}); + +fetchMock.restore().reset(); + +(fetchMock.calls().matched[0][1] as RequestInit).body; +fetchMock.calls().unmatched[0][0].toUpperCase(); +fetchMock.calls("http://test.com")[0][0].toUpperCase(); +(fetchMock.calls("http://test.com")[0][1] as RequestInit).body; + +fetchMock.called("http://test.com"); + +(fetchMock.lastCall()[1] as RequestInit).body; +fetchMock.lastUrl(); +fetchMock.lastOptions(); diff --git a/fetch-mock/fetch-mock.d.ts b/fetch-mock/fetch-mock.d.ts new file mode 100644 index 0000000000..490b4c7dfd --- /dev/null +++ b/fetch-mock/fetch-mock.d.ts @@ -0,0 +1,207 @@ +// Type definitions for fetch-mock 5.0.0 +// Project: https://github.com/wheresrhys/fetch-mock +// Definitions by: Alexey Svetliakov , Tamir Duberstein +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +declare module "fetch-mock" { + type MockRequest = Request | RequestInit; + + /** + * Mock matcher function + * @param url + * @param opts + */ + type MockMatcherFunction = (url: string, opts: MockRequest) => boolean + /** + * Mock matcher. Can be one of following: + * string: Either + * an exact url to match e.g. 'http://www.site.com/page.html' + * if the string begins with a `^`, the string following the `^` must + begin the url e.g. '^http://www.site.com' would match + 'http://www.site.com' or 'http://www.site.com/page.html' + * '*' to match any url + * RegExp: A regular expression to test the url against + * Function(url, opts): A function (returning a Boolean) that is passed the + url and opts fetch() is called with (or, if fetch() was called with one, + the Request instance) + */ + type MockMatcher = string | RegExp | MockMatcherFunction; + + /** + * Mock response object + */ + interface MockResponseObject { + /** + * Set the response body + */ + body?: string | {}; + /** + * Set the response status + * @default 200 + */ + status?: number; + /** + * Set the response headers. + */ + headers?: { [key: string]: string }; + /** + * If this property is present then a Promise rejected with the value + of throws is returned + */ + throws?: boolean; + /** + * This property determines whether or not the request body should be + JSON.stringified before being sent + * @default true + */ + sendAsJson?: boolean; + } + /** + * Response: A Response instance - will be used unaltered + * number: Creates a response with this status + * string: Creates a 200 response with the string as the response body + * object: As long as the object is not a MockResponseObject it is + converted into a json string and returned as the body of a 200 response + * If MockResponseObject was given then it's used to configure response + * Function(url, opts): A function that is passed the url and opts fetch() + is called with and that returns any of the responses listed above + */ + type MockResponse = Response | Promise + | number | Promise + | string | Promise + | Object | Promise + | MockResponseObject | Promise; + /** + * Mock response function + * @param url + * @param opts + */ + type MockResponseFunction = (url: string, opts: MockRequest) => MockResponse; + + /** + * Mock options object + */ + interface MockOptions { + /** + * A unique string naming the route. Used to subsequently retrieve + references to the calls, grouped by name. + * @default matcher.toString() + * + * Note: If a non-unique name is provided no error will be thrown + (because names are optional, auto-generated ones may legitimately + clash) + */ + name?: string; + /** + * http method to match + */ + method?: string; + /** + * as specified above + */ + matcher?: MockMatcher; + /** + * as specified above + */ + response?: MockResponse | MockResponseFunction; + } + + type MockCall = [string, MockRequest]; + + interface MatchedRoutes { + matched: Array; + unmatched: Array; + } + + interface FetchMockStatic { + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + */ + mock(matcher: MockMatcher, response: MockResponse | MockResponseFunction): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Calls to .mock() can be chained. + * @param matcher Condition for selecting which requests to mock + * @param response Configures the http response returned by the mock + * @param options Additional properties defining the route to mock + */ + mock(matcher: MockMatcher, response: MockResponse | MockResponseFunction, options: MockOptions): this; + /** + * Replaces fetch() with a stub which records its calls, grouped by + route, and optionally returns a mocked Response object or passes the + call through to fetch(). Calls to .mock() can be chained. + * @param options The route to mock + */ + mock(options: MockOptions): this; + /** + * Chainable method that restores fetch() to its unstubbed state and + clears all data recorded for its calls. + */ + restore(): this; + /** + * Chainable method that clears all data recorded for fetch()'s calls + */ + reset(): this; + /** + * Returns all calls to fetch, grouped by whether fetch-mock matched + them or not. + */ + calls(): MatchedRoutes; + /** + * Returns all calls to fetch matching matcherName. + */ + calls(matcherName?: string): Array; + /** + * Returns a Boolean indicating whether fetch was called and a route + was matched. + */ + called(): boolean; + /** + * Returns a Boolean indicating whether fetch was called and a route + named matcherName was matched. + */ + called(matcherName?: string): boolean; + /** + * Returns the arguments for the last matched call to fetch + */ + lastCall(): MockCall; + /** + * Returns the arguments for the last call to fetch matching + matcherName + */ + lastCall(matcherName?: string): MockCall; + /** + * Returns the url for the last matched call to fetch + */ + lastUrl(): string; + /** + * Returns the url for the last call to fetch matching matcherName + */ + lastUrl(matcherName?: string): string; + /** + * Returns the options for the last matched call to fetch + */ + lastOptions(): MockRequest; + /** + * Returns the options for the last call to fetch matching matcherName + */ + lastOptions(matcherName?: string): MockRequest; + /** + * Set some global config options, which include + * sendAsJson [default `true`] - by default fetchMock will + convert objects to JSON before sending. This is overrideable + for each call but for some scenarios, e.g. when dealing with a + lot of array buffers, it can be useful to default to `false` + */ + configure(opts: Object): void; + } + + var fetchMock: FetchMockStatic; + export = fetchMock; +} diff --git a/form-data/form-data-tests.ts b/form-data/form-data-tests.ts index 141a1ace86..3a9db203da 100644 --- a/form-data/form-data-tests.ts +++ b/form-data/form-data-tests.ts @@ -1,7 +1,134 @@ +/// -import formData = require('form-data'); +import FormData = require('form-data'); +import fs = require('fs'); +import http = require('http'); +import request = require('request'); +import fetch = require('node-fetch'); -var value: any; -var fd = new formData.FormData(); -var obj: Object = fd.getHeaders(); -value = fd.pipe(value); +import * as ImportUsingES6Syntax from 'form-data'; + +() => { + var form = new FormData(); + form.append('my_field', 'my value'); + form.append('my_buffer', new Buffer(10)); + form.append('my_file', fs.createReadStream('/foo/bar.jpg')); +} + +() => { + var form = new FormData(); + + http.request('http://nodejs.org/images/logo.png', function (response) { + form.append('my_field', 'my value'); + form.append('my_buffer', new Buffer(10)); + form.append('my_logo', response); + }); +} + +() => { + var form = new FormData(); + + form.append('my_field', 'my value'); + form.append('my_buffer', new Buffer(10)); + form.append('my_logo', request('http://nodejs.org/images/logo.png')); +} + +() => { + var form = new FormData(); + form.submit('http://example.org/', function (err, res) { + // res – response object (http.IncomingMessage) // + res.resume(); + }); +} + + +() => { + var form = new FormData(); + var request = http.request({ + method: 'post', + host: 'example.org', + path: '/upload', + headers: form.getHeaders() + }); + + form.pipe(request); + + request.on('response', function (res: any) { + console.log(res.statusCode); + }); +} + + +() => { + var form = new FormData(); + form.submit('example.org/upload', function (err, res) { + console.log(res.statusCode); + }); +} + +() => { + var CRLF = '\r\n'; + var form = new FormData(); + var buffer = new Buffer(''); + + var options = { + header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF, + knownLength: 1 + }; + + form.append('my_buffer', buffer, options); + + form.submit('http://example.com/', function (err, res) { + if (err) throw err; + console.log('Done'); + }); +} + +() => { + var form = new FormData(); + form.submit({ + host: 'example.com', + path: '/probably.php?extra=params', + auth: 'username:password' + }, function (err, res) { + console.log(res.statusCode); + }); +} + +() => { + var form = new FormData(); + form.submit({ + host: 'example.com', + path: '/surelynot.php', + headers: { 'x-test-header': 'test-header-value' } + }, function (err, res) { + console.log(res.statusCode); + }); +} + +() => { + var formData = { + my_field: 'my_value', + my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), + }; + + request.post({ url: 'http://service.com/upload', formData: formData }, function (err, httpResponse, body) { + if (err) { + return console.error('upload failed:', err); + } + console.log('Upload successful! Server responded with:', body); + }); +} + +() => { + var form = new FormData(); + + form.append('a', 1); + + fetch('http://example.com', { method: 'POST', body: form }) + .then(function (res) { + return res.json(); + }).then(function (json) { + console.log(json); + }); +} diff --git a/form-data/index.d.ts b/form-data/index.d.ts index 0aa5ff33ad..606ffdbd4a 100644 --- a/form-data/index.d.ts +++ b/form-data/index.d.ts @@ -1,15 +1,23 @@ // Type definitions for form-data // Project: https://github.com/felixge/node-form-data -// Definitions by: Carlos Ballesteros Velasco +// Definitions by: Carlos Ballesteros Velasco , Leon Yu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Imported from: https://github.com/soywiz/typescript-node-definitions/form-data.d.ts +export = FormData; -export declare class FormData { - append(key: string, value: any, options?: any): FormData; - getHeaders(): Object; +declare class FormData { + append(key: string, value: any, options?: any): void; + getHeaders(): FormData.Dictionary; // TODO expand pipe pipe(to: any): any; submit(params: string | Object, callback: (error: any, response: any) => void): any; + getBoundary(): string; +} + +declare namespace FormData { + interface Dictionary { + [key: string]: T; + } } diff --git a/google.visualization/google.visualization-tests.ts b/google.visualization/google.visualization-tests.ts index f14bbdeaa9..2cbd8220f2 100644 --- a/google.visualization/google.visualization-tests.ts +++ b/google.visualization/google.visualization-tests.ts @@ -488,3 +488,25 @@ function test_formatter_PatternFormat() { table.draw(view, { allowHtml: true, showRowNumber: true, width: '100%', height: '100%' }); } + +function test_ChartsLoad() { + google.charts.load('current', {packages: ['corechart', 'table', 'sankey']}); + + function drawChart() { + // Define the chart to be drawn. + var data = new google.visualization.DataTable(); + data.addColumn('string', 'Element'); + data.addColumn('number', 'Percentage'); + data.addRows([ + ['Nitrogen', 0.78], + ['Oxygen', 0.21], + ['Other', 0.01] + ]); + + // Instantiate and draw the chart. + var chart = new google.visualization.PieChart(document.getElementById('myPieChart')); + chart.draw(data, null); + } + + google.charts.setOnLoadCallback(drawChart); +} diff --git a/google.visualization/index.d.ts b/google.visualization/index.d.ts index 9ed800798c..a4dc1b7b1a 100644 --- a/google.visualization/index.d.ts +++ b/google.visualization/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Google Visualisation Apis // Project: https://developers.google.com/chart/ -// Definitions by: Dan Ludwig +// Definitions by: Dan Ludwig , Gregory Moore // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace google { @@ -9,6 +9,12 @@ declare namespace google { function setOnLoadCallback(handler: Function): void; function setOnLoadCallback(handler: () => void): void; + // https://developers.google.com/chart/interactive/docs/basic_load_libs + namespace charts { + function load(version: string, packages: Object): void; + function setOnLoadCallback(handler: Function): void; + } + //https://developers.google.com/chart/interactive/docs/reference namespace visualization { @@ -141,6 +147,7 @@ declare namespace google { id?: string; role?: string; pattern?: string; + p?: any; } export interface DataObject { @@ -186,6 +193,42 @@ declare namespace google { function arrayToDataTable(data: any[], firstRowIsData?: boolean): DataTable; + //#endregion + //#region Query + + // https://developers.google.com/chart/interactive/docs/reference#query + export class Query { + constructor(dataSourceUrl: string, options?: QueryOptions); + + abort(): void; + + setRefreshInterval(intervalSeconds: number): void; + setTimeout(timeoutSeconds: number): void; + setQuery(queryString:string): void; + + send(callback: (response: QueryResponse) => void): void; + } + + export interface QueryOptions { + sendMethod?: string, + makeRequestParams?: Object + } + + //#endregion + //#region QueryResponse + + // https://developers.google.com/chart/interactive/docs/reference#queryresponse + export class QueryResponse { + constructor(responseObject: Object); + + getDataTable(): DataTable; + getDetailedMessage(): string; + getMessage(): string; + getReasons(): string[]; + hasWarning(): boolean; + isError(): boolean; + } + //#endregion //#region DataView diff --git a/gulp-insert/gulp-insert-tests.ts b/gulp-insert/gulp-insert-tests.ts new file mode 100644 index 0000000000..e420cf5e4a --- /dev/null +++ b/gulp-insert/gulp-insert-tests.ts @@ -0,0 +1,21 @@ +/// +/// + +import * as gulp from 'gulp'; +import * as insert from 'gulp-insert'; + +gulp.task('gulp-insert-tests', () => { + return gulp.src('*.js') + .pipe(insert.prepend('/* Inserted using gulp-insert prepend method */\n')) + .pipe(insert.prepend('\n/* Inserted using gulp-insert append method */')) + .pipe(insert.wrap( + '/* Inserted using gulp-insert wrap method */\n', + '\n/* Inserted using gulp-insert wrap method */' + )) + .pipe(insert.transform((contents, file) => { + var comment = '/* Local file: ' + file.path + ' */\n'; + return comment + contents; + })) + .pipe(gulp.dest('gulp-insert')); +}); + diff --git a/gulp-insert/gulp-insert.d.ts b/gulp-insert/gulp-insert.d.ts new file mode 100644 index 0000000000..9777280d5b --- /dev/null +++ b/gulp-insert/gulp-insert.d.ts @@ -0,0 +1,52 @@ +// Type definitions for gulp-insert 0.5.0 +// Project: https://github.com/rschmukler/gulp-insert +// Definitions by: Shant Marouti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module 'gulp-insert' { + + import File = require('vinyl'); + + interface Transformer { + (contents: string, file: File): string + } + + namespace Insert { + + /** + * Prepends a string onto the contents + * @param {string} content + * @returns {NodeJS.ReadWriteStream} + */ + function prepend(content: string): NodeJS.ReadWriteStream; + + /** + * Appends a string onto the contents + * @param {string} content + * @returns {NodeJS.ReadWriteStream} + */ + function append(content: string): NodeJS.ReadWriteStream; + + /** + * Wraps the contents with two strings + * @param {string} prepend + * @param {string} append + * @returns {NodeJS.ReadWriteStream} + */ + function wrap(prepend: string, append: string): NodeJS.ReadWriteStream; + + /** + * Calls a function with the contents of the file + * @param {Transformer} transformer + * @returns {NodeJS.ReadWriteStream} + */ + function transform(transformer: Transformer): NodeJS.ReadWriteStream; + + } + + module Insert { } + export = Insert; +} \ No newline at end of file diff --git a/gulp/index.d.ts b/gulp/index.d.ts index df64efeddd..185aed2ef0 100644 --- a/gulp/index.d.ts +++ b/gulp/index.d.ts @@ -151,9 +151,14 @@ declare namespace gulp { dot?: boolean; /** - * By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid - * filesystem path is returned. Set this flag to disable that behavior. - */ + * Set to match only fles, not directories. Set this flag to prevent copying empty directories + */ + nodir?: boolean; + + /** + * By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid + * filesystem path is returned. Set this flag to disable that behavior. + */ nomount?: boolean; /** diff --git a/hammerjs/index.d.ts b/hammerjs/index.d.ts index bfc6e7cb4f..faba777b7a 100644 --- a/hammerjs/index.d.ts +++ b/hammerjs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Hammer.js 2.0.4 +// Type definitions for Hammer.js 2.0.8 // Project: http://hammerjs.github.io/ // Definitions by: Philip Bulley , Han Lin Yap // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -11,7 +11,7 @@ declare module "hammerjs" { interface HammerStatic { - new( element:HTMLElement | SVGElement, options?:any ): HammerManager; + new( element:HTMLElement | SVGElement, options?:HammerOptions ): HammerManager; defaults:HammerDefaults; @@ -68,16 +68,22 @@ interface HammerStatic prefixed( obj:any, property:string ):string; } -interface HammerDefaults +type RecognizerTuple = + [RecognizerStatic] + | [RecognizerStatic, RecognizerOptions] + | [RecognizerStatic, RecognizerOptions, string | string[]] + | [RecognizerStatic, RecognizerOptions, string | string[], (string | Recognizer) | (string | Recognizer)[]]; + +interface HammerDefaults extends HammerOptions { domEvents:boolean; enable:boolean; - preset:any[]; + preset:RecognizerTuple[]; touchAction:string; cssProps:CssProps; - inputClass():void; - inputTarget():void; + inputClass:() => void; + inputTarget:EventTarget; } interface CssProps @@ -90,13 +96,25 @@ interface CssProps userSelect:string; } -interface HammerOptions extends HammerDefaults +interface HammerOptions { + cssProps?:CssProps; + domEvents?:boolean; + enable?:boolean | ((manager: HammerManager) => boolean); + preset?:RecognizerTuple[]; + touchAction?:string; + recognizers?:RecognizerTuple[]; + inputClass?:() => void; + inputTarget?:EventTarget; } interface HammerManagerConstructor { - new( element:HTMLElement, options?:any ):HammerManager; + new( element:EventTarget, options?:HammerOptions ):HammerManager; +} + +interface HammerListener { + (event:HammerInput): void } interface HammerManager @@ -109,8 +127,8 @@ interface HammerManager emit( event:string, data:any ):void; get( recogniser:Recognizer ):Recognizer; get( recogniser:string ):Recognizer; - off( events:string, handler?:( event:HammerInput ) => void ):void; - on( events:string, handler:( event:HammerInput ) => void ):void; + off( events:string, handler?:HammerListener ):void; + on( events:string, handler:HammerListener ):void; recognize( inputData:any ):void; remove( recogniser:Recognizer ):HammerManager; remove( recogniser:string ):HammerManager; @@ -157,7 +175,7 @@ declare class HammerInput direction:number; /** Direction moved from it's starting point. Matches the DIRECTION constants. */ - offsetDirection:string; + offsetDirection:number; /** Scaling that has been done when multi-touch. 1 on a single touch. */ scale:number; @@ -178,7 +196,7 @@ declare class HammerInput pointerType:string; /** Event type, matches the INPUT constants. */ - eventType:string; + eventType:number; /** true when the first input. */ isFirst:boolean; @@ -221,9 +239,22 @@ declare class TouchMouseInput extends HammerInput constructor( manager:HammerManager, callback:Function ); } +interface RecognizerOptions { + direction?: number; + enable?: boolean | ((recognizer: Recognizer, inputData: HammerInput) => boolean); + event?: string; + interval?: number; + pointers?: number; + posThreshold?: number; + taps?: number + threshold?: number; + time?: number; + velocity?: number; +} + interface RecognizerStatic { - new( options?:any ):Recognizer; + new( options?:RecognizerOptions ):Recognizer; } interface Recognizer @@ -246,7 +277,7 @@ interface Recognizer requireFailure( otherRecognizer:Recognizer ):Recognizer; requireFailure( otherRecognizer:string ):Recognizer; reset():void; - set( options?:any ):Recognizer; + set( options?:RecognizerOptions ):Recognizer; tryEmit( input:HammerInput ):void; } @@ -258,12 +289,12 @@ interface AttrRecognizerStatic interface AttrRecognizer extends Recognizer { - new( options?:any ):AttrRecognizer; + new( options?:RecognizerOptions ):AttrRecognizer; } interface PanRecognizerStatic { - new( options?:any ):PanRecognizer; + new( options?:RecognizerOptions ):PanRecognizer; } interface PanRecognizer extends AttrRecognizer @@ -272,7 +303,7 @@ interface PanRecognizer extends AttrRecognizer interface PinchRecognizerStatic { - new( options?:any ):PinchRecognizer; + new( options?:RecognizerOptions ):PinchRecognizer; } interface PinchRecognizer extends AttrRecognizer @@ -281,7 +312,7 @@ interface PinchRecognizer extends AttrRecognizer interface PressRecognizerStatic { - new( options?:any ):PressRecognizer; + new( options?:RecognizerOptions ):PressRecognizer; } interface PressRecognizer extends AttrRecognizer @@ -290,7 +321,7 @@ interface PressRecognizer extends AttrRecognizer interface RotateRecognizerStatic { - new( options?:any ):RotateRecognizer; + new( options?:RecognizerOptions ):RotateRecognizer; } interface RotateRecognizer extends AttrRecognizer @@ -299,7 +330,7 @@ interface RotateRecognizer extends AttrRecognizer interface SwipeRecognizerStatic { - new( options?:any ):SwipeRecognizer; + new( options?:RecognizerOptions ):SwipeRecognizer; } interface SwipeRecognizer extends AttrRecognizer @@ -308,7 +339,7 @@ interface SwipeRecognizer extends AttrRecognizer interface TapRecognizerStatic { - new( options?:any ):TapRecognizer; + new( options?:RecognizerOptions ):TapRecognizer; } interface TapRecognizer extends AttrRecognizer diff --git a/handsontable/index.d.ts b/handsontable/index.d.ts index 790eb4b087..7a82509baa 100644 --- a/handsontable/index.d.ts +++ b/handsontable/index.d.ts @@ -232,7 +232,7 @@ declare namespace ht { getCellMeta(row: number, col: number): Object; getCellRenderer(row: number, col: number): Function; getCellValidator(row: number, col: number): any; - getColHeader(col: number): any[]|string; + getColHeader(col?: number): any[]|string; getColWidth(col: number): number; getCoords(elem: Element): Object; getCopyableData(row: number, column: number): string; diff --git a/hapi/index.d.ts b/hapi/index.d.ts index 33c6d63f1e..79e138eb13 100644 --- a/hapi/index.d.ts +++ b/hapi/index.d.ts @@ -963,7 +963,7 @@ export interface IServerInjectResponse { payload: string; rawPayload: Buffer; raw: { - req: http.ClientRequest; + req: http.IncomingMessage; res: http.ServerResponse }; result: string; @@ -1198,7 +1198,7 @@ export class Request extends Events.EventEmitter { query: any; /** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/ raw: { - req: http.ClientRequest; + req: http.IncomingMessage; res: http.ServerResponse; }; /** the route public interface.*/ diff --git a/howler/index.d.ts b/howler/index.d.ts index c52b9c334f..9e245a8058 100644 --- a/howler/index.d.ts +++ b/howler/index.d.ts @@ -52,20 +52,20 @@ interface Howl { onpause: Function; onplay: Function; load(): Howl; - play(sprite?: string, callback?: (soundId: number) => void): Howl; - play(callback?: (soundId: number) => void): Howl; - pause(soundId?: number): Howl; - stop(soundId?: number): Howl; - mute(soundId?: number): Howl; - unmute(soundId?: number): Howl; - fade(from: number, to: number, duration: number, callback?: Function, soundId?: number): Howl; + play(sprite?: string, callback?: (soundId: string) => void): Howl; + play(callback?: (soundId: string) => void): Howl; + pause(soundId?: string): Howl; + stop(soundId?: string): Howl; + mute(soundId?: string): Howl; + unmute(soundId?: string): Howl; + fade(from: number, to: number, duration: number, callback?: Function, soundId?: string): Howl; loop(): boolean; loop(loop: boolean): Howl; - pos(position?: number, soundId?: number): number; - pos3d(x: number, y: number, z: number, soundId?: number): any; + pos(position?: number, soundId?: string): number; + pos3d(x: number, y: number, z: number, soundId?: string): any; sprite(definition?: IHowlSoundSpriteDefinition): IHowlSoundSpriteDefinition; volume(): number; - volume(volume?: number, soundId?: number): Howl; + volume(volume?: number, soundId?: string): Howl; urls(): string[]; urls(urls: string[]): Howl; on(event: string, listener?: Function): Howl; diff --git a/http-errors/http-errors-tests.ts b/http-errors/http-errors-tests.ts index 2ad5817d44..d7440fbc16 100644 --- a/http-errors/http-errors-tests.ts +++ b/http-errors/http-errors-tests.ts @@ -4,12 +4,19 @@ import * as express from 'express'; var app = express(); +declare global { + namespace Express { + export interface Request { + user?: any + } + } +} + app.use(function (req, res, next) { if (!req.user) return next(createError(401, 'Please login to view this page.')); next(); }); - /* Examples taken from https://github.com/jshttp/http-errors/blob/1.3.1/test/test.js */ // createError(status) diff --git a/ioredis/index.d.ts b/ioredis/index.d.ts index 3e4866670a..2a836cc065 100644 --- a/ioredis/index.d.ts +++ b/ioredis/index.d.ts @@ -38,7 +38,8 @@ declare module IORedis { } interface Redis extends NodeJS.EventEmitter, Commander { - connect(callback: Function): Promise; + status: string; + connect(callback?: Function): Promise; disconnect(): void; duplicate(): Redis; monitor(calback: (error: Error, monitor: NodeJS.EventEmitter) => void): Promise; @@ -56,6 +57,7 @@ declare module IORedis { subscribe(channel: string): any; get(args: any[], callback?: ResCallbackT): any; get(...args: any[]): any; + getBuffer(key: string, callback?: ResCallbackT): any; set(args: any[], callback?: ResCallbackT): any; set(...args: any[]): any; setnx(args: any[], callback?: ResCallbackT): any; @@ -227,8 +229,12 @@ declare module IORedis { renamenx(...args: any[]): any; expire(args: any[], callback?: ResCallbackT): any; expire(...args: any[]): any; + pexpire(args: any[], callback?: ResCallbackT): any; + pexpire(...args: any[]): any; expireat(args: any[], callback?: ResCallbackT): any; expireat(...args: any[]): any; + pexpireat(args: any[], callback?: ResCallbackT): any; + pexpireat(...args: any[]): any; keys(args: any[], callback?: ResCallbackT): any; keys(...args: any[]): any; dbsize(args: any[], callback?: ResCallbackT): any; @@ -504,8 +510,12 @@ declare module IORedis { renamenx(...args: any[]): Pipeline; expire(args: any[], callback?: ResCallbackT): Pipeline; expire(...args: any[]): Pipeline; + pexpire(args: any[], callback?: ResCallbackT): Pipeline; + pexpire(...args: any[]): Pipeline; expireat(args: any[], callback?: ResCallbackT): Pipeline; expireat(...args: any[]): Pipeline; + pexpireat(args: any[], callback?: ResCallbackT): Pipeline; + pexpireat(...args: any[]): Pipeline; keys(args: any[], callback?: ResCallbackT): Pipeline; keys(...args: any[]): Pipeline; dbsize(args: any[], callback?: ResCallbackT): Pipeline; diff --git a/iscroll/iscroll-5-tests.ts b/iscroll/iscroll-5-tests.ts index 7b485c4599..3e19397d0f 100644 --- a/iscroll/iscroll-5-tests.ts +++ b/iscroll/iscroll-5-tests.ts @@ -33,4 +33,9 @@ myScroll1.scrollToElement(document.getElementById('selectedElement'), 250); myScroll2.on('scrollStart', function () { console.log('scroll started'); }); var myScroll9 = new IScroll(document.getElementById('wrapper')); -var myScroll10 = new IScroll(document.getElementById('wrapper'), { scrollbarClass: 'myScrollbar' }); \ No newline at end of file +var myScroll10 = new IScroll(document.getElementById('wrapper'), { scrollbarClass: 'myScrollbar' }); +var myScroll11 = new IScroll(document.getElementById('wrapper'), { preventDefaultException: [ /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ ] }); +var myScroll12 = new IScroll(document.getElementById('wrapper'), { preventDefaultException: { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ } }); + +var myScroll13 = new IScroll(document.getElementById('wrapper'), { bounceEasing: 'circular' }); +var myScroll14 = new IScroll(document.getElementById('wrapper'), { bounceEasing: { style: 'cubic-bezier(0,0,1,1)', fn: function (k) { return k; } } }); diff --git a/iscroll/iscroll-5.d.ts b/iscroll/iscroll-5.d.ts index 0b972e2863..31e9acaf6c 100644 --- a/iscroll/iscroll-5.d.ts +++ b/iscroll/iscroll-5.d.ts @@ -51,10 +51,10 @@ interface IScrollOptions { bounceTime?: number; ///String or function - bounceEasing?: any; + bounceEasing?: string|{ style: string, fn: (k: any) => any }; preventDefault?: boolean; - preventDefaultException?: boolean; + preventDefaultException?: Array|Object; HWCompositing?: boolean; diff --git a/jest/index.d.ts b/jest/index.d.ts index daedf995d2..98137eef82 100644 --- a/jest/index.d.ts +++ b/jest/index.d.ts @@ -26,6 +26,7 @@ declare namespace jest { function autoMockOn(): void; function clearAllTimers(): void; function currentTestPath(): string; + function disableAutomock(): void; function fn(implementation?: Function): Mock; function dontMock(moduleName: string): void; function genMockFromModule(moduleName: string): Mock; diff --git a/jquery.contextMenu/index.d.ts b/jquery.contextMenu/index.d.ts index e56843ba81..5748c76edc 100644 --- a/jquery.contextMenu/index.d.ts +++ b/jquery.contextMenu/index.d.ts @@ -28,6 +28,7 @@ interface JQueryContextMenuOptions { items: any; reposition?: boolean; className?: string; + itemClickEvent?: string; } interface JQueryStatic { diff --git a/jquery.fileupload/index.d.ts b/jquery.fileupload/index.d.ts index 18541a0617..db5f8e27e2 100644 --- a/jquery.fileupload/index.d.ts +++ b/jquery.fileupload/index.d.ts @@ -17,13 +17,13 @@ interface JQueryFileInputOptions { * The drop target element(s), by the default the complete document. * Set to null to disable drag & drop support: */ - dropZone?: HTMLElement; + dropZone?: Element | Element[] | JQuery | string; /** * The paste target element(s), by the default the complete document. * Set to null to disable paste support: */ - pasteZone?: HTMLElement; + pasteZone?: Element | Element[] | JQuery | string; /** * The file input field(s), that are listened to for change events. @@ -31,7 +31,7 @@ interface JQueryFileInputOptions { * of the widget element on plugin initialization. * Set to null to disable the change listener. */ - fileInput?: HTMLElement; + fileInput?: Element | Element[] | JQuery | string; /** * By default, the file input field is replaced with a clone after diff --git a/jquery.payment/index.d.ts b/jquery.payment/index.d.ts index 61408d6ca9..1899eceaf4 100644 --- a/jquery.payment/index.d.ts +++ b/jquery.payment/index.d.ts @@ -77,33 +77,38 @@ declare namespace JQueryPayment { /** * Card type */ - type: string; + type?: string; - /* + /** * Regex used to identify the card type. For the best experience, this should be * the shortest pattern that can guarantee the card is of a particular type. */ - pattern: RegExp; + pattern?: RegExp; + + /** + * Array of prefixes used to identify the card type. + */ + patterns?: number[]; /** * Array of valid card number lengths. */ - length: number[]; + length?: number[]; /** * Array of valid card CVC lengths. */ - cvcLength: number[]; + cvcLength?: number[]; /** * Boolean indicating whether a valid card number should satisfy the Luhn check. */ - luhn: boolean; + luhn?: boolean; /** * Regex used to format the card number. Each match is joined with a space. */ - format: RegExp; + format?: RegExp; } } diff --git a/jquery.payment/jquery.payment-tests.ts b/jquery.payment/jquery.payment-tests.ts new file mode 100644 index 0000000000..6ef1c2154d --- /dev/null +++ b/jquery.payment/jquery.payment-tests.ts @@ -0,0 +1,45 @@ +/// +/// + +$.payment.cards.push({ + // Card type, as returned by $.payment.cardType. + type: 'mastercard', + // Array of prefixes used to identify the card type. + patterns: [ + 51, 52, 53, 54, 55, + 22, 23, 24, 25, 26, 27 + ], + // Array of valid card number lengths. + length: [16], + // Array of valid card CVC lengths. + cvcLength: [3], + // Boolean indicating whether a valid card number should satisfy the Luhn check. + luhn: true, + // Regex used to format the card number. Each match is joined with a space. + format: /(\d{1,4})/g +}) + +$('[data-numeric]').payment('restrictNumeric'); + +$.payment.validateCardNumber('4242 4242 4242 4242') === true; //=> true + +$.payment.validateCardExpiry('05', '20') === true; //=> true +$.payment.validateCardExpiry('05', '2015') === true; //=> true +$.payment.validateCardExpiry('05', '05') === true; //=> false + +$.payment.validateCardCVC('123') === true; //=> true +$.payment.validateCardCVC('123', 'amex') === true; //=> true +$.payment.validateCardCVC('1234', 'amex') === true; //=> true +$.payment.validateCardCVC('12344') === false; //=> false + +$.payment.cardType('4242 4242 4242 4242') === 'visa'; //=> 'visa' + +$.payment.cardExpiryVal('03 / 2025') === {month: 3, year: 2025}; //=> {month: 3, year: 2025} +$.payment.cardExpiryVal('05 / 04') === {month: 3, year: 2025}; //=> {month: 5, year: 2004} +$('input.cc-exp').payment('cardExpiryVal') //=> {month: 4, year: 2020} + +var valid = $.payment.validateCardNumber($('input.cc-num').val()); + +if (!valid) { + alert('Your card is not valid!'); +} \ No newline at end of file diff --git a/jquery.timer/index.d.ts b/jquery.timer/index.d.ts index e6b26e0b2e..f43e887787 100644 --- a/jquery.timer/index.d.ts +++ b/jquery.timer/index.d.ts @@ -28,4 +28,8 @@ interface JQueryTimer { interface JQuery { timer: JQueryTimer; -} \ No newline at end of file +} + +interface JQueryStatic { + timer: JQueryTimer; +} diff --git a/jquery/index.d.ts b/jquery/index.d.ts index 5dc88bf795..0f72c709cf 100644 --- a/jquery/index.d.ts +++ b/jquery/index.d.ts @@ -442,6 +442,7 @@ interface JQueryDeferred extends JQueryGenericPromise { * Interface of the JQuery extension of the W3C event object */ interface BaseJQueryEventObject extends Event { + currentTarget: Element; data: any; delegateTarget: Element; isDefaultPrevented(): boolean; diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index 4d964b9416..bec2999df0 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -1524,6 +1524,9 @@ function test_eventParams() { $(window).on('mousewheel', (e) => { var delta = (e.originalEvent).deltaY; }); + $( "p" ).click(function( event ) { + alert( event.currentTarget === this ); // true + }); } function test_extend() { diff --git a/jqueryui/index.d.ts b/jqueryui/index.d.ts index 7e99ce5f61..58526715de 100644 --- a/jqueryui/index.d.ts +++ b/jqueryui/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jQueryUI 1.9 +// Type definitions for jQueryUI 1.11 // Project: http://jqueryui.com/ // Definitions by: Boris Yankov , John Reilly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -626,6 +626,36 @@ declare namespace JQueryUI { interface Selectable extends Widget, SelectableOptions { } + // SelectMenu ////////////////////////////////////////////////// + + interface SelectMenuOptions extends SelectMenuEvents { + appendTo?: string; + disabled?: boolean; + icons?: any; + position?: JQueryPositionOptions; + width?: number; + } + + interface SelectMenuUIParams { + item?: JQuery; + } + + interface SelectMenuEvent { + (event: Event, ui: SelectMenuUIParams): void; + } + + interface SelectMenuEvents { + change?: SelectMenuEvent; + close?: SelectMenuEvent; + create?: SelectMenuEvent; + focus?: SelectMenuEvent; + open?: SelectMenuEvent; + select?: SelectMenuEvent; + } + + interface SelectMenu extends Widget, SelectMenuOptions { + } + // Slider ////////////////////////////////////////////////// interface SliderOptions extends SliderEvents { @@ -1676,6 +1706,22 @@ interface JQuery { selectable(optionLiteral: string, options: JQueryUI.SelectableOptions): any; selectable(optionLiteral: string, optionName: string, optionValue: any): JQuery; + selectmenu(): JQuery; + selectmenu(methodName: 'close'): JQuery; + selectmenu(methodName: 'destroy'): JQuery; + selectmenu(methodName: 'disable'): JQuery; + selectmenu(methodName: 'enable'): JQuery; + selectmenu(methodName: 'instance'): any; + selectmenu(methodName: 'menuWidget'): JQuery; + selectmenu(methodName: 'open'): JQuery; + selectmenu(methodName: 'refresh'): JQuery; + selectmenu(methodName: 'widget'): JQuery; + selectmenu(methodName: string): JQuery; + selectmenu(options: JQueryUI.SelectMenuOptions): JQuery; + selectmenu(optionLiteral: string, optionName: string): any; + selectmenu(optionLiteral: string, options: JQueryUI.SelectMenuOptions): any; + selectmenu(optionLiteral: string, optionName: string, optionValue: any): JQuery; + slider(): JQuery; slider(methodName: 'destroy'): void; slider(methodName: 'disable'): void; diff --git a/jqueryui/jqueryui-tests.ts b/jqueryui/jqueryui-tests.ts index 20cd77ec65..0063a6115b 100644 --- a/jqueryui/jqueryui-tests.ts +++ b/jqueryui/jqueryui-tests.ts @@ -1475,6 +1475,59 @@ function test_menu() { $(".selector").menu({ select: (e, ui) => { } }); } +function test_selectmenu() { + // Options + $("#selectmenu").selectmenu(); + $(".selector").selectmenu({ appendTo: ".selector" }); + $(".selector").selectmenu({ disabled: true }); + $(".selector").selectmenu({ icons: { submenu: "ui-icon-circle-triangle-e" } }); + $(".selector").selectmenu({ position: { my: "left top", at: "right-5 top+5" } }); + $(".selector").selectmenu({ width: 47 }); + + // Events + $("#selectmenu").selectmenu({ change: (event, ui) => {}}); + $("#selectmenu").selectmenu({ close: (event, ui) => {}}); + $("#selectmenu").selectmenu({ create: (event, ui) => {}}); + $("#selectmenu").selectmenu({ focus: (event, ui) => {}}); + $("#selectmenu").selectmenu({ open: (event, ui) => {}}); + $("#selectmenu").selectmenu({ select: (event, ui) => {}}); + + // Events and options + $("#selectmenu").selectmenu({ + appendTo: ".selector", + disabled: true, + icons: { submenu: "ui-icon-circle-triangle-e" }, + position: { my: "left top", at: "right-5 top+5" }, + width: 47, + change: (event, ui) => {}, + close: (event, ui) => {}, + create: (event, ui) => {}, + focus: (event, ui) => {}, + open: (event, ui) => {}, + select: (event, ui) => {} + }); + + // passing in option + $(".selector").selectmenu("option", { disabled: true }); + + // Fetching option value + var disabled = $(".selector").selectmenu("option", "disabled"); + + // Setting option value + $(".selector").selectmenu("option", "disabled", true); + $(".selector").selectmenu("option", "position", { my: "left top", at: "right-5 top+5" } ); + + // Methods + $(".selector").selectmenu("close"); + $(".selector").selectmenu("destroy"); + + // Chaining + $("#number") + .selectmenu() + .selectmenu("menuWidget") + .addClass("overflow"); +} + function test_progressbar() { $("#progressbar").progressbar({ diff --git a/jsonwebtoken/index.d.ts b/jsonwebtoken/index.d.ts index 104e3586e7..4cdbf3d924 100644 --- a/jsonwebtoken/index.d.ts +++ b/jsonwebtoken/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jsonwebtoken 6.2.0 +// Type definitions for jsonwebtoken 7.1.6 // Project: https://github.com/auth0/node-jsonwebtoken // Definitions by: Maxime LUCE , Daniel Heim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -47,14 +47,17 @@ export interface SignOptions { jwtid?: string; noTimestamp?: boolean; headers?: Object; + encoding?: string; } export interface VerifyOptions { algorithms?: string[]; - audience?: string; - issuer?: string; + audience?: string | string[]; + clockTolerance?: number; + issuer?: string | string[]; ignoreExpiration?: boolean; ignoreNotBefore?: boolean; + jwtId?: string; subject?: string; /** *@deprecated diff --git a/jszip/index.d.ts b/jszip/index.d.ts index ef17f15cbc..46fe0f870c 100644 --- a/jszip/index.d.ts +++ b/jszip/index.d.ts @@ -4,6 +4,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface JSZip { + files: {[key: string]: JSZipObject}; + /** * Get a file from the archive * @@ -46,6 +48,13 @@ interface JSZip { */ folder(name: RegExp): JSZipObject[]; + /** + * Call a callback function for each entry at this folder level. + * + * @param callback function + */ + forEach(callback: (relativePath: string, file: JSZipObject) => void): void; + /** * Get all files wchich match the given filter function * @@ -63,23 +72,40 @@ interface JSZip { remove(path: string): JSZip; /** - * Generates a new archive - * - * @param options Optional options for the generator - * @return The serialized archive + * @deprecated since version 3.0 + * @see {@link generateAsync} + * http://stuk.github.io/jszip/documentation/upgrade_guide.html */ generate(options?: JSZipGeneratorOptions): any; /** - * Deserialize zip file + * Generates a new archive asynchronously + * + * @param options Optional options for the generator + * @return The serialized archive + */ + generateAsync(options?: JSZipGeneratorOptions, onUpdate?: Function): Promise; + + /** + * @deprecated since version 3.0 + * @see {@link loadAsync} + * http://stuk.github.io/jszip/documentation/upgrade_guide.html + */ + load(): void; + + /** + * Deserialize zip file asynchronously * * @param data Serialized zip file * @param options Options for deserializing - * @return Returns the JSZip instance + * @return Returns promise */ - load(data: any, options: JSZipLoadOptions): JSZip; + loadAsync(data: any, options?: JSZipLoadOptions): Promise; } +type Serialization = ("string" | "text" | "base64" | "binarystring" | "uint8array" | + "arraybuffer" | "blob" | "nodebuffer"); + interface JSZipObject { name: string; dir: boolean; @@ -87,11 +113,31 @@ interface JSZipObject { comment: string; options: JSZipObjectOptions; - asText(): string; - asBinary(): string; - asArrayBuffer(): ArrayBuffer; - asUint8Array(): Uint8Array; - //asNodeBuffer(): Buffer; + /** + * Prepare the content in the asked type. + * @param {String} type the type of the result. + * @param {Function} onUpdate a function to call on each internal update. + * @return Promise the promise of the result. + */ + async(type: Serialization, onUpdate?: Function): Promise; + + /** + * @deprecated since version 3.0 + */ + asText(): void; + /** + * @deprecated since version 3.0 + */ + asBinary(): void; + /** + * @deprecated since version 3.0 + */ + asArrayBuffer(): void; + /** + * @deprecated since version 3.0 + */ + asUint8Array(): void; + //asNodeBuffer(): void; } interface JSZipFileOptions { @@ -140,18 +186,6 @@ interface JSZipSupport { nodebuffer: boolean; } -interface DEFLATE { - /** pako.deflateRaw, level:0-9 */ - compress(input: string, compressionOptions: {level:number}): Uint8Array; - compress(input: number[], compressionOptions: {level:number}): Uint8Array; - compress(input: Uint8Array, compressionOptions: {level:number}): Uint8Array; - - /** pako.inflateRaw */ - uncompress(input: string): Uint8Array; - uncompress(input: number[]): Uint8Array; - uncompress(input: Uint8Array): Uint8Array; -} - declare var JSZip: { /** * Create JSZip instance @@ -181,9 +215,6 @@ declare var JSZip: { prototype: JSZip; support: JSZipSupport; - compressions: { - DEFLATE: DEFLATE; - } } declare module "jszip" { diff --git a/jszip/jszip-tests.ts b/jszip/jszip-tests.ts index 1e283e6d68..da6366fbcb 100644 --- a/jszip/jszip-tests.ts +++ b/jszip/jszip-tests.ts @@ -6,44 +6,70 @@ var SEVERITY = { FATAL: 4 } +function createTestZip(): JSZip { + var zip = new JSZip(); + zip.file("test.txt", "test string"); + zip.file("test/test.txt", "test string"); + return zip +} + +function filterWithFileAsync(zip: JSZip, as: Serialization, + cb: (relativePath: string, file: JSZipObject, value: any) => boolean) + : Promise { + var promises: Promise[] = []; + var promiseIndices: {[key: string]: number} = {}; + zip.forEach((relativePath: string, file: JSZipObject) => { + var promise = file.async(as); + promiseIndices[file.name] = promises.length; + promises.push(promise); + }); + return Promise.all(promises).then(function(values: any[]) { + var filtered = zip.filter((relativePath: string, file: JSZipObject) => { + var index = promiseIndices[file.name]; + return cb(relativePath, file, values[index]); + }); + return Promise.resolve(filtered); + }); +} + function testJSZip() { - var newJszip = new JSZip(); - - newJszip.file("test.txt", "test string"); - newJszip.file("test/test.txt", "test string"); - - var serializedZip = newJszip.generate({compression: "DEFLATE", type: "base64"}); - - newJszip = new JSZip(); - newJszip.load(serializedZip, {base64: true, checkCRC32: true}); - - if (newJszip.file("test.txt").asText() === "test string") { + var zip = createTestZip(); + zip.generateAsync({compression: "DEFLATE", type: "base64"}).then(function(serializedZip: any) { + var newJszip = new JSZip(); + return newJszip.loadAsync(serializedZip, {base64: true/*, checkCRC32: true*/}); + }).then(function(newJszip: JSZip) { + newJszip.file("test.txt").async('text').then(function(text: string) { + if (text === "test string") { log(SEVERITY.INFO, "all ok"); } else { log(SEVERITY.ERROR, "no matching file found"); } - if (newJszip.file("test/test.txt").asText() === "test string") { + }).catch((e: any) => log(SEVERITY.ERROR, e)); + + newJszip.file("test/test.txt").async('text').then(function(text: string) { + if (text === "test string") { log(SEVERITY.INFO, "all ok"); } else { log(SEVERITY.ERROR, "no matching file found"); } + }).catch((e: any) => log(SEVERITY.ERROR, e)); var folder = newJszip.folder("test"); - if(folder.file("test.txt").asText() == "test string") { + folder.file("test.txt").async('text').then(function(text: string) { + if (text == "test string") { log(SEVERITY.INFO, "all ok"); - } - else { + } else { log(SEVERITY.ERROR, "wrong file"); } + }).catch((e: any) => log(SEVERITY.ERROR, e)); var folders = newJszip.folder(new RegExp("^test")); - if(folders.length == 1) { + if (folders.length == 1) { log(SEVERITY.INFO, "all ok"); - if(folders[0].dir == true) { + if (folders[0].dir == true) { log(SEVERITY.INFO, "all ok"); - } - else { + } else { log(SEVERITY.ERROR, "wrong file"); } } else { @@ -51,67 +77,50 @@ function testJSZip() { } var files = newJszip.file(new RegExp("^test")); - if(files.length == 2) { + if (files.length == 2) { log(SEVERITY.INFO, "all ok"); - if (files[0].asText() == "test string" && files[1].asText() == "test string") { + Promise.all([files[0].async('text'), files[1].async('text')]).then(function(texts: string[]) { + if (texts[0] == "test string" && texts[1] == 'test string') { log(SEVERITY.INFO, "all ok"); - } - else { + } else { log(SEVERITY.ERROR, "wrong data in files"); } - } - else { + }); + } else { log(SEVERITY.ERROR, "wrong number of files"); } - var filterFiles = newJszip.filter((relativePath: string, file: JSZipObject) => { - if (file.asText() == "test string") { + filterWithFileAsync(newJszip, 'text', (relativePath: string, file: JSZipObject, text: string) => { + if (text == "test string") { return true; } return false; - }); - - if(filterFiles.length == 2) { + }).then(function(filterFiles: JSZipObject[]) { + if (filterFiles.length == 2) { log(SEVERITY.INFO, "all ok"); - } - else { + } else { log(SEVERITY.ERROR, "wrong number of files"); } + }).catch((e: any) => log(SEVERITY.ERROR, e)); + }).catch((e: any)=> { console.error(e) }); +} +function testJSZipRemove() { + var newJszip = createTestZip(); newJszip.remove("test/test.txt"); - filterFiles = newJszip.filter((relativePath: string, file: JSZipObject) => { - if (file.asText() == "test string") { + filterWithFileAsync(newJszip, 'text', (relativePath: string, file: JSZipObject, text: string) => { + if (text == "test string") { return true; } return false; - }); - - if(filterFiles.length == 1) { + }).then(function(filterFiles: JSZipObject[]) { + if (filterFiles.length == 1) { log(SEVERITY.INFO, "all ok"); - } - else { + } else { log(SEVERITY.ERROR, "wrong number of files"); } - - var uncompressedStr = JSZip.compressions.DEFLATE.uncompress( - JSZip.compressions.DEFLATE.compress("\0\1\2\3\4\5\6\7",{level:9})); - var uncompressedArr = JSZip.compressions.DEFLATE.uncompress( - JSZip.compressions.DEFLATE.compress([0,1,2,3,4,5,6,7],{level:9})); - var uncompressedUint8Arr = JSZip.compressions.DEFLATE.uncompress( - JSZip.compressions.DEFLATE.compress(new Uint8Array([0,1,2,3,4,5,6,7]),{level:9})); - - var every_match = [0,1,2,3,4,5,6,7].every(function(val, i){ - return uncompressedStr[i] === val && - uncompressedArr[i] === val && - uncompressedUint8Arr[i] === val; - }); - if(every_match) { - log(SEVERITY.INFO, "compress and uncompress ok."); - }else{ - log(SEVERITY.ERROR, "compress or uncompress failed."); - } - + }).catch((e: any) => log(SEVERITY.ERROR, e)); } function log(severity:number, message: any) { @@ -140,3 +149,4 @@ function log(severity:number, message: any) { } testJSZip(); +testJSZipRemove(); diff --git a/kafka-node/index.d.ts b/kafka-node/index.d.ts index 81bfb7a0b3..89d68de63e 100644 --- a/kafka-node/index.d.ts +++ b/kafka-node/index.d.ts @@ -28,7 +28,7 @@ export declare class HighLevelProducer { } export declare class Consumer { - constructor(client: Client, fetchRequests: Array, options: ConsumerOptions); + constructor(client: Client, fetchRequests: Array, options: ConsumerOptions); on(eventName: string, cb: (message: string) => any): void; on(eventName: string, cb: (error: any) => any): void; addTopics(topics: Array, cb: (error: any, added: boolean) => any): void; diff --git a/karma/index.d.ts b/karma/index.d.ts index 7280537480..8cae4a0fa4 100644 --- a/karma/index.d.ts +++ b/karma/index.d.ts @@ -25,6 +25,7 @@ declare namespace karma { server: DeprecatedServer; Server: Server; runner: Runner; + stopper: Stopper; launcher: Launcher; VERSION: string; } @@ -54,6 +55,15 @@ declare namespace karma { run(options?: ConfigOptions | ConfigFile, callback?: ServerCallback): void; } + + interface Stopper { + /** + * This function will signal a running server to stop. The equivalent of karma stop. + */ + stop(options?: ConfigOptions, callback?: ServerCallback): void; + } + + interface TestResults { disconnected: boolean; error: boolean; diff --git a/karma/karma-tests.ts b/karma/karma-tests.ts index 8e72e9bd88..03fd0d04bf 100644 --- a/karma/karma-tests.ts +++ b/karma/karma-tests.ts @@ -28,6 +28,12 @@ karma.runner.run({port: 9876}, (exitCode: number) => { process.exit(exitCode); }); +karma.stopper.stop({port: 9876}, function(exitCode) { + if (exitCode === 0) { + console.log('Server stop as initiated') + } + process.exit(exitCode) +}); //var Server = require('karma').Server; => cannot use this syntax otherwise Server is of type any var server = new karma.Server({logLevel: 'debug', port: 9876}, function(exitCode: number) { diff --git a/kendo-ui/index.d.ts b/kendo-ui/index.d.ts index 922c2b9eba..2eed98f846 100644 --- a/kendo-ui/index.d.ts +++ b/kendo-ui/index.d.ts @@ -4411,6 +4411,7 @@ declare namespace kendo.ui { name?: string; text?: GridColumnCommandItemText; className?: string; + template?: string; imageClass?: string; click?: Function; } diff --git a/knex/index.d.ts b/knex/index.d.ts index 804abc288e..7510cf4208 100644 --- a/knex/index.d.ts +++ b/knex/index.d.ts @@ -12,6 +12,7 @@ type Callback = Function; type Client = Function; type Value = string | number | boolean | Date | Array | Array | Array | Array; type ColumnName = string | Knex.Raw | Knex.QueryBuilder; +type TableName = string | Knex.Raw | Knex.QueryBuilder; interface Knex extends Knex.QueryInterface { (tableName?: string): Knex.QueryBuilder; @@ -162,12 +163,12 @@ declare namespace Knex { interface Join { (raw: Raw): QueryBuilder; - (tableName: string, callback: (joinClause: JoinClause) => any): QueryBuilder; (tableName: string, columns: { [key: string]: string | Raw }): QueryBuilder; - (tableName: string, raw: Raw): QueryBuilder; - (tableName: string, column1: string, column2: string): QueryBuilder; - (tableName: string, column1: string, raw: Raw): QueryBuilder; - (tableName: string, column1: string, operator: string, column2: string): QueryBuilder; + (tableName: string, callback: Function): QueryBuilder; + (tableName: TableName, raw: Raw): QueryBuilder; + (tableName: TableName, column1: string, column2: string): QueryBuilder; + (tableName: TableName, column1: string, raw: Raw): QueryBuilder; + (tableName: TableName, column1: string, operator: string, column2: string): QueryBuilder; } interface JoinClause { @@ -177,6 +178,20 @@ declare namespace Knex { on(column1: string, column2: string): JoinClause; on(column1: string, raw: Raw): JoinClause; on(column1: string, operator: string, column2: string): JoinClause; + andOn(raw: Raw): JoinClause; + andOn(callback: Function): JoinClause; + andOn(columns: { [key: string]: string | Raw }): JoinClause; + andOn(column1: string, column2: string): JoinClause; + andOn(column1: string, raw: Raw): JoinClause; + andOn(column1: string, operator: string, column2: string): JoinClause; + orOn(raw: Raw): JoinClause; + orOn(callback: Function): JoinClause; + orOn(columns: { [key: string]: string | Raw }): JoinClause; + orOn(column1: string, column2: string): JoinClause; + orOn(column1: string, raw: Raw): JoinClause; + orOn(column1: string, operator: string, column2: string): JoinClause; + using(column: string | string[] | Raw | { [key: string]: string | Raw }): JoinClause; + type(type: string): JoinClause; } interface JoinRaw { diff --git a/knex/knex-tests.ts b/knex/knex-tests.ts index a73856418a..3b7c75eac1 100644 --- a/knex/knex-tests.ts +++ b/knex/knex-tests.ts @@ -153,6 +153,10 @@ knex('users') .join('contacts', 'users.id', 'contacts.user_id') .select('users.id', 'contacts.phone'); +knex('users') + .join(knex('contacts').select('user_id', 'phone').as('contacts'), 'users.id', 'contacts.user_id') + .select('users.id', 'contacts.phone'); + knex.select('*').from('users').join('accounts', function() { this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id') }); diff --git a/koa-mount/index.d.ts b/koa-mount/index.d.ts index 9c79156406..eac8a488f3 100644 --- a/koa-mount/index.d.ts +++ b/koa-mount/index.d.ts @@ -16,5 +16,6 @@ declare function mount(prefix: string, app: Function): Function; declare function mount(prefix: string, app: Koa): Function; -export = mount; +declare namespace mount { } +export = mount; diff --git a/koa-mount/koa-mount-tests.ts b/koa-mount/koa-mount-tests.ts index e3cc831971..2fcf784ef6 100644 --- a/koa-mount/koa-mount-tests.ts +++ b/koa-mount/koa-mount-tests.ts @@ -2,7 +2,7 @@ import * as Koa from "koa"; -import mount = require("koa-mount"); +import * as mount from "koa-mount"; const a = new Koa(); diff --git a/koa/index.d.ts b/koa/index.d.ts index fd4922d0d8..6cdb0cbcd1 100644 --- a/koa/index.d.ts +++ b/koa/index.d.ts @@ -14,127 +14,167 @@ =============================================== */ /// - - import { EventEmitter } from "events"; +import * as cookies from "cookies"; import * as http from "http"; import * as net from "net"; +declare namespace Koa { } +export = Koa; + declare namespace Koa { export interface Context extends Request, Response { - body?: any; - request?: Request; - response?: Response; - originalUrl?: string; - state?: any; + app: Koa; + req: http.IncomingMessage; + res: http.ServerResponse; + request: Request; + response: Response; + + cookies: cookies.ICookies; + originalUrl: string; + state: any; + name?: string; - cookies?: any; - writable?: Boolean; - respond?: Boolean; - app?: Koa; - req?: http.IncomingMessage; - res?: http.ServerResponse; - onerror(err: any): void; + respond?: boolean; + + assert(test: any, ...args: any[]): void; + onerror(err?: any): void; + throw(...args: any[]): void; + toJSON(): any; inspect(): any; - throw(code?: any, message?: any): void; - assert(test: any, status: number, message: string): void; } export interface Request { - _querycache?: string; - app?: Koa; - req?: http.IncomingMessage; - res?: http.ServerResponse; - response?: Response; - ctx?: Context; - headers?: any; - header?: any; - method?: string; - length?: any; - url?: string; - origin?: string; - originalUrl?: string; - href?: string; - path?: string; - querystring?: string; - query?: any; - search?: string; - idempotent?: Boolean; - socket?: net.Socket; - protocol?: string; - host?: string; - hostname?: string; - fresh?: Boolean; - stale?: Boolean; + app: Koa; + req: http.IncomingMessage; + res: http.ServerResponse; + ctx: Context; + response: Response; + + fresh: boolean; + header: any; + headers: any; + host: string; + hostname: string; + href: string; + idempotent: boolean; + ip: string; + ips: string[]; + method: string; + origin: string; + originalUrl: string; + path: string; + protocol: string; + query: any; + querystring: string; + search: string; + secure: boolean; + socket: net.Socket; + stale: boolean; + subdomains: string[]; + type: string; + url: string; + charset?: string; - secure?: Boolean; - ips?: Array; - ip?: string; - subdomains?: Array; - accept?: any; - type?: string; - accepts?: () => any; - acceptsEncodings?: () => any; - acceptsCharsets?: () => any; - acceptsLanguages?: () => any; - is?: (types: any) => any; - toJSON?: () => any; - inspect?: () => any; - get?: (field: string) => string; + length?: number; + + accepts(): string[]; + accepts(arg: string): void | string; + accepts(arg: string[]): void | string; + accepts(...args: string[]): void | string; + acceptsCharsets(): string[]; + acceptsCharsets(arg: string): void | string; + acceptsCharsets(arg: string[]): void | string; + acceptsCharsets(...args: string[]): void | string; + acceptsEncodings(): string[]; + acceptsEncodings(arg: string): void | string; + acceptsEncodings(arg: string[]): void | string; + acceptsEncodings(...args: string[]): void | string; + acceptsLanguages(): string[]; + acceptsLanguages(arg: string): void | string; + acceptsLanguages(arg: string[]): void | string; + acceptsLanguages(...args: string[]): void | string; + get(field: string): string; + is(): string[]; + is(arg: string): void | string; + is(arg: string[]): void | string; + is(...args: string[]): void | string; + + toJSON(): any; + inspect(): any; } export interface Response { - _body?: any; - _explicitStatus?: Boolean; - app?: Koa; - res?: http.ServerResponse; - req?: http.IncomingMessage; - ctx?: Context; - request?: Request; - socket?: net.Socket; - header?: any; - headers?: any; - status?: number; - message?: string; - type?: string; - body?: any; - length?: any; - headerSent?: Boolean; - lastModified?: Date; - etag?: string; - writable?: Boolean; - is?: (types: any) => any; - redirect?: (url: string, alt: string) => void; - attachment?: (filename?: string) => void; - vary?: (field: string) => void; - get?: (field: string) => string; - set?: (field: any, val: any) => void; - remove?: (field: string) => void; - append?: (field: string, val: any) => void; - toJSON?: () => any; - inspect?: () => any; + app: Koa; + req: http.IncomingMessage; + res: http.ServerResponse; + ctx: Context; + request: Request; + + body: any; + etag: string; + header: any; + headers: any; + headerSent: boolean; + lastModified: Date; + message: string; + socket: net.Socket; + status: number; + type: string; + writable: boolean; + + charset?: string; + length?: number; + + append(field: string, val: string | string[]): void; + attachment(filename?: string): void; + get(field: string): string; + is(): string[]; + is(arg: string): void | string; + is(arg: string[]): void | string; + is(...args: string[]): void | string; + redirect(url: string, alt?: string): void; + remove(field: string): void; + set(field: string, val: string | string[]): void; + set(field: any): void; + vary(field: string): void; + + toJSON(): any; + inspect(): any; } } declare class Koa extends EventEmitter { - keys: Array; subdomainOffset: number; - proxy: Boolean; server: http.Server; env: string; context: Koa.Context; + keys: string[]; + proxy: boolean; request: Koa.Request; response: Koa.Response; - silent: Boolean; + silent: boolean; + constructor(); - use(middleware: (ctx: Koa.Context, next: Function) => any): Koa; + + // From node.d.ts + listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): http.Server; + listen(port: number, hostname?: string, listeningListener?: Function): http.Server; + listen(port: number, backlog?: number, listeningListener?: Function): http.Server; + listen(port: number, listeningListener?: Function): http.Server; + listen(path: string, backlog?: number, listeningListener?: Function): http.Server; + listen(path: string, listeningListener?: Function): http.Server; + listen(handle: any, backlog?: number, listeningListener?: Function): http.Server; + listen(handle: any, listeningListener?: Function): http.Server; + listen(options: net.ListenOptions, listeningListener?: Function): http.Server; + callback(): (req: http.IncomingMessage, res: http.ServerResponse) => void; - listen(port: number, callback?: Function): http.Server; + onerror(err: any): void; + use(middleware: (ctx: Koa.Context, next: () => Promise) => any): Koa; + toJSON(): any; inspect(): any; onerror(err: any): void; } -declare namespace Koa { } -export = Koa; diff --git a/load-json-file/load-json-file-tests.ts b/load-json-file/load-json-file-tests.ts new file mode 100644 index 0000000000..89884bf78a --- /dev/null +++ b/load-json-file/load-json-file-tests.ts @@ -0,0 +1,15 @@ +/// +import * as loadJsonFile from 'load-json-file'; + +function assert(actual: string, expected: string): void { + if (actual !== expected) { + throw new Error(`${JSON.stringify(actual)} !== ${JSON.stringify(expected)}`); + } +} + +loadJsonFile('../package.json').then(pkg => { + assert(pkg.name, 'definitely-typed'); +}); + +const pkg = loadJsonFile.sync('../package.json'); +assert(pkg.name, 'definitely-typed'); diff --git a/load-json-file/load-json-file.d.ts b/load-json-file/load-json-file.d.ts new file mode 100644 index 0000000000..3da3c5ac2f --- /dev/null +++ b/load-json-file/load-json-file.d.ts @@ -0,0 +1,26 @@ +// Type definitions for load-json-file v2.0.0 +// Project: https://github.com/sindresorhus/load-json-file +// Definitions by: Sam Verschueren +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "load-json-file" { + + interface LoadJsonFile { + /** + * Returns a promise for the parsed JSON. + * + * @param filepath + */ + (filepath: string): Promise; + /** + * Returns the parsed JSON. + * + * @param filepath + */ + sync(filepath: string): any; + } + + const loadJsonFile: LoadJsonFile; + + export = loadJsonFile; +} diff --git a/lodash/index.d.ts b/lodash/index.d.ts index f1772191cd..35c6611596 100644 --- a/lodash/index.d.ts +++ b/lodash/index.d.ts @@ -2000,6 +2000,18 @@ declare module _ { flattenDeep(): LoDashExplicitArrayWrapper; } + // _.flattenDepth + interface LoDashStatic { + /** + * Recursively flatten array up to depth times. + * + * @param array The array to recursively flatten. + * @param number The maximum recursion depth. + * @return Returns the new flattened array. + */ + flattenDepth(array: ListOfRecursiveArraysOrValues, depth?: number): T[]; + } + //_.fromPairs interface LoDashStatic { /** @@ -13463,31 +13475,28 @@ declare module _ { iteratee: ListIterator ): number; - /** - * @see _.sumBy - **/ - sumBy( - collection: Dictionary, - iteratee: DictionaryIterator - ): number; - /** * @see _.sumBy */ - sumBy( - collection: List|Dictionary, + sumBy( + collection: List<{}>, iteratee: string ): number; /** * @see _.sumBy */ - sumBy(collection: List|Dictionary): number; + sumBy( + collection: List + ): number; /** * @see _.sumBy */ - sumBy(collection: List|Dictionary): number; + sumBy( + collection: List<{}>, + iteratee: Dictionary<{}> + ): number; } interface LoDashImplicitArrayWrapper { @@ -13506,15 +13515,15 @@ declare module _ { /** * @see _.sumBy */ - sumBy(): number; + sumBy(iteratee: Dictionary<{}>): number; } interface LoDashImplicitObjectWrapper { /** * @see _.sumBy - **/ - sumBy( - iteratee: ListIterator|DictionaryIterator + */ + sumBy( + iteratee: ListIterator<{}, number> ): number; /** @@ -13525,7 +13534,7 @@ declare module _ { /** * @see _.sumBy */ - sumBy(): number; + sumBy(iteratee: Dictionary<{}>): number; } interface LoDashExplicitArrayWrapper { @@ -13545,14 +13554,19 @@ declare module _ { * @see _.sumBy */ sumBy(): LoDashExplicitWrapper; + + /** + * @see _.sumBy + */ + sumBy(iteratee: Dictionary<{}>): LoDashExplicitWrapper; } interface LoDashExplicitObjectWrapper { /** * @see _.sumBy */ - sumBy( - iteratee: ListIterator|DictionaryIterator + sumBy( + iteratee: ListIterator<{}, number> ): LoDashExplicitWrapper; /** @@ -13563,7 +13577,7 @@ declare module _ { /** * @see _.sumBy */ - sumBy(): LoDashExplicitWrapper; + sumBy(iteratee: Dictionary<{}>): LoDashExplicitWrapper; } /********** @@ -19414,15 +19428,10 @@ declare module "lodash/flattenDeep" { export = flattenDeep; } -/** -* uncoment it if definition exists -*/ -/* declare module "lodash/flattenDepth" { const flattenDepth: typeof _.flattenDepth; export = flattenDepth; } -*/ declare module "lodash/flip" { const flip: typeof _.flip; diff --git a/lodash/lodash-3.10-tests.ts b/lodash/lodash-3.10-tests.ts index 585ac34145..140e91208a 100644 --- a/lodash/lodash-3.10-tests.ts +++ b/lodash/lodash-3.10-tests.ts @@ -7700,8 +7700,13 @@ namespace TestRound { // _.sum namespace TestSum { let array: number[]; + let objectArray: { 'age': number }[]; + let list: _.List; + let objectList: _.List<{ 'age': number }>; + let dictionary: _.Dictionary; + let objectDictionary: _.Dictionary<{ 'age': number }>; let listIterator: (value: number, index: number, collection: _.List) => number; let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => number; @@ -7713,36 +7718,36 @@ namespace TestSum { result = _.sum(array); result = _.sum(array, listIterator); result = _.sum(array, listIterator, any); - result = _.sum(array, ''); + result = _.sum(objectArray, 'age'); result = _.sum(list); result = _.sum(list); result = _.sum(list, listIterator); result = _.sum(list, listIterator, any); - result = _.sum(list, ''); + result = _.sum(objectList, 'age'); result = _.sum(dictionary); result = _.sum(dictionary); result = _.sum(dictionary, dictionaryIterator); result = _.sum(dictionary, dictionaryIterator, any); - result = _.sum(dictionary, ''); + result = _.sum(objectDictionary, 'age'); result = _(array).sum(); result = _(array).sum(listIterator); result = _(array).sum(listIterator, any); - result = _(array).sum(''); + result = _(objectArray).sum('age'); result = _(list).sum(); result = _(list).sum(listIterator); result = _(list).sum(listIterator, any); - result = _(list).sum(''); + result = _(objectList).sum('age'); result = _(dictionary).sum(); result = _(dictionary).sum(dictionaryIterator); result = _(dictionary).sum(dictionaryIterator, any); - result = _(dictionary).sum(''); + result = _(objectDictionary).sum('age'); } { @@ -7751,18 +7756,18 @@ namespace TestSum { result = _(array).chain().sum(); result = _(array).chain().sum(listIterator); result = _(array).chain().sum(listIterator, any); - result = _(array).chain().sum(''); + result = _(objectArray).chain().sum(''); result = _(list).chain().sum(); result = _(list).chain().sum(listIterator); result = _(list).chain().sum(listIterator, any); - result = _(list).chain().sum(''); + result = _(objectList).chain().sum('age'); result = _(dictionary).chain().sum(); result = _(dictionary).chain().sum(dictionaryIterator); result = _(dictionary).chain().sum(dictionaryIterator, any); - result = _(dictionary).chain().sum(''); + result = _(objectDictionary).chain().sum('age'); } } diff --git a/lodash/lodash-3.10.d.ts b/lodash/lodash-3.10.d.ts index 3948215468..eca84d937f 100644 --- a/lodash/lodash-3.10.d.ts +++ b/lodash/lodash-3.10.d.ts @@ -12065,8 +12065,8 @@ declare module _ { /** * @see _.sum */ - sum( - collection: List|Dictionary, + sum( + collection: List<{}>|Dictionary<{}>, iteratee: string ): number; diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 46b4bd4357..18786f28d0 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -7896,49 +7896,41 @@ namespace TestSum { // _.sumBy namespace TestSumBy { let array: number[]; + let objectArray: { 'age': number }[]; + let list: _.List; - let dictionary: _.Dictionary; + let objectList: _.List<{ 'age': number }>; let listIterator: (value: number, index: number, collection: _.List) => number; - let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => number; { let result: number; - result = _.sumBy(array); - result = _.sumBy(array, listIterator); - result = _.sumBy(array, ''); + result = _.sumBy(array); + result = _.sumBy(array, listIterator); + result = _.sumBy(objectArray, 'age'); + result = _.sumBy(objectArray, { 'age': 30 }); - - result = _.sumBy(list); - result = _.sumBy(list, listIterator); - result = _.sumBy(list, ''); - - result = _.sumBy(dictionary); - result = _.sumBy(dictionary, dictionaryIterator); - result = _.sumBy(dictionary, ''); + result = _.sumBy(list); + result = _.sumBy(list, listIterator); + result = _.sumBy(objectList, 'age'); + result = _.sumBy(objectList, { 'age': 30 }); result = _(array).sumBy(listIterator); - result = _(array).sumBy(''); + result = _(objectArray).sumBy('age'); - result = _(list).sumBy(listIterator); - result = _(list).sumBy(''); - - result = _(dictionary).sumBy(dictionaryIterator); - result = _(dictionary).sumBy(''); + result = _(list).sumBy(listIterator); + result = _(objectList).sumBy('age'); } { let result: _.LoDashExplicitWrapper; result = _(array).chain().sumBy(listIterator); - result = _(array).chain().sumBy(''); + result = _(objectArray).chain().sumBy('age'); - result = _(list).chain().sumBy(listIterator); - result = _(list).chain().sumBy(''); - - result = _(dictionary).chain().sumBy(dictionaryIterator); - result = _(dictionary).chain().sumBy(''); + result = _(list).chain().sumBy(listIterator); + result = _(objectList).chain().sumBy('age'); } } diff --git a/mailparser/index.d.ts b/mailparser/index.d.ts index 6ece4483d2..6d19c96320 100644 --- a/mailparser/index.d.ts +++ b/mailparser/index.d.ts @@ -5,6 +5,8 @@ /// +import StreamModule = require("stream"); +import Stream = StreamModule.Stream; import WritableStream = NodeJS.WritableStream; import EventEmitter = NodeJS.EventEmitter; @@ -33,6 +35,7 @@ interface Attachment { generatedFileName: string; // e.g. 'image.png' checksum: string; // the md5 hash of the file, e.g. 'e4cef4c6e26037bcf8166905207ea09b' content: Buffer; // possibly a SlowBuffer + stream: Stream; // a stream to read the attachment if streamAttachments is set to true } // emitted with the 'end' event diff --git a/mailparser/mailparser-tests.ts b/mailparser/mailparser-tests.ts index 18c84bef95..30338b7fb6 100644 --- a/mailparser/mailparser-tests.ts +++ b/mailparser/mailparser-tests.ts @@ -1,6 +1,7 @@ import mailparser_mod = require("mailparser"); import MailParser = mailparser_mod.MailParser; import ParsedMail = mailparser_mod.ParsedMail; +import Attachment = mailparser_mod.Attachment; var mailparser = new MailParser(); @@ -57,7 +58,7 @@ var mp = new MailParser({ streamAttachments: true }) -mp.on("attachment", function(attachment, mail){ +mp.on("attachment", function(attachment : Attachment, mail : ParsedMail){ var output = fs.createWriteStream(attachment.generatedFileName); attachment.stream.pipe(output); }); diff --git a/match-media-mock/match-media-mock-tests.ts b/match-media-mock/match-media-mock-tests.ts new file mode 100644 index 0000000000..613996f361 --- /dev/null +++ b/match-media-mock/match-media-mock-tests.ts @@ -0,0 +1,15 @@ +/// + +import { create } from "match-media-mock"; + +const matchMediaMock = create(); +matchMediaMock.setConfig({type: 'screen', width: 1200}) + +matchMediaMock('(max-width: 991px)').matches // false +matchMediaMock('(max-width: 1240px)').matches // true + +const mediaQueryList = matchMediaMock('(max-width: 991px)'); +const listener = (mql: MediaQueryList) => { }; + +mediaQueryList.addListener(listener) +mediaQueryList.removeListener(listener) diff --git a/match-media-mock/match-media-mock.d.ts b/match-media-mock/match-media-mock.d.ts new file mode 100644 index 0000000000..7e7161c8cb --- /dev/null +++ b/match-media-mock/match-media-mock.d.ts @@ -0,0 +1,35 @@ +// Type definitions for match-media-mock 0.1.0 +// Project: https://github.com/azazdeaz/match-media-mock +// Definitions by: Alexey Svetliakov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "match-media-mock" { + /** + * Mock configuration options + */ + interface ConfigOptions { + /** + * Screen type + */ + type?: string; + /** + * Screen height + */ + height?: number; + /** + * Screen width + */ + width?: number; + } + interface MatchMediaMock { + /** + * Set configuration + */ + setConfig(config: ConfigOptions): void; + /** + * Execute query based on provided configuration + */ + (query: string): MediaQueryList; + } + export function create(): MatchMediaMock; +} diff --git a/material-ui/index.d.ts b/material-ui/index.d.ts index 8c0bb78401..aa9987698f 100644 --- a/material-ui/index.d.ts +++ b/material-ui/index.d.ts @@ -451,7 +451,7 @@ declare namespace __MaterialUI { export function themeDecorator(muiTheme: Styles.MuiTheme): (Component: TFunction) => TFunction; interface MuiThemeProviderProps extends React.Props { - muiTheme: Styles.MuiTheme; + muiTheme?: Styles.MuiTheme; } export class MuiThemeProvider extends React.Component{ } @@ -661,7 +661,7 @@ declare namespace __MaterialUI { hoverColor?: string; href?: string; icon?: React.ReactNode; - label?: string; + label?: React.ReactNode; labelPosition?: "before" | "after"; labelStyle?: React.CSSProperties; linkButton?: boolean; @@ -687,7 +687,7 @@ declare namespace __MaterialUI { fullWidth?: boolean; href?: string; icon?: React.ReactNode; - label?: string; + label?: React.ReactNode; labelColor?: string; labelPosition?: "before" | "after"; labelStyle?: React.CSSProperties; diff --git a/material-ui/material-ui-tests.tsx b/material-ui/material-ui-tests.tsx index 26d767ea2c..1c9d73ff40 100644 --- a/material-ui/material-ui-tests.tsx +++ b/material-ui/material-ui-tests.tsx @@ -680,7 +680,7 @@ const FlatButtonExampleComplex = () => ( Label before} labelPosition="before" primary={true} style={styles.button} @@ -741,7 +741,7 @@ const RaisedButtonExampleComplex = () => ( Label before} labelPosition="before" primary={true} icon={} diff --git a/mathjs/index.d.ts b/mathjs/index.d.ts index 4bfbd89723..9671dd8005 100644 --- a/mathjs/index.d.ts +++ b/mathjs/index.d.ts @@ -1333,10 +1333,15 @@ declare namespace mathjs { export interface MathNode { isNode: boolean; - isSymbolNode: boolean; + isSymbolNode?: boolean; + isConstantNode?: boolean; + isOperatorNode?: boolean; + op?: string; + fn?: string; + args?: MathNode[]; type: string; - name: string; - value: any; + name?: string; + value?: any; compile(): EvalFunction; eval(): any; diff --git a/meteor-accounts-phone/meteor-accounts-phone-tests.ts b/meteor-accounts-phone/meteor-accounts-phone-tests.ts new file mode 100644 index 0000000000..0604d54939 --- /dev/null +++ b/meteor-accounts-phone/meteor-accounts-phone-tests.ts @@ -0,0 +1,50 @@ +/// + +let booleanResult: boolean; +const options = {}; +function noop() {} + +SMS.twilio = { + FROM: 'me', + ACCOUNT_SID: 'my-account-sid', + AUTH_TOKEN: 'my-auth-token' +}; + +SMS.phoneTemplate = { + from: 'me', + text: noop +}; + +SMS.send(options); +SMS.send(options, noop); + +Meteor.loginWithPhoneAndPassword(options, 'password'); +Meteor.loginWithPhoneAndPassword('options', 'password'); +Meteor.loginWithPhoneAndPassword(options, 'password', noop); +Meteor.loginWithPhoneAndPassword('options', 'password', noop); + +Accounts._options = { + verificationCodeLength: 4, + verificationMaxRetries: 10, + verificationRetriesWaitTime: 60 * 1000, + verificationWaitTime: 10 * 1000, + sendPhoneVerificationCodeOnCreation: true, + forbidClientAccountCreation: true, + phoneVerificationMasterCode: ['1234'], + adminPhoneNumbers: ['+972546999999'] +}; + +Accounts.createUserWithPhone(options); +Accounts.createUserWithPhone(options, noop); + +Accounts.requestPhoneVerification('+972546999999'); +Accounts.requestPhoneVerification('+972546999999', noop); + +Accounts.verifyPhone('+972546999999', '1234'); +Accounts.verifyPhone('+972546999999', '1234', noop); +Accounts.verifyPhone('+972546999999', '1234', '123456'); +Accounts.verifyPhone('+972546999999', '1234', '123456', noop); + +booleanResult = Accounts.isPhoneVerified(); + +Accounts.onPhoneVerification(noop); diff --git a/meteor-accounts-phone/meteor-accounts-phone.d.ts b/meteor-accounts-phone/meteor-accounts-phone.d.ts new file mode 100644 index 0000000000..fe8a610d7f --- /dev/null +++ b/meteor-accounts-phone/meteor-accounts-phone.d.ts @@ -0,0 +1,69 @@ +// Type definitions for accounts-phone 0.0.21 +// Project: https://github.com/okland/accounts-phone +// Definitions by: Eytan Manor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace SMS { + var twilio: { + FROM?: string; + ACCOUNT_SID?: string; + AUTH_TOKEN?: string; + }; + + var phoneTemplate: { + from: string; + text: Function; + }; + + function send(options: Object, callback?: Function): void; +} + +declare namespace Meteor { + function loginWithPhoneAndPassword(selector: Object | String, password: String, callback?: Function): void; +} + +declare module 'meteor/meteor' { + namespace Meteor { + function loginWithPhoneAndPassword(selector: Object | String, password: String, callback?: Function): void; + } +} + +declare namespace Accounts { + var _options: { + verificationCodeLength?: number, + verificationMaxRetries?: number, + verificationRetriesWaitTime?: number, + verificationWaitTime?: number, + sendPhoneVerificationCodeOnCreation?: boolean, + forbidClientAccountCreation?: boolean, + phoneVerificationMasterCode?: Array, + adminPhoneNumbers?: Array + }; + + function createUserWithPhone(options: Object, callback?: Function): void; + function requestPhoneVerification(phone: string, callback?: Function): void; + function verifyPhone(phone: string, code: string, newPassword?: string | Function, callback?: Function): void; + function isPhoneVerified(): boolean; + function onPhoneVerification(func: Function): void; +} + +declare module 'meteor/accounts-base' { + namespace Accounts { + var _options: { + verificationCodeLength?: number, + verificationMaxRetries?: number, + verificationRetriesWaitTime?: number, + verificationWaitTime?: number, + sendPhoneVerificationCodeOnCreation?: boolean, + forbidClientAccountCreation?: boolean, + phoneVerificationMasterCode?: Array, + adminPhoneNumbers?: Array + }; + + function createUserWithPhone(options: Object, callback?: Function): void; + function requestPhoneVerification(phone: string, callback?: Function): void; + function verifyPhone(phone: string, code: string, newPassword?: string | Function, callback?: Function): void; + function isPhoneVerified(): boolean; + function onPhoneVerification(func: Function): void; + } +} \ No newline at end of file diff --git a/meteor-publish-composite/index.d.ts b/meteor-publish-composite/index.d.ts index c5475e6d94..cd8b93b816 100644 --- a/meteor-publish-composite/index.d.ts +++ b/meteor-publish-composite/index.d.ts @@ -63,3 +63,18 @@ declare namespace Meteor { PublishCompositeConfig|PublishCompositeConfig[] ) : void; } + +declare module 'meteor/meteor' { + namespace Meteor { + function publishComposite( + name : string, + config : PublishCompositeConfig|PublishCompositeConfig[] + ) : void; + + function publishComposite( + name : string, + configFunc : (...args : any[]) => + PublishCompositeConfig|PublishCompositeConfig[] + ) : void; + } +} diff --git a/microsoft-ajax/index.d.ts b/microsoft-ajax/index.d.ts index 4853092a5c..6c6d34dc9d 100644 --- a/microsoft-ajax/index.d.ts +++ b/microsoft-ajax/index.d.ts @@ -257,14 +257,6 @@ interface ErrorConstructor { //#endregion } -interface Error { - /** - * Updates the fileName and lineNumber properties of an Error instance to indicate where the error was thrown instead of where the error was created. Use this function if you are creating custom error types. - */ - popStackFrame(): void; -} - - interface String { diff --git a/mocha/index.d.ts b/mocha/index.d.ts index eb167c83c9..5304f9333a 100644 --- a/mocha/index.d.ts +++ b/mocha/index.d.ts @@ -29,10 +29,6 @@ interface MochaSetupOptions { grep?: any; } -interface MochaDone { - (error?: Error): void; -} - declare var mocha: Mocha; declare var describe: Mocha.IContextDefinition; declare var xdescribe: Mocha.IContextDefinition; @@ -46,55 +42,29 @@ declare var xit: Mocha.ITestDefinition; declare var test: Mocha.ITestDefinition; declare var specify: Mocha.ITestDefinition; -declare function before(action: () => void): void; +interface MochaDone { + (error?: any): any; +} -declare function before(action: (done: MochaDone) => void): void; +interface ActionFunction { + (done: MochaDone): any | PromiseLike +} -declare function before(description: string, action: () => void): void; - -declare function before(description: string, action: (done: MochaDone) => void): void; - -declare function setup(action: () => void): void; - -declare function setup(action: (done: MochaDone) => void): void; - -declare function after(action: () => void): void; - -declare function after(action: (done: MochaDone) => void): void; - -declare function after(description: string, action: () => void): void; - -declare function after(description: string, action: (done: MochaDone) => void): void; - -declare function teardown(action: () => void): void; - -declare function teardown(action: (done: MochaDone) => void): void; - -declare function beforeEach(action: () => void): void; - -declare function beforeEach(action: (done: MochaDone) => void): void; - -declare function beforeEach(description: string, action: () => void): void; - -declare function beforeEach(description: string, action: (done: MochaDone) => void): void; - -declare function suiteSetup(action: () => void): void; - -declare function suiteSetup(action: (done: MochaDone) => void): void; - -declare function afterEach(action: () => void): void; - -declare function afterEach(action: (done: MochaDone) => void): void; - -declare function afterEach(description: string, action: () => void): void; - -declare function afterEach(description: string, action: (done: MochaDone) => void): void; - -declare function suiteTeardown(action: () => void): void; - -declare function suiteTeardown(action: (done: MochaDone) => void): void; +declare function setup(action: ActionFunction): void; +declare function teardown(action: ActionFunction): void; +declare function suiteSetup(action: ActionFunction): void; +declare function suiteTeardown(action: ActionFunction): void; +declare function before(action: ActionFunction): void; +declare function before(description: string, action: ActionFunction): void; +declare function after(action: ActionFunction): void; +declare function after(description: string, action: ActionFunction): void; +declare function beforeEach(action: ActionFunction): void; +declare function beforeEach(description: string, action: ActionFunction): void; +declare function afterEach(action: ActionFunction): void; +declare function afterEach(description: string, action: ActionFunction): void; declare class Mocha { + currentTest: Mocha.ITestDefinition; constructor(options?: { grep?: RegExp; ui?: string; @@ -176,13 +146,11 @@ declare namespace Mocha { } interface ITestDefinition { - (expectation: string, assertion?: () => void): ITest; - (expectation: string, assertion?: (done: MochaDone) => void): ITest; - only(expectation: string, assertion?: () => void): ITest; - only(expectation: string, assertion?: (done: MochaDone) => void): ITest; - skip(expectation: string, assertion?: () => void): void; - skip(expectation: string, assertion?: (done: MochaDone) => void): void; + (expectation: string, assertion?: ActionFunction): ITest; + only(expectation: string, assertion?: ActionFunction): ITest; + skip(expectation: string, assertion?: ActionFunction): void; timeout(ms: number): void; + state: "failed" | "passed"; } export module reporters { diff --git a/mongoose-promise/index.d.ts b/mongoose-promise/index.d.ts new file mode 100644 index 0000000000..d2622bb6f9 --- /dev/null +++ b/mongoose-promise/index.d.ts @@ -0,0 +1,128 @@ +// Type definitions for Mongoose-Promise 4.5.4 +// Project: http://mongoosejs.com/ +// Definitions by: simonxca +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* + * These are the default promises included in the Mongoose v4.x + * definitions. They will be deprecated beginning Mongoose V5.x + * in favor of native ES6 Promises. + * + * You can switch the promise library that mongoose uses by: + * + * 1. Including this somewhere in your code: + * mongoose.Promise = YOUR_PROMISE; + * + * 2. Including this somewhere in your main .d.ts file: + * type MongoosePromise = YOUR_PROMISE; + */ + +/* + * http://mongoosejs.com/docs/api.html#promise-js + * + * Callback signatures are from the mPromise type definitions. + */ +interface MongoosePromise { + /** + * Promise constructor. + * Promises are returned from executed queries. + * @param fn a function which will be called when the promise + * is resolved that accepts fn(err, ...){} as signature + * @event err Emits when the promise is rejected + * @event complete Emits when the promise is fulfilled + * @deprecated Mongoose 5.0 will use native promises by default (or bluebird, if native + * promises are not present) but still support plugging in your own ES6-compatible + * promises library. Mongoose 5.0 will not support mpromise. + */ + new(fn?: (err: any, arg: T) => void): MongoosePromise; + new(fn?: (err: any, ...args: T[]) => void): MongoosePromise; +} + +declare class MongoosePromise { + /** + * Adds a single function as a listener to both err and complete. + * It will be executed with traditional node.js argument position when the promise is resolved. + * @deprecated Use onResolve instead. + */ + addBack(listener: (err: any, arg: T) => void): this; + addBack(listener: (err: any, ...args: T[]) => void): this; + + /** + * Adds a listener to the complete (success) event. + * @deprecated Adds a listener to the complete (success) event. + */ + addCallback(listener: (arg: T) => void): this; + addCallback(listener: (...args: T[]) => void): this; + + /** + * Adds a listener to the err (rejected) event. + * @deprecated Use onReject instead. + */ + addErrback(listener: (err: any) => void): this; + + /** ES6-style .catch() shorthand */ + catch(onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; + + /** + * Signifies that this promise was the last in a chain of then()s: if a handler passed + * to the call to then which produced this promise throws, the exception will go uncaught. + */ + end(): void; + + /** + * Rejects this promise with err. + * If the promise has already been fulfilled or rejected, not action is taken. + * Differs from #reject by first casting err to an Error if it is not instanceof Error. + */ + error(err: any): this; + + /** + * Adds listener to the event. + * If event is either the success or failure event and the event has already been emitted, + * thelistener is called immediately and passed the results of the original emitted event. + */ + on(event: string, listener: Function): this; + + /** + * Rejects this promise with reason. + * If the promise has already been fulfilled or rejected, not action is taken. + */ + reject(reason: Object | string | Error): this; + + /** + * Resolves this promise to a rejected state if err is passed or a fulfilled state if no err is passed. + * If the promise has already been fulfilled or rejected, not action is taken. + * err will be cast to an Error if not already instanceof Error. + * NOTE: overrides mpromise#resolve to provide error casting. + * @param err error or null + * @param val value to fulfill the promise with + */ + resolve(err?: any, val?: Object): this; + + /** + * Creates a new promise and returns it. If onFulfill or onReject are passed, they are added as + * SUCCESS/ERROR callbacks to this promise after the nextTick. + * Conforms to promises/A+ specification. + */ + then(onFulFill: (arg: T) => void | TRes | PromiseLike, + onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; + then(onFulfill: (...args: T[]) => void | TRes | PromiseLike, + onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; + + /** + * Fulfills this promise with passed arguments. Alias of mpromise#fulfill. + * @deprecated Use fulfill instead. + */ + complete(args: T): this; + complete(...args: T[]): this; + + /** Fulfills this promise with passed arguments. */ + fulfill(...args: T[]): this; + fulfill(arg: T): this; + + /** ES6-style promise constructor wrapper around mpromise. */ + static ES6(resolver: ( + complete: (...args: TRes[]) => void | TRes | PromiseLike, + error: (e: any) => void | TRes | PromiseLike + ) => void): MongoosePromise; +} \ No newline at end of file diff --git a/mongoose-promise/mongoose-promise-tests.ts b/mongoose-promise/mongoose-promise-tests.ts new file mode 100644 index 0000000000..b3cdfa2354 --- /dev/null +++ b/mongoose-promise/mongoose-promise-tests.ts @@ -0,0 +1,44 @@ +var cb = function () {}; + +var mongopromise: MongoosePromise; +mongopromise.addBack(function (err, arg) { + err.stack; + arg.toFixed(); +}).addBack(function (err, arg1, arg2) { + err.stack; + arg1.toFixed(); + arg2.toFixed(); +}); +mongopromise.addCallback(function (arg) { + arg.toFixed(); +}).addCallback(function (arg1, arg2) { + arg1.toFixed(); + arg2.toFixed(); +}); +mongopromise.addErrback(function (err) { + err.stack; +}).addErrback(cb); +mongopromise.catch(function (err) { + err.stack; +}).catch(cb); +mongopromise.end(); +mongopromise.error(999).error([]); +mongopromise.on('init', cb).on('init', cb); +mongopromise.reject({}).reject('').reject(new Error('hi')); +mongopromise.resolve(new Error('hi'), {}).resolve(); +mongopromise.then(function (arg) { + arg.toFixed(); + return 9; +}, function (err) { + err.stack; + return 9; +}).then(function (arg1, arg2) { + arg1.toFixed(); + arg2.toFixed(); +}); +mongopromise.complete(); +/* static properties */ +MongoosePromise.ES6(function (complete, error) { + complete.apply(this); + error.apply(this); +}); \ No newline at end of file diff --git a/mongoose-promise/tsconfig.json b/mongoose-promise/tsconfig.json new file mode 100644 index 0000000000..45378dfc67 --- /dev/null +++ b/mongoose-promise/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mongoose-promise-tests.ts" + ] +} \ No newline at end of file diff --git a/mongoose/index.d.ts b/mongoose/index.d.ts index b0999f37a1..6a346462cd 100644 --- a/mongoose/index.d.ts +++ b/mongoose/index.d.ts @@ -1,653 +1,2630 @@ -// Type definitions for Mongoose 3.8.5 +// Type definitions for Mongoose 4.5.4 // Project: http://mongoosejs.com/ -// Definitions by: horiuchi +// Definitions by: simonxca , horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// +/// /// +/// + +/* + * Guidelines for maintaining these definitions: + * - If you spot an error here or there, please submit a PR. + * Give some examples/links to documentation if you can. + * + * For patches and minor releases: + * - Browse the changelog at https://github.com/Automattic/mongoose/blob/master/History.md + * and make necessary changes. Afterwards, update the version number at the top so we know + * which version we are on. + * + * For major releases: + * - Refer to the updated docs at http://mongoosejs.com/docs/api.html + * - On the left-hand side of the docs is a list of .js files. Reset and update the TODO list below + * then go through one-by-one, making any updates to params list, return type, etc. For documentation + * changes just copy/paste them into here. + * - Check the files off as you go. Some files below might not have anything in them. That's ok, this + * is just a simple heuristic to keep track of our progress. + * + * TODO for version 4.x [updated][tested]: + * [x][x] index.js + * [x][x] querystream.js + * [x][x] connection.js + * [x][x] utils.js + * [x][x] browser.js + * [x][x] drivers/node-mongodb-native/collection.js + * [x][x] drivers/node-mongodb-native/connection.js + * [x][x] error/messages.js + * [x][x] error/validation.js + * [x][x] error.js + * [x][x] querycursor.js + * [x][x] virtualtype.js + * [x][x] schema.js + * [x][x] document.js + * [x][x] types/subdocument.js + * [x][x] types/array.js + * [x][x] types/documentarray.js + * [x][x] types/buffer.js + * [x][x] types/objectid.js + * [x][x] types/embedded.js + * [x][x] query.js + * [x][x] schema/array.js + * [x][x] schema/string.js + * [x][x] schema/documentarray.js + * [x][x] schema/number.js + * [x][x] schema/date.js + * [x][x] schema/buffer.js + * [x][x] schema/boolean.js + * [x][x] schema/objectid.js + * [x][x] schema/mixed.js + * [x][x] schema/embedded.js + * [x][x] aggregate.js + * [x][x] schematype.js + * [x][x] promise.js + * [x][x] ES6Promise.js + * [x][x] model.js + * [x][x] collection.js + */ + +/* +For easier searching, add a header to each section like so: +To find a section, CTRL+F and type "section ___.js" +/* + * section filename.js + * http://mongoosejs.com/docs/api.html#filename-js + */ declare module "mongoose" { - function connect(uri: string, options?: ConnectionOptions, callback?: (err: any) => void): Mongoose; - function createConnection(): Connection; - function createConnection(uri: string, options?: ConnectionOptions): Connection; - function createConnection(host: string, database_name: string, port?: number, options?: ConnectionOptions): Connection; - function disconnect(callback?: (err?: any) => void): Mongoose; + import events = require('events'); + import mongodb = require('mongodb'); + import stream = require('stream'); - function model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; - function modelNames(): string[]; - function plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + /* + * Some mongoose classes have the same name as the native JS classes + * Keep references to native classes using a "Native" prefix + */ + type NativeBuffer = Buffer; + type NativeDate = Date; + type NativeError = Error; - function get(key: string): any; - function set(key: string, value: any): void; + /* + * Public API + */ + export = mongoose; - var mongo: any; - var mquery: any; - var version: string; - var connection: Connection; - - export class Mongoose { - connect(uri: string, options?: ConnectOpenOptionsBase, callback?: (err: any) => void): Mongoose; - createConnection(): Connection; - createConnection(uri: string, options?: Object): Connection; - createConnection(host: string, database_name: string, port?: number, options?: ConnectOpenOptionsBase): Connection; - disconnect(callback?: (err?: any) => void): Mongoose; - get(key: string): any; - model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; - modelNames(): string[]; - plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; - set(key: string, value: any): void; - - mongo: any; - mquery: any; - version: string; - connection: Connection; - Promise: any; - } - - export interface Connection extends NodeJS.EventEmitter { - constructor(base: Mongoose): Connection; - - close(callback?: (err: any) => void): Connection; - collection(name: string, options?: Object): Collection; - model(name: string, schema?: Schema, collection?: string): Model; - modelNames(): string[]; - open(host: string, database?: string, port?: number, options?: OpenSetConnectionOptions, callback?: (err: any) => void): Connection; - openSet(uris: string, database?: string, options?: OpenSetConnectionOptions, callback?: (err: any) => void): Connection; - - db: any; - collections: { [index: string]: Collection }; - readyState: number; - } - - export interface ConnectOpenOptionsBase { - db?: any; - server?: any; - replset?: any; - /** Username for authentication if not supplied in the URI. */ - user?: string; - /** Password for authentication if not supplied in the URI. */ - pass?: string; - /** Options for authentication */ - auth?: any; - } - - export interface ConnectionOptions extends ConnectOpenOptionsBase { - /** Passed to the underlying driver's Mongos instance. */ - mongos?: MongosOptions; - } - - interface OpenSetConnectionOptions extends ConnectOpenOptionsBase { - /** If true, enables High Availability support for mongos */ - mongos?: boolean; - } - - interface MongosOptions { - /** Turn on high availability monitoring. (default: true) */ - ha?: boolean; - /** Time between each replicaset status check. (default: 5000) */ - haInterval?: number; + /* + * section index.js + * http://mongoosejs.com/docs/api.html#index-js + * + * require('mongoose') is not actually a class with static + * methods. It is an instance of the Mongoose class. + * + * Reasons we use a class with static properties below: + * 1. MongooseThenable extends mongoose, so we need a + * scope to wrap everything. We can't use a namespace + * since namespaces can't be inherited from. + * 2. We can't use an interface to wrap everything, since + * some properties of mongoose are class constructors. + * Exporting an interface won't, for example, let us + * call new mongoose.Schema({}) + * 3. We can't use a normal class since require('mongoose') + * is an instance object. All of its properties are + * immediately accessible: require('mongoose').model('') + * If we export a normal class and import * as mongoose + * we'll have to call new mongoose() before we can use + * any of its methods, which would be inaccurate. + * + * NOTE: the static properties below cannot be used for + * type-checking. If you want to use the names for + * type-checking you must add a corresponding interface + * inside namespace mongoose {} defined below. + */ + /** + * Contains all the public properties and methods that can + * be accessed by mongoose = require('mongoose') + */ + class mongoose { + /* Class constructors */ + static Aggregate: typeof _mongoose.Aggregate; + static CastError: typeof _mongoose.CastError; + static Collection: _mongoose.Collection; + static Connection: typeof _mongoose.Connection; + static Document: typeof _mongoose.Document; + static DocumentProvider: any; + static Error: typeof _mongoose.Error; + static Model: _mongoose.ModelConstructor<{}>; + static Mongoose: { + // recursive constructor + new(...args: any[]): typeof mongoose; + } /** - * Number of connections in the connection pool for each - * server instance. (default: 5 (for legacy reasons)) */ - poolSize?: number; - /** - * Use ssl connection (needs to have a mongod server with - * ssl support). (default: false). + * To assign your own promise library: + * + * 1. Include this somewhere in your code: + * mongoose.Promise = YOUR_PROMISE; + * + * 2. Include this somewhere in your main .d.ts file: + * type MongoosePromise = YOUR_PROMISE; */ - ssl?: boolean; + static Promise: any; + static PromiseProvider: any; + static Query: typeof _mongoose.ModelQuery; + static Schema: typeof _mongoose.Schema; + static SchemaType: typeof _mongoose.SchemaType; + static SchemaTypes: typeof _mongoose.Schema.Types; + static Types: { + Subdocument: typeof _mongoose.Types.Subdocument; + Array: typeof _mongoose.Types.Array; + DocumentArray: typeof _mongoose.Types.DocumentArray; + Buffer: typeof _mongoose.Types.Buffer; + ObjectId: typeof _mongoose.Types.ObjectId; + Embedded: typeof _mongoose.Types.Embedded; + } + static VirtualType: typeof _mongoose.VirtualType; + + /* Properties */ + /** Expose connection states for user-land */ + static STATES: Object + /** The default connection of the mongoose module. */ + static connection: _mongoose.Connection; + /** The node-mongodb-native driver Mongoose uses. */ + static mongo: typeof mongodb; /** - * Validate mongod server certificate against ca - * (needs to have a mongod server with ssl support, 2.4 or higher) - * (default: true) + * The mquery query builder Mongoose uses. + * Currently there is no mquery type definition. */ - sslValidate?: boolean; - /** Turn on high availability monitoring. */ - sslCA?: (Buffer | string)[]; - sslKey?: Buffer | string; - sslPass?: Buffer | string; - socketOptions?: { - noDelay?: boolean; - keepAlive?: number; - connectionTimeoutMS?: number; - socketTimeoutMS?: number; - }; + static mquery: any; + /** The Mongoose version */ + static version: string; + + /* Methods */ + /** + * Opens the default mongoose connection. + * Options passed take precedence over options included in connection strings. + * @returns pseudo-promise wrapper around this + */ + static connect(uris: string, + options?: _mongoose.MongooseConnectOptions, + callback?: (err: mongodb.MongoError) => void): typeof _mongoose.MongooseThenable; + static connect(uris: string, + callback?: (err: mongodb.MongoError) => void): typeof _mongoose.MongooseThenable; + + /** + * Creates a Connection instance. + * Each connection instance maps to a single database. This method is helpful + * when mangaging multiple db connections. + * @param uri a mongodb:// URI + * @param options options to pass to the driver + * @returns the created Connection object + */ + static createConnection(): _mongoose.Connection; + static createConnection(uri: string, + options?: _mongoose.MongooseConnectOptions + ): _mongoose.Connection; + static createConnection(host: string, database_name: string, port?: number, + options?: _mongoose.MongooseConnectOptions + ): _mongoose.Connection; + + /** + * Disconnects all connections. + * @param fn called after all connection close. + * @returns pseudo-promise wrapper around this + */ + static disconnect(fn?: (error: any) => void): typeof _mongoose.MongooseThenable; + + /** Gets mongoose options */ + static get(key: string): any; + + /** + * Defines a model or retrieves it. + * Models defined on the mongoose instance are available to all connection + * created by the same mongoose instance. + * @param name model name + * @param collection (optional, induced from model name) + * @param skipInit whether to skip initialization (defaults to false) + */ + static model(name: string, schema?: _mongoose.Schema, collection?: string, + skipInit?: boolean): _mongoose.ModelConstructor; + static model(name: string, schema?: _mongoose.Schema, collection?: string, + skipInit?: boolean): Statics & _mongoose.ModelConstructor; + + /** + * Returns an array of model names created on this instance of Mongoose. + * Does not include names of models created using connection.model(). + */ + static modelNames(): string[]; + + /** + * Declares a global plugin executed on all Schemas. + * Equivalent to calling .plugin(fn) on each Schema you create. + * @param fn plugin callback + * @param opts optional options + */ + static plugin(fn: Function, opts?: Object): typeof mongoose; + + /** Sets mongoose options */ + static set(key: string, value: any): void; } - export interface Collection { - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeOrderedBulkOp - initializeOrderedBulkOp(options?: CollectionOptions): OrderedBulkOperation; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeUnorderedBulkOp - initializeUnorderedBulkOp(options?: CollectionOptions): UnorderedBulkOperation; + /** All the types that are exposed for type checking. */ + namespace mongoose { + type Aggregate = _mongoose.Aggregate; + type CastError = _mongoose.CastError; + type Collection = _mongoose.Collection; + type Connection = _mongoose.Connection; + type Document = _mongoose.Document; + type Error = _mongoose.Error; + type ValidationError = _mongoose.ValidationError; + + /** Document created from model constructors. */ + type model = _mongoose.Model; + /** Model Constructor. */ + type Model = _mongoose.ModelConstructor; + + type Mongoose = typeof mongoose; + type Promise = _mongoose._MongoosePromise; + type Query = _mongoose.Query; + type QueryCursor = _mongoose.QueryCursor; + type QueryStream = _mongoose.QueryStream; + type Schema = _mongoose.Schema; + namespace Schema { + namespace Types { + type Array = _mongoose.Schema._Types.Array; + type String = _mongoose.Schema._Types.String; + type DocumentArray = _mongoose.Schema._Types.DocumentArray; + type Number = _mongoose.Schema._Types.Number; + type Date = _mongoose.Schema._Types.Date; + type Buffer = _mongoose.Schema._Types.Buffer; + type Boolean = _mongoose.Schema._Types.Boolean; + type Bool = _mongoose.Schema._Types.Boolean; + type ObjectId = _mongoose.Schema._Types.ObjectId; + type Oid = _mongoose.Schema._Types.ObjectId; + type Mixed = _mongoose.Schema._Types.Mixed; + type Object = _mongoose.Schema._Types.Mixed; + type Embedded = _mongoose.Schema._Types.Embedded; + } + } + type SchemaType = _mongoose.SchemaType; + namespace Types { + type Subdocument = _mongoose.Types.Subdocument; + type Array = _mongoose.Types.Array; + type DocumentArray = _mongoose.Types.DocumentArray; + type Buffer = _mongoose.Types.Buffer; + type ObjectId = _mongoose.Types.ObjectId; + type Embedded = _mongoose.Types.Embedded; + } + type VirtualType = _mongoose.VirtualType; + type ConnectionOptions = _mongoose.MongooseConnectOptions; } - export interface CollectionOptions { - //The write concern. - w?: number | string; - //The write concern timeout. - wtimeout?: number; - //Specify a journal write concern. - j?: boolean; - } + /* + * Public API Details. + */ + namespace _mongoose { + /* + * section index.js + * http://mongoosejs.com/docs/api.html#index-js + */ + class MongooseThenable extends mongoose { + /** + * Ability to use mongoose object as a pseudo-promise so .connect().then() + * and .disconnect().then() are viable. + */ + static then(onFulfill?: () => void | TRes | PromiseLike, + onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; - //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html - export interface OrderedBulkOperation { - length: number; - //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#execute - execute(callback: MongoCallback): void; - execute(options?: FSyncOptions): Promise; - execute(options: FSyncOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#find - find(selector: Object): FindOperatorsOrdered; - //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#insert - insert(doc: Object): OrderedBulkOperation; - } + /** + * Ability to use mongoose object as a pseudo-promise so .connect().then() + * and .disconnect().then() are viable. + */ + static catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; + } - //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html - export interface UnorderedBulkOperation { - //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#execute - execute(callback: MongoCallback): void; - execute(options?: FSyncOptions): Promise; - execute(options: FSyncOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#find - find(selector: Object): FindOperatorsUnordered; - //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#insert - insert(doc: Object): UnorderedBulkOperation; - } + class CastError extends _mongoose.Error { + /** + * The Mongoose CastError constructor + * @param type The name of the type + * @param value The value that failed to cast + * @param path The path a.b.c in the doc where this cast error occurred + * @param reason The original error that was thrown + */ + constructor(type: string, value: any, path: string, reason?: NativeError); + } - export interface MongoCallback { - (error: MongoError, result: T): void; - } + interface MongooseConnectOptions extends + ConnectionOpenOptions, + ConnectionOpenSetOptions {} - // http://mongodb.github.io/node-mongodb-native/2.1/api/MongoError.html - export class MongoError extends Error { - constructor(message: string); - static create(options: Object): MongoError; - } + /* + * section querystream.js + * http://mongoosejs.com/docs/api.html#querystream-js + * + * QueryStream can only be accessed using query#stream(), we only + * expose its interface here to enable type-checking. + */ + interface QueryStream extends stream.Stream { + /** + * Provides a Node.js 0.8 style ReadStream interface for Queries. + * @event data emits a single Mongoose document + * @event error emits when an error occurs during streaming. This will emit before the close event. + * @event close emits when the stream reaches the end of the cursor or an error occurs, or the stream + * is manually destroyed. After this event, no more events are emitted. + */ + constructor(query: Query, options?: { + /** + * optional function which accepts a mongoose document. The return value + * of the function will be emitted on data. + */ + transform?: Function; + [other: string]: any; + }): QueryStream; - //http://mongodb.github.io/node-mongodb-native/2.1/api/BulkWriteResult.html - export interface BulkWriteResult { - ok: number; - nInserted: number; - nUpdated: number; - nUpserted: number; - nModified: number; - nRemoved: number; + /** + * Destroys the stream, closing the underlying cursor, which emits the close event. + * No more events will be emitted after the close event. + */ + destroy(err?: NativeError): void; - getInsertedIds(): Array; - getLastOp(): Object; - getRawResponse(): Object; - getUpsertedIdAt(index: number): Object; - getUpsertedIds(): Array; - getWriteConcernError(): WriteConcernError; - getWriteErrorAt(index: number): WriteError; - getWriteErrorCount(): number; - getWriteErrors(): Array; - hasWriteErrors(): boolean; - } + /** Pauses this stream. */ + pause(): void; + /** Pipes this query stream into another stream. This method is inherited from NodeJS Streams. */ + pipe(destination: T, options?: { end?: boolean; }): T; + /** Resumes this stream. */ + resume(): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/WriteError.html - export interface WriteError { - //Write concern error code. - code: number; - //Write concern error original bulk operation index. - index: number; - //Write concern error message. - errmsg: string; - } + /** Flag stating whether or not this stream is paused. */ + paused: boolean; + /** Flag stating whether or not this stream is readable. */ + readable: boolean; + } - //http://mongodb.github.io/node-mongodb-native/2.1/api/WriteConcernError.html - export interface WriteConcernError { - //Write concern error code. - code: number; - //Write concern error message. - errmsg: string; - } + /* + * section connection.js + * http://mongoosejs.com/docs/api.html#connection-js + * + * The Connection class exposed by require('mongoose') + * is actually the driver's NativeConnection class. + * connection.js defines a base class that the native + * versions extend. See: + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js + */ + abstract class ConnectionBase extends events.EventEmitter { + /** + * For practical reasons, a Connection equals a Db. + * @param base a mongoose instance + * @event connecting Emitted when connection.{open,openSet}() is executed on this connection. + * @event connected Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios. + * @event open Emitted after we connected and onOpen is executed on all of this connections models. + * @event disconnecting Emitted when connection.close() was executed. + * @event disconnected Emitted after getting disconnected from the db. + * @event close Emitted after we disconnected and onClose executed on all of this connections models. + * @event reconnected Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection. + * @event error Emitted when an error occurs on this connection. + * @event fullsetup Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected. + * @event all Emitted in a replica-set scenario, when all nodes specified in the connection string are connected. + */ + constructor(base: typeof mongoose); - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#removeUser - export interface FSyncOptions { - w?: number | string; - wtimeout?: number; - j?: boolean; - fsync?: boolean - } + /** + * Opens the connection to MongoDB. + * @param mongodb://uri or the host to which you are connecting + * @param database database name + * @param port database port + * @param options Mongoose forces the db option forceServerObjectId false and cannot be overridden. + * Mongoose defaults the server auto_reconnect options to true which can be overridden. + * See the node-mongodb-native driver instance for options that it understands. + * Options passed take precedence over options included in connection strings. + */ + open(connection_string: string, database?: string, port?: number, + options?: ConnectionOpenOptions, callback?: (err: any) => void): any; - //http://mongodb.github.io/node-mongodb-native/2.1/api/FindOperatorsOrdered.html - export interface FindOperatorsOrdered { - delete(): OrderedBulkOperation; - deleteOne(): OrderedBulkOperation; - replaceOne(doc: Object): OrderedBulkOperation; - update(doc: Object): OrderedBulkOperation; - updateOne(doc: Object): OrderedBulkOperation; - upsert(): FindOperatorsOrdered; - } + /** + * Opens the connection to a replica set. + * @param uris comma-separated mongodb:// URIs + * @param database database name if not included in uris + * @param options passed to the internal driver + */ + openSet(uris: string, database?: string, options?: ConnectionOpenSetOptions, + callback?: (err: any) => void): any; - //http://mongodb.github.io/node-mongodb-native/2.1/api/FindOperatorsUnordered.html - export interface FindOperatorsUnordered { - length: number; - remove(): UnorderedBulkOperation; - removeOne(): UnorderedBulkOperation; - replaceOne(doc: Object): UnorderedBulkOperation; - update(doc: Object): UnorderedBulkOperation; - updateOne(doc: Object): UnorderedBulkOperation; - upsert(): FindOperatorsUnordered; - } + /** Closes the connection */ + close(callback?: (err: any) => void): _MongoosePromise; - export class SchemaType { } - export class VirtualType { - get(fn: Function): VirtualType; - set(fn: Function): VirtualType; - } - export module Types { - export class ObjectId { - constructor(id?: string | number); - toHexString(): string; - equals(other: ObjectId): boolean; - getTimestamp(): Date; - isValid(): boolean; - static createFromTime(time: number): ObjectId; - static createFromHexString(hexString: string): ObjectId; - static isValid(id?: string | number): boolean; + /** + * Retrieves a collection, creating it if not cached. + * Not typically needed by applications. Just talk to your collection through your model. + * @param name name of the collection + * @param options optional collection options + */ + collection(name: string, options?: Object): Collection; + + /** + * Defines or retrieves a model. + * When no collection argument is passed, Mongoose produces a collection name by passing + * the model name to the utils.toCollectionName method. This method pluralizes the name. + * If you don't like this behavior, either pass a collection name or set your schemas + * collection name option. + * @param name the model name + * @param schema a schema. necessary when defining a model + * @param collection name of mongodb collection (optional) if not given it will be induced from model name + * @returns The compiled model + */ + model(name: string, schema?: Schema, collection?: string): ModelConstructor; + model(name: string, schema?: Schema, collection?: string): Statics & ModelConstructor; + + /** Returns an array of model names created on this connection. */ + modelNames(): string[]; + + /** A hash of the global options that are associated with this connection */ + config: Object; + + /** The mongodb.Db instance, set when the connection is opened */ + db: mongodb.Db; + + /** A hash of the collections associated with this connection */ + collections: { [index: string]: Collection }; + + /** + * Connection ready state + * 0 = disconnected + * 1 = connected + * 2 = connecting + * 3 = disconnecting + * Each state change emits its associated event name. + */ + readyState: number; + } + + interface ConnectionOptionsBase { + /** passed to the connection db instance */ + db?: any; + /** passed to the connection server instance(s) */ + server?: any; + /** passed to the connection ReplSet instance */ + replset?: any; + /** username for authentication */ + user?: string; + /** password for authentication */ + pass?: string; + /** options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) */ + auth?: any; + } + + /** See the node-mongodb-native driver instance for options that it understands. */ + interface ConnectionOpenOptions extends ConnectionOptionsBase { + /** mongoose-specific options */ + config?: { + /** + * set to false to disable automatic index creation for all + * models associated with this connection. + */ + autoIndex?: boolean; + }; + } + + /** See the node-mongodb-native driver instance for options that it understands. */ + interface ConnectionOpenSetOptions extends ConnectionOptionsBase { + /** + * If true, enables High Availability support for mongos + * If connecting to multiple mongos servers, set the mongos option to true. + */ + mongos?: boolean; + } + + /* + * section drivers/node-mongodb-native/collection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js + */ + interface Collection extends CollectionBase { + /** + * Collection constructor + * @param name name of the collection + * @param conn A MongooseConnection instance + * @param opts optional collection options + */ + new(name: string, conn: Connection, opts?: Object): Collection; + /** Formatter for debug print args */ + $format(arg: any): string; + /** Debug print helper */ + $print(name: any, i: any, args: any[]): void; + /** Retreives information about this collections indexes. */ + getIndexes(): any; + } + + /* + * section drivers/node-mongodb-native/connection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js + */ + class Connection extends ConnectionBase { + /** + * Switches to a different database using the same connection pool. + * @param name The database name + * @returns New Connection Object + */ + useDb(name: string): Connection; + + /** Expose the possible connection states. */ + static STATES: Object; + } + + /* + * section error/validation.js + * http://mongoosejs.com/docs/api.html#error-validation-js + */ + class ValidationError extends Error { + /** Console.log helper */ + toString(): string; + } + + /* + * section error.js + * http://mongoosejs.com/docs/api.html#error-js + */ + class Error extends global.Error { + /** + * MongooseError constructor + * @param msg Error message + */ + constructor(msg: string); + + /** + * The default built-in validator error messages. These may be customized. + * As you might have noticed, error messages support basic templating + * {PATH} is replaced with the invalid document path + * {VALUE} is replaced with the invalid value + * {TYPE} is replaced with the validator type such as "regexp", "min", or "user defined" + * {MIN} is replaced with the declared min value for the Number.min validator + * {MAX} is replaced with the declared max value for the Number.max validator + */ + static messages: Object; + + /** For backwards compatibility. Same as mongoose.Error.messages */ + static Messages: Object; + } + + /* + * section querycursor.js + * http://mongoosejs.com/docs/api.html#querycursor-js + * + * Callback signatures are from: http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close + * QueryCursor can only be accessed by query#cursor(), we only + * expose its interface to enable type-checking. + */ + interface QueryCursor extends stream.Readable { + /** + * A QueryCursor is a concurrency primitive for processing query results + * one document at a time. A QueryCursor fulfills the Node.js streams3 API, + * in addition to several other mechanisms for loading documents from MongoDB + * one at a time. + * Unless you're an advanced user, do not instantiate this class directly. + * Use Query#cursor() instead. + * @param options query options passed to .find() + * @event cursor Emitted when the cursor is created + * @event error Emitted when an error occurred + * @event data Emitted when the stream is flowing and the next doc is ready + * @event end Emitted when the stream is exhausted + */ + constructor(query: Query, options: Object): QueryCursor; + + /** Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error. */ + close(callback?: (error: any, result: any) => void): _MongoosePromise; + + /** + * Execute fn for every document in the cursor. If fn returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + * @param callback executed when all docs have been processed + */ + eachAsync(fn: (doc: Model) => any, callback?: (err: any) => void): _MongoosePromise>; + + /** + * Get the next document from this cursor. Will return null when there are + * no documents left. + */ + next(callback?: (err: any) => void): _MongoosePromise; + } + + /* + * section virtualtype.js + * http://mongoosejs.com/docs/api.html#virtualtype-js + */ + class VirtualType { + /** This is what mongoose uses to define virtual attributes via Schema.prototype.virtual. */ + constructor(options: Object, name: string); + /** Applies getters to value using optional scope. */ + applyGetters(value: Object, scope: Object): any; + /** Applies setters to value using optional scope. */ + applySetters(value: Object, scope: Object): any; + /** Defines a getter. */ + get(fn: Function): this; + /** Defines a setter. */ + set(fn: Function): this; + } + + /* + * section schema.js + * http://mongoosejs.com/docs/api.html#schema-js + */ + class Schema extends events.EventEmitter { + /** + * Schema constructor. + * When nesting schemas, (children in the example above), always declare + * the child schema first before passing it into its parent. + * @event init Emitted after the schema is compiled into a Model. + */ + constructor(definition?: Object, options?: SchemaOptions); + + /** Adds key path / schema type pairs to this schema. */ + add(obj: Object, prefix?: string): void; + + /** + * Iterates the schemas paths similar to Array.forEach. + * @param fn callback function + * @returns this + */ + eachPath(fn: (path: string, type: SchemaType) => void): this; + + /** + * Gets a schema option. + * @param key option name + */ + get(key: string): any; + + /** + * Defines an index (most likely compound) for this schema. + * @param options Options to pass to MongoDB driver's createIndex() function + * @param options.expires Mongoose-specific syntactic sugar, uses ms to convert + * expires option into seconds for the expireAfterSeconds in the above link. + */ + index(fields: Object, options?: { + expires?: string; + [other: string]: any; + }): this; + + /** Compiles indexes from fields and schema-level indexes */ + indexes(): any[]; + + /** + * Adds an instance method to documents constructed from Models compiled from this schema. + * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. + */ + method(method: string, fn: Function): this; + method(methodObj: { [name: string]: Function }): this; + + /** + * Gets/sets schema paths. + * Sets a path (if arity 2) + * Gets a path (if arity 1) + */ + path(path: string): SchemaType; + path(path: string, constructor: any): this; + + /** + * Returns the pathType of path for this schema. + * @returns whether it is a real, virtual, nested, or ad-hoc/undefined path. + */ + pathType(path: string): string; + + /** + * Registers a plugin for this schema. + * @param plugin callback + */ + plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this; + + /** + * Defines a post hook for the document + * Post hooks fire on the event emitted from document instances of Models compiled + * from this schema. + * @param method name of the method to hook + * @param fn callback + */ + post(method: string, fn: (doc: Model) => void, ...args: any[]): this; + post(method: string, fn: (doc: Model, next: (err?: NativeError) => void, + ...otherArgs: any[]) => void): this; + + /** + * Defines a pre hook for the document. + */ + pre(method: string, fn: (next: (err?: NativeError) => void) => void, + errorCb?: (err: Error) => void): this; + pre(method: string, parallel: boolean, fn: (next: (err?: NativeError) => void, done: () => void) => void, + errorCb?: (err: Error) => void): this; + + /** + * Adds a method call to the queue. + * @param name name of the document method to call later + * @param args arguments to pass to the method + */ + queue(name: string, args: any[]): this; + + /** + * Removes the given path (or [paths]). + */ + remove(path: string | string[]): void; + + /** + * @param invalidate refresh the cache + * @returns an Array of path strings that are required by this schema. + */ + requiredPaths(invalidate?: boolean): string[]; + + /** + * Sets/gets a schema option. + * @param key option name + * @param value if not passed, the current option value is returned + */ + set(key: string): any; + set(key: string, value: any): this; + + /** + * Adds static "class" methods to Models compiled from this schema. + */ + static(name: string, fn: Function): this; + static(nameObj: { [name: string]: Function }): this; + + /** Creates a virtual type with the given name. */ + virtual(name: string, options?: Object): VirtualType; + + /** Returns the virtual type with the given name. */ + virtualpath(name: string): VirtualType; + + /** The allowed index types */ + static indexTypes: string[]; + + /** + * Reserved document keys. + * Keys in this object are names that are rejected in schema declarations + * b/c they conflict with mongoose functionality. Using these key name + * will throw an error. + */ + static reserved: Object; + + static Types: { + Array: typeof _mongoose.Schema._Types.Array; + String: typeof _mongoose.Schema._Types.String; + DocumentArray: typeof _mongoose.Schema._Types.DocumentArray; + Number: typeof _mongoose.Schema._Types.Number; + Date: typeof _mongoose.Schema._Types.Date; + Buffer: typeof _mongoose.Schema._Types.Buffer; + Boolean: typeof _mongoose.Schema._Types.Boolean; + Bool: typeof _mongoose.Schema._Types.Boolean; + ObjectId: typeof _mongoose.Schema._Types.ObjectId; + Oid: typeof _mongoose.Schema._Types.ObjectId; + Mixed: typeof _mongoose.Schema._Types.Mixed; + Object: typeof _mongoose.Schema._Types.Mixed; + Embedded: typeof _mongoose.Schema._Types.Embedded; + } + + /** Object of currently defined methods on this schema. */ + methods: any; + /** Object of currently defined statics on this schema. */ + statics: any; + } + + interface SchemaOptions { + /** defaults to null (which means use the connection's autoIndex option) */ + autoIndex?: boolean; + /** defaults to true */ + bufferCommands?: boolean; + /** defaults to false */ + capped?: boolean; + /** no default */ + collection?: string; + /** defaults to false. */ + emitIndexErrors?: boolean; + /** defaults to true */ + id?: boolean; + /** defaults to true */ + _id?: boolean; + /** controls document#toObject behavior when called manually - defaults to true */ + minimize?: boolean; + read?: string; + /** defaults to true. */ + safe?: boolean; + /** defaults to null */ + shardKey?: boolean; + /** defaults to true */ + strict?: boolean; + /** no default */ + toJSON?: Object; + /** no default */ + toObject?: Object; + /** defaults to 'type' */ + typeKey?: string; + /** defaults to false */ + useNestedStrict?: boolean; + /** defaults to true */ + validateBeforeSave?: boolean; + /** defaults to "__v" */ + versionKey?: boolean; + /** + * skipVersioning allows excluding paths from + * versioning (the internal revision will not be + * incremented even if these paths are updated). + */ + skipVersioning?: Object; + /** + * If set timestamps, mongoose assigns createdAt + * and updatedAt fields to your schema, the type + * assigned is Date. + */ + timestamps?: Object; + } + + /* + * section document.js + * http://mongoosejs.com/docs/api.html#document-js + */ + class Document { + /** Checks if a path is set to its default. */ + $isDefault(path?: string): boolean; + + /** + * Takes a populated field and returns it to its unpopulated state. + * If the path was not populated, this is a no-op. + */ + depopulate(path: string): void; + + /** + * Returns true if the Document stores the same data as doc. + * Documents are considered equal when they have matching _ids, unless neither document + * has an _id, in which case this function falls back to usin deepEqual(). + * @param doc a document to compare + */ + equals(doc: Document): boolean; + + /** + * Explicitly executes population and returns a promise. + * Useful for ES2015 integration. + * @returns promise that resolves to the document when population is done + */ + execPopulate(): _MongoosePromise; + + /** + * Returns the value of a path. + * @param type optionally specify a type for on-the-fly attributes + */ + get(path: string, type?: any): any; + + /** + * Initializes the document without setters or marking anything modified. + * Called internally after a document is returned from mongodb. + * @param doc document returned by mongo + * @param fn callback + */ + init(doc: Document, fn?: () => void): this; + init(doc: Document, opts: Object, fn?: () => void): this; + + /** Helper for console.log */ + inspect(options?: Object): any; + + /** + * Marks a path as invalid, causing validation to fail. + * The errorMsg argument will become the message of the ValidationError. + * The value argument (if passed) will be available through the ValidationError.value property. + * @param path the field to invalidate + * @param errorMsg the error which states the reason path was invalid + * @param value optional invalid value + * @param kind optional kind property for the error + * @returns the current ValidationError, with all currently invalidated paths + */ + invalidate(path: string, errorMsg: string | NativeError, value: any, kind?: string): ValidationError | boolean; + + /** Returns true if path was directly set and modified, else false. */ + isDirectModified(path: string): boolean; + + /** Checks if path was initialized */ + isInit(path: string): boolean; + + /** + * Returns true if this document was modified, else false. + * If path is given, checks if a path or any full path containing path as part of its path + * chain has been modified. + */ + isModified(path?: string): boolean; + + /** Checks if path was selected in the source query which initialized this document. */ + isSelected(path: string): boolean; + + /** + * Marks the path as having pending changes to write to the db. + * Very helpful when using Mixed types. + * @param path the path to mark modified + */ + markModified(path: string): void; + + /** Returns the list of paths that have been modified. */ + modifiedPaths(): string[]; + + /** + * Populates document references, executing the callback when complete. + * If you want to use promises instead, use this function with + * execPopulate() + * Population does not occur unless a callback is passed or you explicitly + * call execPopulate(). Passing the same path a second time will overwrite + * the previous path options. See Model.populate() for explaination of options. + * @param path The path to populate or an options object + * @param callback When passed, population is invoked + */ + populate(callback: (err: any, res: this) => void): this; + populate(path: string, callback?: (err: any, res: this) => void): this; + populate(options: ModelPopulateOptions, callback?: (err: any, res: this) => void): this; + + /** Gets _id(s) used during population of the given path. If the path was not populated, undefined is returned. */ + populated(path: string): any; + + /** + * Sets the value of a path, or many paths. + * @param path path or object of key/vals to set + * @param val the value to set + * @param type optionally specify a type for "on-the-fly" attributes + * @param options optionally specify options that modify the behavior of the set + */ + set(path: string, val: any, options?: Object): void; + set(path: string, val: any, type: any, options?: Object): void; + set(value: Object): void; + + /** + * The return value of this method is used in calls to JSON.stringify(doc). + * This method accepts the same options as Document#toObject. To apply the + * options to every document of your schema by default, set your schemas + * toJSON option to the same argument. + */ + toJSON(options?: DocumentToObjectOptions): Object; + + /** + * Converts this document into a plain javascript object, ready for storage in MongoDB. + * Buffers are converted to instances of mongodb.Binary for proper storage. + */ + toObject(options?: DocumentToObjectOptions): Object; + + /** Helper for console.log */ + toString(): string; + + /** + * Clears the modified state on the specified path. + * @param path the path to unmark modified + */ + unmarkModified(path: string): void; + + /** Sends an update command with this document _id as the query selector. */ + update(doc: Object, callback?: (err: any, raw: any) => void): Query; + update(doc: Object, options: ModelUpdateOptions, + callback?: (err: any, raw: any) => void): Query; + + /** + * Executes registered validation rules for this document. + * @param optional options internal options + * @param callback callback called after validation completes, passing an error if one occurred + */ + validate(callback?: (err: any) => void): _MongoosePromise; + validate(optional: Object, callback?: (err: any) => void): _MongoosePromise; + + /** + * Executes registered validation rules (skipping asynchronous validators) for this document. + * This method is useful if you need synchronous validation. + * @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[]): _mongoose.Error; + + /** Hash containing current validation errors. */ + errors: Object; + /** The string version of this documents _id. */ + id: string; + /** This documents _id. */ + _id: any; + /** Boolean flag specifying if the document is new. */ + isNew: boolean; + /** The documents schema. */ + schema: Schema; + } + + interface DocumentToObjectOptions { + /** apply all getters (path and virtual getters) */ + getters?: boolean; + /** apply virtual getters (can override getters option) */ + virtuals?: boolean; + /** remove empty objects (defaults to true) */ + minimize?: boolean; + /** + * A transform function to apply to the resulting document before returning + * @param doc The mongoose document which is being converted + * @param ret The plain object representation which has been converted + * @param options The options in use (either schema options or the options passed inline) + */ + transform?: (doc: Model, ret: Object, options: Object) => any; + /** depopulate any populated paths, replacing them with their original refs (defaults to false) */ + depopulate?: boolean; + /** whether to include the version key (defaults to true) */ + versionKey?: boolean; + /** + * keep the order of object keys. If this is set to true, + * Object.keys(new Doc({ a: 1, b: 2}).toObject()) will + * always produce ['a', 'b'] (defaults to false) + */ + retainKeyOrder?: boolean; + } + + namespace Types { + /* + * section types/subdocument.js + * http://mongoosejs.com/docs/api.html#types-subdocument-js + */ + class Subdocument extends Document { + /** Returns the top level document of this sub-document. */ + ownerDocument(): Document; + + /** + * Null-out this subdoc + * @param callback optional callback for compatibility with Document.prototype.remove + */ + remove(callback?: (err: any) => void): void; + remove(options: Object, callback?: (err: any) => void): void; + } + + /* + * section types/array.js + * http://mongoosejs.com/docs/api.html#types-array-js + */ + class Array extends global.Array { + /** + * Atomically shifts the array at most one time per document save(). + * Calling this mulitple times on an array before saving sends the same command as + * calling it once. This update is implemented using the MongoDB $pop method which + * enforces this restriction. + */ + $shift(): T; + + /** Alias of pull */ + remove(...args: any[]): this; + + /** + * Pops the array atomically at most one time per document save(). + * Calling this mulitple times on an array before saving sends the same command as + * calling it once. This update is implemented using the MongoDB $pop method which + * enforces this restriction. + */ + $pop(): T; + + /** + * Adds values to the array if not already present. + * @returns the values that were added + */ + addToSet(...args: any[]): T[]; + + /** + * Return the index of obj or -1 if not found. + * @param obj he item to look for + */ + indexOf(obj: any): number; + + /** Helper for console.log */ + inspect(): any; + + /** + * Marks the entire array as modified, which if saved, will store it as a $set + * operation, potentially overwritting any changes that happen between when you + * retrieved the object and when you save it. + * @returns new length of the array + */ + nonAtomicPush(...args: any[]): number; + + /** + * Wraps Array#pop with proper change tracking. + * marks the entire array as modified which will pass the entire thing to $set + * potentially overwritting any changes that happen between when you retrieved + * the object and when you save it. + */ + pop(): T; + + /** + * Pulls items from the array atomically. Equality is determined by casting + * the provided value to an embedded document and comparing using + * the Document.equals() function. + */ + pull(...args: any[]): this; + + /** + * Wraps Array#push with proper change tracking. + * @returns new length of the array + */ + push(...args: any[]): number; + + /** Sets the casted val at index i and marks the array modified. */ + set(i: number, val: any): this; + + /** + * Wraps Array#shift with proper change tracking. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + shift(): T; + + /** + * Wraps Array#sort with proper change tracking. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + sort(compareFn?: (a: T, b: T) => number): this; + + /** + * Wraps Array#splice with proper change tracking and casting. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + splice(...args: any[]): T[]; + + /** Returns a native js Array. */ + toObject(options?: Object): T[]; + + /** + * Wraps Array#unshift with proper change tracking. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + unshift(...args: any[]): number; + } + + /* + * section types/documentarray.js + * http://mongoosejs.com/docs/api.html#types-documentarray-js + */ + class DocumentArray extends _mongoose.Types.Array { + /** + * Creates a subdocument casted to this schema. + * This is the same subdocument constructor used for casting. + * @param obj the value to cast to this arrays SubDocument schema + */ + create(obj: Object): Subdocument; + + /** + * Searches array items for the first document with a matching _id. + * @returns the subdocument or null if not found. + */ + id(id: ObjectId | string | number | NativeBuffer): Embedded; + + /** Helper for console.log */ + inspect(): T[]; + + /** + * Returns a native js Array of plain js objects + * @param options optional options to pass to each documents toObject + * method call during conversion + */ + toObject(options?: Object): T[]; + } + + /* + * section types/buffer.js + * http://mongoosejs.com/docs/api.html#types-buffer-js + */ + class Buffer extends global.Buffer { + /** + * Copies the buffer. + * Buffer#copy does not mark target as modified so you must copy + * from a MongooseBuffer for it to work as expected. This is a + * work around since copy modifies the target, not this. + */ + copy(target: NativeBuffer, ...nodeBufferArgs: any[]): number; + + /** Determines if this buffer is equals to other buffer */ + equals(other: NativeBuffer): boolean; + + /** Sets the subtype option and marks the buffer modified. */ + subtype(subtype: number): void; + + /** Converts this buffer to its Binary type representation. */ + toObject(subtype?: number): mongodb.Binary; + + /** Writes the buffer. */ + write(string: string, ...nodeBufferArgs: any[]): number; + } + + /* + * section types/objectid.js + * http://mongoosejs.com/docs/api.html#types-objectid-js + */ + var ObjectId: typeof mongodb.ObjectID; + interface ObjectId extends mongodb.ObjectID {} + + /* + * section types/embedded.js + * http://mongoosejs.com/docs/api.html#types-embedded-js + */ + class Embedded extends Document { + /** Helper for console.log */ + inspect(): Object; + + /** + * Marks a path as invalid, causing validation to fail. + * @param path the field to invalidate + * @param err error which states the reason path was invalid + */ + invalidate(path: string, err: string | NativeError): boolean; + + /** Returns the top level document of this sub-document. */ + ownerDocument(): Document; + /** Returns this sub-documents parent document. */ + parent(): Document; + /** Returns this sub-documents parent array. */ + parentArray(): DocumentArray; + + /** Removes the subdocument from its parent array. */ + remove(options?: { + noop?: boolean; + }, fn?: (err: any) => void): this; + + /** + * Marks the embedded doc modified. + * @param path the path which changed + */ + markModified(path: string): void; + } + } + + /* + * section query.js + * http://mongoosejs.com/docs/api.html#query-js + */ + type Query = ModelQuery; + + /* + * Query.find() will return Query[]> however we need the + * type T to create this so we save T in another parameter. + */ + class ModelQuery extends mquery { + /** + * Specifies a javascript function or expression to pass to MongoDBs query system. + * Only use $where when you have a condition that cannot be met using other MongoDB + * operators like $lt. Be sure to read about all of its caveats before using. + * @param js javascript string or function + */ + $where(js: string | Function): this; + + /** + * Specifies an $all query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + all(val: number): this; + all(path: string, val: number): this; + + /** + * Specifies arguments for a $and condition. + * @param array array of conditions + */ + and(array: Object[]): this; + + /** Specifies the batchSize option. Cannot be used with distinct() */ + batchSize(val: number): this; + + /** + * Specifies a $box condition + * @param Upper Right Coords + */ + box(val: Object): this; + box(lower: number[], upper: number[]): this; + + /** Casts this query to the schema of model, If obj is present, it is cast instead of this query.*/ + cast(model: Model | ModelConstructor, obj?: Object): Object; + + /** + * Executes the query returning a Promise which will be + * resolved with either the doc(s) or rejected with the error. + * Like .then(), but only takes a rejection handler. + */ + catch(reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; + + /** + * DEPRECATED Alias for circle + * Specifies a $center or $centerSphere condition. + * @deprecated Use circle instead. + */ + center(area: Object): this; + center(path: string, area: Object): this; + + /** + * DEPRECATED Specifies a $centerSphere condition + * @deprecated Use circle instead. + */ + centerSphere(path: string, val: Object): this; + centerSphere(val: Object): this; + + /** Specifies a $center or $centerSphere condition. */ + circle(area: Object): this; + circle(path: string, area: Object): this; + + /** Specifies the comment option. Cannot be used with distinct() */ + comment(val: string): this; + + /** + * Specifying this query as a count query. Passing a callback executes the query. + * @param criteria mongodb selector + */ + count(callback?: (err: any, count: number) => void): Query; + count(criteria: Object, callback?: (err: any, count: number) => void): Query; + + /** + * Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a + * Streams3-compatible interface, as well as a .next() function. + */ + cursor(options?: Object): QueryCursor; + + /** Declares or executes a distict() operation. Passing a callback executes the query. */ + distinct(callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, criteria: Object | Query, + callback?: (err: any, res: any[]) => void): Query; + + /** Specifies an $elemMatch condition */ + elemMatch(criteria: (elem: Query) => void): this; + elemMatch(criteria: Object): this; + elemMatch(path: string | Object | Function, criteria: (elem: Query) => void): this; + elemMatch(path: string | Object | Function, criteria: Object): this; + + /** Specifies the complementary comparison value for paths specified with where() */ + equals(val: Object): this; + + /** Executes the query */ + exec(callback?: (err: any, res: T) => void): _MongoosePromise; + exec(operation: string | Function, callback?: (err: any, res: T) => void): _MongoosePromise; + + /** Specifies an $exists condition */ + exists(val?: boolean): this; + exists(path: string, val?: boolean): this; + + /** + * Finds documents. When no callback is passed, the query is not executed. When the + * query is executed, the result will be an array of documents. + * @param criteria mongodb selector + */ + find(callback?: (err: any, res: Model[]) => void): ModelQuery[], ModelType>; + find(criteria: Object, + callback?: (err: any, res: Model[]) => void): ModelQuery[], ModelType>; + + /** + * Declares the query a findOne operation. When executed, the first found document is + * passed to the callback. Passing a callback executes the query. The result of the query + * is a single document. + * @param criteria mongodb selector + * @param projection optional fields to return + */ + findOne(callback?: (err: any, res: Model) => void): ModelQuery, ModelType>; + findOne(criteria: Object, + callback?: (err: any, res: Model) => void): ModelQuery, ModelType>; + + /** + * Issues a mongodb findAndModify remove command. + * Finds a matching document, removes it, passing the found document (if any) to the + * callback. Executes immediately if callback is passed. + */ + findOneAndRemove(callback?: (error: any, doc: Model, result: any) => void): ModelQuery, ModelType>; + findOneAndRemove(conditions: Object, + callback?: (error: any, doc: Model, result: any) => void): ModelQuery, ModelType>; + findOneAndRemove(conditions: Object, options: QueryFindOneAndRemoveOptions, + callback?: (error: any, doc: Model, result: any) => void): ModelQuery, ModelType>; + + /** + * Issues a mongodb findAndModify update command. + * Finds a matching document, updates it according to the update arg, passing any options, and returns + * the found document (if any) to the callback. The query executes immediately if callback is passed. + */ + findOneAndUpdate(callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; + findOneAndUpdate(update: Object, + callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; + findOneAndUpdate(query: Object | Query, update: Object, + callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; + findOneAndUpdate(query: Object | Query, update: Object, options: QueryFindOneAndUpdateOptions, + callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; + + /** + * Specifies a $geometry condition. geometry() must come after either intersects() or within(). + * @param object Must contain a type property which is a String and a coordinates property which + * is an Array. See the examples. + */ + geometry(object: { type: string, coordinates: any[] }): this; + + /** + * Returns the current query conditions as a JSON object. + * @returns current query conditions + */ + getQuery(): any; + + /** + * Returns the current update operations as a JSON object. + * @returns current update operations + */ + getUpdate(): any; + + /** + * Specifies a $gt query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + gt(val: number): this; + gt(path: string, val: number): this; + + /** + * Specifies a $gte query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + gte(val: number): this; + gte(path: string, val: number): this; + + /** + * Sets query hints. + * @param val a hint object + */ + hint(val: Object): this; + + /** + * Specifies an $in query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + in(val: any[]): this; + in(path: string, val: any[]): this; + + /** Declares an intersects query for geometry(). MUST be used after where(). */ + intersects(arg?: Object): this; + + /** + * Sets the lean option. + * Documents returned from queries with the lean option enabled are plain + * javascript objects, not MongooseDocuments. They have no save method, + * getters/setters or other Mongoose magic applied. + * @param bool defaults to true + */ + lean(bool?: boolean): Query; + + /** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */ + limit(val: number): this; + + /** + * Specifies a $lt query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + lt(val: number): this; + lt(path: string, val: number): this; + + /** + * Specifies a $lte query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + lte(val: number): this; + lte(path: string, val: number): this; + + /** + * Specifies a $maxDistance query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + maxDistance(val: number): this; + maxDistance(path: string, val: number): this; + + /** @deprecated Alias of maxScan */ + maxscan(val: number): this; + /** Specifies the maxScan option. Cannot be used with distinct() */ + maxScan(val: number): this; + + /** + * Merges another Query or conditions object into this one. + * When a Query is passed, conditions, field selection and options are merged. + */ + merge(source: Object | Query): this; + + /** Specifies a $mod condition */ + mod(val: number[]): this; + mod(path: string, val: number[]): this; + + /** + * Specifies a $ne query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + ne(val: any): this; + ne(path: string, val: any): this; + + /** Specifies a $near or $nearSphere condition. */ + near(val: Object): this; + near(path: string, val: Object): this; + + /** + * DEPRECATED Specifies a $nearSphere condition + * @deprecated Use query.near() instead with the spherical option set to true. + */ + nearSphere(val: Object): this; + nearSphere(path: string, val: Object): this; + + /** + * Specifies a $nin query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + nin(val: any[]): this; + nin(path: string, val: any[]): this; + + /** + * Specifies arguments for a $nor condition. + * @param array array of conditions + */ + nor(array: Object[]): this; + + /** + * Specifies arguments for an $or condition. + * @param array array of conditions + */ + or(array: Object[]): this; + + /** Specifies a $polygon condition */ + polygon(...coordinatePairs: number[][]): this; + polygon(path: string, ...coordinatePairs: number[][]): this; + + /** + * Specifies paths which should be populated with other documents. + * Paths are populated after the query executes and a response is received. A separate + * query is then executed for each path specified for population. After a response for + * each query has also been returned, the results are passed to the callback. + * @param path either the path to populate or an object specifying all parameters + * @param select Field selection for the population query + * @param model The model you wish to use for population. If not specified, populate + * will look up the model by the name in the Schema's ref field. + * @param match Conditions for the population query + * @param options Options for the population query (sort, etc) + */ + populate(path: string | Object, select?: string | Object, model?: string | Model, + match?: Object, options?: Object): this; + populate(options: ModelPopulateOptions): this; + + /** + * Determines the MongoDB nodes from which to read. + * @param pref one of the listed preference options or aliases + * @tags optional tags for this query + */ + read(pref: string, tags?: Object[]): this; + + /** + * Specifies a $regex query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + regex(val: RegExp): this; + regex(path: string, val: RegExp): this; + + /** + * Declare and/or execute this query as a remove() operation. + * The operation is only executed when a callback is passed. To force execution without a callback, + * you must first call remove() and then execute it by using the exec() method. + * @param criteria mongodb selector + */ + remove(callback?: (err: any) => void): Query; + remove(criteria: Object | Query, callback?: (err: any) => void): Query; + + /** Specifies which document fields to include or exclude (also known as the query "projection") */ + select(arg: string | Object): this; + /** Determines if field selection has been made. */ + selected(): boolean; + /** Determines if exclusive field selection has been made.*/ + selectedExclusively(): boolean; + /** Determines if inclusive field selection has been made. */ + selectedInclusively(): boolean; + /** Sets query options. */ + setOptions(options: Object): this; + + /** + * Specifies a $size query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + size(val: number): this; + size(path: string, val: number): this; + + /** Specifies the number of documents to skip. Cannot be used with distinct() */ + skip(val: number): this; + + /** + * DEPRECATED Sets the slaveOk option. + * @param v defaults to true + * @deprecated in MongoDB 2.2 in favor of read preferences. + */ + slaveOk(v?: boolean): this; + + /** + * Specifies a $slice projection for an array. + * @param val number/range of elements to slice + */ + slice(val: number | number[]): this; + slice(path: string, val: number | number[]): this; + + /** Specifies this query as a snapshot query. Cannot be used with distinct() */ + snapshot(v?: boolean): this; + + /** + * Sets the sort order + * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. + * If a string is passed, it must be a space delimited list of path names. The + * sort order of each path is ascending unless the path name is prefixed with - + * which will be treated as descending. + */ + sort(arg: string | Object): this; + + /** Returns a Node.js 0.8 style read stream interface. */ + stream(options?: { transform?: Function; }): QueryStream; + + /** + * Sets the tailable option (for use with capped collections). Cannot be used with distinct() + * @param bool defaults to true + * @param opts options to set + * @param opts.numberOfRetries if cursor is exhausted, retry this many times before giving up + * @param opts.tailableRetryInterval if cursor is exhausted, wait this many milliseconds before retrying + */ + tailable(bool?: boolean, opts?: { + numberOfRetries?: number; + tailableRetryInterval?: number; + }): this; + + /** Executes this query and returns a promise */ + then(resolve?: (res: T) => void | TRes | PromiseLike, + reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; + + /** + * Converts this query to a customized, reusable query + * constructor with all arguments and options retained. + */ + toConstructor(): typeof ModelQuery; + + /** + * Declare and/or execute this query as an update() operation. + * All paths passed that are not $atomic operations will become $set ops. + * @param doc the update command + */ + update(callback?: (err: any, affectedRows: number) => void): Query; + update(doc: Object, callback?: (err: any, affectedRows: number) => void): Query; + update(criteria: Object, doc: Object, + callback?: (err: any, affectedRows: number) => void): Query; + update(criteria: Object, doc: Object, options: QueryUpdateOptions, + callback?: (err: any, affectedRows: number) => void): Query; + + /** Specifies a path for use with chaining. */ + where(path?: string | Object, val?: any): this; + + /** Defines a $within or $geoWithin argument for geo-spatial queries. */ + within(val?: Object): this; + within(coordinate: number[], ...coordinatePairs: number[][]): this; + + /** Flag to opt out of using $geoWithin. */ + static use$geoWithin: boolean; + } + + // https://github.com/aheckmann/mquery + // mquery currently does not have a type definition please + // replace it if one is ever created + class mquery {} + + interface QueryFindOneAndRemoveOptions { + /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ + sort?: any; + /** puts a time limit on the query - requires mongodb >= 2.6.0 */ + maxTimeMS?: number; + /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ + passRawResult?: boolean; + } + + interface QueryFindOneAndUpdateOptions extends QueryFindOneAndRemoveOptions { + /** if true, return the modified document rather than the original. defaults to false (changed in 4.0) */ + new?: boolean; + /** creates the object if it doesn't exist. defaults to false. */ + upsert?: boolean; + /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ + fields?: Object | string; + /** if true, runs update validators on this command. Update validators validate the update operation against the model's schema. */ + runValidators?: boolean; + /** + * if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document + * is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator. + */ + setDefaultsOnInsert?: boolean; + /** + * if set to 'query' and runValidators is on, this will refer to the query in custom validator + * functions that update validation runs. Does nothing if runValidators is false. + */ + context?: string; + } + + interface QueryUpdateOptions extends ModelUpdateOptions { + /** + * if set to 'query' and runValidators is on, this will refer to the query + * in customvalidator functions that update validation runs. Does nothing + * if runValidators is false. + */ + context?: string; + } + + namespace Schema { + namespace _Types { + /* + * section schema/array.js + * http://mongoosejs.com/docs/api.html#schema-array-js + */ + class Array extends SchemaType { + /** Array SchemaType constructor */ + constructor(key: string, cast?: SchemaType, options?: Object); + + /** + * Check if the given value satisfies a required validator. The given value + * must be not null nor undefined, and have a non-zero length. + */ + checkRequired(value: T): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/string.js + * http://mongoosejs.com/docs/api.html#schema-string-js + */ + class String extends SchemaType { + /** String SchemaType constructor. */ + constructor(key: string, options?: Object); + + /** Check if the given value satisfies a required validator. */ + checkRequired(value: any, doc: Document): boolean; + + /** + * Adds an enum validator + * @param args enumeration values + */ + enum(args: string | string[] | Object): this; + + /** Adds a lowercase setter. */ + lowercase(): this; + + /** + * Sets a regexp validator. Any value that does not pass regExp.test(val) will fail validation. + * @param regExp regular expression to test against + * @param message optional custom error message + */ + match(regExp: RegExp, message?: string): this; + + /** + * Sets a maximum length validator. + * @param value maximum string length + * @param message optional custom error message + */ + maxlength(value: number, message?: string): this; + + /** + * Sets a minimum length validator. + * @param value minimum string length + * @param message optional custom error message + */ + minlength(value: number, message?: string): this; + + /** Adds a trim setter. The string value will be trimmed when set. */ + trim(): this; + /** Adds an uppercase setter. */ + uppercase(): this; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + } + + /* + * section schema/documentarray.js + * http://mongoosejs.com/docs/api.html#schema-documentarray-js + */ + class DocumentArray extends Array { + /** SubdocsArray SchemaType constructor */ + constructor(key: string, schema: Schema, options?: Object); + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/number.js + * http://mongoosejs.com/docs/api.html#schema-number-js + */ + class Number extends SchemaType { + /** Number SchemaType constructor. */ + constructor(key: string, options?: Object); + + /** Check if the given value satisfies a required validator. */ + checkRequired(value: any, doc: Document): boolean; + + /** + * Sets a maximum number validator. + * @param maximum number + * @param message optional custom error message + */ + max(maximum: number, message?: string): this; + + /** + * Sets a minimum number validator. + * @param value minimum number + * @param message optional custom error message + */ + min(value: number, message?: string): this; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/date.js + * http://mongoosejs.com/docs/api.html#schema-date-js + */ + class Date extends SchemaType { + /** Date SchemaType constructor. */ + constructor(key: string, options?: Object); + + /** + * Check if the given value satisfies a required validator. To satisfy + * a required validator, the given value must be an instance of Date. + */ + checkRequired(value: any, doc: Document): boolean; + + /** Declares a TTL index (rounded to the nearest second) for Date types only. */ + expires(when: number | string): this; + + /** + * Sets a maximum date validator. + * @param maximum date + * @param message optional custom error message + */ + max(maximum: NativeDate, message?: string): this; + + /** + * Sets a minimum date validator. + * @param value minimum date + * @param message optional custom error message + */ + min(value: NativeDate, message?: string): this; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/buffer.js + * http://mongoosejs.com/docs/api.html#schema-buffer-js + */ + class Buffer extends SchemaType { + /** Buffer SchemaType constructor */ + constructor(key: string, options?: Object); + + /** + * Check if the given value satisfies a required validator. To satisfy a + * required validator, a buffer must not be null or undefined and have + * non-zero length. + */ + checkRequired(value: any, doc: Document): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + } + + /* + * section schema/boolean.js + * http://mongoosejs.com/docs/api.html#schema-boolean-js + */ + class Boolean extends SchemaType { + /** Boolean SchemaType constructor. */ + constructor(path: string, options?: Object); + + /** + * Check if the given value satisfies a required validator. For a + * boolean to satisfy a required validator, it must be strictly + * equal to true or to false. + */ + checkRequired(value: any): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/objectid.js + * http://mongoosejs.com/docs/api.html#schema-objectid-js + */ + class ObjectId extends SchemaType { + /** ObjectId SchemaType constructor. */ + constructor(key: string, options?: Object); + + /** + * Adds an auto-generated ObjectId default if turnOn is true. + * @param turnOn auto generated ObjectId defaults + */ + auto(turnOn: boolean): this; + + /** Check if the given value satisfies a required validator. */ + checkRequired(value: any, doc: Document): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/mixed.js + * http://mongoosejs.com/docs/api.html#schema-mixed-js + */ + class Mixed extends SchemaType { + /** Mixed SchemaType constructor. */ + constructor(path: string, options?: Object); + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/embedded.js + * http://mongoosejs.com/docs/api.html#schema-embedded-js + */ + class Embedded extends SchemaType { + /** Sub-schema schematype constructor */ + constructor(schema: Schema, key: string, options?: Object); + } + } + } + + /* + * section aggregate.js + * http://mongoosejs.com/docs/api.html#aggregate-js + */ + class Aggregate { + /** + * Aggregate constructor used for building aggregation pipelines. + * Returned when calling Model.aggregate(). + * @param ops aggregation operator(s) or operator array + */ + constructor(ops?: Object | any[], ...args: any[]); + + /** Adds a cursor flag */ + addCursorFlag(flag: string, value: boolean): this; + + /** + * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) + * @param value Should tell server it can use hard drive to store data during aggregation. + * @param tags optional tags for this query + */ + allowDiskUse(value: boolean, tags?: any[]): this; + + /** + * Appends new operators to this aggregate pipeline + * @param ops operator(s) to append + */ + append(...ops: Object[]): this; + + /** + * Sets the cursor option option for the aggregation query (ignored for < 2.6.0). + * Note the different syntax below: .exec() returns a cursor object, and no callback + * is necessary. + * @param options set the cursor batch size + */ + cursor(options: Object): this; + + // If cursor option is on, could return an object + /** Executes the aggregate pipeline on the currently bound Model. */ + exec(callback?: (err: any, result: T) => void): _MongoosePromise | any; + + /** Execute the aggregation with explain */ + explain(callback?: (err: any, result: T) => void): _MongoosePromise; + + /** + * Appends a new custom $group operator to this aggregate pipeline. + * @param arg $group operator contents + */ + group(arg: Object): this; + + /** + * Appends a new $limit operator to this aggregate pipeline. + * @param num maximum number of records to pass to the next stage + */ + limit(num: number): this; + + /** + * Appends new custom $lookup operator(s) to this aggregate pipeline. + * @param options to $lookup as described in the above link + */ + lookup(options: Object): this; + + /** + * Appends a new custom $match operator to this aggregate pipeline. + * @param arg $match operator contents + */ + match(arg: Object): this; + + /** + * Binds this aggregate to a model. + * @param model the model to which the aggregate is to be bound + */ + model(model: Model): this; + + /** + * Appends a new $geoNear operator to this aggregate pipeline. + * MUST be used as the first operator in the pipeline. + */ + near(parameters: Object): this; + + /** + * Appends a new $project operator to this aggregate pipeline. + * Mongoose query selection syntax is also supported. + * @param arg field specification + */ + project(arg: string | Object): this; + + /** + * Sets the readPreference option for the aggregation query. + * @param pref one of the listed preference options or their aliases + * @param tags optional tags for this query + */ + read(pref: string, tags?: Object[]): this; + + /** + * Appends new custom $sample operator(s) to this aggregate pipeline. + * @param size number of random documents to pick + */ + sample(size: number): this; + + /** + * Appends a new $skip operator to this aggregate pipeline. + * @param num number of records to skip before next stage + */ + skip(num: number): this; + + /** + * Appends a new $sort operator to this aggregate pipeline. + * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. + * If a string is passed, it must be a space delimited list of path names. The sort order + * of each path is ascending unless the path name is prefixed with - which will be treated + * as descending. + */ + sort(arg: string | Object): this; + + /** Provides promise for aggregate. */ + then(resolve?: (val: T) => void | TRes | PromiseLike, + reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise + + /** + * Appends new custom $unwind operator(s) to this aggregate pipeline. + * Note that the $unwind operator requires the path name to start with '$'. + * Mongoose will prepend '$' if the specified field doesn't start '$'. + * @param fields the field(s) to unwind + */ + unwind(...fields: string[]): this; + } + + /* + * section schematype.js + * http://mongoosejs.com/docs/api.html#schematype-js + */ + class SchemaType { + /** SchemaType constructor */ + constructor(path: string, options?: Object, instance?: string); + + /** + * Sets a default value for this SchemaType. + * Defaults can be either functions which return the value to use as the + * default or the literal value itself. Either way, the value will be cast + * based on its schema type before being set during document creation. + * @param val the default value + */ + default(val: any): any; + + /** Adds a getter to this schematype. */ + get(fn: Function): this; + + /** + * Declares the index options for this schematype. + * Indexes are created in the background by default. Specify background: false to override. + */ + index(options: Object | boolean | string): this; + + /** + * Adds a required validator to this SchemaType. The validator gets added + * to the front of this SchemaType's validators array using unshift(). + * @param required enable/disable the validator + * @param message optional custom error message + */ + required(required: boolean, message?: string): this; + + /** Sets default select() behavior for this path. */ + select(val: boolean): this; + /** Adds a setter to this schematype. */ + set(fn: Function): this; + /** Declares a sparse index. */ + sparse(bool: boolean): this; + /** Declares a full text index. */ + text(bool: boolean): this; + /** Declares an unique index. */ + unique(bool: boolean): this; + + /** + * Adds validator(s) for this document path. + * Validators always receive the value to validate as their first argument + * and must return Boolean. Returning false means validation failed. + * @param obj validator + * @param errorMsg optional error message + * @param type optional validator type + */ + validate(obj: RegExp | Function | Object, errorMsg?: string, + type?: string): this; + } + + /** + * section promise.js + * http://mongoosejs.com/docs/api.html#promise-js + * + * You must assign a promise library: + * + * 1. To use mongoose's default promise library: + * Install mongoose-promise.d.ts + * + * 2. To use native ES6 promises, add this line to your main .d.ts file: + * type MongoosePromise = Promise; + * + * 3. To use another promise library (for example q): + * Install q.d.ts + * Then add this line to your main .d.ts file: + * type MongoosePromise = Q.Promise; + */ + type _MongoosePromise = MongoosePromise; + + /* + * section model.js + * http://mongoosejs.com/docs/api.html#model-js + * + * Mongoose Models use multiple inheritance from Document and EventEmitter. + * When calling methods that return a model such as mongoose.connect(), + * they actual return an instance of the Model constructor (think of it + * like a new class) which can then instantiate its own objects. + */ + type ModelConstructor = IModelConstructor & events.EventEmitter; + type Model = T & _Model & events.EventEmitter; + + interface IModelConstructor { + /** + * Model constructor + * Provides the interface to MongoDB collections as well as creates document instances. + * @param doc values with which to create the document + * @event error If listening to this event, it is emitted when a document + * was saved without passing a callback and an error occurred. If not + * listening, the event bubbles to the connection used to create this Model. + * @event index Emitted after Model#ensureIndexes completes. If an error + * occurred it is passed with the event. + * @event index-single-start Emitted when an individual index starts within + * Model#ensureIndexes. The fields and options being used to build the index + * are also passed with the event. + * @event index-single-done Emitted when an individual index finishes within + * Model#ensureIndexes. If an error occurred it is passed with the event. + * The fields, options, and index name are also passed. + */ + new(doc?: Object): Model; + + /** + * Finds a single document by its _id field. findById(id) is almost* + * equivalent to findOne({ _id: id }). findById() triggers findOne hooks. + * @param id value of _id to query by + * @param projection optional fields to return + */ + findById(id: Object | string | number, + callback?: (err: any, res: Model) => void): ModelQuery, T>; + findById(id: Object | string | number, projection: Object, + callback?: (err: any, res: Model) => void): ModelQuery, T>; + findById(id: Object | string | number, projection: Object, options: Object, + callback?: (err: any, res: Model) => void): ModelQuery, T>; + + model(name: string): ModelConstructor; + model(name: string): Statics & ModelConstructor; + + /** + * Creates a Query and specifies a $where condition. + * @param argument is a javascript string or anonymous function + */ + $where(argument: string | Function): ModelQuery[], T>; + + /** + * Performs aggregations on the models collection. + * If a callback is passed, the aggregate is executed and a Promise is returned. + * If a callback is not passed, the aggregate itself is returned. + * @param ... aggregation pipeline operator(s) or operator array + */ + aggregate(...aggregations: Object[]): Aggregate; + aggregate(...aggregationsWithCallback: Object[]): _MongoosePromise; + + /** Counts number of matching documents in a database collection. */ + count(conditions: Object, callback?: (err: any, count: number) => void): Query; + + /** + * Shortcut for saving one or more documents to the database. MyModel.create(docs) + * does new MyModel(doc).save() for every doc in docs. + * Triggers the save() hook. + */ + create(docs: any[], callback?: (err: any, res: Model[]) => void): _MongoosePromise[]>; + create(...docs: Object[]): _MongoosePromise>; + create(...docsWithCallback: Object[]): _MongoosePromise>; + + /** + * Adds a discriminator type. + * @param name discriminator model name + * @param schema discriminator model schema + */ + discriminator(name: string, schema: Schema): Model; + + /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ + distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, conditions: Object, + callback?: (err: any, res: any[]) => void): Query; + + /** + * Sends ensureIndex commands to mongo for each index declared in the schema. + * @param options internal options + * @param cb optional callback + */ + ensureIndexes(callback?: (err: any) => void): _MongoosePromise; + ensureIndexes(options: Object, callback?: (err: any) => void): _MongoosePromise; + + /** + * Finds documents. + * @param projection optional fields to return + */ + find(callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; + find(conditions: Object, callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; + find(conditions: Object, projection: Object, + callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; + find(conditions: Object, projection: Object, options: Object, + callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; + + + + /** + * Issue a mongodb findAndModify remove command by a document's _id field. + * findByIdAndRemove(id, ...) is equivalent to findOneAndRemove({ _id: id }, ...). + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * Executes immediately if callback is passed, else a Query object is returned. + * @param id value of _id to query by + */ + findByIdAndRemove(): ModelQuery, T>; + findByIdAndRemove(id: Object | number | string, + callback?: (err: any, res: Model) => void): ModelQuery, T>; + findByIdAndRemove(id: Object | number | string, options: { + /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ + sort?: Object; + /** sets the document fields to return */ + select?: Object; + }, callback?: (err: any, res: Model) => void): ModelQuery, T>; + + /** + * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) + * is equivalent to findOneAndUpdate({ _id: id }, ...). + * @param id value of _id to query by + */ + findByIdAndUpdate(): ModelQuery, T>; + findByIdAndUpdate(id: Object | number | string, update: Object, + callback?: (err: any, res: Model) => void): ModelQuery, T>; + findByIdAndUpdate(id: Object | number | string, update: Object, + options: ModelFindByIdAndUpdateOptions, + callback?: (err: any, res: Model) => void): ModelQuery, T>; + + /** + * Finds one document. + * The conditions are cast to their respective SchemaTypes before the command is sent. + * @param projection optional fields to return + */ + findOne(conditions?: Object, + callback?: (err: any, res: Model) => void): ModelQuery, T>; + findOne(conditions: Object, projection: Object, + callback?: (err: any, res: Model) => void): ModelQuery, T>; + findOne(conditions: Object, projection: Object, options: Object, + callback?: (err: any, res: Model) => void): ModelQuery, T>; + + /** + * Issue a mongodb findAndModify remove command. + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * Executes immediately if callback is passed else a Query object is returned. + */ + findOneAndRemove(): ModelQuery, T>; + findOneAndRemove(conditions: Object, + callback?: (err: any, res: Model) => void): ModelQuery, T>; + findOneAndRemove(conditions: Object, options: { + /** + * if multiple docs are found by the conditions, sets the sort order to choose + * which doc to update + */ + sort?: Object; + /** puts a time limit on the query - requires mongodb >= 2.6.0 */ + maxTimeMS?: number; + /** sets the document fields to return */ + select?: Object; + }, callback?: (err: any, res: Model) => void): ModelQuery, T>; + + /** + * Issues a mongodb findAndModify update command. + * Finds a matching document, updates it according to the update arg, passing any options, + * and returns the found document (if any) to the callback. The query executes immediately + * if callback is passed else a Query object is returned. + */ + findOneAndUpdate(): ModelQuery, T>; + findOneAndUpdate(conditions: Object, update: Object, + callback?: (err: any, res: Model) => void): ModelQuery, T>; + findOneAndUpdate(conditions: Object, update: Object, + options: ModelFindOneAndUpdateOptions, + callback?: (err: any, res: Model) => void): ModelQuery, T>; + + /** + * geoNear support for Mongoose + * @param GeoJSON point or legacy coordinate pair [x,y] to search near + * @param options for the qurery + * @param callback optional callback for the query + */ + geoNear(point: number[] | { + type: string; + coordinates: number[] + }, options: { + /** return the raw object */ + lean?: boolean; + [other: string]: any; + }, callback?: (err: any, res: Model[], stats: any) => void): ModelQuery[], T>; + + /** + * Implements $geoSearch functionality for Mongoose + * @param conditions an object that specifies the match condition (required) + * @param options for the geoSearch, some (near, maxDistance) are required + * @param callback optional callback + */ + geoSearch(conditions: Object, options: { + /** x,y point to search for */ + near: number[]; + /** the maximum distance from the point near that a result can be */ + maxDistance: number; + /** The maximum number of results to return */ + limit?: number; + /** return the raw object instead of the Mongoose Model */ + lean?: boolean; + }, callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; + + /** + * Shortcut for creating a new Document from existing raw data, + * pre-saved in the DB. The document returned has no paths marked + * as modified initially. + */ + hydrate(obj: Object): Model; + + /** + * Shortcut for validating an array of documents and inserting them into + * MongoDB if they're all valid. This function is faster than .create() + * because it only sends one operation to the server, rather than one for each + * document. + * This function does not trigger save middleware. + */ + insertMany(docs: any[], callback?: (error: any, docs: Model[]) => void): _MongoosePromise[]>; + insertMany(doc: any, callback?: (error: any, doc: Model) => void): _MongoosePromise>; + insertMany(...docsWithCallback: Object[]): _MongoosePromise>; + + /** + * Executes a mapReduce command. + * @param o an object specifying map-reduce options + * @param callbackoptional callback + */ + mapReduce( + o: ModelMapReduceOption, Key, Value>, + callback?: (err: any, res: any) => void + ): _MongoosePromise; + + /** + * Populates document references. + * @param docs Either a single document or array of documents to populate. + * @param options A hash of key/val (path, options) used for population. + * @param callback Optional callback, executed upon completion. Receives err and the doc(s). + */ + populate(docs: Object[], options: ModelPopulateOptions | ModelPopulateOptions[], + callback?: (err: any, res: Model[]) => void): _MongoosePromise[]>; + populate(docs: Object, options: ModelPopulateOptions | ModelPopulateOptions[], + callback?: (err: any, res: Model) => void): _MongoosePromise>; + + /** Removes documents from the collection. */ + remove(conditions: Object, callback?: (err: any) => void): Query; + + /** + * Updates documents in the database without returning them. + * All update values are cast to their appropriate SchemaTypes before being sent. + */ + update(conditions: Object, doc: Object, + callback?: (err: any, raw: any) => void): Query; + update(conditions: Object, doc: Object, options: ModelUpdateOptions, + callback?: (err: any, raw: any) => void): Query; + + /** Creates a Query, applies the passed conditions, and returns the Query. */ + where(path: string, val?: Object): Query; + } + + class _Model extends Document { + /** Signal that we desire an increment of this documents version. */ + increment(): this; + + /** + * Returns another Model instance. + * @param name model name + */ + model(name: string): ModelConstructor; + model(name: string): Statics & ModelConstructor; + + /** + * Removes this document from the db. + * @param fn optional callback + */ + remove(fn?: (err: any, product: Model) => void): _MongoosePromise>; + + /** + * Saves this document. + * @param options options optional options + * @param options.safe overrides schema's safe option + * @param options.validateBeforeSave set to false to save without validating. + * @param fn optional callback + */ + save(fn?: (err: any, product: Model, numAffected: number) => void): _MongoosePromise>; + + /** Base Mongoose instance the model uses. */ + base: typeof mongoose; + /** + * If this is a discriminator model, baseModelName is the + * name of the base model. + */ + baseModelName: String; + /** Collection the model uses. */ + collection: Collection; + /** Connection the model uses. */ + db: Connection; + /** Registered discriminators for this model. */ + discriminators: any; + /** The name of the model */ + modelName: string; + /** Schema the model uses. */ + schema: Schema; + } + + interface ModelFindByIdAndUpdateOptions { + /** true to return the modified document rather than the original. defaults to false */ + new?: boolean; + /** creates the object if it doesn't exist. defaults to false. */ + upsert?: boolean; + /** + * if true, runs update validators on this command. Update validators validate the + * update operation against the model's schema. + */ + runValidators?: boolean; + /** + * if this and upsert are true, mongoose will apply the defaults specified in the model's + * schema if a new document is created. This option only works on MongoDB >= 2.4 because + * it relies on MongoDB's $setOnInsert operator. + */ + setDefaultsOnInsert?: boolean; + /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ + sort?: Object; + /** sets the document fields to return */ + select?: Object; + } + + interface ModelFindOneAndUpdateOptions extends ModelFindByIdAndUpdateOptions { + /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ + fields?: Object | string; + /** puts a time limit on the query - requires mongodb >= 2.6.0 */ + maxTimeMS?: number; + /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ + passRawResult?: boolean; + } + + interface ModelPopulateOptions { + /** space delimited path(s) to populate */ + path: string; + /** optional fields to select */ + select?: any; + /** optional query conditions to match */ + match?: Object; + /** optional name of the model to use for population */ + model?: string; + /** optional query options like sort, limit, etc */ + options?: Object; + } + + interface ModelUpdateOptions { + /** safe mode (defaults to value set in schema (true)) */ + safe?: boolean; + /** whether to create the doc if it doesn't match (false) */ + upsert?: boolean; + /** whether multiple documents should be updated (false) */ + multi?: boolean; + /** + * If true, runs update validators on this command. Update validators validate + * the update operation against the model's schema. + */ + runValidators?: boolean; + /** + * If this and upsert are true, mongoose will apply the defaults specified in the + * model's schema if a new document is created. This option only works on MongoDB >= 2.4 + * because it relies on MongoDB's $setOnInsert operator. + */ + setDefaultsOnInsert?: boolean; + /** overrides the strict option for this update */ + strict?: boolean; + /** disables update-only mode, allowing you to overwrite the doc (false) */ + overwrite?: boolean; + /** other options */ + [other: string]: any; + } + + interface ModelMapReduceOption { + map: Function | string; + reduce: (key: Key, vals: T[]) => Val; + /** query filter object. */ + query?: Object; + /** sort input objects using this key */ + sort?: Object; + /** max number of documents */ + limit?: number; + /** keep temporary data default: false */ + keeptemp?: boolean; + /** finalize function */ + finalize?: (key: Key, val: Val) => Val; + /** scope variables exposed to map/reduce/finalize during execution */ + scope?: Object; + /** it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X default: false */ + jsMode?: boolean; + /** provide statistics on job execution time. default: false */ + verbose?: boolean; + readPreference?: string; + /** sets the output target for the map reduce job. default: {inline: 1} */ + out?: { + /** the results are returned in an array */ + inline?: number; + /** + * {replace: 'collectionName'} add the results to collectionName: the + * results replace the collection + */ + replace?: string; + /** + * {reduce: 'collectionName'} add the results to collectionName: if + * dups are detected, uses the reducer / finalize functions + */ + reduce?: string; + /** + * {merge: 'collectionName'} add the results to collectionName: if + * dups exist the new docs overwrite the old + */ + merge?: string; + }; + } + + interface MapReduceResult { + _id: Key; + value: Val; + } + + /* + * section collection.js + * http://mongoosejs.com/docs/api.html#collection-js + */ + interface CollectionBase extends mongodb.Collection { + /* + * Abstract methods. Some of these are already defined on the + * mongodb.Collection interface so they've been commented out. + */ + ensureIndex(...args: any[]): any; + //find(...args: any[]): any; + findAndModify(...args: any[]): any; + //findOne(...args: any[]): any; + getIndexes(...args: any[]): any; + //insert(...args: any[]): any; + //mapReduce(...args: any[]): any; + //save(...args: any[]): any; + //update(...args: any[]): any; + + /** The collection name */ + collectionName: string; + /** The Connection instance */ + conn: Connection; + /** The collection name */ + name: string; } } - - export class Schema { - static Types: { - String: String; - ObjectId: Types.ObjectId; - OId: Types.ObjectId; - Mixed: any; - }; - - methods: any; - statics: any; - - constructor(schema?: Object, options?: Object); - - add(obj: Object, prefix?: string): void; - eachPath(fn: (path: string, type: any) => void): Schema; - get(key: string): any; - index(fields: Object, options?: Object): Schema; - indexes(): void; - method(name: string, fn: Function): Schema; - method(method: Object): Schema; - path(path: string): any; - path(path: string, constructor: any): Schema; - pathType(path: string): string; - plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Schema; - - pre(method: string, fn: HookSyncCallback, errorCb?: HookErrorCallback): Schema; - pre(method: string, isAsync: boolean, fn: HookAsyncCallback, errorCb?: HookErrorCallback): Schema; - post(method: string, fn: (doc: Document, next?: HookNextFunction) => any ): Schema; - - requiredPaths(): string[]; - set(key: string, value: any): void; - static(name: string, fn: Function): Schema; - virtual(name: string, options?: Object): VirtualType; - virtualpath(name: string): VirtualType; - - } - - // hook functions: https://github.com/vkarpov15/hooks-fixed - export interface HookSyncCallback { - (next: HookNextFunction, ...hookArgs:any[]): any; - } - - export interface HookAsyncCallback { - (next: HookNextFunction, done: HookDoneFunction, ...hookArgs:any[]): any; - } - - export interface HookErrorCallback { - (error: Error): any; - } - - export interface HookNextFunction { - (error: Error): any; - (...hookArgs:any[]): any; - } - - export interface HookDoneFunction { - (error: Error): any; - (...hookArgs:any[]): any; - } - - export interface SchemaOption { - autoIndex?: boolean; - bufferCommands?: boolean; - capped?: boolean; - collection?: string; - id?: boolean; - _id?: boolean; - minimize?: boolean; - read?: string; - safe?: boolean; - shardKey?: boolean; - strict?: boolean; - toJSON?: Object; - toObject?: Object; - versionKey?: boolean; - } - - export interface Model extends NodeJS.EventEmitter { - new (doc?: Object, fields?: Object, skipInit?: boolean): T; - - aggregate(...aggregations: Object[]): Aggregate; - aggregate(aggregation: Object, callback: (err: any, res: T[]) => void): Promise; - aggregate(aggregation1: Object, aggregation2: Object, callback: (err: any, res: T[]) => void): Promise; - aggregate(aggregation1: Object, aggregation2: Object, aggregation3: Object, callback: (err: any, res: T[]) => void): Promise; - count(conditions: Object, callback?: (err: any, count: number) => void): Query; - - create(doc: Object, fn?: (err: any, res: T) => void): Promise; - create(doc1: Object, doc2: Object, fn?: (err: any, res1: T, res2: T) => void): Promise; - create(doc1: Object, doc2: Object, doc3: Object, fn?: (err: any, res1: T, res2: T, res3: T) => void): Promise; - discriminator(name: string, schema: Schema): Model; - distinct(field: string, callback?: (err: any, res: T[]) => void): Query; - distinct(field: string, conditions: Object, callback?: (err: any, res: T[]) => void): Query; - ensureIndexes(callback: (err: any) => void): Promise; - - find(): Query; - find(cond: Object, callback?: (err: any, res: T[]) => void): Query; - find(cond: Object, fields: Object, callback?: (err: any, res: T[]) => void): Query; - find(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T[]) => void): Query; - findById(id: string, callback?: (err: any, res: T) => void): Query; - findById(id: string, fields: Object, callback?: (err: any, res: T) => void): Query; - findById(id: string, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; - findByIdAndRemove(id: string, callback?: (err: any, res: T) => void): Query; - findByIdAndRemove(id: string, options: Object, callback?: (err: any, res: T) => void): Query; - findByIdAndUpdate(id: string, update: Object, callback?: (err: any, res: T) => void): Query; - findByIdAndUpdate(id: string, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; - findOne(cond?: Object, callback?: (err: any, res: T) => void): Query; - findOne(cond: Object, fields: Object, callback?: (err: any, res: T) => void): Query; - findOne(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; - findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; - findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; - - geoNear(point: { type: string; coordinates: number[] }, options: Object, callback?: (err: any, res: T[], stats: any) => void): Query; - geoNear(point: number[], options: Object, callback?: (err: any, res: T[], stats: any) => void): Query; - geoSearch(cond: Object, options: GeoSearchOption, callback?: (err: any, res: T[]) => void): Query; - increment(): T; - mapReduce(options: MapReduceOption, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; - mapReduce(options: MapReduceOption2, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; - model(name: string): Model; - - populate(doc: U, options: Object, callback?: (err: any, res: U) => void): Promise; - populate(doc: U[], options: Object, callback?: (err: any, res: U[]) => void): Promise; - update(cond: Object, update: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; - update(cond: Object, update: Object, options: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; - remove(cond: Object, callback?: (err: any) => void): Query<{}>; - save(callback?: (err: any, result: T, numberAffected: number) => void): Query; - where(path: string, val?: Object): Query; - - $where(argument: string): Query; - $where(argument: Function): Query; - - base: Mongoose; - collection: Collection; - db: any; - discriminators: any; - modelName: string; - schema: Schema; - } - export interface FindAndUpdateOption { - new?: boolean; - upsert?: boolean; - sort?: Object; - select?: Object; - } - export interface GeoSearchOption { - near: number[]; - maxDistance: number; - limit?: number; - lean?: boolean; - } - export interface MapReduceOption { - map: () => void; - reduce: (key: Key, vals: T[]) => Val; - query?: Object; - limit?: number; - keeptemp?: boolean; - finalize?: (key: Key, val: Val) => Val; - scope?: Object; - jsMode?: boolean; - verbose?: boolean; - out?: { - inline?: number; - replace?: string; - reduce?: string; - merge?: string; - }; - } - export interface MapReduceOption2 { - map: string; - reduce: (key: Key, vals: T[]) => Val; - query?: Object; - limit?: number; - keeptemp?: boolean; - finalize?: (key: Key, val: Val) => Val; - scope?: Object; - jsMode?: boolean; - verbose?: boolean; - out?: { - inline?: number; - replace?: string; - reduce?: string; - merge?: string; - }; - } - export interface MapReduceResult { - _id: Key; - value: Val; - } - - export class Query { - exec(callback?: (err: any, res: T) => void): Promise; - exec(operation: string, callback?: (err: any, res: T) => void): Promise; - exec(operation: Function, callback?: (err: any, res: T) => void): Promise; - - all(val: number): Query; - all(path: string, val: number): Query; - and(array: Object[]): Query; - box(val: Object): Query; - box(a: number[], b: number[]): Query; - batchSize(val: number): Query; - cast(model: Model, obj: Object): U; - //center(): Query; - //centerSphere(path: string, val: Object): Query; - circle(area: Object): Query; - circle(path: string, area: Object): Query; - comment(val: any): Query; - count(callback?: (err: any, count: number) => void): Query; - count(criteria: Object, callback?: (err: any, count: number) => void): Query; - distinct(callback?: (err: any, res: T) => void): Query; - distinct(field: string, callback?: (err: any, res: T) => void): Query; - distinct(criteria: Object, field: string, callback?: (err: any, res: T) => void): Query; - distinct(criteria: Query, field: string, callback?: (err: any, res: T) => void): Query; - elemMatch(criteria: Object): Query; - elemMatch(criteria: (elem: Query) => void): Query; - elemMatch(path: string, criteria: Object): Query; - elemMatch(path: string, criteria: (elem: Query) => void): Query; - equals(val: Object): Query; - exists(val?: boolean): Query; - exists(path: string, val?: boolean): Query; - find(callback?: (err: any, res: T) => void): Query; - find(criteria: Object, callback?: (err: any, res: T) => void): Query; - findOne(callback?: (err: any, res: T) => void): Query; - findOne(criteria: Object, callback?: (err: any, res: T) => void): Query; - findOneAndRemove(callback?: (err: any, res: T) => void): Query; - findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; - findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(update: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; - geometry(object: Object): Query; - gt(val: number): Query; - gt(path: string, val: number): Query; - gte(val: number): Query; - gte(path: string, val: number): Query; - hint(val: Object): Query; - in(val: any[]): Query; - in(path: string, val: any[]): Query; - intersects(arg?: Object): Query; - lean(bool?: boolean): Query; - limit(val: number): Query; - lt(val: number): Query; - lt(path: string, val: number): Query; - lte(val: number): Query; - lte(path: string, val: number): Query; - maxDistance(val: number): Query; - maxDistance(path: string, val: number): Query; - maxScan(val: number): Query; - merge(source: Query): Query; - merge(source: Object): Query; - mod(val: number[]): Query; - mod(path: string, val: number[]): Query; - ne(val: any): Query; - ne(path: string, val: any): Query; - near(val: Object): Query; - near(path: string, val: Object): Query; - nearSphere(val: Object): Query; - nearSphere(path: string, val: Object): Query; - nin(val: any[]): Query; - nin(path: string, val: any[]): Query; - nor(array: Object[]): Query; - or(array: Object[]): Query; - polygon(...coordinatePairs: number[][]): Query; - polygon(path: string, ...coordinatePairs: number[][]): Query; - populate(path: string, select?: string, match?: Object, options?: Object): Query; - populate(path: string, select: string, model: string, match?: Object, options?: Object): Query; - populate(opt: PopulateOption): Query; - read(pref: string, tags?: Object[]): Query; - regex(val: RegExp): Query; - regex(path: string, val: RegExp): Query; - remove(callback?: (err: any, res: T) => void): Query; - remove(criteria: Object, callback?: (err: any, res: T) => void): Query; - select(arg: string): Query; - select(arg: Object): Query; - setOptions(options: Object): Query; - size(val: number): Query; - size(path: string, val: number): Query; - skip(val: number): Query; - slaveOk(v?: boolean): Query; - slice(val: number): Query; - slice(val: number[]): Query; - slice(path: string, val: number): Query; - slice(path: string, val: number[]): Query; - snapshot(v?: boolean): Query; - sort(arg: Object): Query; - sort(arg: string): Query; - stream(options?: { transform?: Function; }): QueryStream; - tailable(v?: boolean): Query; - toConstructor(): Query; - update(callback?: (err: any, affectedRows: number, doc: T) => void): Query; - update(doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; - update(criteria: Object, doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; - update(criteria: Object, doc: Object, options: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; - where(path?: string, val?: any): Query; - where(path?: Object, val?: any): Query; - within(val?: Object): Query; - within(coordinate: number[], ...coordinatePairs: number[][]): Query; - - $where(argument: string): Query; - $where(argument: Function): Query; - - static use$geoWithin: boolean; - } - - export interface PopulateOption { - path: string; - select?: string; - model?: string; - match?: Object; - options?: Object; - } - - export interface QueryStream extends NodeJS.EventEmitter { - destory(err?: any): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - paused: number; - readable: boolean; - } - - export interface Document { - id?: string; - _id: any; - - equals(doc: Document): boolean; - get(path: string, type?: new (...args: any[]) => any): any; - inspect(options?: Object): string; - invalidate(path: string, errorMsg: string, value: any): void; - invalidate(path: string, error: Error, value: any): void; - isDirectModified(path: string): boolean; - isInit(path: string): boolean; - isModified(path?: string): boolean; - isSelected(path: string): boolean; - markModified(path: string): void; - modifiedPaths(): string[]; - populate(callback?: (err: any, res: T) => void): Document; - populate(path?: string, callback?: (err: any, res: T) => void): Document; - populate(opt: PopulateOption, callback?: (err: any, res: T) => void): Document; - populated(path: string): any; - remove(callback?: (err: any) => void): Query; - save(callback?: (err: any, res: T) => void): void; - set(path: string, val: any, type?: new (...args: any[]) => any, options?: Object): void; - set(path: string, val: any, options?: Object): void; - set(value: Object): void; - toJSON(options?: Object): Object; - toObject(options?: Object): Object; - toString(): string; - update(doc: Object, options: Object, callback: (err: any, affectedRows: number, raw: any) => void): Query; - validate(cb: (err: any) => void): void; - - isNew: boolean; - errors: Object; - schema: Object; - } - - - export class Aggregate { - constructor(...options: Object[]); - - append(...options: Object[]): Aggregate; - group(arg: Object): Aggregate; - limit(num: number): Aggregate; - match(arg: Object): Aggregate; - near(parameters: Object): Aggregate; - project(arg: string): Aggregate; - project(arg: Object): Aggregate; - select(filter: string): Aggregate; - skip(num: number): Aggregate; - sort(arg: string): Aggregate; - sort(arg: Object): Aggregate; - unwind(fiels: string, ...rest: string[]): Aggregate; - - exec(callback?: (err: any, result: T) => void): Promise; - read(pref: string, ...tags: Object[]): Aggregate; - } - - export class Promise { - constructor(fn?: (err: any, result: T) => void); - - then(onFulFill: (result: T) => void | U | Promise, onReject?: (err: any) => void | U | Promise): Promise; - end(): void; - - fulfill(result: T): Promise; - reject(err: any): Promise; - resolve(err: any, result: T): Promise; - - onFulfill(listener: (result: T) => void): Promise; - onReject(listener: (err: any) => void): Promise; - onResolve(listener: (err: any, result: T) => void): Promise; - on(event: string, listener: Function): Promise; - - // Deprecated methods. - addBack(listener: (err: any, result: T) => void): Promise; - addCallback(listener: (result: T) => void): Promise; - addErrback(listener: (err: any) => void): Promise; - complete(result: T): Promise; - error(err: any): Promise; - } - -} +} \ No newline at end of file diff --git a/mongoose/mongoose-3.x-tests.ts b/mongoose/mongoose-3.x-tests.ts new file mode 100644 index 0000000000..5264b7cd0b --- /dev/null +++ b/mongoose/mongoose-3.x-tests.ts @@ -0,0 +1,392 @@ +/// + +var fs = require('fs'); +import mongoose = require('mongoose'); + +var createInstance = new mongoose.Mongoose(); + +var Schema = mongoose.Schema; +var CreateSchema = new Schema({}); + +mongoose.connect('mongodb://user:pass@localhost:port/database'); +mongoose.connect('mongodb://hostA:27501,hostB:27501', { mongos: true }); + +var conn: mongoose.Connection = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); +conn = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port', { replset: { strategy: 'ping', rs_name: 'testSet' }}); +conn = mongoose.createConnection('localhost', 'database', 27014); +conn = mongoose.createConnection('localhost', 'database', 27014, { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' }); +conn = mongoose.createConnection(); +conn.open('localhost', 'database', 27014, {}); + +var db = mongoose.createConnection(); +db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019"); +db.openSet('mongodb://mongosA:27501,mongosB:27501', 'db', { mongos: true }, (err: any) => {}); +db.close(); + +var collection = db.collection('collection1'); + +mongoose.connection.on('error', (err: any) => {}); +mongoose.disconnect(); + +mongoose.set('test', 1234567890); +var value = mongoose.get('test'); +mongoose.set('debug', true); + +interface IActor extends mongoose.Document { + name: string; +} +mongoose.model('Actor', new Schema({ name: String })); +db.model('Actor', new Schema({ name: String })); +var schema: mongoose.Schema = new Schema({ name: String }, { collection: 'actor' }); +schema.set('collection', 'actor'); +var Model = mongoose.model('Actor', schema, 'actor'); + +interface IZip extends mongoose.Document { + _id: string; +} +interface IPerson extends mongoose.Document { + _id: mongoose.Types.ObjectId; +} +interface IThing extends mongoose.Document { + _id: number; +} + +var names: string[] = mongoose.modelNames(); +var names: string[] = db.modelNames(); +mongoose.plugin((schema: mongoose.Schema) => { +}, { index: true }); + + +var aggregate = new mongoose.Aggregate(); +var aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }); +var aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); +var aggregate = new mongoose.Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]); +aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); +aggregate.append([{ $match: { daw: 'Logic Audio X' }} ]); +aggregate.group({ _id: "$department" }); +aggregate.skip(10); +aggregate.limit(10); +aggregate.match({ department: { $in: [ "sales", "engineering" ] } }); +aggregate.near({ + near: [40.724, -73.997], + distanceField: "dist.calculated", // required + maxDistance: 0.008, + query: { type: "public" }, + includeLocs: "dist.location", + uniqueDocs: true, + num: 5 +}); +aggregate.project("a b -_id"); +aggregate.project({a: 1, b: 1, _id: 0}); +aggregate.project({ + newField: '$b.nested', + plusTen: { $add: ['$val', 10]}, + sub: { + name: '$a' + } +}); +aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); +aggregate.sort({ field: 'asc', test: -1 }); +aggregate.sort('field -test'); +aggregate.unwind("tags"); +aggregate.unwind("a", "b", "c"); +var p = aggregate.exec(); +aggregate.read('primaryPreferred').exec((err: any, result: {}) => {}); + + +var p = new mongoose.Promise; +var p2 = p.then(function() { throw new Error('shucks') }).end(); +setTimeout(function() { + p.fulfill({}); +}, 10); +var promise = new mongoose.Promise(); +promise.then(function (meetups: number) { + return new mongoose.Promise(); +}).then(function (people: string[]) { + if (people.length < 10000) { + throw new Error('Too few people!!!'); + } else { + throw new Error('Still need more people!!!'); + } +}).then(null, function (err: Error) { +}).end(); + + +Model.findOne({ name: 'john' }, (err: any, doc: mongoose.Document) => { + doc.invalidate('size', 'must be less than 20', 14); + doc.validate((err: any) => { }); + + doc.set('documents.0.title', 'changed'); + doc.get('documents.0'); + doc.set({ + 'path' : 1, + 'path2' : { + 'path' : 2 + } + }); + doc.set('path', 'value', { strict: false }); + doc.set('path3', '1', Number); + doc.get('path3', Number); + doc.id; + doc._id; + + doc.isModified(); + doc.isModified('documents'); + doc.isModified('documents.0.title'); + doc.isDirectModified('documents.0.title'); + doc.isDirectModified('documents'); + doc.isSelected('name'); + + doc.markModified('mixed.type'); + doc.populate('user'); + doc.populate('other', (err: any, doc: mongoose.Document) => {}); + doc.populated('author'); + doc.save(); + + doc.toJSON({ getters: true, virtuals: false }); + var data: any = doc.toObject(); + delete data['age']; + delete data['weight']; + data['isAwesome'] = true; +}); + +Model.model('User').findById('id', (err: any, res: IActor) => {}); +Model.count({ type: 'jungle' }, (err: any, count: number) => {}); +Model.remove((err: any, res: IActor[]) => {}); +Model.save((err: any, res: IActor, numberAffected: number) => {}); +Model.create({ type: 'jelly bean' }, { type: 'snickers' }, (err: any, res1: IActor, res2: IActor) => {}); +Model.create({ type: 'jawbreaker' }); +Model.create({ type: 'muffin' }).then(function (res) { + res.name; +}); +Model.distinct('url', { clicks: {$gt: 100}}, (err: any, result: IActor[]) => {}); +Model.distinct('url'); + +Model.aggregate( + { $group: { _id: null, maxBalance: { $max: '$balance' }}}, + { $project: { _id: 0, maxBalance: 1 }}, + (err: any, res: IActor[]) => {}); +Model.aggregate() + .group({ _id: null, maxBalance: { $max: '$balance' } }) + .select('-id maxBalance') + .exec((err: any, res: IActor[]) => {}); +Model.ensureIndexes((err) => {}); + +Model.find({ name: 'john', age: { $gte: 18 }}); +Model.find({ name: 'john', age: { $gte: 18 }}, (err: any, docs: IActor[]) => {}); +Model.find({ name: /john/i }, 'name friends', (err: any, docs: IActor[]) => {}); +Model.find({ name: /john/i }, null, { skip: 10 }); +Model.find({ name: /john/i }, null, { skip: 10 }, (err: any, docs: IActor[]) => {}); +Model.find({ name: /john/i }, null, { skip: 10 }).exec((err: any, docs: IActor[]) => {}); +var query = Model.find({ name: /john/i }, null, { skip: 10 }); +var promise1 = query.exec(); +promise1.addBack((err: any, docs: IActor[]) => {}); + +Model.findById('id', (err: any, res: IActor) => {}); +Model.findById('id').exec((err: any, res: IActor) => {}); +Model.findById('id', 'name length', (err: any, res: IActor) => {}); +Model.findById('id', '-length').exec((err: any, res: IActor) => {}); +Model.findById('id', 'name', { lean: true }, (err: any, res: IActor) => {}); +Model.findById('id', 'name').lean().exec((err: any, res: IActor) => {}); +Model.findByIdAndRemove('id1', { select: 'name' }, (err: any, res: IActor) => {}); +Model.findByIdAndRemove('id1', { select: 'name' }).exec((err: any, res: IActor) => {}); +Model.findByIdAndRemove('id1', (err: any, res: IActor) => {}); +Model.findByIdAndRemove('id1').exec((err: any, res: IActor) => {}); +Model.findByIdAndUpdate('id2', { $set: { name: 'jason borne' }}, { upsert: true }, (err: any, res: IActor) => {}); + +Model.findOne({ type: 'iphone' }, (err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }).exec((err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }, 'name', (err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }, 'name').exec((err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }, 'name', { lean: true }, (err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }, 'name', { lean: true }).exec((err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }).select('name').lean().exec((err: any, res: IActor) => {}); +Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }, (err: any, res: IActor) => {}); +Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }).exec((err: any, res: IActor) => {}); +Model.findOneAndUpdate({ type: 'iphone' }, { $set: { name: 'jason borne' }}, { upsert: true }, (err: any, res: IActor) => {}); + +Model.geoNear([1, 3], { maxDistance : 5, spherical : true }, (err: any, res: IActor[], stats: any) => {}); +Model.geoNear({ type : "Point", coordinates : [9,9] }, { maxDistance : 5, spherical : true }, (err: any, res: IActor[], stats: any) => {}); +Model.geoSearch({ type : "house" }, { near: [10, 10], maxDistance: 5 }, (err: any, res: IActor[]) => {}); + +var o = { + map: function () { this.emit(this.name, 1) }, + reduce: function (k: string, vals: IActor[]) { return vals.length }, +}; +Model.mapReduce(o, (err: any, res: any[]) => {}); + +Model.findById('id', (err: any, res: IActor) => { + var opts = [ + { path: 'company', match: { x: 1 }, select: 'name' }, + { path: 'notes', options: { limit: 10 }, model: 'override' } + ]; + Model.populate(res, opts, (err: any, res: IActor) => {}); +}); +Model.find({ type: 'iphone' }, (err: any, res: IActor[]) => { + var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]; + var promise = Model.populate(res, opts); + promise.then(console.log).end(); +}); +Model.populate({ name: 'Test A' }, { path: 'weapon', model: 'Weapon' }, (err: any, user: IActor) => {}); +Model.populate([ + { name: 'User hoge' }, + { name: 'User fuga' }, +], { path: 'weapon' }, (err: any, users: IActor[]) => {}); + +Model.remove({ title: 'baby born from alien father' }, (err: any) => {}); +var query2 = Model.remove({ _id: 'id' }); +query2.exec(); +Model.update({ age: { $gt: 18 } }, { oldEnough: true }, (err: any, numberAffected: number, raw: any) => {}); +Model.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, (err: any, numberAffected: number, raw: any) => {}); +Model.update({ _id: 'id' }, { $set: { text: 'changed' }}).exec(); + +Model.where('age').gte(21).lte(65).exec((err: any, res: IActor[]) => {}); +var query3 =Model + .where('age').gt(21).lt(65) + .where('name', /^b/i).all('type', 1); +query3.all(25); +query3.and([{ color: 'green' }, { status: 'ok' }]); +query3.batchSize(100); +query3.where('loc').within().box([40.73083, -73.99756], [40.741404, -73.988135]); +query3.where('loc').within().circle({ center: [50, 50], radius: 10, unique: true }); +query3.circle('loc', { center: [50, 50], radius: 10, unique: true }); +query3.comment('login query'); +query3.where({ 'color': 'black' }).count(); +query3.count({ color: 'black' }).count((err: any, count: number) => {}); +query3.count({ color: 'black' }, (err: any, count: number) => {}); +query3.where({ color: 'black' }).count((err: any, count: number) => {}); +query3.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}); +query3.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}); +query.elemMatch('comment', (elem: mongoose.Query) => { + elem.where('author').equals('autobot'); + elem.where('votes').gte(5); +}); +query3.where('age').equals(49); +query3.where('age', 49); +query3.exec(); +query3.exec('update'); +query3.where('name').exists(); +query3.where('name').exists(true); +query3.find().exists('name'); +query3.where('name').exists(false); +query3.find().exists('name', false); +query3.find({ name: 'Los Pollos Hermanos' }).find((err: any, res: IActor[]) => {}); +query3.where('loc').within().geometry({ type: 'Polygon', coordinates: [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] }); +query3.find().where('age').gt(21); +query3.find().gt('age', 21); +query3.hint({ indexA: 1, indexB: -1}); +query3.where('path').intersects().geometry({ type: 'LineString', coordinates: [[180.0, 11.0], [180, 9.0]] }); +query3.where('path').intersects({ type: 'LineString', coordinates: [[180.0, 11.0], [180, 9.0]] }); +query3.maxScan(100); +query3.where('loc').near({ center: [10, 10] }); +query3.where('loc').near({ center: [10, 10], maxDistance: 5 }); +query3.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); +query3.near('loc', { center: [10, 10], maxDistance: 5 }); +query3.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); +query3.nor([{ color: 'green' }, { status: 'ok' }]); +query3.or([{ color: 'red' }, { status: 'emergency' }]); +query3.where('loc').within().polygon([10,20], [13, 25], [7,15]); +query3.polygon('loc', [10,20], [13, 25], [7,15]); + +query3.findOne().populate('owner').exec((err: any, res: IActor[]) => {}); +query3.find().populate({ + path: 'owner', + select: 'name', + match: { color: 'black' }, + options: { sort: { name: -1 }} +}).exec((err: any, res: IActor[]) => {}); +query3.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec((err: any, res: IActor[]) => {}); + +query3.read('primary'); +query3.read('p'); +query3.read('primaryPreferred'); +query3.read('pp'); +query3.read('secondary'); +query3.read('s'); +query3.read('secondaryPreferred'); +query3.read('sp'); +query3.read('nearest'); +query3.read('n'); +query3.read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]); +query3.remove({ artist: 'Anne Murray' }, (err: any, res: IActor[]) => {}); +query3.select('a b -c'); +query3.select({a: 1, b: 1, c: 0}); +query3.select('+path'); +query3.where('tags').size(0); +query3.skip(100).limit(20); +query3.slaveOk(); +query3.slaveOk(true); +query3.slaveOk(false); +query3.slice('comments', -5); +query3.slice('comments', [10, 5]) +query3.where('comments').slice(5); +query3.where('comments').slice([-10, 5]); +query3.snapshot(); +query3.snapshot(true); +query3.snapshot(false); +query3.sort({ field: 'asc', test: -1 }); +query3.sort('field -test'); +Model.find({ name: /^hello/ }).stream({ transform: JSON.stringify }).pipe(fs.createWriteStream('./test.json')); +var stream = Model.find({ name: /^hello/ }).stream(); +stream + .on('data', (doc: IActor) => {}) + .on('error', (err: any) => {}) + .on('close', () => {}); + +query3.tailable(); +query3.tailable(false); +var AdvQuery = query3.toConstructor(); +query3.update({ title: 'words' }); +query3.update({ $set: { title: 'words' }}); +query3.update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, (err: any, row: number, raw: any) => {}); + +query3.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); +query3.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); +query3.where('loc').within({ polygon: [[],[],[],[]] }); +query3.where('loc').within([], [], []); // polygon +query3.where('loc').within([], []); // box +query3.where('loc').within({ type: 'LineString', coordinates: [] }); // geometry + +mongoose.Query.use$geoWithin = false; + + +var ToySchema = new Schema({}); +ToySchema.add({ name: 'string', color: 'string', price: 'number' }); +schema.eachPath(function(path: string, value: any) {}); +schema.index({ first: 1, last: -1 }); +schema.indexes(); +schema.method('meow', function() { + console.log('meeeeeoooooooooooow'); +}); +var Kitty = mongoose.model('Kitty', schema); +var fizz: any = new Kitty({ name: 'kitty' }); +fizz.meow(); +schema.method({ + purr: function() {}, + scratch: function() {}, +}); +schema.path('name'); +schema.path('name', Number); +schema.pathType('name'); +schema.plugin(function() {}); +schema.post('save', function(doc: IActor) {}); +schema.pre('save', function(next: () => void) {}); +schema.requiredPaths(); +schema.static('findByName', function(name: string, callback: () => void) {}); +schema.virtual('display_name') + .get(function(): string { return this.name; }) + .set((value: string): void => {}); + +var id: mongoose.Types.ObjectId = new mongoose.Types.ObjectId('foo'); +var id: mongoose.Types.ObjectId = new mongoose.Types.ObjectId(); +var id2: mongoose.Types.ObjectId = new mongoose.Types.ObjectId(123); +var id2: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromTime(123); +var id2: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromHexString('foo'); +var isValid:boolean = mongoose.Types.ObjectId.isValid('570d350b67b1ae0600e8bee8'); +var s = id.toHexString(); +var valid = id.isValid(); +var eq = id.equals(id2); + +var kitty1 = new Kitty({}); +var kitty2 = new Kitty({}); +var kittyEq = kitty1._id.equals(kitty2._id); \ No newline at end of file diff --git a/mongoose/mongoose-3.x.d.ts b/mongoose/mongoose-3.x.d.ts new file mode 100644 index 0000000000..6602cd9953 --- /dev/null +++ b/mongoose/mongoose-3.x.d.ts @@ -0,0 +1,653 @@ +// Type definitions for Mongoose 3.8.5 +// Project: http://mongoosejs.com/ +// Definitions by: horiuchi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "mongoose" { + function connect(uri: string, options?: ConnectionOptions , callback?: (err: any) => void): Mongoose; + function createConnection(): Connection; + function createConnection(uri: string, options?: ConnectionOptions): Connection; + function createConnection(host: string, database_name: string, port?: number, options?: ConnectionOptions): Connection; + function disconnect(callback?: (err?: any) => void): Mongoose; + + function model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; + function modelNames(): string[]; + function plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + + function get(key: string): any; + function set(key: string, value: any): void; + + var mongo: any; + var mquery: any; + var version: string; + var connection: Connection; + + export class Mongoose { + connect(uri: string, options?: ConnectOpenOptionsBase, callback?: (err: any) => void): Mongoose; + createConnection(): Connection; + createConnection(uri: string, options?: Object): Connection; + createConnection(host: string, database_name: string, port?: number, options?: ConnectOpenOptionsBase): Connection; + disconnect(callback?: (err?: any) => void): Mongoose; + get(key: string): any; + model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; + modelNames(): string[]; + plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + set(key: string, value: any): void; + + mongo: any; + mquery: any; + version: string; + connection: Connection; + Promise: any; + } + + export interface Connection extends NodeJS.EventEmitter { + constructor(base: Mongoose): Connection; + + close(callback?: (err: any) => void): Connection; + collection(name: string, options?: Object): Collection; + model(name: string, schema?: Schema, collection?: string): Model; + modelNames(): string[]; + open(host: string, database?: string, port?: number, options?: OpenSetConnectionOptions, callback?: (err: any) => void): Connection; + openSet(uris: string, database?: string, options?: OpenSetConnectionOptions, callback?: (err: any) => void): Connection; + + db: any; + collections: {[index: string]: Collection}; + readyState: number; + } + + export interface ConnectOpenOptionsBase { + db?: any; + server?: any; + replset?: any; + /** Username for authentication if not supplied in the URI. */ + user?: string; + /** Password for authentication if not supplied in the URI. */ + pass?: string; + /** Options for authentication */ + auth?: any; + } + + export interface ConnectionOptions extends ConnectOpenOptionsBase { + /** Passed to the underlying driver's Mongos instance. */ + mongos?: MongosOptions; + } + + interface OpenSetConnectionOptions extends ConnectOpenOptionsBase { + /** If true, enables High Availability support for mongos */ + mongos?: boolean; + } + + interface MongosOptions { + /** Turn on high availability monitoring. (default: true) */ + ha?: boolean; + /** Time between each replicaset status check. (default: 5000) */ + haInterval?: number; + /** + * Number of connections in the connection pool for each + * server instance. (default: 5 (for legacy reasons)) */ + poolSize?: number; + /** + * Use ssl connection (needs to have a mongod server with + * ssl support). (default: false). + */ + ssl?: boolean; + /** + * Validate mongod server certificate against ca + * (needs to have a mongod server with ssl support, 2.4 or higher) + * (default: true) + */ + sslValidate?: boolean; + /** Turn on high availability monitoring. */ + sslCA?: (Buffer|string)[]; + sslKey?: Buffer|string; + sslPass?: Buffer|string; + socketOptions?: { + noDelay?: boolean; + keepAlive?: number; + connectionTimeoutMS?: number; + socketTimeoutMS?: number; + }; + } + + export interface Collection { + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeOrderedBulkOp + initializeOrderedBulkOp(options?: CollectionOptions): OrderedBulkOperation; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeUnorderedBulkOp + initializeUnorderedBulkOp(options?: CollectionOptions): UnorderedBulkOperation; + } + + export interface CollectionOptions { + //The write concern. + w?: number | string; + //The write concern timeout. + wtimeout?: number; + //Specify a journal write concern. + j?: boolean; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html + export interface OrderedBulkOperation { + length: number; + //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#execute + execute(callback: MongoCallback): void; + execute(options?: FSyncOptions): Promise; + execute(options: FSyncOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#find + find(selector: Object): FindOperatorsOrdered; + //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#insert + insert(doc: Object): OrderedBulkOperation; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html + export interface UnorderedBulkOperation { + //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#execute + execute(callback: MongoCallback): void; + execute(options?: FSyncOptions): Promise; + execute(options: FSyncOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#find + find(selector: Object): FindOperatorsUnordered; + //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#insert + insert(doc: Object): UnorderedBulkOperation; + } + + export interface MongoCallback { + (error: MongoError, result: T): void; + } + + // http://mongodb.github.io/node-mongodb-native/2.1/api/MongoError.html + export class MongoError extends Error { + constructor(message: string); + static create(options: Object): MongoError; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/BulkWriteResult.html + export interface BulkWriteResult { + ok: number; + nInserted: number; + nUpdated: number; + nUpserted: number; + nModified: number; + nRemoved: number; + + getInsertedIds(): Array; + getLastOp(): Object; + getRawResponse(): Object; + getUpsertedIdAt(index: number): Object; + getUpsertedIds(): Array; + getWriteConcernError(): WriteConcernError; + getWriteErrorAt(index: number): WriteError; + getWriteErrorCount(): number; + getWriteErrors(): Array; + hasWriteErrors(): boolean; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/WriteError.html + export interface WriteError { + //Write concern error code. + code: number; + //Write concern error original bulk operation index. + index: number; + //Write concern error message. + errmsg: string; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/WriteConcernError.html + export interface WriteConcernError { + //Write concern error code. + code: number; + //Write concern error message. + errmsg: string; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#removeUser + export interface FSyncOptions { + w?: number | string; + wtimeout?: number; + j?: boolean; + fsync?: boolean + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/FindOperatorsOrdered.html + export interface FindOperatorsOrdered { + delete(): OrderedBulkOperation; + deleteOne(): OrderedBulkOperation; + replaceOne(doc: Object): OrderedBulkOperation; + update(doc: Object): OrderedBulkOperation; + updateOne(doc: Object): OrderedBulkOperation; + upsert(): FindOperatorsOrdered; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/FindOperatorsUnordered.html + export interface FindOperatorsUnordered { + length: number; + remove(): UnorderedBulkOperation; + removeOne(): UnorderedBulkOperation; + replaceOne(doc: Object): UnorderedBulkOperation; + update(doc: Object): UnorderedBulkOperation; + updateOne(doc: Object): UnorderedBulkOperation; + upsert(): FindOperatorsUnordered; + } + + export class SchemaType { } + export class VirtualType { + get(fn: Function): VirtualType; + set(fn: Function): VirtualType; + } + export module Types { + export class ObjectId { + constructor(id?: string|number); + toHexString(): string; + equals(other: ObjectId): boolean; + getTimestamp(): Date; + isValid(): boolean; + static createFromTime(time: number): ObjectId; + static createFromHexString(hexString: string): ObjectId; + static isValid(id?: string|number):boolean; + } + } + + export class Schema { + static Types: { + String: String; + ObjectId: Types.ObjectId; + OId: Types.ObjectId; + Mixed: any; + }; + + methods: any; + statics: any; + + constructor(schema?: Object, options?: Object); + + add(obj: Object, prefix?: string): void; + eachPath(fn: (path: string, type: any) => void): Schema; + get(key: string): any; + index(fields: Object, options?: Object): Schema; + indexes(): void; + method(name: string, fn: Function): Schema; + method(method: Object): Schema; + path(path: string): any; + path(path: string, constructor: any): Schema; + pathType(path: string): string; + plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Schema; + + pre(method: string, fn: HookSyncCallback, errorCb?: HookErrorCallback): Schema; + pre(method: string, isAsync: boolean, fn: HookAsyncCallback, errorCb?: HookErrorCallback): Schema; + post(method: string, fn: (doc: Document, next?: HookNextFunction) => any ): Schema; + + requiredPaths(): string[]; + set(key: string, value: any): void; + static(name: string, fn: Function): Schema; + virtual(name: string, options?: Object): VirtualType; + virtualpath(name: string): VirtualType; + + } + + // hook functions: https://github.com/vkarpov15/hooks-fixed + export interface HookSyncCallback { + (next: HookNextFunction, ...hookArgs:any[]): any; + } + + export interface HookAsyncCallback { + (next: HookNextFunction, done: HookDoneFunction, ...hookArgs:any[]): any; + } + + export interface HookErrorCallback { + (error: Error): any; + } + + export interface HookNextFunction { + (error: Error): any; + (...hookArgs:any[]): any; + } + + export interface HookDoneFunction { + (error: Error): any; + (...hookArgs:any[]): any; + } + + export interface SchemaOption { + autoIndex?: boolean; + bufferCommands?: boolean; + capped?: boolean; + collection?: string; + id?: boolean; + _id?: boolean; + minimize?: boolean; + read?: string; + safe?: boolean; + shardKey?: boolean; + strict?: boolean; + toJSON?: Object; + toObject?: Object; + versionKey?: boolean; + } + + export interface Model extends NodeJS.EventEmitter { + new(doc?: Object, fields?: Object, skipInit?: boolean): T; + + aggregate(...aggregations: Object[]): Aggregate; + aggregate(aggregation: Object, callback: (err: any, res: T[]) => void): Promise; + aggregate(aggregation1: Object, aggregation2: Object, callback: (err: any, res: T[]) => void): Promise; + aggregate(aggregation1: Object, aggregation2: Object, aggregation3: Object, callback: (err: any, res: T[]) => void): Promise; + count(conditions: Object, callback?: (err: any, count: number) => void): Query; + + create(doc: Object, fn?: (err: any, res: T) => void): Promise; + create(doc1: Object, doc2: Object, fn?: (err: any, res1: T, res2: T) => void): Promise; + create(doc1: Object, doc2: Object, doc3: Object, fn?: (err: any, res1: T, res2: T, res3: T) => void): Promise; + discriminator(name: string, schema: Schema): Model; + distinct(field: string, callback?: (err: any, res: T[]) => void): Query; + distinct(field: string, conditions: Object, callback?: (err: any, res: T[]) => void): Query; + ensureIndexes(callback: (err: any) => void): Promise; + + find(): Query; + find(cond: Object, callback?: (err: any, res: T[]) => void): Query; + find(cond: Object, fields: Object, callback?: (err: any, res: T[]) => void): Query; + find(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T[]) => void): Query; + findById(id: string, callback?: (err: any, res: T) => void): Query; + findById(id: string, fields: Object, callback?: (err: any, res: T) => void): Query; + findById(id: string, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findByIdAndRemove(id: string, callback?: (err: any, res: T) => void): Query; + findByIdAndRemove(id: string, options: Object, callback?: (err: any, res: T) => void): Query; + findByIdAndUpdate(id: string, update: Object, callback?: (err: any, res: T) => void): Query; + findByIdAndUpdate(id: string, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; + findOne(cond?: Object, callback?: (err: any, res: T) => void): Query; + findOne(cond: Object, fields: Object, callback?: (err: any, res: T) => void): Query; + findOne(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; + + geoNear(point: { type: string; coordinates: number[] }, options: Object, callback?: (err: any, res: T[], stats: any) => void): Query; + geoNear(point: number[], options: Object, callback?: (err: any, res: T[], stats: any) => void): Query; + geoSearch(cond: Object, options: GeoSearchOption, callback?: (err: any, res: T[]) => void): Query; + increment(): T; + mapReduce(options: MapReduceOption, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; + mapReduce(options: MapReduceOption2, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; + model(name: string): Model; + + populate(doc: U, options: Object, callback?: (err: any, res: U) => void): Promise; + populate(doc: U[], options: Object, callback?: (err: any, res: U[]) => void): Promise; + update(cond: Object, update: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; + update(cond: Object, update: Object, options: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; + remove(cond: Object, callback?: (err: any) => void): Query<{}>; + save(callback?: (err: any, result: T, numberAffected: number) => void): Query; + where(path: string, val?: Object): Query; + + $where(argument: string): Query; + $where(argument: Function): Query; + + base: Mongoose; + collection: Collection; + db: any; + discriminators: any; + modelName: string; + schema: Schema; + } + export interface FindAndUpdateOption { + new?: boolean; + upsert?: boolean; + sort?: Object; + select?: Object; + } + export interface GeoSearchOption { + near: number[]; + maxDistance: number; + limit?: number; + lean?: boolean; + } + export interface MapReduceOption { + map: () => void; + reduce: (key: Key, vals: T[]) => Val; + query?: Object; + limit?: number; + keeptemp?: boolean; + finalize?: (key: Key, val: Val) => Val; + scope?: Object; + jsMode?: boolean; + verbose?: boolean; + out?: { + inline?: number; + replace?: string; + reduce?: string; + merge?: string; + }; + } + export interface MapReduceOption2 { + map: string; + reduce: (key: Key, vals: T[]) => Val; + query?: Object; + limit?: number; + keeptemp?: boolean; + finalize?: (key: Key, val: Val) => Val; + scope?: Object; + jsMode?: boolean; + verbose?: boolean; + out?: { + inline?: number; + replace?: string; + reduce?: string; + merge?: string; + }; + } + export interface MapReduceResult { + _id: Key; + value: Val; + } + + export class Query { + exec(callback?: (err: any, res: T) => void): Promise; + exec(operation: string, callback?: (err: any, res: T) => void): Promise; + exec(operation: Function, callback?: (err: any, res: T) => void): Promise; + + all(val: number): Query; + all(path: string, val: number): Query; + and(array: Object[]): Query; + box(val: Object): Query; + box(a: number[], b: number[]): Query; + batchSize(val: number): Query; + cast(model: Model, obj: Object): U; + //center(): Query; + //centerSphere(path: string, val: Object): Query; + circle(area: Object): Query; + circle(path: string, area: Object): Query; + comment(val: any): Query; + count(callback?: (err: any, count: number) => void): Query; + count(criteria: Object, callback?: (err: any, count: number) => void): Query; + distinct(callback?: (err: any, res: T) => void): Query; + distinct(field: string, callback?: (err: any, res: T) => void): Query; + distinct(criteria: Object, field: string, callback?: (err: any, res: T) => void): Query; + distinct(criteria: Query, field: string, callback?: (err: any, res: T) => void): Query; + elemMatch(criteria: Object): Query; + elemMatch(criteria: (elem: Query) => void): Query; + elemMatch(path: string, criteria: Object): Query; + elemMatch(path: string, criteria: (elem: Query) => void): Query; + equals(val: Object): Query; + exists(val?: boolean): Query; + exists(path: string, val?: boolean): Query; + find(callback?: (err: any, res: T) => void): Query; + find(criteria: Object, callback?: (err: any, res: T) => void): Query; + findOne(callback?: (err: any, res: T) => void): Query; + findOne(criteria: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(update: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; + geometry(object: Object): Query; + gt(val: number): Query; + gt(path: string, val: number): Query; + gte(val: number): Query; + gte(path: string, val: number): Query; + hint(val: Object): Query; + in(val: any[]): Query; + in(path: string, val: any[]): Query; + intersects(arg?: Object): Query; + lean(bool?: boolean): Query; + limit(val: number): Query; + lt(val: number): Query; + lt(path: string, val: number): Query; + lte(val: number): Query; + lte(path: string, val: number): Query; + maxDistance(val: number): Query; + maxDistance(path: string, val: number): Query; + maxScan(val: number): Query; + merge(source: Query): Query; + merge(source: Object): Query; + mod(val: number[]): Query; + mod(path: string, val: number[]): Query; + ne(val: any): Query; + ne(path: string, val: any): Query; + near(val: Object): Query; + near(path: string, val: Object): Query; + nearSphere(val: Object): Query; + nearSphere(path: string, val: Object): Query; + nin(val: any[]): Query; + nin(path: string, val: any[]): Query; + nor(array: Object[]): Query; + or(array: Object[]): Query; + polygon(...coordinatePairs: number[][]): Query; + polygon(path: string, ...coordinatePairs: number[][]): Query; + populate(path: string, select?: string, match?: Object, options?: Object): Query; + populate(path: string, select: string, model: string, match?: Object, options?: Object): Query; + populate(opt: PopulateOption): Query; + read(pref: string, tags?: Object[]): Query; + regex(val: RegExp): Query; + regex(path: string, val: RegExp): Query; + remove(callback?: (err: any, res: T) => void): Query; + remove(criteria: Object, callback?: (err: any, res: T) => void): Query; + select(arg: string): Query; + select(arg: Object): Query; + setOptions(options: Object): Query; + size(val: number): Query; + size(path: string, val: number): Query; + skip(val: number): Query; + slaveOk(v?: boolean): Query; + slice(val: number): Query; + slice(val: number[]): Query; + slice(path: string, val: number): Query; + slice(path: string, val: number[]): Query; + snapshot(v?: boolean): Query; + sort(arg: Object): Query; + sort(arg: string): Query; + stream(options?: { transform?: Function; }): QueryStream; + tailable(v?: boolean): Query; + toConstructor(): Query; + update(callback?: (err: any, affectedRows: number, doc: T) => void): Query; + update(doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; + update(criteria: Object, doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; + update(criteria: Object, doc: Object, options: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; + where(path?: string, val?: any): Query; + where(path?: Object, val?: any): Query; + within(val?: Object): Query; + within(coordinate: number[], ...coordinatePairs: number[][]): Query; + + $where(argument: string): Query; + $where(argument: Function): Query; + + static use$geoWithin: boolean; + } + + export interface PopulateOption { + path: string; + select?: string; + model?: string; + match?: Object; + options?: Object; + } + + export interface QueryStream extends NodeJS.EventEmitter { + destory(err?: any): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + paused: number; + readable: boolean; + } + + export interface Document { + id?: string; + _id: any; + + equals(doc: Document): boolean; + get(path: string, type?: new(...args: any[]) => any): any; + inspect(options?: Object): string; + invalidate(path: string, errorMsg: string, value: any): void; + invalidate(path: string, error: Error, value: any): void; + isDirectModified(path: string): boolean; + isInit(path: string): boolean; + isModified(path?: string): boolean; + isSelected(path: string): boolean; + markModified(path: string): void; + modifiedPaths(): string[]; + populate(callback?: (err: any, res: T) => void): Document; + populate(path?: string, callback?: (err: any, res: T) => void): Document; + populate(opt: PopulateOption, callback?: (err: any, res: T) => void): Document; + populated(path: string): any; + remove(callback?: (err: any) => void): Query; + save(callback?: (err: any, res: T) => void): void; + set(path: string, val: any, type?: new(...args: any[]) => any, options?: Object): void; + set(path: string, val: any, options?: Object): void; + set(value: Object): void; + toJSON(options?: Object): Object; + toObject(options?: Object): Object; + toString(): string; + update(doc: Object, options: Object, callback: (err: any, affectedRows: number, raw: any) => void): Query; + validate(cb: (err: any) => void): void; + + isNew: boolean; + errors: Object; + schema: Object; + } + + + export class Aggregate { + constructor(...options: Object[]); + + append(...options: Object[]): Aggregate; + group(arg: Object): Aggregate; + limit(num: number): Aggregate; + match(arg: Object): Aggregate; + near(parameters: Object): Aggregate; + project(arg: string): Aggregate; + project(arg: Object): Aggregate; + select(filter: string): Aggregate; + skip(num: number): Aggregate; + sort(arg: string): Aggregate; + sort(arg: Object): Aggregate; + unwind(fiels: string, ...rest: string[]): Aggregate; + + exec(callback?: (err: any, result: T) => void): Promise; + read(pref: string, ...tags: Object[]): Aggregate; + } + + export class Promise { + constructor(fn?: (err: any, result: T) => void); + + then(onFulFill: (result: T) => void | U | Promise, onReject?: (err: any) => void | U | Promise): Promise; + end(): void; + + fulfill(result: T): Promise; + reject(err: any): Promise; + resolve(err: any, result: T): Promise; + + onFulfill(listener: (result: T) => void): Promise; + onReject(listener: (err: any) => void): Promise; + onResolve(listener: (err: any, result: T) => void): Promise; + on(event: string, listener: Function): Promise; + + // Deprecated methods. + addBack(listener: (err: any, result: T) => void): Promise; + addCallback(listener: (result: T) => void): Promise; + addErrback(listener: (err: any) => void): Promise; + complete(result: T): Promise; + error(err: any): Promise; + } + +} \ No newline at end of file diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 24cbdffc65..ea41e5688c 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1,74 +1,901 @@ +import * as mongoose from 'mongoose'; var fs = require('fs'); -import mongoose = require('mongoose'); -var createInstance = new mongoose.Mongoose(); +// dummy variables +var cb = function () {}; -var Schema = mongoose.Schema; -var CreateSchema = new Schema({}); +/* + * Most of these tests are taken directly from the examples + * in the Mongoose API documentation. + * + * http://mongoosejs.com/docs/guide.html + * http://mongoosejs.com/docs/api.html + */ -mongoose.connect('mongodb://user:pass@localhost:port/database'); -mongoose.connect('mongodb://hostA:27501,hostB:27501', { mongos: true }); +/* + * section index.js + * http://mongoosejs.com/docs/api.html#index-js + */ +var connectUri = 'mongodb://user:pass@localhost:port/database'; +mongoose.connect(connectUri).then(cb).catch(cb); +mongoose.connect(connectUri, { + user: 'larry', + pass: 'housan', + config: { + autoIndex: true + }, + mongos: true +}).then(cb).fulfill(); +mongoose.connect(connectUri, function (error) { + error.stack; +}); +var mongooseConnection: mongoose.Connection = mongoose.createConnection(); +mongoose.createConnection(connectUri).open(''); +mongoose.createConnection(connectUri, { + db: { + native_parser: true + } +}).open(''); +mongoose.createConnection('localhost', 'database', 3000).open(''); +mongoose.createConnection('localhost', 'database', 3000, { + user: 'larry', + config: { + autoIndex: false + } +}).open(''); +mongoose.disconnect(cb).then(cb).fulfill; +mongoose.get('test'); +mongoose.model('Actor', new mongoose.Schema({ + name: String +}), 'collectionName', true).find({}); +mongoose.model('Actor').find({}); +mongoose.modelNames()[0].toLowerCase(); +new (new mongoose.Mongoose()).Mongoose().connect(''); +mongoose.plugin(cb, {}).connect(''); +mongoose.set('test', 'value'); +mongoose.set('debug', function(collectionName: any, methodName: any, arg1: any, arg2: any) {}); +mongoose.STATES.hasOwnProperty(''); +mongoose.connection.on('error', cb); +new mongoose.mongo.MongoError('error').stack; +mongoose.SchemaTypes.String; +mongoose.Types.ObjectId; +mongoose.version.toLowerCase(); -var conn: mongoose.Connection = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); -conn = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port', { replset: { strategy: 'ping', rs_name: 'testSet' }}); -conn = mongoose.createConnection('localhost', 'database', 27014); -conn = mongoose.createConnection('localhost', 'database', 27014, { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' }); -conn = mongoose.createConnection(); -conn.open('localhost', 'database', 27014, {}); +/* + * section querystream.js + * http://mongoosejs.com/docs/api.html#querystream-js + */ +var querystream: mongoose.QueryStream; +querystream.destroy(new Error()); +querystream.pause(); +querystream.pipe(process.stdout, {end: true}).end(); +querystream.resume(); +querystream.paused; +querystream.readable; +/* inherited properties */ +querystream.getMaxListeners(); +/* practical examples */ +var QSModel: typeof mongoose.Model; +var QSStream: mongoose.QueryStream = QSModel.find().stream(); +QSStream.on('data', function (doc: any) { + doc.save(); +}).on('error', function (err: any) { + throw err; +}).on('close', cb); +QSModel.where('created').gte(20000).stream().pipe(process.stdout); -var db = mongoose.createConnection(); -db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019"); -db.openSet('mongodb://mongosA:27501,mongosB:27501', 'db', { mongos: true }, (err: any) => {}); -db.close(); +/* + * section collection.js + * http://mongoosejs.com/docs/api.html#collection-js + * + * section drivers/node-mongodb-native/collection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js + */ +var coll1: mongoose.Collection; +coll1.$format(999).toLowerCase(); +coll1.$print('name', 'i', [1, 2, 3]); +coll1.getIndexes(); +/* inherited properties */ +coll1.collectionName; +coll1.conn; +coll1.name; +coll1.ensureIndex(); +coll1.find({}); +coll1.insert({}, {}); -var collection = db.collection('collection1'); +var coll2 = new mongoose.Collection('', new mongoose.Connection(null)); +coll2.$format(999).toLowerCase(); +/* inherited properties */ +coll2.initializeOrderedBulkOp; +coll2.indexExists; -mongoose.connection.on('error', (err: any) => {}); -mongoose.disconnect(); - -mongoose.set('test', 1234567890); -var value = mongoose.get('test'); -mongoose.set('debug', true); - -interface IActor extends mongoose.Document { - name: string; +/* + * section connection.js + * http://mongoosejs.com/docs/api.html#connection-js + * + * section section drivers/node-mongodb-native/connection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js + */ +var conn1: mongoose.Connection = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); +conn1 = new mongoose.Connection(mongoose); +conn1.open('mongodb://localhost/test', 'myDb', 27017, { + replset: null, + config: { + autoIndex: false + } +}, function (err) {}).open(''); +conn1.openSet('mongodb://localhost/test', 'db', { + replset: null, + mongos: true +}, function (err) {}).then(cb).catch(cb); +conn1.close().catch(function (err) {}); +conn1.collection('name').$format(999); +conn1.model('myModel', new mongoose.Schema({}), 'myCol').find(); +interface IStatics { + staticMethod1: (a: number) => string; } -mongoose.model('Actor', new Schema({ name: String })); -db.model('Actor', new Schema({ name: String })); -var schema: mongoose.Schema = new Schema({ name: String }, { collection: 'actor' }); -schema.set('collection', 'actor'); -var Model = mongoose.model('Actor', schema, 'actor'); +conn1.model<{}, IStatics>('').staticMethod1; +conn1.modelNames()[0].toLowerCase(); +conn1.config.hasOwnProperty(''); +conn1.db.bufferMaxEntries; +conn1.collections['coll'].$format(999); +conn1.readyState.toFixed(); +conn1.useDb('myDb').useDb(''); +mongoose.Connection.STATES.hasOwnProperty(''); +/* inherited properties */ +conn1.on('data', cb); +conn1.addListener('close', cb); -interface IZip extends mongoose.Document { - _id: string; -} -interface IPerson extends mongoose.Document { - _id: mongoose.Types.ObjectId; -} -interface IThing extends mongoose.Document { - _id: number; +/* + * section error/validation.js + * http://mongoosejs.com/docs/api.html#error-validation-js + */ +var validationError: mongoose.ValidationError; +validationError.toString().toLowerCase(); +/* inherited properties */ +validationError.stack; +validationError.message; + +/* + * section error.js + * http://mongoosejs.com/docs/api.html#error-js + */ +var mongooseError: mongoose.Error = new mongoose.Error('error'); +/* inherited properties */ +mongooseError.message; +mongooseError.name; +mongooseError.stack; +/* static properties */ +mongoose.Error.messages.hasOwnProperty(''); +mongoose.Error.Messages.hasOwnProperty(''); + +/* + * section querycursor.js + * http://mongoosejs.com/docs/api.html#querycursor-js + */ +var querycursor: mongoose.QueryCursor; +querycursor.close(function (error, result) { + result.execPopulate(); +}).catch(cb); +querycursor.eachAsync(function (doc) { + doc.execPopulate(); +}, function (err) {}).catch(cb); +querycursor.next(cb).catch(cb); +/* inherited properties */ +querycursor.pause(); +querycursor.pipe(process.stdout); +/* practical example */ +var QCModel = mongoose.model('QC', new mongoose.Schema({name: String})); +QCModel.find({}).cursor({}).on('data', function (doc: any) { + doc.depopulate('name'); +}).on('error', function (error: any) { + throw error; +}).close().then(cb).catch(cb); + +/* + * section virtualtype.js + * http://mongoosejs.com/docs/api.html#virtualtype-js + */ +var virtualtype: mongoose.VirtualType = new mongoose.VirtualType({}, 'hello'); +virtualtype.applyGetters({}, {}); +virtualtype.applySetters({}, {}); +virtualtype.get(cb).get(cb); +virtualtype.set(cb).set(cb); + +/* + * section schema.js + * http://mongoosejs.com/docs/api.html#schema-js + */ +var schema: mongoose.Schema = new mongoose.Schema({ + name: String, + binary: Buffer, + living: Boolean, + updated: { type: Date, default: Date.now }, + age: { type: Number, min: 18, max: 65 }, + mixed: mongoose.Schema.Types.Mixed, + _someId: mongoose.Schema.Types.ObjectId, + array: [], + ofString: [String], + ofNumber: [Number], + ofDates: [Date], + ofBuffer: [Buffer], + ofBoolean: [Boolean], + ofMixed: [mongoose.Schema.Types.Mixed], + ofObjectId: [mongoose.Schema.Types.ObjectId], + nested: { + stuff: { type: String, lowercase: true, trim: true } + } +}); +schema.add({ + mixedArray: { + type: [mongoose.Schema.Types.Mixed], + required: true + } +}, 'prefix'); +schema.eachPath(function (path, type) { + path.toLowerCase(); + type.sparse(true); +}).eachPath(cb); +schema.get('path'); +schema.index({ + name: 1, + binary: -1 +}).index({}, {}); +schema.indexes().slice(); +schema.method('name', cb).method({ + m1: cb, + m2: cb +}); +schema.path('a', mongoose.Schema.Types.Buffer).path('a'); +schema.pathType('m1').toLowerCase(); +schema.plugin(function (schema, opts) { + schema.get('path'); + opts.hasOwnProperty(''); +}).plugin(cb, {opts: true}); +schema.post('post', function (doc) {}).post('post', function (doc, next) { + next(new Error()); +}); +schema.queue('m1', [1, 2, 3]).queue('m2', [[]]); +schema.remove('path'); +schema.remove(['path1', 'path2', 'path3']); +schema.requiredPaths(true)[0].toLowerCase(); +schema.set('key', 999).set('key'); +schema.static('static', cb).static({ + s1: cb, + s2: cb +}); +schema.virtual('virt', {}).applyGetters({}, {}); +schema.virtualpath('path').applyGetters({}, {}); +/* static properties */ +mongoose.Schema.indexTypes[0].toLowerCase(); +mongoose.Schema.reserved.hasOwnProperty(''); +/* inherited properties */ +schema.addListener('e', cb); +/* practical examples */ +var animalSchema = new mongoose.Schema({ + name: String, + type: String +}); +animalSchema.methods.findSimilarTypes = function (cb: any) { + return this.model('Aminal').find({ type: this.type }, cb); +}; +var Animal: any = mongoose.model('Animal', animalSchema); +var dog: any = new Animal({type: 'dog'}); +dog['findSimilarTypes'](function (err: any, dogs: any) { + console.log(dogs); +}); +new mongoose.Schema({ + title: String, + author: String, + body: String, + comments: [{ body: String, date: Date }], + date: { type: Date, default: Date.now }, + hidden: Boolean, + meta: { + votes: Number, + favs: Number + } +}); +animalSchema.statics.findByName = function(name: any, cb: any) { + return this.find({ name: new RegExp(name, 'i') }, cb); +}; +Animal['findByName']('fido', function(err: any, animals: any) { + console.log(animals); +}); +animalSchema.virtual('name.full').get(function () { + return this.name.first + ' ' + this.name.last; +}); +new mongoose.Schema({ + child: new mongoose.Schema({ name: 'string' }) +}); +new mongoose.Schema({ + eggs: { + type: Number, + min: [6, 'Too few eggs'], + max: 12 + }, + bacon: { + type: Number, + required: [true, 'Why no bacon?'] + }, + drink: { + type: String, + enum: ['Coffee', 'Tea'] + } +}); + +(new mongoose.Schema({})).plugin(function (schema: any, options: any) { + schema.add({ lastMod: Date }) + schema.pre('save', function (next: Function) { + this.lastMod = new Date + next() + }) + if (options && options['index']) { + schema.path('lastMod').index(options['index']) + } +}, { index: true }).plugin(function (schema: any, options: any) { + schema.add({ lastMod: Date }) + schema.pre('save', function (next: Function) { + this.lastMod = new Date + next() + }) + if (options && options['index']) { + schema.path('lastMod').index(options['index']) + } +}); + +/* + * section document.js + * http://mongoosejs.com/docs/api.html#document-js + */ +var doc: mongoose.Document; +doc.$isDefault('path').valueOf(); +doc.depopulate('path'); +doc.equals(doc).valueOf(); +doc.execPopulate().then(function (arg) { + arg.execPopulate(); +}).catch(function (err) {}); +doc.get('path', Number); +doc.init(doc, cb).init(doc, {}, cb); +doc.inspect(); +doc.invalidate('path', new Error('hi'), 999).toString(); +doc.isDirectModified('path').valueOf(); +doc.isInit('path').valueOf(); +doc.isModified('path').valueOf(); +doc.isSelected('path').valueOf(); +doc.markModified('path'); +doc.modifiedPaths()[0].toLowerCase(); +doc.populate(function (err, doc) { + doc.populate('path', function (err, doc) { + doc.populate({ + path: 'path', + select: 'path', + match: {} + }); + }); +}); +doc.populated('path'); +doc.set('path', 999, {}); +doc.set({ + path: 999 +}); +doc.toJSON({ + getters: true, + virtuals: false +}); +doc.toObject({ + transform: function (doc, ret, options) { + doc.toObject(); + } +}); +doc.toString().toLowerCase(); +doc.unmarkModified('path'); +doc.update(doc, cb).cursor(); +doc.update(doc, { + safe: true, + upsert: true +}, cb).cursor(); +doc.validate({}, function (err) {}); +doc.validate().then(null).catch(null); +doc.validateSync(['path1', 'path2']).stack; +/* practical examples */ +var MyModel = mongoose.model('test', new mongoose.Schema({ + name: { + type: String, + default: 'Val ' + } +})); +doc = new MyModel(); +doc.$isDefault('name'); +MyModel.findOne().populate('author').exec(function (err, doc) { + doc.depopulate('author'); +}); +doc.populate('path'); +doc.populate({path: 'hello'}); +doc.populate('path', cb) +doc.populate({path: 'hello'}, cb); +doc.populate(cb); +doc.populate({path: 'hello'}).execPopulate().catch(cb); +doc.update({$inc: {wheels:1}}, { w: 1 }, cb); + +/* + * section types/subdocument.js + * http://mongoosejs.com/docs/api.html#types-subdocument-js + */ +// The constructor is private api, but we'll use it to test +var subdocument: mongoose.Types.Subdocument = new mongoose.Types.Subdocument(); +subdocument.ownerDocument().errors; +subdocument.remove({}, function (err) { + return 6; +}); +/* inherited properties */ +subdocument.execPopulate(); + +/* + * section types/array.js + * http://mongoosejs.com/docs/api.html#types-array-js + */ +var mongooseArray: mongoose.Types.Array = new mongoose.Types.Array(); +mongooseArray.$shift().toLowerCase(); +mongooseArray.remove().$shift(); +mongooseArray.$pop().toLowerCase(); +mongooseArray.addToSet('hi', 9, 9, '4')[0].toLowerCase(); +mongooseArray.indexOf({name: 'obj'}).toFixed(); +mongooseArray.inspect(); +mongooseArray.nonAtomicPush(9, 8, 'hi').toFixed(); +mongooseArray.pop().toLowerCase(); +mongooseArray.pull(5, 4, 'hi').$shift(); +mongooseArray.push([]).toFixed(); +mongooseArray.set(1, 'hi').$shift(); +mongooseArray.shift().toLowerCase(); +mongooseArray.sort(function (a, b) { + return a.length - b.length; +}).unshift(); +mongooseArray.splice(4, 1).unshift(); +mongooseArray.toObject({depopulate: true}).unshift(); +mongooseArray.unshift(2, 4, 'hi').toFixed(); +/* inherited properties */ +mongooseArray.concat(); +mongooseArray.length; + +/* + * section types/documentarray.js + * http://mongoosejs.com/docs/api.html#types-documentarray-js + */ +// The constructor is private api, but we'll use it to test +var documentArray: mongoose.Types.DocumentArray = + new mongoose.Types.DocumentArray(); +documentArray.create({}).errors; +documentArray.id(new Buffer('hi')); +documentArray.inspect(); +documentArray.toObject({}).length; +/* inherited from mongoose.Types.Array */ +documentArray.$shift(); +/* inherited from Native Array */ +documentArray.concat(); + +/* + * section types/buffer.js + * http://mongoosejs.com/docs/api.html#types-buffer-js + */ +var mongooseBuffer: mongoose.Types.Buffer = new mongoose.Types.Buffer('hello'); +mongooseBuffer.copy(mongooseBuffer, 1, 2, 3).toFixed(); +mongooseBuffer.copy(new Buffer('hi')).toFixed(); +mongooseBuffer.equals(new Buffer('hi')).valueOf(); +mongooseBuffer.subtype(123); +mongooseBuffer.toObject().value(); +mongooseBuffer.write('world', 3, 2, 1).toFixed(); +/* inherited properties */ +mongooseBuffer.compare(mongooseBuffer); +/* inherited static properties */ +mongoose.Types.Buffer.from([1, 2, 3]); + +/* + * section types/objectid.js + * http://mongoosejs.com/docs/api.html#types-objectid-js + */ +var objectId: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromHexString('0x1234'); +objectId = new mongoose.Types.ObjectId(12345); +objectId.getTimestamp(); +/* practical examples */ +export interface IManagerSchema extends mongoose.Document { + user: mongoose.Schema.Types.ObjectId; } +export var ManagerSchema = new mongoose.Schema({ + user: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + required: true + } +}); -var names: string[] = mongoose.modelNames(); -var names: string[] = db.modelNames(); -mongoose.plugin((schema: mongoose.Schema) => { -}, { index: true }); +/* + * section types/embedded.js + * http://mongoosejs.com/docs/api.html#types-embedded-js + */ +var embeddedDocument: mongoose.Types.Embedded = new mongoose.Types.Embedded(); +embeddedDocument.inspect().hasOwnProperty(''); +embeddedDocument.invalidate('hi', new Error('bleh')).valueOf(); +embeddedDocument.ownerDocument().execPopulate(); +embeddedDocument.parent().execPopulate(); +embeddedDocument.parentArray().$shift(); +embeddedDocument.remove().invalidate('hi', new Error('hi')); +embeddedDocument.markModified('path'); +/* inherited properties */ +embeddedDocument.execPopulate(); +/* + * section query.js + * http://mongoosejs.com/docs/api.html#query-js + */ +var query: mongoose.Query; +query.$where('').$where(cb); +query.all(99).all('path', 99); +query.and([{ color: 'green' }, { status: 'ok' }]).and([]); +query.batchSize(100).batchSize(100); +var lowerLeft = [40.73083, -73.99756] +var upperRight = [40.741404, -73.988135] +query.where('loc').within().box(lowerLeft, upperRight) +query.box({ ll : lowerLeft, ur : upperRight }).box({}); +var queryModel = mongoose.model('QModel') +query.cast(new queryModel(), {}).hasOwnProperty(''); +query.catch(function (err) {}).catch(); +query.center({}).center({}); +query.centerSphere({ center: [50, 50], radius: 10 }).centerSphere('path', {}); +query.circle({ center: [50, 50], radius: 10 }).circle('path'); +query.comment('comment').comment('comment'); +query.where({color: 'black'}).count(function (err, count) { + count.toFixed(); +}).then(function (res) { + res.toFixed(); +}).catch(function (err) {}); +query.cursor().close(); +query.distinct('field', {}, cb); +query.distinct('field', {}); +query.distinct('field', cb); +query.distinct('field'); +query.distinct(cb); +query.distinct(); +query.elemMatch('comment', { + author: 'autobot', + votes: {$gte: 5} +}).elemMatch('comment', function (elem) { + elem.where('author').equals('autobot'); + elem.where('votes').gte(5); +}); +query.where('age').equals(49); +query.exec('find', function (err, res) { + res[0].execPopulate(); +}).then(function (arg) { + arg[0].execPopulate(); +}).catch(cb); +query.where('name').exists().exists('age', false); +query.find({name: 'aa'}, function (err, res) { + res[0].execPopulate(); +}).find(); +query.findOne(function (err, res) { + res.execPopulate(); +}).findOne(); +query.findOneAndRemove({name: 'aa'}, { + passRawResult: true +}, function (err, doc) { + doc.execPopulate(); +}).findOneAndRemove(); +query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}, { -var aggregate = new mongoose.Aggregate(); -var aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }); -var aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); -var aggregate = new mongoose.Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]); +}); +query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}, { + passRawResult: true +}, cb); +query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}, cb); +query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}); +query.findOneAndUpdate({name: 'bb'}, cb); +query.findOneAndUpdate({name: 'bb'}); +query.findOneAndUpdate(cb); +query.findOneAndUpdate().then(function (doc) { + doc.execPopulate(); +}).catch(cb); +var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] +query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) +var polyB = [[ 0, 0 ], [ 1, 1 ]] +query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) +var polyC = [ 0, 0 ] +query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) +query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) +query.getQuery(); +query.getUpdate(); +query.find().where('age').gt(21); +query.find().gt('age', 21); +query.find().where('age').gte(21); +query.find().gte('age', 21); +query.hint({ indexA: 1, indexB: -1}).hint({}); +query.in([1, 2, 3]).in('num', [1, 2, 3]); +query.where('path').intersects().geometry({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}); +query.where('path').intersects({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}); +query.find().lean().exec(function (err: any, docs: any) { + docs[0]; +}); +query.limit(20).limit(20); +query.find().where('age').lt(21); +query.find().lt('age', 21); +query.find().where('age').lte(21); +query.find().lte('age', 21); +query.maxDistance('path', 21).maxDistance(21); +query.maxscan(100).maxScan(100); +query.maxScan(100).maxScan(100); +query.merge(query).merge({}); +query.mod([1, 2]).mod([5, 6]); +query.find().where('age').ne(21); +query.find().ne('age', 21); +query.where('loc').near({ center: [10, 10] }); +query.where('loc').near({ center: [10, 10], maxDistance: 5 }); +query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); +query.near('loc', { center: [10, 10], maxDistance: 5 }); +query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); +query.find().where('age').in([20, 21]); +query.find().in('age', [20, 21]); +query.nor([{ color: 'green' }, { status: 'ok' }]).nor([]); +query.or([{ color: 'red' }, { status: 'emergency' }]).or([]); +query.where('loc').within().polygon([10,20], [13, 25], [7,15]); +query.polygon('loc', [10,20], [13, 25], [7,15]); +query.findOne().populate('owner').exec(function (err, kitten) { + kitten.execPopulate(); +}); +query.find().populate({ + path: 'owner' + , select: 'name' + , match: { color: 'black' } + , options: { sort: { name: -1 }} +}).exec(function (err, kittens) { + kittens[0].execPopulate(); +}); +query.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) { + kittens[0].execPopulate(); +}); +query.read('primary', []).read('primary'); +query.regex(/re/).regex('path', /re/); +query.remove({}, cb); +query.remove({}); +query.remove(cb); +query.remove(); +query.select('a b'); +query.select('-c -d'); +query.select({ a: 1, b: 1 }); +query.select({ c: 0, d: 0 }); +query.select('+path'); +query.selected(); +query.selectedExclusively(); +query.selectedInclusively(); +query.setOptions({ + tailable: true, + batchSize: true, + lean: false +}); +query.size(0).size('age', 0); +query.skip(100).skip(100); +query.slaveOk().slaveOk(false); +query.slice('comments', 5); +query.slice('comments', -5); +query.slice('comments', [10, 5]); +query.where('comments').slice(5); +query.where('comments').slice([-10, 5]); +query.snapshot().snapshot(true); +query.sort({ field: 'asc', test: -1 }); +query.sort('field -test'); +query.stream().on('data', function (doc: any) { +}).on('error', function (err: any) { +}).on('close', function () { +}); +query.tailable().tailable(false); +query.then(cb).catch(cb); +(new (query.toConstructor())()).toConstructor(); +query.update({}, doc, { + +}, cb); +query.update({}, doc, { + +}); +query.update({}, doc, cb); +query.update({}, doc); +query.update(doc, cb); +query.update(doc); +query.update(cb); +query.update(true); +query.update(); +query.where('age').gte(21).lte(65) + .where('name', /^vonderful/i) + .where('friends').slice(10) + .exec(cb); +query.where('path').within().box({}) +query.where('path').within().circle({}) +query.where('path').within().geometry({type: 'c', coordinates: []}); +query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); +query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); +query.where('loc').within({ polygon: [[],[],[],[]] }); +query.where('loc').within([], [], []); +query.where('loc').within([], []); +query.where('loc').within({ type: 'LineString', coordinates: [] }); +mongoose.Query.use$geoWithin = false; +/* practical example */ +query. + find({ + occupation: /host/, + 'name.last': 'Ghost', + age: { $gt: 17, $lt: 66 }, + likes: { $in: ['vaporizing', 'talking'] } + }). + limit(10). + sort({ occupation: -1 }). + select({ name: 1, occupation: 1 }). + exec(cb).then(cb).catch(cb); +query. + find({ occupation: /host/ }). + where('name.last').equals('Ghost'). + where('age').gt(17).lt(66). + where('likes').in(['vaporizing', 'talking']). + limit(10). + sort('-occupation'). + select('name occupation'). + exec(cb).then(cb).catch(cb); + +/* + * section schema/array.js + * http://mongoosejs.com/docs/api.html#schema-array-js + */ +var schemaArray: mongoose.Schema.Types.Array = new mongoose.Schema.Types.Array('key', new mongoose.SchemaType('hi'), {}); +schemaArray.checkRequired('hello').valueOf(); +/** static properties */ +mongoose.Schema.Types.Array.schemaName.toLowerCase(); +/** inherited properties */ +schemaArray.sparse(true); + +/* + * section schema/string.js + * http://mongoosejs.com/docs/api.html#schema-string-js + */ +var schemastring: mongoose.Schema.Types.String = new mongoose.Schema.Types.String('hello'); +schemastring.checkRequired(234, new mongoose.Document()).valueOf(); +schemastring.enum(['hi', 'a', 'b']).enum('hi').enum({}); +schemastring.lowercase().lowercase(); +schemastring.match(/re/, 'error').match(/re/); +schemastring.maxlength(999, 'error').maxlength(999); +schemastring.minlength(999, 'error').minlength(999); +schemastring.trim().trim(); +schemastring.uppercase().uppercase(); +/* static properties */ +mongoose.Schema.Types.String.schemaName.toLowerCase(); +/* inherited properties */ +schemastring.sparse(true); + +/* + * section schema/documentarray.js + * http://mongoosejs.com/docs/api.html#schema-documentarray-js + */ +var documentarray: mongoose.Schema.Types.DocumentArray = new mongoose.Schema.Types.DocumentArray('key', new mongoose.Schema()); +/* static properties */ +mongoose.Schema.Types.DocumentArray.schemaName.toLowerCase(); +/* inherited properties */ +documentarray.sparse(true); + +/* + * section schema/number.js + * http://mongoosejs.com/docs/api.html#schema-number-js + */ +var schemanumber: mongoose.Schema.Types.Number = new mongoose.Schema.Types.Number('num', {}); +schemanumber.checkRequired(999, new mongoose.Document()).valueOf(); +schemanumber.max(999, 'error').max(999); +schemanumber.min(999, 'error').min(999); +/* static properties */ +mongoose.Schema.Types.Number.schemaName.toLowerCase(); +/* inherited properties */ +schemanumber.sparse(true); + +/* + * section schema/date.js + * http://mongoosejs.com/docs/api.html#schema-date-js + */ +var schemadate: mongoose.Schema.Types.Date = new mongoose.Schema.Types.Date('99'); +schemadate.checkRequired([], new mongoose.Document()).valueOf(); +schemadate.expires(99).expires('now'); +schemadate.max(new Date(), 'error').max(new Date('')); +schemadate.min(new Date(), 'error').min(new Date('')); +/* static properties */ +mongoose.Schema.Types.Date.schemaName.toLowerCase(); +/* inherited properties */ +schemadate.sparse(true); + +/* + * section schema/buffer.js + * http://mongoosejs.com/docs/api.html#schema-buffer-js + */ +var schemabuffer: mongoose.Schema.Types.Buffer = new mongoose.Schema.Types.Buffer('99'); +schemabuffer.checkRequired(999, new mongoose.Document()).valueOf(); +/* static properties */ +mongoose.Schema.Types.Buffer.schemaName.toLowerCase(); +/* inherited properties */ +schemabuffer.sparse(true); + +/* + * section schema/boolean.js + * http://mongoosejs.com/docs/api.html#schema-boolean-js + */ +var schemaboolean: mongoose.Schema.Types.Boolean = new mongoose.Schema.Types.Boolean('99'); +schemaboolean.checkRequired(99).valueOf(); +/* static properties */ +mongoose.Schema.Types.Boolean.schemaName.toLowerCase(); +/* inherited properties */ +schemaboolean.sparse(true); + +/* + * section schema/objectid.js + * http://mongoosejs.com/docs/api.html#schema-objectid-js + */ +var schemaobjectid: mongoose.Schema.Types.ObjectId = new mongoose.Schema.Types.ObjectId('99'); +schemaobjectid.auto(true).auto(false); +schemaobjectid.checkRequired(99, new mongoose.Document()).valueOf(); +/* static properties */ +mongoose.Schema.Types.ObjectId.schemaName.toLowerCase(); +/* inherited properties */ +schemaobjectid.sparse(true); + +/* + * section schema/mixed.js + * http://mongoosejs.com/docs/api.html#schema-mixed-js + */ +var schemamixed: mongoose.Schema.Types.Mixed = new mongoose.Schema.Types.Mixed('99'); +/* static properties */ +mongoose.Schema.Types.Mixed.schemaName.toLowerCase(); +/* inherited properties */ +schemamixed.sparse(true); + +/* + * section schema/embedded.js + * http://mongoosejs.com/docs/api.html#schema-embedded-js + */ +var schemaembedded: mongoose.Schema.Types.Embedded = + new mongoose.Schema.Types.Embedded(new mongoose.Schema(), '99'); +/* inherited properties */ +schemaembedded.sparse(true); + +/* + * section aggregate.js + * http://mongoosejs.com/docs/api.html#aggregate-js + */ +var aggregate: mongoose.Aggregate; +aggregate = mongoose.model('ex').aggregate({ $match: { age: { $gte: 21 }}}); +aggregate = new mongoose.Aggregate(); +aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }); +aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); +aggregate = new mongoose.Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]); +aggregate.addCursorFlag('flag', true).addCursorFlag('', false); +aggregate.allowDiskUse(true).allowDiskUse(false, []); aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); aggregate.append([{ $match: { daw: 'Logic Audio X' }} ]); -aggregate.group({ _id: "$department" }); -aggregate.skip(10); -aggregate.limit(10); -aggregate.match({ department: { $in: [ "sales", "engineering" ] } }); +aggregate.cursor({ batchSize: 1000 }).exec().each(cb); +aggregate.exec().then(cb).catch(cb); +aggregate.explain(cb).then(cb).catch(cb); +aggregate.group({ _id: "$department" }).group({ _id: "$department" }); +aggregate.limit(10).limit(10); +var lookupOpt = { + from: 'users', localField: + 'userId', foreignField: '_id', + as: 'users' +}; +aggregate.lookup(lookupOpt).lookup(lookupOpt); +aggregate.match({ + department: {$in: [ "sales", "engineering"]} +}); +aggregate.model(new (mongoose.model('xx'))()).model(null); aggregate.near({ near: [40.724, -73.997], - distanceField: "dist.calculated", // required + distanceField: "dist.calculated", maxDistance: 0.008, query: { type: "public" }, includeLocs: "dist.location", @@ -78,314 +905,449 @@ aggregate.near({ aggregate.project("a b -_id"); aggregate.project({a: 1, b: 1, _id: 0}); aggregate.project({ - newField: '$b.nested', - plusTen: { $add: ['$val', 10]}, - sub: { + newField: '$b.nested' + , plusTen: { $add: ['$val', 10]} + , sub: { name: '$a' } -}); -aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); +}) +aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ]}}); +aggregate.read('primaryPreferred').read('pp'); +aggregate.sample(3).sample(3); +aggregate.skip(10).skip(10); aggregate.sort({ field: 'asc', test: -1 }); aggregate.sort('field -test'); -aggregate.unwind("tags"); -aggregate.unwind("a", "b", "c"); -var p = aggregate.exec(); -aggregate.read('primaryPreferred').exec((err: any, result: {}) => {}); +aggregate.then(cb).catch(cb); +aggregate.unwind("tags").unwind('tags'); +aggregate.unwind("a", "b", "c").unwind('tag1', 'tag2'); +/* + * section schematype.js + * http://mongoosejs.com/docs/api.html#schematype-js + */ +new mongoose.SchemaType('hello', 9, 'hello' ); +var STSchema = new mongoose.Schema({ + mixed: mongoose.Schema.Types.Mixed +}); +var schematype = schema.path('mixed'); +schematype.default('default'); +STSchema.path('born').get(cb).get(cb); +STSchema.path('name').index(true).index({ unique: true, sparse: true }); +schematype.required(true, 'mess').required(true); +schematype.select(true).select(false); +STSchema.path('name').set(cb).set(cb); +schematype.sparse(true).sparse(true); +schematype.text(true).text(true); +schematype.unique(true).unique(true); +schematype.validate(/re/) + .validate({}, 'error') + .validate(cb, 'try', 'tri'); -var p = new mongoose.Promise; -var p2 = p.then(function() { throw new Error('shucks') }).end(); -setTimeout(function() { - p.fulfill({}); -}, 10); -var promise = new mongoose.Promise(); -promise.then(function (meetups: number) { - return new mongoose.Promise(); -}).then(function (people: string[]) { - if (people.length < 10000) { - throw new Error('Too few people!!!'); - } else { - throw new Error('Still need more people!!!'); - } -}).then(null, function (err: Error) { -}).end(); +/* + * section promise.js + * http://mongoosejs.com/docs/api.html#promise-js + */ +var mongopromise = new mongoose.Promise(); +mongopromise = new mongoose.Promise(function (err: any, arg: any) { + arg.sparse(true); + err.stack; +}); +mongopromise = new mongoose.Promise(function (err: any, arg1: any, arg2: any) { + arg1.sparse(true); + arg2.sparse(true); + err.stack; +}); +mongopromise.addBack(function (err: any, arg: any) { + err.stack; + arg.sparse(true); +}).addBack(function (err: any, arg1: any, arg2: any) { + err.stack; + arg1.sparse(true); + arg2.sparse(true); +}); +mongopromise.addCallback(function (arg: any) { + arg.sparse(true); +}).addCallback(function (arg1: any, arg2: any) { + arg1.sparse(true); + arg2.sparse(true); +}); +mongopromise.addErrback(function (err: any) { + err.stack; +}).addErrback(function () {}); +mongopromise.catch(function (err: any) { + err.stack; +}).catch(function () {}); +mongopromise.end(); +mongopromise.error(999).error([]); +mongopromise.on('init', function () {}).on('init', function () {}); +mongopromise.reject({}).reject('').reject(new Error('hi')); +mongopromise.resolve(new Error('hi'), {}).resolve(); +mongopromise.then(function (arg: any) { + arg.sparse(true); +}, function (err: any) { + err.stack; +}).then(function (arg1: any, arg2: any) { + arg1.sparse(true); + arg2.sparse(true); +}); +mongopromise.complete(new mongoose.SchemaType('')).complete( + new mongoose.SchemaType(''), + new mongoose.SchemaType('') +); +/* static properties */ +mongoose.Promise.ES6(function (complete: Function, error: Function) { + complete.apply(this); + error.apply(this); +}); - -Model.findOne({ name: 'john' }, (err: any, doc: mongoose.Document) => { - doc.invalidate('size', 'must be less than 20', 14); - doc.validate((err: any) => { }); - - doc.set('documents.0.title', 'changed'); - doc.get('documents.0'); - doc.set({ - 'path' : 1, - 'path2' : { - 'path' : 2 - } +/* inherited properties */ +mongopromise.chain(mongopromise); +mongoose.Promise.FAILURE; +/* practical example */ +mongoose.model('') + .findOne({}) + .exec() + .then(function (arg) { + arg.save; + return 1; + }).then(function (num) { + num.toFixed; + return new Promise((resolve, reject) => { + resolve('string'); + }); + }).then(function (str) { + str.toLowerCase + return (mongoose.model('')).findOne({}).exec(); + }).then(function (arg) { + arg.save; + return 1; + }).catch(function (err) { + return 1; + }).then(function (arg) { + arg.toFixed; + return new Promise<{a: string, b: number}>((resolve, reject) => { + resolve({a: 'hi', b: 29}); + }); + }).then(function (arg) { + arg.a.toLowerCase; + arg.b.toFixed; }); - doc.set('path', 'value', { strict: false }); - doc.set('path3', '1', Number); - doc.get('path3', Number); - doc.id; - doc._id; - doc.isModified(); - doc.isModified('documents'); - doc.isModified('documents.0.title'); - doc.isDirectModified('documents.0.title'); - doc.isDirectModified('documents'); - doc.isSelected('name'); +mongoose.model('').findOne({}) + .then(function (arg) { + arg.save; + return 2; + }).then(function (num) { + num.toFixed; + return new Promise((resolve, reject) => { + resolve('str'); + }); + }).then(function (str) { + str.toLowerCase; + }); - doc.markModified('mixed.type'); - doc.populate('user'); - doc.populate('other', (err: any, doc: mongoose.Document) => {}); - doc.populated('author'); - doc.save(); +mongoose.model('').aggregate() + .then(function (arg) { + return 2; + }).then(function (num) { + num.toFixed; + return new Promise((resolve, reject) => { + resolve('str'); + }); + }).then(function (str) { + str.toLowerCase; + }); - doc.toJSON({ getters: true, virtuals: false }); - var data: any = doc.toObject(); - delete data['age']; - delete data['weight']; - data['isAwesome'] = true; +/* pluggable promise */ +mongoose.Promise.race; +mongoose.Promise.all; + +mongoose.model('').findOne() + .exec().addErrback(cb); + +/* + * section model.js + * http://mongoosejs.com/docs/api.html#model-js + */ +var MongoModel = mongoose.model('MongoModel', new mongoose.Schema({ + name: String, + type: { + type: mongoose.Schema.Types.Mixed, + required: true + } +}), 'myCollection', true); +MongoModel.$where('indexOf("val") !== -1').exec(function (err, docs) { + docs[0].save(); }); - -Model.model('User').findById('id', (err: any, res: IActor) => {}); -Model.count({ type: 'jungle' }, (err: any, count: number) => {}); -Model.remove((err: any, res: IActor[]) => {}); -Model.save((err: any, res: IActor, numberAffected: number) => {}); -Model.create({ type: 'jelly bean' }, { type: 'snickers' }, (err: any, res1: IActor, res2: IActor) => {}); -Model.create({ type: 'jawbreaker' }); -Model.create({ type: 'muffin' }).then(function (res) { - res.name; +MongoModel.findById(999, function (err, doc) { + doc.increment(); + doc.save(cb).then(cb).catch(cb); }); -Model.distinct('url', { clicks: {$gt: 100}}, (err: any, result: IActor[]) => {}); -Model.distinct('url'); - -Model.aggregate( - { $group: { _id: null, maxBalance: { $max: '$balance' }}}, - { $project: { _id: 0, maxBalance: 1 }}, - (err: any, res: IActor[]) => {}); -Model.aggregate() +MongoModel = (new MongoModel()).model('MongoModel'); +var mongoModel = new MongoModel(); +mongoModel.remove(function (err, product) { + if (err) throw(err); + MongoModel.findById(product._id, function (err, product) { + product.remove(); + }); +}); +mongoModel.save().then(function (product) { + product.save().then(cb).catch(cb); +}); +MongoModel.aggregate( + { $group: { _id: null, maxBalance: { $max: '$balance' }}} + , { $project: { _id: 0, maxBalance: 1 }} + , cb); +MongoModel.aggregate() .group({ _id: null, maxBalance: { $max: '$balance' } }) - .select('-id maxBalance') - .exec((err: any, res: IActor[]) => {}); -Model.ensureIndexes((err) => {}); - -Model.find({ name: 'john', age: { $gte: 18 }}); -Model.find({ name: 'john', age: { $gte: 18 }}, (err: any, docs: IActor[]) => {}); -Model.find({ name: /john/i }, 'name friends', (err: any, docs: IActor[]) => {}); -Model.find({ name: /john/i }, null, { skip: 10 }); -Model.find({ name: /john/i }, null, { skip: 10 }, (err: any, docs: IActor[]) => {}); -Model.find({ name: /john/i }, null, { skip: 10 }).exec((err: any, docs: IActor[]) => {}); -var query = Model.find({ name: /john/i }, null, { skip: 10 }); -var promise1 = query.exec(); -promise1.addBack((err: any, docs: IActor[]) => {}); - -Model.findById('id', (err: any, res: IActor) => {}); -Model.findById('id').exec((err: any, res: IActor) => {}); -Model.findById('id', 'name length', (err: any, res: IActor) => {}); -Model.findById('id', '-length').exec((err: any, res: IActor) => {}); -Model.findById('id', 'name', { lean: true }, (err: any, res: IActor) => {}); -Model.findById('id', 'name').lean().exec((err: any, res: IActor) => {}); -Model.findByIdAndRemove('id1', { select: 'name' }, (err: any, res: IActor) => {}); -Model.findByIdAndRemove('id1', { select: 'name' }).exec((err: any, res: IActor) => {}); -Model.findByIdAndRemove('id1', (err: any, res: IActor) => {}); -Model.findByIdAndRemove('id1').exec((err: any, res: IActor) => {}); -Model.findByIdAndUpdate('id2', { $set: { name: 'jason borne' }}, { upsert: true }, (err: any, res: IActor) => {}); - -Model.findOne({ type: 'iphone' }, (err: any, res: IActor) => {}); -Model.findOne({ type: 'iphone' }).exec((err: any, res: IActor) => {}); -Model.findOne({ type: 'iphone' }, 'name', (err: any, res: IActor) => {}); -Model.findOne({ type: 'iphone' }, 'name').exec((err: any, res: IActor) => {}); -Model.findOne({ type: 'iphone' }, 'name', { lean: true }, (err: any, res: IActor) => {}); -Model.findOne({ type: 'iphone' }, 'name', { lean: true }).exec((err: any, res: IActor) => {}); -Model.findOne({ type: 'iphone' }).select('name').lean().exec((err: any, res: IActor) => {}); -Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }, (err: any, res: IActor) => {}); -Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }).exec((err: any, res: IActor) => {}); -Model.findOneAndUpdate({ type: 'iphone' }, { $set: { name: 'jason borne' }}, { upsert: true }, (err: any, res: IActor) => {}); - -Model.geoNear([1, 3], { maxDistance : 5, spherical : true }, (err: any, res: IActor[], stats: any) => {}); -Model.geoNear({ type : "Point", coordinates : [9,9] }, { maxDistance : 5, spherical : true }, (err: any, res: IActor[], stats: any) => {}); -Model.geoSearch({ type : "house" }, { near: [10, 10], maxDistance: 5 }, (err: any, res: IActor[]) => {}); - -var o = { - map: function () { this.emit(this.name, 1) }, - reduce: function (k: string, vals: IActor[]) { return vals.length }, -}; -Model.mapReduce(o, (err: any, res: any[]) => {}); - -Model.findById('id', (err: any, res: IActor) => { + .exec(cb); +MongoModel.count({ type: 'jungle' }, function (err, count) { + count.toFixed(); +}); +MongoModel.create({ + type: 'jelly bean' +}, { + type: 'snickers' +}, cb).then(function (a) { + a.save(); +}) +MongoModel.create([{ type: 'jelly bean' }, { + type: 'snickers' +}], function (err, candies) { + var jellybean = candies[0]; + var snickers = candies[1]; +}).then(function (arg) { + arg[0].save(); + arg[1].save(); +}); +MongoModel.discriminator('M', new mongoose.Schema({name: String})); +MongoModel.distinct('url', { clicks: {$gt: 100}}, function (err, result) { +}); +MongoModel.distinct('url').exec(cb); +MongoModel.ensureIndexes({}, cb); +MongoModel.find({ name: 'john', age: { $gte: 18 }}); +MongoModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) { + docs[0].remove(); + docs[1].execPopulate(); +}); +MongoModel.find({ name: /john/i }, 'name friends', function (err, docs) { }) +MongoModel.find({ name: /john/i }, null, { skip: 10 }) +MongoModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {}); +MongoModel.find({ name: /john/i }, null, { skip: 10 }).exec(function (err, docs) {}); +MongoModel.findById(999, function (err, adventure) {}); +MongoModel.findById(999).exec(cb); +MongoModel.findById(999, 'name length', function (err, adventure) { + adventure.save(); +}); +MongoModel.findById(999, 'name length').exec(cb); +MongoModel.findById(999, '-length').exec(function (err, adventure) { + adventure.addListener('click', cb); +}); +MongoModel.findById(999, 'name', { lean: true }, function (err, doc) {}); +MongoModel.findById(999, 'name').lean().exec(function (err, doc) {}); +MongoModel.findByIdAndRemove(999, {}, cb); +MongoModel.findByIdAndRemove(999, {}); +MongoModel.findByIdAndRemove(999, cb); +MongoModel.findByIdAndRemove(999); +MongoModel.findByIdAndRemove(); +MongoModel.findByIdAndUpdate(999, {}, {}, cb); +MongoModel.findByIdAndUpdate(999, {}, {}); +MongoModel.findByIdAndUpdate(999, {}, cb); +MongoModel.findByIdAndUpdate(999, {}); +MongoModel.findByIdAndUpdate(); +MongoModel.findOne({ type: 'iphone' }, function (err, adventure) {}); +MongoModel.findOne({ type: 'iphone' }).exec(function (err, adventure) {}); +MongoModel.findOne({ type: 'iphone' }, 'name', function (err, adventure) {}); +MongoModel.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {}); +MongoModel.findOne({ type: 'iphone' }, 'name', { lean: true }, cb); +MongoModel.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(cb); +MongoModel.findOne({ type: 'iphone' }).select('name').lean().exec(cb); +MongoModel.findOneAndRemove({}, {}, cb); +MongoModel.findOneAndRemove({}, {}); +MongoModel.findOneAndRemove({}, cb); +MongoModel.findOneAndRemove({}); +MongoModel.findOneAndRemove(); +MongoModel.findOneAndUpdate({}, {}, {}, cb); +MongoModel.findOneAndUpdate({}, {}, {}); +MongoModel.findOneAndUpdate({}, {}, cb); +MongoModel.findOneAndUpdate({}, {}); +MongoModel.findOneAndUpdate(); +MongoModel.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) { + results[0].on('data', cb); +}); +MongoModel.geoNear({ type : "Point", coordinates : [9,9] }, { + maxDistance : 5, spherical : true +}, function(err, results, stats) { + console.log(results); +}); +MongoModel.geoSearch({ type : "house" }, { + near: [10, 10], maxDistance: 5 +}, function(err, res) { + res[0].remove(); +}); +MongoModel.hydrate({ + _id: '54108337212ffb6d459f854c', + type: 'jelly bean' +}).execPopulate(); +MongoModel.insertMany([ + { name: 'Star Wars' }, + { name: 'The Empire Strikes Back' } +], function(error, docs) {}); +MongoModel.insertMany({name: 'Star Wars'}, function(error, doc) {}); +MongoModel.mapReduce({ + map: cb, + reduce: cb +}, function (err, results) { + console.log(results) +}).then(function (model) { + return model.find().where('value').gt(10).exec(); +}).then(function (docs) { + console.log(docs); +}).then(null, cb); +MongoModel.findById(999, function (err, user) { var opts = [ - { path: 'company', match: { x: 1 }, select: 'name' }, - { path: 'notes', options: { limit: 10 }, model: 'override' } - ]; - Model.populate(res, opts, (err: any, res: IActor) => {}); + { path: 'company', match: { x: 1 }, select: 'name' } + , { path: 'notes', options: { limit: 10 }, model: 'override' } + ] + MongoModel.populate(user, opts, cb); + MongoModel.populate(user, opts, function (err, user) { + console.log(user); + }); }); -Model.find({ type: 'iphone' }, (err: any, res: IActor[]) => { - var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]; - var promise = Model.populate(res, opts); - promise.then(console.log).end(); +MongoModel.find(999, function (err, users) { + var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }] + var promise = MongoModel.populate(users, opts); + promise.then(console.log); }); -Model.populate({ name: 'Test A' }, { path: 'weapon', model: 'Weapon' }, (err: any, user: IActor) => {}); -Model.populate([ - { name: 'User hoge' }, - { name: 'User fuga' }, -], { path: 'weapon' }, (err: any, users: IActor[]) => {}); - -Model.remove({ title: 'baby born from alien father' }, (err: any) => {}); -var query2 = Model.remove({ _id: 'id' }); -query2.exec(); -Model.update({ age: { $gt: 18 } }, { oldEnough: true }, (err: any, numberAffected: number, raw: any) => {}); -Model.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, (err: any, numberAffected: number, raw: any) => {}); -Model.update({ _id: 'id' }, { $set: { text: 'changed' }}).exec(); - -Model.where('age').gte(21).lte(65).exec((err: any, res: IActor[]) => {}); -var query3 =Model - .where('age').gt(21).lt(65) - .where('name', /^b/i).all('type', 1); -query3.all(25); -query3.and([{ color: 'green' }, { status: 'ok' }]); -query3.batchSize(100); -query3.where('loc').within().box([40.73083, -73.99756], [40.741404, -73.988135]); -query3.where('loc').within().circle({ center: [50, 50], radius: 10, unique: true }); -query3.circle('loc', { center: [50, 50], radius: 10, unique: true }); -query3.comment('login query'); -query3.where({ 'color': 'black' }).count(); -query3.count({ color: 'black' }).count((err: any, count: number) => {}); -query3.count({ color: 'black' }, (err: any, count: number) => {}); -query3.where({ color: 'black' }).count((err: any, count: number) => {}); -query3.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}); -query3.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}); -query.elemMatch('comment', (elem: mongoose.Query) => { - elem.where('author').equals('autobot'); - elem.where('votes').gte(5); +MongoModel.populate({ + name: 'Indiana Jones', + weapon: 389 +}, { + path: 'weapon', + model: 'Weapon' +}, cb); +var users = [{ name: 'Indiana Jones', weapon: 389 }] +users.push({ name: 'Batman', weapon: 8921 }) +MongoModel.populate(users, { path: 'weapon' }, function (err, users) { + users.forEach(cb); }); -query3.where('age').equals(49); -query3.where('age', 49); -query3.exec(); -query3.exec('update'); -query3.where('name').exists(); -query3.where('name').exists(true); -query3.find().exists('name'); -query3.where('name').exists(false); -query3.find().exists('name', false); -query3.find({ name: 'Los Pollos Hermanos' }).find((err: any, res: IActor[]) => {}); -query3.where('loc').within().geometry({ type: 'Polygon', coordinates: [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] }); -query3.find().where('age').gt(21); -query3.find().gt('age', 21); -query3.hint({ indexA: 1, indexB: -1}); -query3.where('path').intersects().geometry({ type: 'LineString', coordinates: [[180.0, 11.0], [180, 9.0]] }); -query3.where('path').intersects({ type: 'LineString', coordinates: [[180.0, 11.0], [180, 9.0]] }); -query3.maxScan(100); -query3.where('loc').near({ center: [10, 10] }); -query3.where('loc').near({ center: [10, 10], maxDistance: 5 }); -query3.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); -query3.near('loc', { center: [10, 10], maxDistance: 5 }); -query3.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); -query3.nor([{ color: 'green' }, { status: 'ok' }]); -query3.or([{ color: 'red' }, { status: 'emergency' }]); -query3.where('loc').within().polygon([10,20], [13, 25], [7,15]); -query3.polygon('loc', [10,20], [13, 25], [7,15]); - -query3.findOne().populate('owner').exec((err: any, res: IActor[]) => {}); -query3.find().populate({ - path: 'owner', - select: 'name', - match: { color: 'black' }, - options: { sort: { name: -1 }} -}).exec((err: any, res: IActor[]) => {}); -query3.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec((err: any, res: IActor[]) => {}); - -query3.read('primary'); -query3.read('p'); -query3.read('primaryPreferred'); -query3.read('pp'); -query3.read('secondary'); -query3.read('s'); -query3.read('secondaryPreferred'); -query3.read('sp'); -query3.read('nearest'); -query3.read('n'); -query3.read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]); -query3.remove({ artist: 'Anne Murray' }, (err: any, res: IActor[]) => {}); -query3.select('a b -c'); -query3.select({a: 1, b: 1, c: 0}); -query3.select('+path'); -query3.where('tags').size(0); -query3.skip(100).limit(20); -query3.slaveOk(); -query3.slaveOk(true); -query3.slaveOk(false); -query3.slice('comments', -5); -query3.slice('comments', [10, 5]) -query3.where('comments').slice(5); -query3.where('comments').slice([-10, 5]); -query3.snapshot(); -query3.snapshot(true); -query3.snapshot(false); -query3.sort({ field: 'asc', test: -1 }); -query3.sort('field -test'); -Model.find({ name: /^hello/ }).stream({ transform: JSON.stringify }).pipe(fs.createWriteStream('./test.json')); -var stream = Model.find({ name: /^hello/ }).stream(); -stream - .on('data', (doc: IActor) => {}) - .on('error', (err: any) => {}) - .on('close', () => {}); - -query3.tailable(); -query3.tailable(false); -var AdvQuery = query3.toConstructor(); -query3.update({ title: 'words' }); -query3.update({ $set: { title: 'words' }}); -query3.update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, (err: any, row: number, raw: any) => {}); - -query3.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); -query3.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); -query3.where('loc').within({ polygon: [[],[],[],[]] }); -query3.where('loc').within([], [], []); // polygon -query3.where('loc').within([], []); // box -query3.where('loc').within({ type: 'LineString', coordinates: [] }); // geometry - -mongoose.Query.use$geoWithin = false; - - -var ToySchema = new Schema({}); -ToySchema.add({ name: 'string', color: 'string', price: 'number' }); -schema.eachPath(function(path: string, value: any) {}); -schema.index({ first: 1, last: -1 }); -schema.indexes(); -schema.method('meow', function() { - console.log('meeeeeoooooooooooow'); +MongoModel.remove({ title: 'baby born from alien father' }, cb); +MongoModel.remove({_id: '999'}).exec().then(cb).catch(cb); +MongoModel.update({ age: { $gt: 18 } }, { oldEnough: true }, cb); +MongoModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, cb); +MongoModel.where('age').gte(21).lte(65).exec(cb); +MongoModel.where('age').gte(21).lte(65).where('name', /^b/i); +new (mongoModel.base.model(''))(); +mongoModel.baseModelName.toLowerCase(); +mongoModel.collection.$format(99); +mongoModel.collection.initializeOrderedBulkOp; +mongoModel.collection.findOne; +mongoModel.db.openSet(''); +mongoModel.discriminators; +mongoModel.modelName.toLowerCase(); +MongoModel = mongoModel.base.model('new', mongoModel.schema); +/* inherited properties */ +mongoModel._id; +mongoModel.execPopulate(); +mongoModel.on('data', cb); +mongoModel.addListener('event', cb); +MongoModel.findOne({ title: /timex/i }) + .populate('_creator', 'name') + .exec(function (err, story) { + story.execPopulate(); + }); +MongoModel.find({ + id: 999 +}) +.populate({ + path: 'fans', + match: { age: { $gte: 21 }}, + select: 'name -_id', + options: { limit: 5 } +}) +.exec(); +/* practical example */ +interface Location extends mongoose.Document { + name: string; + address: string; + rating: number; + facilities: string[]; + coords: number[]; + openingTimes: any[]; + reviews: any[]; +}; +const locationSchema = new mongoose.Schema({ + name: { type: String, required: true }, + address: String, + rating: { type: Number, "default": 0, min: 0, max: 5 }, + facilities: [String], + coords: { type: [Number], index: "2dsphere" }, + openingTimes: [mongoose.Schema.Types.Mixed], + reviews: [mongoose.SchemaTypes.Mixed] }); -var Kitty = mongoose.model('Kitty', schema); -var fizz: any = new Kitty({ name: 'kitty' }); -fizz.meow(); -schema.method({ - purr: function() {}, - scratch: function() {}, +var LocModel = mongoose.model("Location", locationSchema); +LocModel.findById(999) + .select("-reviews -rating") + .exec(function (err, location) { + location.name = 'blah'; + location.address = 'blah'; + location.reviews.forEach(review => {}); + location.facilities.forEach(facility => { + facility.toLowerCase(); + }); + }); +LocModel.find() + .select('-reviews -rating') + .exec(function (err, locations) { + locations.forEach(location => { + location.name = 'blah'; + location.address = 'blah'; + location.reviews.forEach(review => {}); + location.facilities.forEach(facility => { + facility.toLowerCase(); + }); + }); + }); +LocModel.$where('') + .exec(function (err, locations) { + locations[0].name; + locations[1].openingTimes; + }); +LocModel.count({}) + .exec(function (err, count) { + count.toFixed(); + }); +LocModel.distinct('') + .select('-review') + .exec(function (err, distinct) { + distinct.concat; + }) + .then(cb).catch(cb); +LocModel.findByIdAndRemove() + .exec(function (err, doc) { + doc.addListener; + doc.openingTimes; + }); +LocModel.findByIdAndUpdate() + .select({}) + .exec(function (err, location) { + location.reviews; + }); +LocModel.findOne({}, function (err, doc) { doc.openingTimes; }); +LocModel.findOneAndRemove() + .exec(function (err, location) { location.name; }); +LocModel.findOneAndUpdate().exec().then(function (arg) { arg.openingTimes; }); +LocModel.geoSearch({}, { + near: [1, 2], + maxDistance: 22 +}, function (err, res) { res[0].openingTimes; }); +interface IStatics { + staticMethod2: (a: number) => string; +} +var StaticModel = mongoose.model('Location'); +StaticModel.staticMethod2(9).toUpperCase(); +(new StaticModel()).save(function (err, doc) { + doc.openingTimes; + doc.model('').staticMethod2; }); -schema.path('name'); -schema.path('name', Number); -schema.pathType('name'); -schema.plugin(function() {}); -schema.post('save', function(doc: IActor) {}); -schema.pre('save', function(next: () => void) {}); -schema.requiredPaths(); -schema.static('findByName', function(name: string, callback: () => void) {}); -schema.virtual('display_name') - .get(function(): string { return this.name; }) - .set((value: string): void => {}); - -var id: mongoose.Types.ObjectId = new mongoose.Types.ObjectId('foo'); -var id: mongoose.Types.ObjectId = new mongoose.Types.ObjectId(); -var id2: mongoose.Types.ObjectId = new mongoose.Types.ObjectId(123); -var id2: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromTime(123); -var id2: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromHexString('foo'); -var isValid:boolean = mongoose.Types.ObjectId.isValid('570d350b67b1ae0600e8bee8'); -var s = id.toHexString(); -var valid = id.isValid(); -var eq = id.equals(id2); - -var kitty1 = new Kitty({}); -var kitty2 = new Kitty({}); -var kittyEq = kitty1._id.equals(kitty2._id); +StaticModel.model('').staticMethod2; \ No newline at end of file diff --git a/nconf/index.d.ts b/nconf/index.d.ts index 16d0dd9788..86220abfd2 100644 --- a/nconf/index.d.ts +++ b/nconf/index.d.ts @@ -11,7 +11,7 @@ export declare var stores: any; export declare var sources: any[]; export declare function clear(key: string, callback?: ICallbackFunction): any; -export declare function get(key: string, callback?: ICallbackFunction): any; +export function get(key: string, callback?: ICallbackFunction): any; export declare function merge(key: string, value: any, callback?: ICallbackFunction): any; export declare function set(key: string, value: any, callback?: ICallbackFunction): any; export declare function reset(callback?: ICallbackFunction): any; diff --git a/nes/nes-tests.ts b/nes/nes-tests.ts new file mode 100644 index 0000000000..d56b42a8c4 --- /dev/null +++ b/nes/nes-tests.ts @@ -0,0 +1,65 @@ +/// + +import Hapi = require('hapi'); +import Nes = require('nes'); + +let server: Hapi.Server = new Hapi.Server(); +server.connection({port: 8080}); + +server.register(Nes, (regErr: any) => { + if(regErr) { + console.log('register err'); + console.log(regErr); + } else { + let wsServer: Nes.Server = server as Nes.Server; + wsServer.subscription('/item/{id}'); + wsServer.route( { + method: 'GET', + path: '/test', + config: { + handler: (request: Hapi.Request, reply: Hapi.IReply) => { + reply({test: 'passes'}); + } + } + }); + wsServer.start((err: any) => { + if(err) { + console.log('start err'); + console.log(err); + } else { + setTimeout(() => { + wsServer.publish('/item/5', { id: 5, status: 'complete' }); + wsServer.publish('/item/6', { id: 6, status: 'initial' }); + }, 100); + } + }); + } +}); + +let wsClient: Nes.Client = new Nes.Client('ws://localhost:8080'); +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) => { + if(reqErr) { + console.log('request err'); + console.log(reqErr); + } else { + console.log(update); + console.log(payload); + if(payload.test === 'passes') { + process.exit(0); + } + } + }) + }, (subErr) => { + if(subErr) { + console.log('subscribe err'); + console.log(subErr); + } + }); + } +}); diff --git a/nes/nes.d.ts b/nes/nes.d.ts new file mode 100644 index 0000000000..c86627db47 --- /dev/null +++ b/nes/nes.d.ts @@ -0,0 +1,130 @@ +// Type definitions for nes 6.2.1 +// Project: https://github.com/hapijs/nes +// Definitions by: Ivo Stratev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'nes' { + import Hapi = require('hapi'); + + export 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 { + user: any + } + + export interface ServerSubscriptionOptionsFilterOptions { + socket: Socket; + credentials?: any; + params?: any; + } + + export interface ServerSubscriptionOptionsAuthOptions { + mode?: 'required' | 'optional'; + scope?: string | string[]; + entity?: 'user' | 'app' | 'any'; + index?: boolean; + } + + export type ServerOnSubscribeWithParams = (socket: Socket, path: string, params: any, next: (err?: any) => void) => void; + export type ServerOnSubscribeWithoutParams = (socket: Socket, path: string, next: (err?: any) => void) => void; + export type ServerOnSubscribe = ServerOnSubscribeWithParams | ServerOnSubscribeWithoutParams; + + export type ServerOnUnSubscribeWithParams = (socket: Socket, path: string, params: any, next: () => void) => void; + 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; + auth?: boolean | ServerSubscriptionOptionsAuthOptions; + onSubscribe?: ServerOnSubscribe; + onUnsubscribe?: ServerOnUnSubscribe; + } + + export interface ServerPublishOptions { + internal?: any; + user?: any; + } + + export interface ServerEachSokcetOptions { + 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?: ServerEachSokcetOptions): void; + } + + export class Request extends Hapi.Request { + socket: Socket; + } + + export interface ClientOptions { + ws?: any; + timeout?: number | boolean; + } + + export interface ClientConnnectOptions { + auth?: any; + delay?: number; + maxDelay?: number; + retries?: number; + timeout?: number; + } + + export interface ClientRequestOptions { + path: string; + method?: string; + headers?: Object; + payload?: any; + } + + export interface ClientSubscribeFlags { + revoked?: boolean; + } + + export class Client { + constructor(url: string, options?: ClientOptions); + onError: (err: any) => void; + onConnect: () => void; + onDisconnect: () => void; + onUpdate: (message: any) => void; + connect(options: ClientConnnectOptions, 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; + } +} + +declare module 'nes/client' { + export { + Client, + ClientConnnectOptions, + ClientRequestOptions, + ClientSubscribeFlags + } from 'nes'; +} diff --git a/ngstorage/index.d.ts b/ngstorage/index.d.ts index 13c9bc1530..b8fcf023c8 100644 --- a/ngstorage/index.d.ts +++ b/ngstorage/index.d.ts @@ -12,7 +12,8 @@ declare module 'angular' { $default(items: {}): IStorageService; $reset(items?: {}): IStorageService; $apply(): void; - $sync(): void; + $sync(): void; + get(key: string): T; } export interface IStorageProvider extends angular.IServiceProvider { diff --git a/node-fetch/node-fetch.d.ts b/node-fetch/index.d.ts similarity index 94% rename from node-fetch/node-fetch.d.ts rename to node-fetch/index.d.ts index 5cf41ea992..e96071224e 100644 --- a/node-fetch/node-fetch.d.ts +++ b/node-fetch/index.d.ts @@ -87,9 +87,14 @@ declare module _fetch { type BodyInit = ArrayBuffer | ArrayBufferView | Blob | FormData | string; type RequestInfo = Request | string; - function fetch(url: string | Request, init?: RequestInit): Promise; + interface FetchStatic { + (url: string | Request, init?: RequestInit): Promise; + } + } declare module "node-fetch" { - export = _fetch.fetch; + var fetch: _fetch.FetchStatic; + namespace fetch {} + export = fetch; } diff --git a/node-fetch/node-fetch-tests.ts b/node-fetch/node-fetch-tests.ts index 28d7ff7766..2909b28cfa 100644 --- a/node-fetch/node-fetch-tests.ts +++ b/node-fetch/node-fetch-tests.ts @@ -1,6 +1,6 @@ /// -import fetch = require('node-fetch'); +import * as fetch from 'node-fetch'; function test_fetchUrlWithOptions() { var headers = new _fetch.Headers(); diff --git a/node/index.d.ts b/node/index.d.ts index bdaeed405b..8b0648bcea 100644 --- a/node/index.d.ts +++ b/node/index.d.ts @@ -31,10 +31,10 @@ interface ErrorConstructor { // compat for TypeScript 1.8 // if you use with --target es3 or --target es5 and use below definitions, // use the lib.es6.d.ts that is bundled with TypeScript 1.8. -interface MapConstructor {} -interface WeakMapConstructor {} -interface SetConstructor {} -interface WeakSetConstructor {} +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } /************************************************ * * @@ -60,7 +60,7 @@ interface NodeRequireFunction { } interface NodeRequire extends NodeRequireFunction { - resolve(id:string): string; + resolve(id: string): string; cache: any; extensions: any; main: any; @@ -96,7 +96,7 @@ declare var SlowBuffer: { // Buffer class type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; -interface Buffer extends NodeBuffer {} +interface Buffer extends NodeBuffer { } /** * Raw data is stored in instances of the Buffer class. @@ -160,7 +160,7 @@ declare var Buffer: { * @param byteOffset * @param length */ - from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?:number): Buffer; + from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; /** * Copies the passed {buffer} data onto a new Buffer instance. * @@ -220,7 +220,7 @@ declare var Buffer: { * If parameter is omitted, buffer will be filled with zeros. * @param encoding encoding used for call to buf.fill while initalizing */ - alloc(size: number, fill?: string|Buffer|number, encoding?: string): Buffer; + alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; /** * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents * of the newly created Buffer are unknown and may contain sensitive data. @@ -271,7 +271,7 @@ declare namespace NodeJS { export interface ReadableStream extends EventEmitter { readable: boolean; - read(size?: number): string|Buffer; + read(size?: number): string | Buffer; setEncoding(encoding: string): void; pause(): void; resume(): void; @@ -284,7 +284,7 @@ declare namespace NodeJS { export interface WritableStream extends EventEmitter { writable: boolean; - write(buffer: Buffer|string, cb?: Function): boolean; + write(buffer: Buffer | string, cb?: Function): boolean; write(str: string, encoding?: string, cb?: Function): boolean; end(): void; end(buffer: Buffer, cb?: Function): void; @@ -292,7 +292,7 @@ declare namespace NodeJS { end(str: string, encoding?: string, cb?: Function): void; } - export interface ReadWriteStream extends ReadableStream, WritableStream {} + export interface ReadWriteStream extends ReadableStream, WritableStream { } export interface Events extends EventEmitter { } @@ -372,7 +372,7 @@ declare namespace NodeJS { visibility: string; }; }; - kill(pid:number, signal?: string|number): void; + kill(pid: number, signal?: string | number): void; pid: number; title: string; arch: string; @@ -381,7 +381,7 @@ declare namespace NodeJS { nextTick(callback: Function): void; umask(mask?: number): number; uptime(): number; - hrtime(time?:number[]): number[]; + hrtime(time?: number[]): number[]; domain: Domain; // Worker @@ -457,8 +457,8 @@ declare namespace NodeJS { } export interface Timer { - ref() : void; - unref() : void; + ref(): void; + unref(): void; } } @@ -590,7 +590,7 @@ declare module "http" { path?: string; headers?: { [key: string]: any }; auth?: string; - agent?: Agent|boolean; + agent?: Agent | boolean; } export interface Server extends events.EventEmitter, net.Server { @@ -619,6 +619,7 @@ declare module "http" { statusMessage: string; headersSent: boolean; setHeader(name: string, value: string | string[]): void; + setTimeout(msecs: number, callback: Function): ServerResponse; sendDate: boolean; getHeader(name: string): string; removeHeader(name: string): void; @@ -730,7 +731,7 @@ declare module "http" { [errorCode: number]: string; [errorCode: string]: string; }; - export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; export function createClient(port?: number, host?: string): any; export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; @@ -814,19 +815,19 @@ declare module "zlib" { export function createInflateRaw(options?: ZlibOptions): InflateRaw; export function createUnzip(options?: ZlibOptions): Unzip; - export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflate(buf: Buffer, callback: (error: Error, result: any) => void): void; export function deflateSync(buf: Buffer, options?: ZlibOptions): any; - export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) => void): void; export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gzip(buf: Buffer, callback: (error: Error, result: any) => void): void; export function gzipSync(buf: Buffer, options?: ZlibOptions): any; - export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gunzip(buf: Buffer, callback: (error: Error, result: any) => void): void; export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; - export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflate(buf: Buffer, callback: (error: Error, result: any) => void): void; export function inflateSync(buf: Buffer, options?: ZlibOptions): any; - export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) => void): void; export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function unzip(buf: Buffer, callback: (error: Error, result: any) => void): void; export function unzipSync(buf: Buffer, options?: ZlibOptions): any; // Constants @@ -897,7 +898,7 @@ declare module "os" { export function totalmem(): number; export function freemem(): number; export function cpus(): CpuInfo[]; - export function networkInterfaces(): {[index: string]: NetworkInterfaceInfo[]}; + export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; export var EOL: string; } @@ -943,8 +944,8 @@ declare module "https" { }; export interface Server extends tls.Server { } export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; + export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; export var globalAgent: Agent; } @@ -998,7 +999,7 @@ declare module "readline" { pause(): ReadLine; resume(): ReadLine; close(): void; - write(data: string|Buffer, key?: Key): void; + write(data: string | Buffer, key?: Key): void; } export interface Completer { @@ -1023,7 +1024,7 @@ declare module "readline" { export function createInterface(options: ReadLineOptions): ReadLine; export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; - export function moveCursor(stream: NodeJS.WritableStream, dx: number|string, dy: number|string): void; + export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; export function clearLine(stream: NodeJS.WritableStream, dir: number): void; export function clearScreenDown(stream: NodeJS.WritableStream): void; } @@ -1075,6 +1076,7 @@ declare module "child_process" { connected: boolean; disconnect(): void; unref(): void; + ref(): void; } export interface SpawnOptions { @@ -1104,11 +1106,11 @@ declare module "child_process" { export interface ExecOptionsWithBufferEncoding extends ExecOptions { encoding: string; // specify `null`. } - export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; // usage. child_process.exec("tsc", {encoding: null as string}, (err, stdout, stderr) => {}); - export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; export interface ExecFileOptions { cwd?: string; @@ -1125,16 +1127,16 @@ declare module "child_process" { export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { encoding: string; // specify `null`. } - export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; export interface ForkOptions { cwd?: string; @@ -1250,24 +1252,24 @@ declare module "url" { path?: string; } - export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; + export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; export function format(url: Url): string; export function resolve(from: string, to: string): string; } 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[]; + 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[]; } declare module "net" { @@ -1342,12 +1344,12 @@ declare module "net" { maxConnections: number; connections: number; } - export function createServer(connectionListener?: (socket: Socket) =>void ): Server; - export function createServer(options?: { allowHalfOpen?: 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 createServer(connectionListener?: (socket: Socket) => void): Server; + export function createServer(options?: { allowHalfOpen?: 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; - export function createConnection(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; export function createConnection(path: string, connectionListener?: Function): Socket; export function isIP(input: string): number; @@ -1476,7 +1478,7 @@ declare module "fs" { export function readlink(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; export function readlinkSync(path: string | Buffer): string; 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 }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; export function realpathSync(path: string | Buffer, cache?: { [path: string]: string }): string; /* * Asynchronous unlink - deletes the file specified in {path} @@ -1561,11 +1563,9 @@ declare module "fs" { export function readdirSync(path: string | Buffer): string[]; export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function closeSync(fd: number): void; - export function open(path: string | Buffer, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string | Buffer, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string | Buffer, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function openSync(path: string | Buffer, flags: string, mode?: number): number; - export function openSync(path: string | Buffer, flags: string, mode?: string): number; + 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 openSync(path: string | Buffer, flags: string | number, mode?: number): number; 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 utimesSync(path: string | Buffer, atime: number, mtime: number): void; @@ -1651,8 +1651,8 @@ declare module "fs" { export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; - export function watch(filename: string, encoding: string, listener?: (event: string, filename: string) => any): FSWatcher; - export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string) => any): FSWatcher; + export function watch(filename: string, encoding: string, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; + export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void; export function existsSync(path: string | Buffer): boolean; /** Constant for fs.access(). File is visible to the calling process. */ @@ -1667,7 +1667,7 @@ declare module "fs" { 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; /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ - export function accessSync(path: string | Buffer, mode ?: number): void; + export function accessSync(path: string | Buffer, mode?: number): void; export function createReadStream(path: string | Buffer, options?: { flags?: string; encoding?: string; @@ -1834,10 +1834,10 @@ declare module "path" { declare module "string_decoder" { export interface NodeStringDecoder { write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; + end(buffer?: Buffer): string; } export var StringDecoder: { - new (encoding: string): NodeStringDecoder; + new (encoding?: string): NodeStringDecoder; }; } @@ -2069,10 +2069,10 @@ declare module "tls" { context: any; } - export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; - export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) => void): Server; + export function connect(options: TlsOptions, secureConnectionListener?: () => void): ClearTextStream; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; export function createSecureContext(details: SecureContextOptions): SecureContext; } @@ -2108,9 +2108,9 @@ declare module "crypto" { export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; export interface Cipher extends NodeJS.ReadWriteStream { update(data: Buffer): Buffer; - update(data: string, input_encoding: "utf8"|"ascii"|"binary"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "binary"|"base64"|"hex"): string; - update(data: string, input_encoding: "utf8"|"ascii"|"binary", output_encoding: "binary"|"base64"|"hex"): string; + update(data: string, input_encoding: "utf8" | "ascii" | "binary"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "binary" | "base64" | "hex"): string; + update(data: string, input_encoding: "utf8" | "ascii" | "binary", output_encoding: "binary" | "base64" | "hex"): string; final(): Buffer; final(output_encoding: string): string; setAutoPadding(auto_padding: boolean): void; @@ -2120,9 +2120,9 @@ declare module "crypto" { export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; export interface Decipher extends NodeJS.ReadWriteStream { update(data: Buffer): Buffer; - update(data: string, input_encoding: "binary"|"base64"|"hex"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "utf8"|"ascii"|"binary"): string; - update(data: string, input_encoding: "binary"|"base64"|"hex", output_encoding: "utf8"|"ascii"|"binary"): string; + update(data: string, input_encoding: "binary" | "base64" | "hex"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "utf8" | "ascii" | "binary"): string; + update(data: string, input_encoding: "binary" | "base64" | "hex", output_encoding: "utf8" | "ascii" | "binary"): string; final(): Buffer; final(output_encoding: string): string; setAutoPadding(auto_padding: boolean): void; @@ -2151,14 +2151,14 @@ declare module "crypto" { setPrivateKey(public_key: string, encoding?: string): void; } export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number) : Buffer; - export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string) : Buffer; + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number): Buffer; + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; export function randomBytes(size: number): Buffer; - export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; export function pseudoRandomBytes(size: number): Buffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; export interface RsaPublicKey { key: string; padding?: any; @@ -2168,8 +2168,8 @@ declare module "crypto" { passphrase?: string, padding?: any; } - export function publicEncrypt(public_key: string|RsaPublicKey, buffer: Buffer): Buffer - export function privateDecrypt(private_key: string|RsaPrivateKey, buffer: Buffer): Buffer + export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer + export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer } declare module "stream" { @@ -2183,6 +2183,7 @@ declare module "stream" { highWaterMark?: number; encoding?: string; objectMode?: boolean; + read?: (size?: number) => any; } export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { @@ -2204,6 +2205,8 @@ declare module "stream" { highWaterMark?: number; decodeStrings?: boolean; objectMode?: boolean; + write?: (chunk: string|Buffer, encoding: string, callback: Function) => any; + writev?: (chunks: {chunk: string|Buffer, encoding: string}[], callback: Function) => any; } export class Writable extends events.EventEmitter implements NodeJS.WritableStream { @@ -2219,6 +2222,8 @@ declare module "stream" { export interface DuplexOptions extends ReadableOptions, WritableOptions { allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; } // Note: Duplex extends both Readable and Writable. @@ -2233,7 +2238,10 @@ declare module "stream" { end(chunk: any, encoding?: string, cb?: Function): void; } - export interface TransformOptions extends ReadableOptions, WritableOptions {} + export interface TransformOptions extends ReadableOptions, WritableOptions { + transform?: (chunk: string|Buffer, encoding: string, callback: Function) => any; + flush?: (callback: Function) => any; + } // Note: Transform lacks the _read and _write methods of Readable/Writable. export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { @@ -2258,7 +2266,7 @@ declare module "stream" { end(chunk: any, encoding?: string, cb?: Function): void; } - export class PassThrough extends Transform {} + export class PassThrough extends Transform { } } declare module "util" { @@ -2282,11 +2290,11 @@ declare module "util" { export function isDate(object: any): boolean; export function isError(object: any): boolean; export function inherits(constructor: any, superConstructor: any): void; - export function debuglog(key:string): (msg:string,...param: any[])=>void; + export function debuglog(key: string): (msg: string, ...param: any[]) => void; } declare module "assert" { - function internal (value: any, message?: string): void; + function internal(value: any, message?: string): void; namespace internal { export class AssertionError implements Error { name: string; @@ -2296,8 +2304,10 @@ declare module "assert" { operator: string; generatedMessage: boolean; - constructor(options?: {message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function}); + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function + }); } export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; @@ -2573,9 +2583,32 @@ declare module "constants" { export var S_IFREG: number; export var S_IFDIR: number; export var S_IFCHR: number; + export var S_IFBLK: number; + export var S_IFIFO: number; + export var S_IFSOCK: number; + export var S_IRWXU: number; + export var S_IRUSR: number; + export var S_IWUSR: number; + export var S_IXUSR: number; + export var S_IRWXG: number; + export var S_IRGRP: number; + export var S_IWGRP: number; + export var S_IXGRP: number; + export var S_IRWXO: number; + export var S_IROTH: number; + export var S_IWOTH: number; + export var S_IXOTH: number; export var S_IFLNK: number; export var O_CREAT: number; export var O_EXCL: number; + export var O_NOCTTY: number; + export var O_DIRECTORY: number; + export var O_NOATIME: number; + export var O_NOFOLLOW: number; + export var O_SYNC: number; + export var O_SYMLINK: number; + export var O_DIRECT: number; + export var O_NONBLOCK: number; export var O_TRUNC: number; export var O_APPEND: number; export var F_OK: number; diff --git a/node/node-0.10.d.ts b/node/node-0.10.d.ts index 9e73a0e748..80b46a475c 100644 --- a/node/node-0.10.d.ts +++ b/node/node-0.10.d.ts @@ -972,7 +972,7 @@ declare module "fs" { export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; - export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; @@ -1032,10 +1032,10 @@ declare module "path" { declare module "string_decoder" { export interface NodeStringDecoder { write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; + end(): string; } export var StringDecoder: { - new (encoding: string): NodeStringDecoder; + new (encoding?: string): NodeStringDecoder; }; } diff --git a/node/node-0.11-tests.ts b/node/node-0.11-tests.ts index 8bdddba3f3..95f329ac45 100644 --- a/node/node-0.11-tests.ts +++ b/node/node-0.11-tests.ts @@ -12,6 +12,7 @@ import net = require("net"); import dgram = require("dgram"); import querystring = require('querystring'); import readline = require('readline'); +import string_decoder = require('string_decoder'); assert(1 + 1 - 2 === 0, "The universe isn't how it should."); @@ -122,6 +123,18 @@ namespace http_tests { var codeMessage = http.STATUS_CODES[400]; } +//////////////////////////////////////////////////// +/// string_decoder tests : https://nodejs.org/api/string_decoder.html +//////////////////////////////////////////////////// + +namespace string_decoder_tests { + var StringDecoder = string_decoder.StringDecoder; + var buffer = new Buffer('test'); + var decoder = new StringDecoder('utf8'); + var part: string = decoder.write(new Buffer('test')); + var end: string = decoder.end(); +} + //////////////////////////////////////////////////// /// Dgram tests : http://nodejs.org/api/dgram.html //////////////////////////////////////////////////// diff --git a/node/node-0.11.d.ts b/node/node-0.11.d.ts index 02735002eb..212768c21a 100644 --- a/node/node-0.11.d.ts +++ b/node/node-0.11.d.ts @@ -883,7 +883,7 @@ declare module "fs" { export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; - export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; @@ -943,10 +943,10 @@ declare module "path" { declare module "string_decoder" { export interface NodeStringDecoder { write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; + end(): string; } export var StringDecoder: { - new (encoding: string): NodeStringDecoder; + new (encoding?: string): NodeStringDecoder; }; } diff --git a/node/node-0.12-tests.ts b/node/node-0.12-tests.ts index 871272e5d6..e045f7c0ef 100644 --- a/node/node-0.12-tests.ts +++ b/node/node-0.12-tests.ts @@ -14,6 +14,7 @@ import * as querystring from "querystring"; import * as path from "path"; import * as readline from "readline"; import * as childProcess from "child_process"; +import * as string_decoder from "string_decoder"; assert(1 + 1 - 2 === 0, "The universe isn't how it should."); @@ -404,6 +405,18 @@ rl.question("do you like typescript?", function(answer: string) { rl.close(); }); +//////////////////////////////////////////////////// +/// string_decoder tests : https://nodejs.org/api/string_decoder.html +//////////////////////////////////////////////////// + +namespace string_decoder_tests { + var StringDecoder = string_decoder.StringDecoder; + var buffer = new Buffer('test'); + var decoder = new StringDecoder('utf8'); + var part: string = decoder.write(new Buffer('test')); + var end: string = decoder.end(); +} + ////////////////////////////////////////////////////////////////////// /// Child Process tests: https://nodejs.org/api/child_process.html /// ////////////////////////////////////////////////////////////////////// diff --git a/node/node-0.12.d.ts b/node/node-0.12.d.ts index 7f0bd3ec34..49091419a8 100644 --- a/node/node-0.12.d.ts +++ b/node/node-0.12.d.ts @@ -1233,7 +1233,7 @@ declare module "fs" { export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; - export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; /* * Asynchronous readFile - Asynchronously reads the entire contents of a file. * @@ -1480,10 +1480,10 @@ declare module "path" { declare module "string_decoder" { export interface NodeStringDecoder { write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; + end(): string; } export var StringDecoder: { - new (encoding: string): NodeStringDecoder; + new (encoding?: string): NodeStringDecoder; }; } diff --git a/node/node-0.8.8.d.ts b/node/node-0.8.8.d.ts index 94e5f44eea..321c386655 100644 --- a/node/node-0.8.8.d.ts +++ b/node/node-0.8.8.d.ts @@ -772,7 +772,7 @@ declare module "fs" { export function write(fd: string, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: Buffer) =>any): void; export function writeSync(fd: string, buffer: Buffer, offset: number, length: number, position: number): void; export function read(fd: string, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: Buffer) => void): void; - export function readSync(fd: string, buffer: Buffer, offset: number, length: number, position: number): any[]; + export function readSync(fd: string, buffer: Buffer, offset: number, length: number, position?: number): any[]; export function readFile(filename: string, encoding: string, callback: (err: ErrnoException, data: string) => void ): void; export function readFile(filename: string, callback: (err: ErrnoException, data: Buffer) => void ): void; export function readFileSync(filename: string): Buffer; diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 8ead0224a2..8cddf66987 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -19,6 +19,8 @@ import * as childProcess from "child_process"; import * as cluster from "cluster"; import * as os from "os"; import * as vm from "vm"; +import * as string_decoder from "string_decoder"; + // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; @@ -699,6 +701,18 @@ namespace readline_tests { } } +//////////////////////////////////////////////////// +/// string_decoder tests : https://nodejs.org/api/string_decoder.html +//////////////////////////////////////////////////// + +namespace string_decoder_tests { + const StringDecoder = string_decoder.StringDecoder; + const buffer = new Buffer('test'); + const decoder = new StringDecoder('utf8'); + const part: string = decoder.write(new Buffer('test')); + const end: string = decoder.end(); +} + ////////////////////////////////////////////////////////////////////// /// Child Process tests: https://nodejs.org/api/child_process.html /// ////////////////////////////////////////////////////////////////////// diff --git a/node/node-4.d.ts b/node/node-4.d.ts index 87bcf753c9..e0847bb5bc 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -1532,7 +1532,7 @@ declare module "fs" { export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; export function writeSync(fd: number, data: any, position?: number, enconding?: string): number; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; - export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; /* * Asynchronous readFile - Asynchronously reads the entire contents of a file. * @@ -1779,10 +1779,10 @@ declare module "path" { declare module "string_decoder" { export interface NodeStringDecoder { write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; + end(): string; } export var StringDecoder: { - new (encoding: string): NodeStringDecoder; + new (encoding?: string): NodeStringDecoder; }; } diff --git a/node/node-tests.ts b/node/node-tests.ts index 63002da3e3..7cd2c4ea77 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -1,4 +1,3 @@ - import * as assert from "assert"; import * as fs from "fs"; import * as events from "events"; @@ -20,6 +19,9 @@ import * as cluster from "cluster"; import * as os from "os"; import * as vm from "vm"; import * as console2 from "console"; +import * as string_decoder from "string_decoder"; +import * as stream from "stream"; + // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; @@ -289,6 +291,70 @@ function stream_readable_pipe_test() { r.close(); } +// Simplified constructors +function simplified_stream_ctor_test() { + new stream.Readable({ + read: function (size) { + size.toFixed(); + } + }); + + new stream.Writable({ + write: function (chunk, enc, cb) { + chunk.slice(1); + enc.charAt(0); + cb() + }, + writev: function (chunks, cb) { + chunks[0].chunk.slice(0); + chunks[0].encoding.charAt(0); + cb(); + } + }); + + new stream.Duplex({ + read: function (size) { + size.toFixed(); + }, + write: function (chunk, enc, cb) { + chunk.slice(1); + enc.charAt(0); + cb() + }, + writev: function (chunks, cb) { + chunks[0].chunk.slice(0); + chunks[0].encoding.charAt(0); + cb(); + }, + readableObjectMode: true, + writableObjectMode: true + }); + + new stream.Transform({ + transform: function (chunk, enc, cb) { + chunk.slice(1); + enc.charAt(0); + cb(); + }, + flush: function (cb) { + cb() + }, + read: function (size) { + size.toFixed(); + }, + write: function (chunk, enc, cb) { + chunk.slice(1); + enc.charAt(0); + cb() + }, + writev: function (chunks, cb) { + chunks[0].chunk.slice(0); + chunks[0].encoding.charAt(0); + cb(); + } + }) +} + //////////////////////////////////////////////////// /// Crypto tests : http://nodejs.org/api/crypto.html //////////////////////////////////////////////////// @@ -724,6 +790,21 @@ namespace readline_tests { } } +//////////////////////////////////////////////////// +/// string_decoder tests : https://nodejs.org/api/string_decoder.html +//////////////////////////////////////////////////// + +namespace string_decoder_tests { + const StringDecoder = string_decoder.StringDecoder; + const buffer = new Buffer('test'); + const decoder1 = new StringDecoder(); + const decoder2 = new StringDecoder('utf8'); + const part1: string = decoder1.write(new Buffer('test')); + const end1: string = decoder1.end(); + const part2: string = decoder2.write(new Buffer('test')); + const end2: string = decoder1.end(new Buffer('test')); +} + ////////////////////////////////////////////////////////////////////// /// Child Process tests: https://nodejs.org/api/child_process.html /// ////////////////////////////////////////////////////////////////////// diff --git a/nodemailer/index.d.ts b/nodemailer/index.d.ts index 27dda32673..730ce3f8a6 100644 --- a/nodemailer/index.d.ts +++ b/nodemailer/index.d.ts @@ -25,9 +25,15 @@ export interface Plugin { */ export interface Transporter { /** - * Send a mail - */ - sendMail(mail: SendMailOptions, callback?: (error: Error, info: SentMessageInfo) => void): void; + * Send a mail with callback + */ + sendMail(mail: SendMailOptions, callback: (error: Error, info: SentMessageInfo) => void): void; + + /** + * Send a mail + * return Promise + */ + sendMail(mail: SendMailOptions): Promise; /** * Attach a plugin. 'compile' and 'stream' plugins can be attached with use(plugin) method diff --git a/nodemailer/nodemailer-tests.ts b/nodemailer/nodemailer-tests.ts index 33d3d1dbfa..2acbc2aba6 100644 --- a/nodemailer/nodemailer-tests.ts +++ b/nodemailer/nodemailer-tests.ts @@ -1,5 +1,5 @@ -import nodemailer = require('nodemailer'); +import * as nodemailer from 'nodemailer' // create reusable transporter object using SMTP transport var transporter: nodemailer.Transporter = nodemailer.createTransport({ @@ -37,3 +37,8 @@ var mailOptions: nodemailer.SendMailOptions = { transporter.sendMail(mailOptions, (error: Error, info: nodemailer.SentMessageInfo): void => { // nothing }); + +// promise send mail without callback +transporter + .sendMail(mailOptions) + .then(info => info.messageId) \ No newline at end of file diff --git a/openlayers/index.d.ts b/openlayers/index.d.ts index 270876f440..243087c7b4 100644 --- a/openlayers/index.d.ts +++ b/openlayers/index.d.ts @@ -1079,6 +1079,25 @@ declare namespace olx { rightHanded?: boolean; } } + + namespace control { + interface ControlOptions { + /** + * The element is the control's container element. This only needs to be specified if you're developing a custom control. + */ + element?: Element; + + /** + * Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback. + */ + render?: any; + + /** + * Specify a target if you want the control to be rendered outside of the map's viewport. + */ + target?: Element | string; + } + } } /** @@ -2395,6 +2414,7 @@ declare namespace ol { } class Control { + constructor(options: olx.control.ControlOptions); } class FullScreen { diff --git a/openlayers/openlayers-3.14.2-tests.ts b/openlayers/openlayers-3.14.2-tests.ts new file mode 100644 index 0000000000..1bfdc4bf63 --- /dev/null +++ b/openlayers/openlayers-3.14.2-tests.ts @@ -0,0 +1,714 @@ +/// + +// Basic type variables for test functions +var anyValue: any; +var voidValue: void; +var numberValue: number; +var booleanValue: boolean; +var stringValue: string; +var stringArray: Array; +var jsonValue: JSON; +var voidOrBooleanValue: void | boolean; +var domEventTarget: EventTarget; +var fn: Function; +var object: Object; + +// Callback predefinitions for OpenLayers +var preRenderFunction: ol.PreRenderFunction; +var transformFunction: ol.TransformFunction; +var coordinateFormatType: ol.CoordinateFormatType; +var featureStyleFunction: ol.FeatureStyleFunction; +var featureLoader: ol.FeatureLoader; +var easingFunction: (t: number) => number; +var drawGeometryFunction: ol.interaction.DrawGeometryFunctionType; + +// Type variables for OpenLayers +var attribution: ol.Attribution; +var boundingCoordinates: Array; +var circle: ol.geom.Circle; +var color: ol.Color; +var coordinate: ol.Coordinate; +var coordinatesArray: Array; +var coordinatesArrayDim2: Array>; +var extent: ol.Extent; +var olEvent: ol.events.Event; +var eventKey: ol.events.Key; +var eventKeyArray: Array; +var eventKeyMixed: ol.events.Key | Array; +var eventTarget: ol.events.EventTarget; +var feature: ol.Feature; +var featureArray: Array; +var featureCollection: ol.Collection; +var featureFormat: ol.format.Feature; +var featureUrlFunction: ol.FeatureUrlFunction; +var graticule: ol.Graticule; +var geometriesArray: Array; +var geometry: ol.geom.Geometry; +var geometryCollection: ol.geom.GeometryCollection; +var geometryLayout: ol.geom.GeometryLayout; +var geometryType: ol.geom.GeometryType; +var linearRing: ol.geom.LinearRing; +var lineString: ol.geom.LineString; +var loadingStrategy: ol.LoadingStrategy; +var logoOptions: olx.LogoOptions; +var mapBrowserEvent: ol.MapBrowserEvent; +var multiLineString: ol.geom.MultiLineString; +var multiPoint: ol.geom.MultiPoint; +var multiPolygon: ol.geom.MultiPolygon; +var point: ol.geom.Point; +var polygon: ol.geom.Polygon; +var projection: ol.proj.Projection; +var projectionLike: ol.proj.ProjectionLike; +var simpleGeometry: ol.geom.SimpleGeometry; +var size: ol.Size; +var style: ol.style.Style; +var styleArray: Array; +var styleFunction: ol.style.StyleFunction; +var tilegrid: ol.tilegrid.TileGrid; +var transformFn: ol.TransformFunction; +var vectorSource: ol.source.Vector; +var units: ol.proj.Units; + +// +// ol.Attribution +// + +var attribution: ol.Attribution = new ol.Attribution({ + html: stringValue, +}); + +// +// ol.color +// +color = ol.color.asArray(color); +color = ol.color.asArray(stringValue); +stringValue = ol.color.asString(color); +stringValue = ol.color.asString(stringValue); + +// +// ol.extent +// +transformFunction = function (input: number[]) { + var returnData: number[]; + return returnData; +}; +transformFunction = function (input: number[], output: number[]) { + var returnData: number[]; + return returnData; +}; +transformFunction = function (input: number[], output: number[], dimension: number) { + var returnData: number[]; + return returnData; +} +extent = ol.extent.applyTransform(extent, transformFunction); +ol.extent.applyTransform(extent, transformFunction, extent); +extent = ol.extent.boundingExtent(boundingCoordinates) +extent = ol.extent.buffer(extent, numberValue); +ol.extent.buffer(extent, numberValue, extent); +booleanValue = ol.extent.containsCoordinate(extent, coordinate); +booleanValue = ol.extent.containsExtent(extent, extent); +booleanValue = ol.extent.containsXY(extent, numberValue, numberValue); +extent = ol.extent.createEmpty(); +booleanValue = ol.extent.equals(extent, extent); +extent = ol.extent.extend(extent, extent); +coordinate = ol.extent.getBottomLeft(extent); +coordinate = ol.extent.getBottomRight(extent); +coordinate = ol.extent.getCenter(extent); +numberValue = ol.extent.getHeight(extent); +extent = ol.extent.getIntersection(extent, extent); +ol.extent.getIntersection(extent, extent, extent); +size = ol.extent.getSize(extent); +coordinate = ol.extent.getTopLeft(extent); +coordinate = ol.extent.getTopRight(extent); +numberValue = ol.extent.getWidth(extent); +booleanValue = ol.extent.intersects(extent, extent); +booleanValue = ol.extent.isEmpty(extent); + +// +// ol.featureloader +// +featureLoader = ol.featureloader.xhr(stringValue, featureFormat); + +// +// ol.loadingstrategy +// +loadingStrategy = ol.loadingstrategy.all; +loadingStrategy = ol.loadingstrategy.bbox; +loadingStrategy = ol.loadingstrategy.tile(tilegrid); + +// +// +// ol.geom.Circle +// +booleanValue = circle.intersectsExtent(extent); +circle = circle.transform(projectionLike, projectionLike); + +// +// +// ol.geom.Geometry +// +var geometryResult: ol.geom.Geometry; +coordinate = geometryResult.getClosestPoint(coordinate); +geometryResult.getClosestPoint(coordinate, coordinate); +extent = geometryResult.getExtent(); +geometryResult.getExtent(extent); +geometryResult.transform(projectionLike, projectionLike); + +// +// +// ol.geom.GeometryCollection +// +geometryCollection = new ol.geom.GeometryCollection(geometriesArray) +geometryCollection = new ol.geom.GeometryCollection(); +voidValue = geometryCollection.applyTransform(transformFn); +geometryCollection = geometryCollection.clone(); +geometriesArray = geometryCollection.getGeometries(); +geometryType = geometryCollection.getType(); +booleanValue = geometryCollection.intersectsExtent(extent); +voidValue = geometryCollection.setGeometries(geometriesArray); + +// +// +// ol.geom.LinearRing +// +linearRing = new ol.geom.LinearRing(coordinatesArray); +linearRing = new ol.geom.LinearRing(coordinatesArray, geometryLayout); +linearRing = linearRing.clone(); +numberValue = linearRing.getArea(); +coordinatesArray = linearRing.getCoordinates(); +geometryType = linearRing.getType(); +voidValue = linearRing.setCoordinates(coordinatesArray); +voidValue = linearRing.setCoordinates(coordinatesArray, geometryLayout); + +// +// +// ol.geom.LineString +// +lineString = new ol.geom.LineString(coordinatesArray); +lineString = new ol.geom.LineString(coordinatesArray, geometryLayout); +voidValue = lineString.appendCoordinate(coordinate); +lineString = lineString.clone(); +coordinate = lineString.getCoordinateAtM(numberValue); +coordinate = lineString.getCoordinateAtM(numberValue, booleanValue); +coordinatesArray = lineString.getCoordinates(); +numberValue = lineString.getLength(); +geometryType = lineString.getType(); +booleanValue = lineString.intersectsExtent(extent); +voidValue = lineString.setCoordinates(coordinatesArray); +voidValue = lineString.setCoordinates(coordinatesArray, geometryLayout); + +// +// +// ol.geom.MultiLineString +// +var lineStringsArray: Array; + +multiLineString = new ol.geom.MultiLineString(coordinatesArrayDim2); +multiLineString = new ol.geom.MultiLineString(coordinatesArrayDim2, geometryLayout); +voidValue = multiLineString.appendLineString(lineString); +multiLineString = multiLineString.clone(); +coordinate = multiLineString.getCoordinateAtM(numberValue); +coordinate = multiLineString.getCoordinateAtM(numberValue, booleanValue); +coordinate = multiLineString.getCoordinateAtM(numberValue, booleanValue, booleanValue); +coordinatesArrayDim2 = multiLineString.getCoordinates(); +lineString = multiLineString.getLineString(numberValue); +lineStringsArray = multiLineString.getLineStrings(); +geometryType = multiLineString.getType(); +booleanValue = multiLineString.intersectsExtent(extent); +voidValue = multiLineString.setCoordinates(coordinatesArrayDim2); +voidValue = multiLineString.setCoordinates(coordinatesArrayDim2, geometryLayout); + +// +// +// ol.geom.MultiPoint +// +var pointsArray: Array; + +multiPoint = new ol.geom.MultiPoint(coordinatesArray); +multiPoint = new ol.geom.MultiPoint(coordinatesArray, geometryLayout); +voidValue = multiPoint.appendPoint(point); +multiPoint = multiPoint.clone(); +coordinatesArray = multiPoint.getCoordinates(); +point = multiPoint.getPoint(numberValue); +pointsArray = multiPoint.getPoints(); +geometryType = multiPoint.getType(); +booleanValue = multiPoint.intersectsExtent(extent); +voidValue = multiPoint.setCoordinates(coordinatesArray); +voidValue = multiPoint.setCoordinates(coordinatesArray, geometryLayout); + +// +// +// ol.geom.MultiPolygon +// +var coordinatesArrayDim3: Array>>; +var polygonsArray: Array; + +multiPolygon = new ol.geom.MultiPolygon(coordinatesArrayDim3); +multiPolygon = new ol.geom.MultiPolygon(coordinatesArrayDim3, geometryLayout); +voidValue = multiPolygon.appendPolygon(polygon); +multiPolygon = multiPolygon.clone(); +numberValue = multiPolygon.getArea(); +coordinatesArrayDim3 = multiPolygon.getCoordinates(); +coordinatesArrayDim3 = multiPolygon.getCoordinates(booleanValue); +multiPoint = multiPolygon.getInteriorPoints(); +polygon = multiPolygon.getPolygon(numberValue); +polygonsArray = multiPolygon.getPolygons(); +geometryType = multiPolygon.getType(); +booleanValue = multiPolygon.intersectsExtent(extent); +voidValue = multiPolygon.setCoordinates(coordinatesArrayDim3); +voidValue = multiPolygon.setCoordinates(coordinatesArrayDim3, geometryLayout); + +// +// +// ol.geom.Point +// +point = new ol.geom.Point(coordinate); +point = new ol.geom.Point(coordinate, geometryLayout); +point = point.clone(); +coordinate = point.getCoordinates(); +geometryType = point.getType(); +booleanValue = point.intersectsExtent(extent); +voidValue = point.setCoordinates(coordinate); +voidValue = point.setCoordinates(coordinate, geometryLayout); + +// +// +// ol.geom.Polygon +// +var localSphere: ol.Sphere; +var linearRingsArray: Array; + +polygon = new ol.geom.Polygon(coordinatesArrayDim2); +polygon = new ol.geom.Polygon(coordinatesArrayDim2, geometryLayout); +polygon = ol.geom.Polygon.circular(localSphere, coordinate, numberValue); +polygon = ol.geom.Polygon.circular(localSphere, coordinate, numberValue, numberValue); +polygon = ol.geom.Polygon.fromCircle(circle); +polygon = ol.geom.Polygon.fromCircle(circle, numberValue); +polygon = ol.geom.Polygon.fromCircle(circle, numberValue, numberValue); +polygon = ol.geom.Polygon.fromExtent(extent); +voidValue = polygon.appendLinearRing(linearRing); +polygon = polygon.clone(); +numberValue = polygon.getArea(); +coordinatesArrayDim2 = polygon.getCoordinates(); +coordinatesArrayDim2 = polygon.getCoordinates(booleanValue); +point = polygon.getInteriorPoint(); +linearRing = polygon.getLinearRing(numberValue); +numberValue = polygon.getLinearRingCount(); +linearRingsArray = polygon.getLinearRings(); +geometryType = polygon.getType(); +booleanValue = polygon.intersectsExtent(extent); +voidValue = polygon.setCoordinates([[coordinate]]); +voidValue = polygon.setCoordinates([[coordinate]], geometryLayout); + +// +// +// ol.geom.SimpleGeometry +// +simpleGeometry.applyTransform(transformFn); +coordinate = simpleGeometry.getFirstCoordinate(); +coordinate = simpleGeometry.getLastCoordinate(); +geometryLayout = simpleGeometry.getLayout(); +voidValue = simpleGeometry.translate(numberValue, numberValue); + +// +// ol.source +// +var featureCallback: (f: ol.Feature) => any; +vectorSource = new ol.source.Vector({ + attributions: [attribution], + features: featureCollection, + format: featureFormat, + loader: featureLoader, + logo: logoOptions, + strategy: loadingStrategy, + url: stringValue, + useSpatialIndex: booleanValue, + wrapX: booleanValue +}); +vectorSource = new ol.source.Vector({ + features: featureArray +}); +vectorSource = new ol.source.Vector({ + url: featureUrlFunction, + loader: featureLoader +}); +voidValue = vectorSource.addFeature(feature); +voidValue = vectorSource.addFeatures(featureArray); +voidValue = vectorSource.clear(); +voidValue = vectorSource.clear(booleanValue); +anyValue = vectorSource.forEachFeature(featureCallback); +anyValue = vectorSource.forEachFeature(featureCallback, object); +anyValue = vectorSource.forEachFeatureInExtent(extent, featureCallback, object); +anyValue = vectorSource.forEachFeatureIntersectingExtent(extent, featureCallback, object); +feature = vectorSource.getClosestFeatureToCoordinate(coordinate); +extent = vectorSource.getExtent(); +feature = vectorSource.getFeatureById(stringValue); +feature = vectorSource.getFeatureById(numberValue); +featureArray = vectorSource.getFeatures(); +featureArray = vectorSource.getFeaturesAtCoordinate(coordinate); +featureCollection = vectorSource.getFeaturesCollection(); +featureArray = vectorSource.getFeaturesInExtent(extent); +voidValue = vectorSource.removeFeature(feature); + +// +// ol.Feature +// +feature = new ol.Feature(); +feature = new ol.Feature(geometry); +feature = new ol.Feature({ + geometry: geometry, + a: numberValue, + b: stringValue, + c: null, + d: object +}); +feature = feature.clone(); +geometry = feature.getGeometry(); +stringValue = feature.getGeometryName(); +var featureGetId: string | number = feature.getId(); +var featureGetStyle: ol.style.Style | Array | ol.FeatureStyleFunction = feature.getStyle(); +featureStyleFunction = feature.getStyleFunction(); +voidValue = feature.setGeometry(geometry); +voidValue = feature.setGeometryName(stringValue); +voidValue = feature.setId(stringValue); +voidValue = feature.setId(numberValue); +voidValue = feature.setStyle(style); +voidValue = feature.setStyle(styleArray); +voidValue = feature.setStyle(featureStyleFunction); +voidValue = feature.setProperties(object); + +// +// ol.View +// + +var view: ol.View = new ol.View({ + center: [0, 0], + zoom: numberValue, +}); + +// +// ol.layer.Tile +// +var tileLayer: ol.layer.Tile = new ol.layer.Tile({ + source: new ol.source.MapQuest({ layer: 'osm' }) +}); + +// +// ol.Object +// +var olObject: ol.Object = new ol.Object({ + a: numberValue, + b: stringValue, + c: booleanValue, + d: voidValue, + e: object, + f: fn +}); +anyValue = olObject.get(stringValue); +stringArray = olObject.getKeys(); +object = olObject.getProperties(); +voidValue = olObject.set(stringValue, anyValue); +voidValue = olObject.set(stringValue, anyValue, booleanValue); +voidValue = olObject.setProperties(object, booleanValue); +voidValue = olObject.unset(stringValue, booleanValue); + +// +// ol.Observable +// +ol.Observable.unByKey(eventKey); +var 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(olEvent); +voidOrBooleanValue = observable.dispatchEvent(stringValue); +numberValue = observable.getRevision(); +eventKeyMixed = observable.on(stringValue, fn); +eventKeyMixed = observable.on([stringValue, stringValue], fn, {}); +eventKeyMixed = observable.once(stringValue, fn); +eventKeyMixed = observable.once([stringValue, stringValue], fn, {}); +voidValue = observable.un(stringValue, fn); +voidValue = observable.un([stringValue, stringValue], fn, {}); +voidValue = observable.unByKey(eventKey); +voidValue = observable.unByKey(eventKeyArray); + +// +// ol.proj +// +var getPointResolutionFn: (n: number, c: ol.Coordinate) => number; +projection = new ol.proj.Projection({ + code:stringValue, +}); +stringValue = projection.getCode(); +extent = projection.getExtent(); +numberValue = projection.getMetersPerUnit(); +numberValue = projection.getPointResolution(numberValue, coordinate); +units = projection.getUnits(); +extent = projection.getWorldExtent(); +booleanValue = projection.isGlobal(); +voidValue = projection.setExtent(extent); +voidValue = projection.setGetPointResolution(getPointResolutionFn); +voidValue = projection.setGlobal(booleanValue); +voidValue = projection.setWorldExtent(extent); + +// +// ol.Map +// + +var map: ol.Map = new ol.Map({ + view: view, + layers: [tileLayer], + target: stringValue +}); +voidValue = map.beforeRender(preRenderFunction); + +// +// ol.source.ImageWMS +// +var imageWMS: ol.source.ImageWMS = new ol.source.ImageWMS({ + serverType: stringValue, + url:stringValue +}); + +// +// ol.source.Source +// +const source = imageWMS as ol.source.Source; +projection = source.getProjection(); + +// +// ol.source.TileWMS +// +var tileWMS: ol.source.TileWMS = new ol.source.TileWMS({ + params: {}, + serverType: stringValue, + url:stringValue +}); + +voidValue = tileWMS.updateParams(tileWMS.getParams()); +stringValue = tileWMS.getGetFeatureInfoUrl([0, 0], 1, "EPSG:4326", {}); + +// +// ol.source.WMTS +// +var wmts: ol.source.WMTS = new ol.source.WMTS({ + tileGrid: new ol.tilegrid.WMTS({}), + layer: "", + style: "", + matrixSet: "", + wrapX: true +}); + +// +// ol.animation +// +var bounceOptions: olx.animation.BounceOptions; +bounceOptions.duration = numberValue; +bounceOptions.start = numberValue; +bounceOptions.resolution = numberValue; +bounceOptions.easing = easingFunction; +preRenderFunction = ol.animation.bounce(bounceOptions); + +var panOptions: olx.animation.PanOptions; +panOptions.duration = numberValue; +panOptions.start = numberValue; +panOptions.source = coordinate; +panOptions.easing = easingFunction; +preRenderFunction = ol.animation.pan(panOptions); + +var rotateOptions: olx.animation.RotateOptions; +rotateOptions.duration = numberValue; +rotateOptions.start = numberValue; +rotateOptions.anchor = coordinate; +rotateOptions.rotation = numberValue; +rotateOptions.easing = easingFunction; +preRenderFunction = ol.animation.rotate(rotateOptions); + +var zoomOptions: olx.animation.ZoomOptions; +zoomOptions.duration = numberValue; +zoomOptions.start = numberValue; +zoomOptions.resolution = numberValue; +zoomOptions.easing = easingFunction; +preRenderFunction = ol.animation.zoom(zoomOptions); +voidValue = map.beforeRender(preRenderFunction); + +// +// ol.coordinate +// +coordinate = ol.coordinate.add(coordinate, coordinate); +coordinateFormatType = ol.coordinate.createStringXY(); +coordinateFormatType = ol.coordinate.createStringXY(numberValue); +stringValue = ol.coordinate.format(coordinate, stringValue); +stringValue = ol.coordinate.format(coordinate, stringValue, numberValue); +coordinate = ol.coordinate.rotate(coordinate, numberValue); +stringValue = ol.coordinate.toStringHDMS(); +stringValue = ol.coordinate.toStringHDMS(coordinate); +stringValue = ol.coordinate.toStringXY(); +stringValue = ol.coordinate.toStringXY(coordinate); +stringValue = ol.coordinate.toStringXY(coordinate, numberValue); + +// +// ol.easing +// +easingFunction = ol.easing.easeIn; +easingFunction = ol.easing.easeOut; +easingFunction = ol.easing.inAndOut; +easingFunction = ol.easing.linear; +easingFunction = ol.easing.upAndDown; + +// +// ol.Geolocation +// +var geolocation: ol.Geolocation = new ol.Geolocation({ + projection: projection +}); +coordinate = geolocation.getPosition(); + +// +// ol.Graticule +// + +graticule = new ol.Graticule(); +graticule = new ol.Graticule({ + map: map, +}); +var graticuleMap: ol.Map = graticule.getMap(); +var graticuleMeridians: Array = graticule.getMeridians(); +var graticuleParallels: Array = graticule.getParallels(); +voidValue = graticule.setMap(graticuleMap); + +// +// ol.DeviceOrientation +// + +var deviceOrientation: ol.DeviceOrientation = new ol.DeviceOrientation({ + tracking: true, +}); +numberValue = deviceOrientation.getHeading(); + +// +// ol.Overlay +// + +var popup: ol.Overlay = new ol.Overlay({ + element: document.getElementById('popup') +}); +voidValue = map.addOverlay(popup); +var popupElement: Element = popup.getElement(); +var popupMap: ol.Map = popup.getMap(); +var popupOffset: Array = popup.getOffset(); +coordinate = popup.getPosition(); +var popupPositioning: ol.OverlayPositioning = popup.getPositioning(); +voidValue = popup.setElement(popupElement); +voidValue = popup.setMap(popupMap); +voidValue = popup.setOffset(popupOffset); +voidValue = popup.setPosition(coordinate); +voidValue = popup.setPositioning(popupPositioning); + + +// +// ol.format.GeoJSON +// + +var geojsonOptions: olx.format.GeoJSONOptions; +geojsonOptions.defaultDataProjection = "EPSG"; +geojsonOptions.defaultDataProjection = projection; +geojsonOptions.geometryName = "geom"; + +var geojsonFormat: ol.format.GeoJSON; +geojsonFormat = new ol.format.GeoJSON(); +geojsonFormat = new ol.format.GeoJSON(geojsonOptions); + +// Test options +var readOptions: olx.format.ReadOptions; +readOptions.dataProjection = "EPSG"; +readOptions.dataProjection = projection; +readOptions.featureProjection = "EPSG"; +readOptions.featureProjection = projection; + +var writeOptions: olx.format.WriteOptions; +writeOptions.dataProjection = "EPSG"; +writeOptions.dataProjection = projection; +writeOptions.featureProjection = "EPSG"; +writeOptions.featureProjection = projection; +writeOptions.rightHanded = false; + +// Test functions +feature = geojsonFormat.readFeature("json"); +feature = geojsonFormat.readFeature("json", readOptions); +featureArray = geojsonFormat.readFeatures("json"); +featureArray = geojsonFormat.readFeatures("json", readOptions); +geometry = geojsonFormat.readGeometry("geometry"); +geometry = geojsonFormat.readGeometry("geometry", readOptions); +stringValue = geojsonFormat.writeFeature(feature); +stringValue = geojsonFormat.writeFeature(feature, writeOptions); +stringValue = geojsonFormat.writeFeatures(featureArray); +stringValue = geojsonFormat.writeFeatures(featureArray, writeOptions); +stringValue = geojsonFormat.writeGeometry(geometry); +stringValue = geojsonFormat.writeGeometry(geometry, writeOptions); +jsonValue = geojsonFormat.writeFeatureObject(feature); +jsonValue = geojsonFormat.writeFeatureObject(feature, writeOptions); +jsonValue = geojsonFormat.writeFeaturesObject(featureArray); +jsonValue = geojsonFormat.writeFeaturesObject(featureArray, writeOptions); +jsonValue = geojsonFormat.writeGeometryObject(geometry); +jsonValue = geojsonFormat.writeGeometryObject(geometry, writeOptions); + +// +// ol.interactions +// +var modify: ol.interaction.Modify = new ol.interaction.Modify({ + features: new ol.Collection(featureArray) +}); + +var draw: ol.interaction.Draw = new ol.interaction.Draw({ + type: "Point", + clickTolerance: numberValue, + features: new ol.Collection([]), + source: vectorSource, + snapTolerance: numberValue, + maxPoints: numberValue, + minPoints: numberValue, + style: style, + geometryFunction: drawGeometryFunction, + geometryName: stringValue, + condition: ol.events.condition.never, + freehandCondition: ol.events.condition.never, + wrapX: booleanValue +}); +draw = new ol.interaction.Draw({ + type: "Point", + style: styleArray +}); +draw = new ol.interaction.Draw({ + type: "Point", + style: styleFunction +}); + +var dragbox: ol.interaction.DragBox = new ol.interaction.DragBox({ + className: stringValue, + condition: ol.events.condition.always, + boxEndCondition: function (mapBrowserEvent: ol.MapBrowserEvent, startPixel: ol.Pixel, endPixel: ol.Pixel) { + var width: number = endPixel[0] - startPixel[0]; + var height: number = endPixel[1] - startPixel[1]; + return booleanValue; + } +}); +polygon = dragbox.getGeometry(); + +var interaction: ol.interaction.Interaction = new ol.interaction.Interaction({ + handleEvent: function (e: ol.MapBrowserEvent) { + return booleanValue; + } +}); +booleanValue = interaction.handleEvent(mapBrowserEvent); +booleanValue = interaction.getActive(); +map = interaction.getMap(); +voidValue = interaction.setActive(true); + + + +const select: ol.interaction.Select = new ol.interaction.Select({ + layers: (layer: ol.layer.Layer) => true, +}); diff --git a/openlayers/openlayers-3.14.2.d.ts b/openlayers/openlayers-3.14.2.d.ts new file mode 100644 index 0000000000..f8ca153820 --- /dev/null +++ b/openlayers/openlayers-3.14.2.d.ts @@ -0,0 +1,4873 @@ +// Type definitions for OpenLayers v3.14.2 +// Project: http://openlayers.org/ +// Definitions by: Wouter Goedhart +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// we can't use Object, Event, EventTarget, etc within the namespace because they would refer to OpenLayer's versions. +declare type GlobalObject = Object; +declare type GlobalEvent = Event; +declare type GlobalEventTarget = EventTarget; + +declare namespace olx { + + interface AttributionOptions { + + /** HTML markup for this attribution. */ + html: string; + } + + interface DeviceOrientationOptions { + + /** + * Start tracking. Default is false. + */ + tracking?: boolean; + } + + interface FrameState { + + /** + * + */ + pixelRatio: number; + + /** + * + */ + time: number; + + /** + * + */ + viewState: olx.ViewState; + } + + interface FeatureOverlayOptions { + + /** + * Features + */ + features?: Array | ol.Collection | ol.style.StyleFunction; + + /** + * Map + */ + map: ol.Map; + + /** + * Style + */ + style: ol.style.Style | Array; + } + + interface GeolocationOptions { + + /** + * Start Tracking. Default is false. + */ + tracking?: boolean; + + /** + * Tracking options. See http://www.w3.org/TR/geolocation-API/#position_options_interface. + */ + trackingOptions?: PositionOptions; + + /** + * The projection the position is reported in. + */ + projection?: ol.proj.ProjectionLike | ol.proj.Projection; + } + + interface GraticuleOptions { + + /** Reference to an ol.Map object. */ + map?: ol.Map; + + /** The maximum number of meridians and parallels from the center of the map. The default value is 100, which means that at most 200 meridians and 200 parallels will be displayed. The default value is appropriate for conformal projections like Spherical Mercator. If you increase the value more lines will be drawn and the drawing performance will decrease. */ + maxLines?: number; + + /** The stroke style to use for drawing the graticule. If not provided, the lines will be drawn with rgba(0,0,0,0.2), a not fully opaque black. */ + strokeStyle?: ol.style.Stroke; + + /** The target size of the graticule cells, in pixels. Default value is 100 pixels. */ + targetSize?: number; + } + + interface BaseWMSOptions { + + /** Attributions. */ + attributions?: Array; + + /** WMS request parameters. At least a LAYERS param is required. STYLES is '' by default. VERSION is 1.3.0 by default. WIDTH, HEIGHT, BBOX and CRS (SRS for WMS version < 1.3.0) will be set dynamically. */ + params?: any; + + /** The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail. */ + crossOrigin?: string; + + /** experimental Use the ol.Map#pixelRatio value when requesting the image from the remote server. Default is true. */ + hidpi?: boolean; + + /** experimental The type of the remote WMS server: mapserver, geoserver or qgis. Only needed if hidpi is true. Default is undefined. */ + serverType?: ol.source.wms.ServerType; + + /** WMS service URL. */ + url?: string; + + /** Logo. */ + logo?: olx.LogoOptions; + + /** experimental Projection. */ + projection?: ol.proj.ProjectionLike; + } + + interface ImageWMSOptions extends BaseWMSOptions { + + /** experimental Optional function to load an image given a URL. */ + imageLoadFunction?: ol.ImageLoadFunctionType; + + /** Ratio. 1 means image requests are the size of the map viewport, 2 means twice the width and height of the map viewport, and so on. Must be 1 or higher. Default is 1.5. */ + ratio?: number; + + /** Resolutions. If specified, requests will be made for these resolutions only. */ + resolutions?: Array; + } + + interface TileWMSOptions { + + attributions?: Array; + + /**WMS request parameters. At least a LAYERS param is required. STYLES is '' by default. VERSION is 1.3.0 by default. WIDTH, HEIGHT, BBOX and CRS (SRS for WMS version < 1.3.0) will be set dynamically. Required.*/ + params: GlobalObject; + /**The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.*/ + crossOrigin?: string; + + /** The size in pixels of the gutter around image tiles to ignore. By setting this property to a non-zero value, images will be requested that are wider and taller than the tile size by a value of 2 x gutter. Defaults to zero. Using a non-zero value allows artifacts of rendering at tile edges to be ignored. If you control the WMS service it is recommended to address "artifacts at tile edges" issues by properly configuring the WMS service. For example, MapServer has a tile_map_edge_buffer configuration parameter for this. See http://mapserver.org/output/tile_mode.html. */ + gutter?: number; + + /** Use the ol.Map#pixelRatio value when requesting the image from the remote server. Default is true.*/ + hidpi?: boolean; + + logo?: string | olx.LogoOptions; + + /** Tile grid. Base this on the resolutions, tilesize and extent supported by the server. If this is not defined, a default grid will be used: if there is a projection extent, the grid will be based on that; if not, a grid based on a global extent with origin at 0,0 will be used. */ + tileGrid?: ol.tilegrid.TileGrid; + + /** experimental Maximum zoom. */ + maxZoom?: number; + + projection?: ol.proj.ProjectionLike; + reprojectionErrorThreshold?: number; + + /** experimental Optional function to load a tile given a URL. */ + tileLoadFunction?: ol.TileLoadFunctionType; + + /** WMS service URL. */ + url?: string; + + /** WMS service urls. Use this instead of url when the WMS supports multiple urls for GetMap requests. */ + urls?: Array; + + /** experimental The type of the remote WMS server. Currently only used when hidpi is true. Default is undefined. */ + serverType?: ol.source.wms.ServerType; + + /** experimental Whether to wrap the world horizontally. When set to false, only one world will be rendered. When true, tiles will be requested for one world only, but they will be wrapped horizontally to render multiple worlds. The default is true. */ + wrapX?: boolean; + } + /** + * Object literal with config options for the map logo. + */ + interface LogoOptions { + /** + * Link url for the logo. Will be followed when the logo is clicked. + */ + href: string; + + /** + * Image src for the logo + */ + src: string; + + } + + interface MapOptions { + + /** Controls initially added to the map. If not specified, ol.control.defaults() is used. */ + controls?: any; + + /** The ratio between physical pixels and device-independent pixels (dips) on the device. If undefined then it gets set by using window.devicePixelRatio. */ + pixelRatio?: number; + + /** Interactions that are initially added to the map. If not specified, ol.interaction.defaults() is used. */ + interactions?: any; + + /** The element to listen to keyboard events on. This determines when the KeyboardPan and KeyboardZoom interactions trigger. For example, if this option is set to document the keyboard interactions will always trigger. If this option is not specified, the element the library listens to keyboard events on is the map target (i.e. the user-provided div for the map). If this is not document the target element needs to be focused for key events to be emitted, requiring that the target element has a tabindex attribute. */ + keyboardEventTarget?: any; + + /** Layers. If this is not defined, a map with no layers will be rendered. Note that layers are rendered in the order supplied, so if you want, for example, a vector layer to appear on top of a tile layer, it must come after the tile layer. */ + layers?: Array + + /** When set to true, tiles will be loaded during animations. This may improve the user experience, but can also make animations stutter on devices with slow memory. Default is false. */ + loadTilesWhileAnimating?: boolean; + + /** When set to true, tiles will be loaded while interacting with the map. This may improve the user experience, but can also make map panning and zooming choppy on devices with slow memory. Default is false. */ + loadTilesWhileInteracting?: boolean; + + /** The map logo. A logo to be displayed on the map at all times. If a string is provided, it will be set as the image source of the logo. If an object is provided, the src property should be the URL for an image and the href property should be a URL for creating a link. To disable the map logo, set the option to false. By default, the OpenLayers 3 logo is shown. */ + logo?: any; + + /** Overlays initially added to the map. By default, no overlays are added. */ + overlays?: any; + + /** Renderer. By default, Canvas, DOM and WebGL renderers are tested for support in that order, and the first supported used. Specify a ol.RendererType here to use a specific renderer. Note that at present only the Canvas renderer supports vector data. */ + renderer?: any; + + /** The container for the map, either the element itself or the id of the element. If not specified at construction time, ol.Map#setTarget must be called for the map to be rendered. */ + target?: any; + + /** The map's view. No layer sources will be fetched unless this is specified at construction time or through ol.Map#setView. */ + view?: ViewOptions; + } + + interface OverlayOptions { + + /** + * The overlay element. + */ + element?: Element; + + /** + * Offsets in pixels used when positioning the overlay. The fist element in the array is the horizontal offset. A positive value shifts the overlay right. The second element in the array is the vertical offset. A positive value shifts the overlay down. Default is [0, 0]. + */ + offset?: Array; + + /** + * The overlay position in map projection. + */ + position?: ol.Coordinate; + + /** + * Defines how the overlay is actually positioned with respect to its position property. Possible values are 'bottom-left', 'bottom-center', 'bottom-right', 'center-left', 'center-center', 'center-right', 'top-left', 'top-center', and 'top-right'. Default is 'top-left'. + */ + positioning?: ol.OverlayPositioning; + + /** + * Whether event propagation to the map viewport should be stopped. Default is true. If true the overlay is placed in the same container as that of the controls (CSS class name ol-overlaycontainer-stopevent); if false it is placed in the container with CSS class name ol-overlaycontainer. + */ + stopEvent?: boolean; + + /** + * Whether the overlay is inserted first in the overlay container, or appended. Default is true. If the overlay is placed in the same container as that of the controls (see the stopEvent option) you will probably set insertFirst to true so the overlay is displayed below the controls. + */ + insertFirst?: boolean; + + /** + * If set to true the map is panned when calling setPosition, so that the overlay is entirely visible in the current viewport. The default is false. + */ + autoPan?: boolean; + + /** + * The options used to create a ol.animation.pan animation. This animation is only used when autoPan is enabled. By default the default options for ol.animation.pan are used. If set to null the panning is not animated. + */ + autoPanAnimation?: olx.animation.PanOptions; + + /** + * The margin (in pixels) between the overlay and the borders of the map when autopanning. The default is 20. + */ + autoPanMargin?: number; + } + + interface ViewOptions { + + /** The initial center for the view. The coordinate system for the center is specified with the projection option. Default is undefined, and layer sources will not be fetched if this is not set. */ + center?: ol.Coordinate; + + /** Rotation constraint. false means no constraint. true means no constraint, but snap to zero near zero. A number constrains the rotation to that number of values. For example, 4 will constrain the rotation to 0, 90, 180, and 270 degrees. The default is true. */ + constrainRotation?: boolean; + + /** Enable rotation. Default is true. If false a rotation constraint that always sets the rotation to zero is used. The constrainRotation option has no effect if enableRotation is false. */ + enableRotation?: boolean; + + /**The extent that constrains the center, in other words, center cannot be set outside this extent. Default is undefined. */ + extent?: ol.Extent; + + /** The maximum resolution used to determine the resolution constraint. It is used together with minResolution (or maxZoom) and zoomFactor. If unspecified it is calculated in such a way that the projection's validity extent fits in a 256x256 px tile. If the projection is Spherical Mercator (the default) then maxResolution defaults to 40075016.68557849 / 256 = 156543.03392804097. */ + maxResolution?: number; + + /** The minimum resolution used to determine the resolution constraint. It is used together with maxResolution (or minZoom) and zoomFactor. If unspecified it is calculated assuming 29 zoom levels (with a factor of 2). If the projection is Spherical Mercator (the default) then minResolution defaults to 40075016.68557849 / 256 / Math.pow(2, 28) = 0.0005831682455839253. */ + minResolution?: number; + + /** The maximum zoom level used to determine the resolution constraint. It is used together with minZoom (or maxResolution) and zoomFactor. Default is 28. Note that if minResolution is also provided, it is given precedence over maxZoom. */ + maxZoom?: number; + + /** The minimum zoom level used to determine the resolution constraint. It is used together with maxZoom (or minResolution) and zoomFactor. Default is 0. Note that if maxResolution is also provided, it is given precedence over minZoom. */ + minZoom?: number; + + /** The projection. Default is EPSG:3857 (Spherical Mercator). */ + projection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** The initial resolution for the view. The units are projection units per pixel (e.g. meters per pixel). An alternative to setting this is to set zoom. Default is undefined, and layer sources will not be fetched if neither this nor zoom are defined. */ + resolution?: number; + + /** Resolutions to determine the resolution constraint. If set the maxResolution, minResolution, minZoom, maxZoom, and zoomFactor options are ignored. */ + resolutions?: Array; + + /** The initial rotation for the view in radians (positive rotation clockwise). Default is 0. */ + rotation?: number; + + /** Only used if resolution is not defined. Zoom level used to calculate the initial resolution for the view. The initial resolution is determined using the ol.View#constrainResolution method. */ + zoom?: number; + + /** The zoom factor used to determine the resolution constraint. Default is 2. */ + zoomFactor?: number; + } + + interface ViewState { + + /** + * + */ + center: ol.Coordinate; + + /** + * + */ + projection: ol.proj.Projection; + + /** + * + */ + resolution: number; + + /** + * + */ + rotation: number; + } + + interface Projection { + /** + * The SRS identifier code, e.g. EPSG:4326. + */ + code: string; + + /** + * Units. Required unless a proj4 projection is defined for code. + */ + units?: ol.proj.Units; + + /** + * The validity extent for the SRS. + */ + extent?: Array; + + /** + * The axis orientation as specified in Proj4. The default is enu. + */ + axisOrientation?: string; + + /** + * Whether the projection is valid for the whole globe. Default is false. + */ + global?: boolean; + + /** + * experimental The world extent for the SRS. + */ + worldExtent?: ol.Extent; + + /** + * experimental Function to determine resolution at a point. The function is called with + * a {number} view resolution and an {ol.Coordinate} as arguments, and returns the {number} + * resolution at the passed coordinate. + */ + getPointResolution?: (resolution: number, coordinate: ol.Coordinate) => number; + } + + namespace animation { + + interface BounceOptions { + + /** + * The resolution to start the bounce from, typically map.getView().getResolution(). + */ + resolution: number; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number; + } + + interface PanOptions { + + /** + * The resolution to start the bounce from, typically map.getView().getResolution(). + */ + source: ol.Coordinate; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number; + } + + interface RotateOptions { + + /** + * The rotation value (in radians) to begin rotating from, typically map.getView().getRotation(). If undefined then 0 is assumed. + */ + rotation?: number; + + /** + * The rotation center/anchor. The map rotates around the center of the view if unspecified. + */ + anchor?: ol.Coordinate; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number + } + + interface ZoomOptions { + + /** + * The resolution to begin zooming from, typically map.getView().getResolution(). + */ + resolution: number; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number + } + } + + namespace control { + + interface DefaultsOptions { + + /** + * Attribution. Default is true. + */ + attribution?: boolean; + + /** + * Attribution options. + */ + //TODO: Replace with olx.control.AttributionOptions + attributionOptions?: any; + + /** + * Rotate. Default is true; + */ + rotate?: boolean; + + /** + * Rotate options + */ + //TODO: Replace with olx.control.RotateOptions + rotateOptions?: any; + + /** + * Zoom. Default is true + */ + zoom?: boolean; + + /** + * + */ + //TODO: Replace with olx.control.ZoomOptions + zoomOptions?: any; + } + } + + namespace interaction { + interface DefaultsOptions { + altShiftDragRotate?: boolean; + doubleClickZoom?: boolean; + keyboard?: boolean; + mouseWheelZoom?: boolean; + shiftDragZoom?: boolean; + dragPan?: boolean; + pinchRotate?: boolean; + pinchZoom?: boolean; + zoomDelta?: number; + zoomDuration?: number; + } + interface DragBoxOptions { + className?: string + condition?: ol.events.ConditionType + boxEndCondition?: ol.interaction.DragBoxEndConditionType + } + interface InteractionOptions { + handleEvent (e: ol.MapBrowserEvent): boolean + } + interface ModifyOptions { + deleteCondition?: ol.events.ConditionType; + pixelTolerance?: number; + style?: ol.style.Style | Array | ol.style.StyleFunction; + features: ol.Collection; + wrapX?: boolean; + } + interface DrawOptions { + clickTolerance?: number; + features?: ol.Collection; + source?: ol.source.Vector; + snapTolerance?: number; + type: ol.geom.GeometryType; + maxPoints?: number; + minPoints?: number; + style?: ol.style.Style | Array | ol.style.StyleFunction; + geometryFunction?: ol.interaction.DrawGeometryFunctionType; + geometryName?: string; + condition?: ol.events.ConditionType; + freehandCondition?: ol.events.ConditionType; + wrapX?: boolean; + } + interface PointerOptions { + handleDownEvent?: (e: ol.MapBrowserPointerEvent) => boolean; + handleDragEvent?: (e: ol.MapBrowserPointerEvent) => void; + handleEvent?: (e: ol.MapBrowserEvent) => boolean; + handleMoveEvent?: (e: ol.MapBrowserPointerEvent) => void; + handleUpEvent?: (e: ol.MapBrowserPointerEvent) => boolean; + } + interface SelectOptions { + addCondition?: ol.events.ConditionType; + condition?: ol.events.ConditionType; + layers?: Array | ((layer: ol.layer.Layer) => boolean); + style?: ol.style.Style | Array | ol.style.StyleFunction; + removeCondition?: ol.events.ConditionType; + toggleCondition?: ol.events.ConditionType; + multi?: boolean; + features?: ol.Collection; + filter?: ol.interaction.SelectFilterFunction; + wrapX?: boolean; + } + } + + namespace layer { + + interface BaseOptions { + /** + * Opacity (0, 1). Default is 1. + */ + opacity?: number; + + /** + * Visibility. Default is true. + */ + visible?: boolean; + + /** + * The bounding extent for layer rendering. The layer will not be rendered outside of this extent. + */ + extent?: ol.Extent; + + zIndex?: number; + /** + * The minimum resolution (inclusive) at which this layer will be visible. + */ + minResolution?: number; + + /** + * The maximum resolution (exclusive) below which this layer will be visible. + */ + maxResolution?: number; + } + + interface GroupOptions extends BaseOptions { + + /** + * Child layers + */ + layers?: Array | ol.Collection; + } + + interface HeatmapOptions extends VectorOptions { + + /** + * The color gradient of the heatmap, specified as an array of CSS color strings. Default is ['#00f', '#0ff', '#0f0', '#ff0', '#f00']. + */ + gradient?: Array; + + /** + * Radius size in pixels. Default is 8. + */ + radius?: number; + + /** + * Blur size in pixels. Default is 15. + */ + blur?: number; + + /** + * Shadow size in pixels. Default is 250. + */ + shadow?: number; + } + + interface ImageOptions extends LayerOptions { + } + + interface LayerOptions extends BaseOptions { + + /** + * The layer source (or null if not yet set). + */ + source?: ol.source.Source; + } + + interface TileOptions extends LayerOptions { + + /** + * Preload. Load low-resolution tiles up to preload levels. By default preload is 0, which means no preloading. + */ + preload?: number; + + /** + * Source for this layer. + */ + source?: ol.source.Tile; + + /** + * Use interim tiles on error. Default is true. + */ + useInterimTilesOnError?: boolean; + } + + interface VectorOptions extends LayerOptions { + + /** + * Render order. Function to be used when sorting features before rendering. By default features are drawn in the order that they are created. Use null to avoid the sort, but get an undefined draw order. + */ + renderOrder?: (a: ol.Feature, b: ol.Feature) => number; + + map?: ol.Map; + + extent?: ol.Extent; + + minResolution?: number; + + maxResolution?: number; + + opacity?: number; + + /** + * The buffer around the viewport extent used by the renderer when getting features from the vector source for the rendering or hit-detection. Recommended value: the size of the largest symbol, line width or label. Default is 100 pixels. + */ + renderBuffer?: number; + + /** + * Source. + */ + source: ol.source.Vector; + + /** + * Layer style. See ol.style for default style which will be used if this is not defined. + */ + style?: ol.style.Style | Array | ol.style.StyleFunction; + + /** + * When set to true, feature batches will be recreated during animations. This means that no vectors will be shown clipped, but the setting will have a performance impact for large amounts of vector data. When set to false, batches will be recreated when no animation is active. Default is false. + */ + updateWhileAnimating?: boolean; + + /** + * When set to true, feature batches will be recreated during interactions. See also updateWhileInteracting. Default is false. + */ + updateWhileInteracting?: boolean; + + visible?: boolean; + } + } + + namespace source { + + interface VectorOptions { + /** + * Attributions. + */ + attributions?: Array; + + /** + * Features. If provided as {@link ol.Collection}, the features in the source + * and the collection will stay in sync. + */ + features?: Array | ol.Collection; + + /** + * The feature format used by the XHR feature loader when `url` is set. + * Required if `url` is set, otherwise ignored. Default is `undefined`. + */ + format?: ol.format.Feature; + + /** + * The loader function used to load features, from a remote source for example. + * Note that the source will create and use an XHR feature loader when `url` is + * set. + */ + loader?: ol.FeatureLoader; + + /** + * Logo. + */ + logo?: string | olx.LogoOptions; + + /** + * The loading strategy to use. By default an {@link ol.loadingstrategy.all} + * strategy is used, a one-off strategy which loads all features at once. + */ + strategy?: ol.LoadingStrategy; + + /** + * Setting this option instructs the source to use an XHR loader (see + * {@link ol.featureloader.xhr}) and an {@link ol.loadingstrategy.all} for a + * one-off download of all features from that URL. + * Requires `format` to be set as well. + */ + url?: string | ol.FeatureUrlFunction; + + /** + * By default, an RTree is used as spatial index. When features are removed and + * added frequently, and the total number of features is low, setting this to + * `false` may improve performance. + */ + useSpatialIndex?: boolean; + + /** + * Wrap the world horizontally. Default is `true`. For vector editing across the + * -180° and 180° meridians to work properly, this should be set to `false`. The + * resulting geometry coordinates will then exceed the world bounds. + */ + wrapX?: boolean; + } + interface WMTSOptions { + attributions?: Array; + crossOrigin?: string; + logo?: string | olx.LogoOptions; + tileGrid: ol.tilegrid.WMTS; // REQUIRED ! + projection?: ol.proj.ProjectionLike; + reprojectionErrorThreshold?: number; + requestEncoding?: ol.source.WMTSRequestEncoding; + layer: string; //REQUIRED + style: string; //REQUIRED + tileClass?: Function; + tilePixelRatio?: number; + version?: string; + format?: string; + matrixSet: string; //REQUIRED + dimensions?: GlobalObject; + url?: string; + maxZoom?: number; + tileLoadFunction?: ol.TileLoadFunctionType; + urls?: Array; + wrapX: boolean; + } + } + + namespace style { + + interface FillOptions { + color?: ol.Color | string; + } + + interface StyleOptions { + geometry?: string | ol.geom.Geometry | ol.style.GeometryFunction; + fill?: ol.style.Fill; + image?: ol.style.Image; + stroke?: ol.style.Stroke; + text?: ol.style.Text; + zIndex?: number; + } + + interface TextOptions { + font?: string; + offsetX?: number; + offsetY?: number; + scale?: number; + rotation?: number; + text?: string; + textAlign?: string; + textBaseline?: string; + fill?: ol.style.Fill; + stroke?: ol.style.Stroke; + } + interface StrokeOptions { + color?: ol.Color | string; + lineCap?: string; + lineJoin?: string; + lineDash?: Array; + miterLimit?: number; + width?: number; + } + interface IconOptions { + anchor?: Array; + anchorOrigin?: string; + anchorXUnits?: string; + anchorYUnits?: string; + crossOrigin?: string; + img?: ol.Image | HTMLCanvasElement; + offset?: Array; + offsetOrigin?: string; + opacity?: number; + scale?: number; + snapToPixel?: boolean; + rotateWithView?: boolean; + rotation?: number; + size?: ol.Size; + imgSize?: ol.Size; + src?: string; + } + interface CircleOptions { + fill?: ol.style.Fill; + radius: number; + snapToPixel?: boolean; + stroke?: ol.style.Stroke; + } + } + + namespace tilegrid { + + interface TileGridOptions { + + /** + * Extent for the tile grid. No tiles outside this extent will be requested by ol.source.Tile sources. When no origin or origins are configured, the origin will be set to the bottom-left corner of the extent. When no sizes are configured, they will be calculated from the extent. + */ + extent?: ol.Extent; + + /** + * Minimum zoom. Default is 0. + */ + minZoom?: number; + + /** + * Origin, i.e. the bottom-left corner of the grid. Default is null. + */ + origin?: ol.Coordinate; + + /** + * Origins, i.e. the bottom-left corners of the grid for each zoom level. If given, the array length should match the length of the resolutions array, i.e. each resolution can have a different origin. + */ + origins?: Array; + + /** + * Resolutions. The array index of each resolution needs to match the zoom level. This means that even if a minZoom is configured, the resolutions array will have a length of maxZoom + 1. + */ + resolutions?: Array; + + /** + * Tile size. Default is [256, 256]. + */ + tileSize?: number | ol.Size; + + /** + * Tile sizes. If given, the array length should match the length of the resolutions array, i.e. each resolution can have a different tile size. + */ + tileSizes?: Array; + } + + interface WMTSOptions { + + /** + * Extent for the tile grid. No tiles outside this extent will be requested by ol.source.WMTS sources. When no origin or origins are configured, the origin will be calculated from the extent. When no sizes are configured, they will be calculated from the extent. + */ + extent?: ol.Extent; + + /** + * Origin, i.e. the top-left corner of the grid. + */ + origin?: ol.Coordinate; + + /** + * Origins, i.e. the top-left corners of the grid for each zoom level. The length of this array needs to match the length of the resolutions array. + */ + origins?: Array; + + /** + * Resolutions. The array index of each resolution needs to match the zoom level. This means that even if a minZoom is configured, the resolutions array will have a length of maxZoom + 1 + */ + resolutions?: Array; + + /** + * matrix IDs. The length of this array needs to match the length of the resolutions array. + */ + matrixIds?: Array; + + /** + * Number of tile rows and columns of the grid for each zoom level. The values here are the TileMatrixWidth and TileMatrixHeight advertised in the GetCapabilities response of the WMTS, and define the grid's extent together with the origin. An extent can be configured in addition, and will further limit the extent for which tile requests are made by sources. + */ + sizes?: Array; + + /** + * Tile size. + */ + tileSize?: number | ol.Size; + + /** + * Tile sizes. The length of this array needs to match the length of the resolutions array. + */ + tileSizes?: Array; + + /** + * Number of tile columns that cover the grid's extent for each zoom level. Only required when used with a source that has wrapX set to true, and only when the grid's origin differs from the one of the projection's extent. The array length has to match the length of the resolutions array, i.e. each resolution will have a matching entry here. + */ + widths?: Array; + } + + interface XYZOptions { + + /** + * Extent for the tile grid. The origin for an XYZ tile grid is the top-left corner of the extent. The zero level of the grid is defined by the resolution at which one tile fits in the provided extent. If not provided, the extent of the EPSG:3857 projection is used. + */ + extent?: ol.Extent; + + /** + * Maximum zoom. The default is ol.DEFAULT_MAX_ZOOM. This determines the number of levels in the grid set. For example, a maxZoom of 21 means there are 22 levels in the grid set. + */ + maxZoom?: number; + + /** + * Minimum zoom. Default is 0. + */ + minZoom?: number; + + /** + * Tile size in pixels. Default is [256, 256]. + */ + tileSize?: number | ol.Size; + } + + interface ZoomifyOptions { + + /** + * Resolutions + */ + resolutions: Array; + } + } + + namespace view { + + interface FitGeometryOptions { + + /** + * Padding (in pixels) to be cleared inside the view. Values in the array are top, right, bottom and left padding. Default is [0, 0, 0, 0]. + */ + padding?: Array; + + /** + * Constrain the resolution. Default is true. + */ + constrainResolution?: boolean; + + /** + * Get the nearest extent. Default is false. + */ + nearest?: boolean; + + /** + * Minimum resolution that we zoom to. Default is 0. + */ + minResolution?: number; + + /** + * Maximum zoom level that we zoom to. If minResolution is given, this property is ignored. + */ + maxZoom?: number; + } + } + + namespace format { + interface WKTOptions { + /** + * Whether to split GeometryCollections into multiple features on reading. Default is false. + */ + splitCollection?: boolean; + } + + interface GeoJSONOptions { + + /** + * Default data projection. + */ + defaultDataProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * Geometry name to use when creating features + */ + geometryName?: string; + } + + interface ReadOptions { + + /** + * Projection of the data we are reading. If not provided, the projection will be derived from the data (where possible) or the defaultDataProjection of the format is assigned (where set). If the projection can not be derived from the data and if no defaultDataProjection is set for a format, the features will not be reprojected. + */ + dataProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * Projection of the feature geometries created by the format reader. If not provided, features will be returned in the dataProjection. + */ + featureProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + } + + interface WriteOptions { + + /** + * Projection of the data we are writing. If not provided, the defaultDataProjection of the format is assigned (where set). If no defaultDataProjection is set for a format, the features will be returned in the featureProjection. + */ + dataProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * Projection of the feature geometries that will be serialized by the format writer. + */ + featureProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * When writing geometries, follow the right-hand rule for linear ring orientation. This means that polygons will have counter-clockwise exterior rings and clockwise interior rings. By default, coordinates are serialized as they are provided at construction. If true, the right-hand rule will be applied. If false, the left-hand rule will be applied (clockwise for exterior and counter-clockwise for interior rings). Note that not all formats support this. The GeoJSON format does use this property when writing geometries. + */ + rightHanded?: boolean; + } + } +} + +/** + * A high-performance, feature-packed library for all your mapping needs. + */ +declare namespace ol { + + interface TileLoadFunctionType { (image: ol.Image, url: string): void } + + interface FeatureUrlFunction { (extent: ol.Extent, resolution: number, projection: ol.proj.Projection): string } + + interface ImageLoadFunctionType { (image: ol.Image, url: string): void } + + /** + * An attribution for a layer source. + */ + class Attribution { + /** + * @constructor + * @param options Attribution options. + */ + constructor(options: olx.AttributionOptions); + + /** + * Get the attribution markup. + * @returns The attribution HTML. + */ + getHTML(): string; + } + + /** + * 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. + */ + class Collection extends ol.Object { + + /** + * @constructor + * @param opt_array Array. + */ + constructor(opt_array?: Array) + + /** + * Remove all elements from the collection. + */ + clear(): void; + + /** + * Add elements to the collection. This pushes each item in the provided array to the end of the collection. + * @param arr Array. + * @returns This collection. + */ + extend(arr: Array): Collection; + + /** + * Iterate over each element, calling the provided callback. + * @param f The function to call for every element. This function takes 3 arguments (the element, the index and the array). + * @param opt_this The object to use as this in f. + */ + forEach(f: (element: T, index: number, array: Array) => any, opt_this?: any): 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. + * @returns Array. + */ + getArray(): Array; + + /** + * Get the length of this collection. + * @returns The length of the array. + */ + getLength(): number; + + /** + * Insert an element at the provided index. + * @param index Index. + * @param elem Element. + */ + insertAt(index: number, elem: T): void; + + /** + * Get the element at the provided index. + * @param index Index. + * @returns Element. + */ + item(index: number): T; + + /** + * Remove the last element of the collection and return it. Return undefined if the collection is empty. + * @returns Element + */ + pop(): T | void; + + /** + * Insert the provided element at the end of the collection. + * @param elem Element. + * @returns Length. + */ + push(elem: T): number; + + /** + * Remove the first occurrence of an element from the collection. + * @param elem Element. + * @returns The removed element or undefined if none found. + */ + remove(elem: T): T | void; + + /** + * Remove the element at the provided index and return it. Return undefined if the collection does not contain this index. + * @param index Index. + * @returns Value. + */ + removeAt(index: number): T | void; + + /** + * Set the element at the provided index. + * @param index Index. + * @param elem Element. + */ + setAt(index: number, elem: T): void; + } + + /** + * Events emitted by ol.Collection instances are instances of this type. + */ + class CollectionEvent extends ol.events.Event { + + /** + * The element that is added to or removed from the collection. + */ + element: T; + } + + /** + * The ol.DeviceOrientation class provides access to information from DeviceOrientation events. + */ + class DeviceOrientation extends ol.Object { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.DeviceOrientationOptions); + + /** + * Rotation around the device z-axis (in radians). + * @returns The euler angle in radians of the device from the standard Z axis. + */ + getAlpha(): number; + + /** + * Rotation around the device x-axis (in radians). + * @returns The euler angle in radians of the device from the planar X axis. + */ + getBeta(): number; + + /** + * Rotation around the device y-axis (in radians). + * @returns The euler angle in radians of the device from the planar Y axis. + */ + getGamma(): number; + + /** + * The heading of the device relative to north (in radians). + * @returns The heading of the device relative to north, in radians, normalizing for different browser behavior. + */ + getHeading(): number; + + /** + * Determine if orientation is being tracked. + * @returns Changes in device orientation are being tracked. + */ + getTracking(): boolean; + + /** + * Enable or disable tracking of device orientation events. + * @param tracking The status of tracking changes to alpha, beta and gamma. If true, changes are tracked and reported immediately. + */ + setTracking(tracking: boolean): void; + } + + /** + * Events emitted by ol.interaction.DragBox instances are instances of this type. + */ + class DragBoxEvent extends ol.events.Event { + constructor ( + type: string, + coordinate: ol.Coordinate, + mapBrowserEvent: ol.MapBrowserEvent + ); + /** + * The coordinate of the drag event. + */ + coordinate: ol.Coordinate; + mapBrowserEvent: ol.MapBrowserEvent; + } + + /** + * A vector object for geographic features with a geometry and other attribute properties, similar to the features in vector file formats like GeoJSON. + */ + class Feature extends ol.Object { + + /** + * @constructor + * @param geometryOrProperties Geometry. + */ + // TODO: replace any with Object + constructor(geometryOrProperties?: ol.geom.Geometry | any); + + /** + * Clone this feature. If the original feature has a geometry it is also cloned. The feature id is not set in the clone. + * @returns The clone. + */ + clone(): Feature; + + /** + * Get the feature's default geometry. A feature may have any number of named geometries. The "default" geometry (the one that is rendered by default) is set when calling ol.Feature#setGeometry. + * @returns The default geometry for the feature. + */ + getGeometry(): ol.geom.Geometry; + + /** + * Get the name of the feature's default geometry. By default, the default geometry is named geometry. + * @returns Get the property name associated with the default geometry for this feature. + */ + getGeometryName(): string; + + /** + * @returns Id. + */ + getId(): string | number; + + /** + * Get the feature's style. This return for this method depends on what was provided to the ol.Feature#setStyle method. + * The feature style. + */ + getStyle(): ol.style.Style | Array | ol.FeatureStyleFunction; + + /** + * Get the feature's style function. + * @returns Return a function representing the current style of this feature. + */ + getStyleFunction(): ol.FeatureStyleFunction; + + /** + * Set the default geometry for the feature. This will update the property with the name returned by ol.Feature#getGeometryName. + * @param geometry The new geometry. + */ + setGeometry(geometry: ol.geom.Geometry): void; + + /** + * Set the property name to be used when getting the feature's default geometry. When calling ol.Feature#getGeometry, the value of the property with this name will be returned. + * @param name The property name of the default geometry. + */ + setGeometryName(name: string): void; + + /** + * Set the feature id. The feature id is considered stable and may be used when requesting features or comparing identifiers returned from a remote source. The feature id can be used with the ol.source.Vector#getFeatureById method. + * @param id The feature id. + */ + setId(id: string | number): void; + + /** + * Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a resolution and returns an array of styles. If it is null the feature has no style (a null style). + * @param style Style for this feature. + */ + setStyle(style: ol.style.Style): void; + + /** + * Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a resolution and returns an array of styles. If it is null the feature has no style (a null style). + * @param style Style for this feature. + */ + setStyle(style: Array): void; + + /** + * Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a resolution and returns an array of styles. If it is null the feature has no style (a null style). + * @param style Style for this feature. + */ + setStyle(style: ol.FeatureStyleFunction): void; + } + + /** + * A mechanism for changing the style of a small number of features on a temporary basis, for example highlighting. + */ + class FeatureOverlay { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.FeatureOverlayOptions); + + /** + * Add a feature to the overlay. + * @param feature Feature. + */ + addFeature(feature: ol.Feature): void; + + /** + * Get the features on the overlay. + * @returns Features collection. + */ + getFeatures: ol.Collection; + + /** + * Get the map associated with the overlay. + * @returns The map with which this feature overlay is associated. + */ + getMap(): ol.Map; + + /** + * Get the style for features. This returns whatever was passed to the style option at construction or to the setStyle method. + * @returns Overlay style. + */ + getStyle(): ol.style.Style | Array | ol.style.StyleFunction; + + /** + * Get the style function + * @returns Style function + */ + getStyleFunction(): ol.style.StyleFunction; + + /** + * Remove a feature from the overlay. + * @param feature The feature to be removed. + */ + removeFeature(feature: ol.Feature): void; + + /** + * Set the features for the overlay. + * @param features Features collection. + */ + setFeatures(features: ol.Collection): void; + + /** + * Set the map for the overlay. + * @param map Map. + */ + setMap(map: ol.Map): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. + * @param style Overlay style + */ + setStyle(style: ol.style.Style): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. + * @param style Overlay style + */ + setStyle(style: Array): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. + * @param style Overlay style + */ + setStyle(style: ol.style.StyleFunction): void; + } + + /** + * Helper class for providing HTML5 Geolocation capabilities. The Geolocation API is used to locate a user's position. + */ + class Geolocation extends ol.Object { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.GeolocationOptions); + + /** + * Get the accuracy of the position in meters. + * @returns The accuracy of the position measurement in meters. + */ + getAccuracy(): number; + + /** + * Get a geometry of the position accuracy. + * @returns A geometry of the position accuracy. + */ + getAccuracyGeometry(): ol.geom.Geometry; + + /** + * Get the altitude associated with the position. + * @returns The altitude of the position in meters above mean sea level. + */ + getAltitude(): number; + + /** + * Get the altitude accuracy of the position. + * @returns The accuracy of the altitude measurement in meters. + */ + getAltitudeAccuracy(): number; + + /** + * Get the heading as radians clockwise from North. + * @returns The heading of the device in radians from north. + */ + getHeading(): number; + + /** + * Get the position of the device. + * @returns The current position of the device reported in the current projection. + */ + getPosition(): ol.Coordinate; + + /** + * Get the projection associated with the position. + * @returns The projection the position is reported in. + */ + getProjection(): ol.proj.Projection; + + /** + * Get the speed in meters per second. + * @returns The instantaneous speed of the device in meters per second. + */ + getSpeed(): number; + + /** + * Determine if the device location is being tracked. + * @returns The device location is being tracked. + */ + getTracking(): boolean; + + /** + * Get the tracking options. + * @returns PositionOptions as defined by the HTML5 Geolocation spec. + */ + getTrackingOptions(): PositionOptions; + + /** + * Set the projection to use for transforming the coordinates. + * @param projection The projection the position is reported in. + */ + setProjection(projection: ol.proj.Projection): void; + + /** + * Enable or disable tracking. + * @param tracking Enable tracking + */ + setTracking(tracking: boolean): void; + + /** + * Set the tracking options. + * @param options PositionOptions as defined by the HTML5 Geolocation spec. + */ + setTrackingOptions(options: PositionOptions): void; + } + + /** + * Render a grid for a coordinate system on a map. + */ + class Graticule { + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.GraticuleOptions); + + /** + * Get the map associated with this graticule. + * @returns The map. + */ + getMap(): Map; + + /** + * Get the list of meridians. Meridians are lines of equal longitude. + * @returns The meridians. + */ + getMeridians(): Array; + + /** + * Get the list of parallels. Pallels are lines of equal latitude. + * @returns The parallels. + */ + getParallels(): Array; + + /** + * Set the map for this graticule.The graticule will be rendered on the provided map. + * @param map Map + */ + setMap(map: Map): void; + } + + /** + * + */ + class Image extends ol.ImageBase { + + /** + * Get the HTML image element (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLCanvasElement): Image; + + /** + * Get the HTML image element (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLImageElement): Image; + + /** + * Get the HTML image element (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLVideoElement): Image; + } + + /** + * + */ + class ImageBase { + } + + /** + * + */ + class ImageTile extends ol.Tile { + + /** + * Get the HTML image element for this tile (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLCanvasElement): Image; + + /** + * Get the HTML image element for this tile (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLImageElement): Image; + + /** + * Get the HTML image element for this tile (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLVideoElement): Image; + + } + + /** + * Implementation of inertial deceleration for map movement. + */ + class Kinetic { + + /** + * @constructor + * @param decay Rate of decay (must be negative). + * @param minVelocity Minimum velocity (pixels/millisecond). + * @param delay Delay to consider to calculate the kinetic initial values (milliseconds). + */ + constructor(decay: number, minVelocity: number, delay: number); + } + + /** + * The map is the core component of OpenLayers. For a map to render, a view, one or more layers, and a target container are needed. + */ + class Map extends ol.Object { + + /** + * @constructor + * @params options Options. + */ + constructor(options: olx.MapOptions); + + /** + * Add the given control to the map. + * @param control Control. + */ + addControl(control: ol.control.Control): void; + + /** + * Add the given interaction to the map. + * @param interaction Interaction to add. + */ + addInteraction(interaction: ol.interaction.Interaction): void; + + /** + * Adds the given layer to the top of this map. If you want to add a layer elsewhere in the stack, use getLayers() and the methods available on ol.Collection. + * @param layer Layer. + */ + addLayer(layer: ol.layer.Base): void; + + /** + * Add the given overlay to the map. + * @param overlay Overlay. + */ + addOverlay(overlay: ol.Overlay): void; + + /** + * Add functions to be called before rendering. This can be used for attaching animations before updating the map's view. The ol.animation namespace provides several static methods for creating prerender functions. + * @param var_args Any number of pre-render functions. + */ + beforeRender(...var_args: ol.PreRenderFunction[]): void; + + /** + * Detect features that intersect a pixel on the viewport, and execute a callback with each intersecting feature. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. + * @param pixel Pixel. + * @param callback Feature callback. The callback will be called with two arguments. The first argument is one feature at the pixel, the second is the layer of the feature. If the detected feature is not on a layer, but on a ol.FeatureOverlay, then the second argument to this function will be null. To stop detection, callback functions can return a truthy value. + * @param ref Value to use as this when executing callback. + * @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested. + * @param ref2 Value to use as this when executing layerFilter. + * @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value. + */ + forEachFeatureAtPixel(pixel: ol.Pixel, callback: (feature: ol.Feature, layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): void; + + /** + * Detect layers that have a color value at a pixel on the viewport, and execute a callback with each matching layer. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. + * @param pixel Pixel. + * @param callback Layer callback. Will receive one argument, the layer that contains the color pixel. If the detected color value is not from a layer, but from a ol.FeatureOverlay, then the argument to this function will be null. To stop detection, callback functions can return a truthy value. + * @param ref Value to use as this when executing callback. + * @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested. + * @param ref2 Value to use as this when executing layerFilter. + * @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value. + */ + forEachLayerAtPixel(pixel: ol.Pixel, callback: (layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): void; + + /** + * Get the map controls. Modifying this collection changes the controls associated with the map. + * @returns Controls. + */ + getControls(): ol.Collection; + + /** + * Get the coordinate for a given pixel. This returns a coordinate in the map view projection. + * @param pixel Pixel position in the map viewport. + * @returns The coordinate for the pixel position. + */ + getCoordinateFromPixel(pixel: ol.Pixel): ol.Coordinate; + + /** + * Returns the geographical coordinate for a browser event. + * @param event Event. + * @returns Coordinate. + */ + getEventCoordinate(event: GlobalEvent): ol.Coordinate; + + /** + * Returns the map pixel position for a browser event relative to the viewport. + * @param event Event. + * @returns Pixel. + */ + getEventPixel(event: GlobalEvent): ol.Pixel; + + /** + * Get the map interactions. Modifying this collection changes the interactions associated with the map. + * @returns Interactions + */ + getInteractions(): ol.Collection; + + /** + * Get the layergroup associated with this map. + * @returns A layer group containing the layers in this map. + */ + getLayerGroup(): ol.layer.Group; + + /** + * Get the collection of layers associated with this map. + * @returns Layers. + */ + getLayers(): ol.Collection; + + /** + * Get the map overlays. Modifying this collection changes the overlays associated with the map. + * @returns Overlays. + */ + getOverlays(): ol.Collection; + + /** + * Get the pixel for a coordinate. This takes a coordinate in the map view projection and returns the corresponding pixel. + * @param coordinate A map coordinate. + * @returns A pixel position in the map viewport. + */ + getPixelFromCoordinate(coordinate: ol.Coordinate): ol.Pixel; + + /** + * Get the size of this map. + * @returns The size in pixels of the map in the DOM. + */ + getSize(): ol.Size; + + /** + * Get the target in which this map is rendered. Note that this returns what is entered as an option or in setTarget: if that was an element, it returns an element; if a string, it returns that. + * @returns The Element or id of the Element that the map is rendered in. + */ + getTarget(): Element | string; + + /** + * Get the DOM element into which this map is rendered. In contrast to getTarget this method always return an Element, or null if the map has no target. + * @returns The element that the map is rendered in. + */ + getTargetElement(): Element; + + /** + * Get the view associated with this map. A view manages properties such as center and resolution. + * @returns The view that controls this map. + */ + getView(): View; + + /** + * Get the element that serves as the map viewport. + * @returns Viewport. + */ + getViewport(): Element; + + /** + * Detect if features intersect a pixel on the viewport. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. + * @param pixel Pixel. + * @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested. + * @param ref Value to use as this when executing layerFilter. + * @returns Is there a feature at the given pixel? + */ + hasFeatureAtPixel(pixel: ol.Pixel, layerFilter?: (layer: ol.layer.Layer) => boolean, ref?: any): boolean; + + /** + * Remove the given control from the map. + * @param control Control. + * @returns The removed control (or undefined if the control was not found). + */ + removeControl(control: ol.control.Control): ol.control.Control; + + /** + * Remove the given interaction from the map. + * @param interaction Interaction to remove. + * @returns The removed interaction (or undefined if the interaction was not found). + */ + removeInteraction(interaction: ol.interaction.Interaction): ol.interaction.Interaction; + + /** + * Removes the given layer from the map. + * @param layer Layer. + * @returns The removed layer (or undefined if the layer was not found). + */ + removeLayer(layer: ol.layer.Base): ol.layer.Base; + + /** + * Remove the given overlay from the map. + * @param overlay Overlay. + * @returns The removed overlay (or undefined if the overlay was not found). + */ + removeOverlay(overlay: ol.Overlay): ol.Overlay; + + /** + * Request a map rendering (at the next animation frame). + */ + render(): void; + + /** + * Requests an immediate render in a synchronous manner. + */ + renderSync(): void; + + /** + * Sets the layergroup of this map. + * @param layerGroup A layer group containing the layers in this map. + */ + setLayerGroup(layerGroup: ol.layer.Group): void; + + /** + * Set the size of this map. + * @param size The size in pixels of the map in the DOM. + */ + setSize(size: ol.Size): void; + + /** + * Set the target element to render this map into. + * @param target The Element that the map is rendered in. + */ + setTarget(target: Element): void; + + /** + * Set the target element to render this map into. + * @param target The id of the element that the map is rendered in. + */ + setTarget(target: string): void; + + /** + * Set the view for this map. + * @param view The view that controls this map. + */ + setView(view: View): void; + + /** + * Force a recalculation of the map viewport size. This should be called when third-party code changes the size of the map viewport. + * */ + updateSize(): void; + } + + /** + * Events emitted as map browser events are instances of this type. See ol.Map for which events trigger a map browser event. + */ + class MapBrowserEvent extends MapEvent { + + /** + * The coordinate of the original browser event + */ + coordinate: Coordinate; + + /** + * Indicates if the map is currently being dragged. Only set for POINTERDRAG and POINTERMOVE events. Default is false. + */ + dragging: boolean; + + /** + * The frame state at the time of the event + */ + frameState: olx.FrameState; + + /** + * The map where the event occured + */ + map: Map; + + /** + * The original browser event + */ + originalEvent: GlobalEvent; + + /** + * The pixel of the original browser event. + */ + pixel: Pixel; + + + // Methods + + /** + * Prevents the default browser action. + */ + preventDefault(): void; + + /** + * Prevents further propagation of the current event. + */ + stopPropagation(): void; + } + + class MapBrowserPointerEvent extends ol.MapBrowserEvent { + constructor (type: string, + map: ol.Map, + pointerEvent: ol.pointer.PointerEvent, + opt_dragging?: boolean, + opt_frameState?: olx.FrameState) + pointerEvent: ol.pointer.PointerEvent; + } + + /** + * Events emitted as map events are instances of this type. See ol.Map for which events trigger a map event. + */ + class MapEvent extends ol.events.Event { + + constructor (type: string, map: ol.Map, opt_frameState?: olx.FrameState) + + /** + * The frame state at the time of the event. + */ + frameState: olx.FrameState; + + /** + * The map where the event occurred. + */ + map: Map; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. Most non-trivial classes inherit from this. + */ + class Object extends Observable { + + /** + * @constructor + * @param values An object with key-value pairs. + */ + constructor(values?: GlobalObject); + + /** + * Gets a value. + * @param key Key name. + * @returns Value. + */ + get(key: string): any; + + /** + * Get a list of object property names. + * @returns List of property names. + */ + getKeys(): Array; + + /** + * Get an object of all property names and values. + * @returns Object. + */ + getProperties(): GlobalObject; + + /** + * @returns Revision. + */ + getRevision(): number; + + /** + * Sets a value. + * @param key Key name. + * @param value Value. + * @param opt_silent Update without triggering an event. + */ + set(key: string, value: any, opt_silent?: boolean): void; + + /** + * Sets a collection of key-value pairs. Note that this changes any existing properties and adds new ones (it does not remove any existing properties). + * @param values Values. + * @param opt_silent Update without triggering an event. + */ + setProperties(values: GlobalObject, opt_silent?: boolean): void; + + /** + * Unsets a property. + */ + unset(key: string, opt_silent?: boolean): void; + } + + /** + * Events emitted by ol.Object instances are instances of this type. + */ + class ObjectEvent extends ol.events.Event { + + /** + * The name of the property whose value is changing. + */ + key: string; + + /** + * The old value. To get the new value use e.target.get(e.key) where e is the event object. + */ + oldValue: any; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. An event target providing convenient methods for listener registration and unregistration. A generic change event is always available through ol.Observable#changed. + */ + class Observable extends ol.events.EventTarget { + + /** + * Removes an event listener using the key returned by on() or once(). + */ + static unByKey(key: any): void; + + /** + * Increases the revision counter and dispatches a 'change' event. + */ + changed(): void; + + /** + * @returns Revision. + */ + getRevision(): number; + + /** + * Listen for a certain type of event. + * @param type The array of event types. + * @param listener The listener function. + * @param opt_this The object to use as this in listener. + * @returns Unique key for the listener. + */ + on(type: string | Array, listener: Function, opt_this?: GlobalObject): ol.events.Key | Array; + + /** + * Listen once for a certain type of event. + * @param type The array of event types. + * @param listener The listener function. + * @param opt_this The object to use as this in listener. + * @returns Unique key for the listener. + */ + once(type: string | Array, listener: Function, opt_this?: GlobalObject): ol.events.Key | Array; + + /** + * Unlisten for a certain type of event. + * @param type The array of event types. + * @param listener The listener function. + * @param opt_this The object to use as this in listener. + * @returns Unique key for the listener. + */ + un(type: string | Array, listener: Function, opt_this?: GlobalObject): void; + + /** + * Removes an event listener using the key returned by on() or once(). Note that using the ol.Observable.unByKey static function is to be preferred. + * @param key The key returned by on() or once() + */ + unByKey(key: ol.events.Key | Array): void; + } + + /** + * An element to be displayed over the map and attached to a single map location. + */ + class Overlay extends ol.Object { + + /** + * @constructor + * @param options Overlay options. + */ + constructor(options: olx.OverlayOptions); + + /** + * Get the DOM element of this overlay. + * @returns The Element containing the overlay. + */ + getElement(): Element; + + /** + * Get the map associated with this overlay. + * @returns The map that the overlay is part of. + */ + getMap(): ol.Map; + + /** + * Get the offset of this overlay. + * @returns The offset. + */ + getOffset(): Array; + + /** + * Get the current position of this overlay. + * @returns The spatial point that the overlay is anchored at. + */ + getPosition(): ol.Coordinate; + + /** + * Get the current positioning of this overlay. + * @returns How the overlay is positioned relative to its point on the map. + */ + getPositioning(): ol.OverlayPositioning; + + /** + * Set the DOM element to be associated with this overlay. + * @param element The element containing the overlay. + */ + setElement(element: Element): void; + + /** + * Set the map to be associated with this overlay. + * @param map The map that the overlay is part of. + */ + setMap(map: Map): void; + + /** + * Set the offset for this overlay. + * @param offset Offset. + */ + setOffset(offset: Array): void; + + /** + * Set the position for this overlay. If the position is undefined the overlay is hidden. + * @param position The spatial point that the overlay is anchored at. + */ + setPosition(position: ol.Coordinate): void; + + /** + * Set the positioning for this overlay. + * @param positioning How the overlay is positioned relative to its point on the map. + */ + setPositioning(positioning: ol.OverlayPositioning): void; + } + + /** + * Events emitted by ol.interaction.Select instances are instances of this type. + */ + class SelectEvent { + + /** + * Deselected features array. + */ + deselected: Array; + + /** + * Associated ol.MapBrowserEvent; + */ + mapBrowserEvent: ol.MapBrowserEvent; + + /** + * Selected features array. + */ + selected: Array + } + + /** + * Class to create objects that can be used with ol.geom.Polygon.circular. + */ + class Sphere { + + /** + * @constructor + * @param radius Radius. + */ + constructor(radius: number); + + /** + * Returns the geodesic area for a list of coordinates. + * @param coordinates List of coordinates of a linear ring. If the ring is oriented clockwise, the area will be positive, otherwise it will be negative. + * @returns Area. + */ + geodesicArea(coordinates: Array): number; + + /** + * Returns the distance from c1 to c2 using the haversine formula. + * @param c1 Coordinate 1. + * @param c2 Coordinate 2. + * @returns Haversine distance. + */ + haversineDistance(c1: ol.Coordinate, c2: ol.Coordinate): number; + } + + /** + * Base class for tiles. + */ + class Tile { + + /** + * Get the tile coordinate for this tile. + * @returns TileCoord. + */ + getTileCoord(): ol.TileCoord; + } + + /** + * An ol.View object represents a simple 2D view of the map. + */ + class View extends ol.Object { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.ViewOptions); + + /** + * Calculate the extent for the current view state and the passed size. The size is the pixel dimensions of the box into which the calculated extent should fit. In most cases you want to get the extent of the entire map, that is map.getSize(). + * @param size Box pixel size + * @returns Extent. + */ + calculateExtent(size: ol.Size): ol.Extent; + + /** + * Center on coordinate and view position. + * @param coordinate Coordinate. + * @param size Box pixel size + * @param position Position on the view to center on + */ + centerOn(coordinate: ol.Coordinate, size: ol.Size, position: ol.Pixel): void; + + /** + * Get the constrained center of this view. + * @param center Center. + * @returns Constrained center. + */ + constrainCenter(center: ol.Coordinate): ol.Coordinate; + + /** + * Get the constrained resolution of this view. + * @param resolution: Resolution. + * @param delta Delta. Default is 0. + * @param direction Direction. Default is 0. + * @returns Constrained resolution + */ + constrainResolution(resolution: number, delta?: number, direction?: number): number; + + /** + * Fit the map view to the passed extent and size. The size is pixel dimensions of the box to fit the extent into. In most cases you will want to use the map size, that is map.getSize(). + * @param geometry Geometry. + * @param size Box pixel size. + * @param opt_options Options + */ + fit(geometry: ol.geom.SimpleGeometry | ol.Extent, size: ol.Size, opt_options?: olx.view.FitGeometryOptions): void; + + /** + * Get the view center. + * @returns The center of the view. + */ + getCenter(): ol.Coordinate; + + /** + * Get the view projection + * @returns The projection of the view. + */ + getProjection(): ol.proj.Projection; + + /** + * Get the view resolution + * @returns The resolution of the view. + */ + getResolution(): number; + + /** + * Get the view rotation + * @returns The rotation of the view in radians + */ + getRotation(): number; + + /** + * Get the current zoom level. Return undefined if the current resolution is undefined or not a "constrained resolution". + * @returns Zoom. + */ + getZoom(): number; + + /** + * Rotate the view around a given coordinate. + * @param rotation New rotation value for the view. + * @param anchor The rotation center. + */ + rotate(rotation: number, anchor: ol.Coordinate): void; + + /** + * Set the center of the current view. + * @param center The center of the view. + */ + setCenter(center: ol.Coordinate): void; + + /** + * Set the resolution for this view. + * @param resolution The resolution of the view. + */ + setResolution(resolution: number): void; + + /** + * Set the rotation for this view. + * @param rotation The rotation of the view in radians. + */ + setRotation(rotation: number): void; + + /** + * Zoom to a specific zoom level. + * @param zoom Zoom level. + */ + setZoom(zoom: number): void; + } + + // NAMESPACES + + /** + * The animation static methods are designed to be used with the ol.Map#beforeRender method. + */ + namespace animation { + + /** + * Generate an animated transition that will "bounce" the resolution as it approaches the final value. + * @param options Bounce options. + */ + function bounce(options: olx.animation.BounceOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view center. + * @param options Pan options. + */ + function pan(options: olx.animation.PanOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view rotation. + * @param options Rotate options. + */ + function rotate(options: olx.animation.RotateOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view resolution. + * @param options Zoom options. + */ + function zoom(options: olx.animation.ZoomOptions): ol.PreRenderFunction; + } + + /** + * Return the color as an array. This function maintains a cache of calculated arrays which means the result should not be modified. + */ + namespace color { + + /** + * Return the color as an array. This function maintains a cache of calculated arrays which means the result should not be modified. + * @param color Color. + */ + function asArray(color: ol.Color): ol.Color; + + /** + * Return the color as an array. This function maintains a cache of calculated arrays which means the result should not be modified. + * @param color Color. + */ + function asArray(color: string): ol.Color; + + /** + * Return the color as an rgba string. + * @param color Color. + */ + function asString(color: ol.Color): string; + + /** + * Return the color as an rgba string. + * @param color Color. + */ + function asString(color: string): string; + } + + namespace control { + + /** + * Set of controls included in maps by default. Unless configured otherwise, this returns a collection containing an instance of each of the following controls: ol.control.Zoom, ol.control.Rotate, ol.control.Attribution + * @param options Defaults options + * @returns Control.s + */ + function defaults(options?: olx.control.DefaultsOptions): ol.Collection; + + /** + * Units for the scale line. Supported values are 'degrees', 'imperial', 'nautical', 'metric', 'us'. + */ + interface ScaleLineUnits extends String { } + + class Attribution { + } + + class Control { + } + + class FullScreen { + } + + class MousePosition { + } + + class OverviewMap { + } + + class Rotate { + } + + class ScaleLine { + } + + class Zoom { + } + + class ZoomSlider { + } + + class ZoomToExtent { + } + } + + namespace coordinate { + + /** + * Add delta to coordinate. coordinate is modified in place and returned by the function. + * @param coordinate Coordinate + * @param delta Delta + * @returns The input coordinate adjusted by the given delta. + */ + function add(coordinate: ol.Coordinate, delta: ol.Coordinate): ol.Coordinate; + + /** + * Returns a ol.CoordinateFormatType function that can be used to format a {ol.Coordinate} to a string. + * @param fractionDigits The number of digits to include after the decimal point. Default is 0. + * @returns Coordinate format + */ + function createStringXY(fractionDigits?: number): ol.CoordinateFormatType; + + /** + * Transforms the given 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. + * @param coordinate Coordinate + * @param template A template string with {x} and {y} placeholders that will be replaced by first and second coordinate values. + * @param fractionDigits The number of digits to include after the decimal point. Default is 0. + * @returns Formatted coordinate + */ + function format(coordinate: ol.Coordinate, template: string, fractionDigits?: number): string; + + /** + * Rotate coordinate by angle. coordinate is modified in place and returned by the function. + * @param coordinate Coordinate + * @param angle Angle in radian + * @returns Coordinatee + */ + function rotate(coordinate: ol.Coordinate, angle: number): ol.Coordinate; + + /** + * Format a geographic coordinate with the hemisphere, degrees, minutes, and seconds. + * @param coordinate COordinate + * @returns Hemisphere, degrees, minutes and seconds. + */ + function toStringHDMS(coordinate?: ol.Coordinate): string; + + /** + * Format a coordinate as a comma delimited string. + * @param coordinate Coordinate + * @param fractionDigits The number of digits to include after the decimal point. Default is 0. + * @returns XY + */ + function toStringXY(coordinate?: ol.Coordinate, fractionDigits?: number): string; + } + + /** + * Easing functions for ol.animation. + */ + namespace easing { + + /** + * Start slow and speed up. + * @param t Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function easeIn(t: number): number; + + /** + * Start fast and slow down. + * @param t Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function easeOut(t: number): number; + + /** + * Start slow, speed up, and then slow down again. + * @param t Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function inAndOut(t: number): number; + + /** + * Maintain a constant speed over time. + * @param t Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function linear(t: number): number; + + /** + * Start slow, speed up, and at the very end slow down again. This has the same general behavior as ol.easing.inAndOut, but the final slowdown is delayed. + * @param t Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function upAndDown(t: number): number; + } + + interface ModifyEventType extends String { + MODIFYSTART: any; + MODIFYEND: any; + } + + namespace events { + namespace condition { + function altKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function altShiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function always(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function click(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function doubleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function mouseOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function never(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function noModifierKeys(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function platformModifierKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function pointerMove(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function shiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function singleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function targetNotEditable(mapBrowserEvent: ol.MapBrowserEvent): boolean; + } + interface ConditionType { (mapBrowseEvent: ol.MapBrowserEvent): boolean; } + + class Event { + constructor(type: string, opt_target?: GlobalObject); + propagationStopped: boolean; + type: string; + target: Object; + preventDefault(): void; + stopPropagation(): void; + static preventDefault(evt: GlobalEvent | ol.events.Event): void; + static stopPropagation(evt: GlobalEvent | ol.events.Event): void; + } + + class EventTarget { + addEventListener(type: string, listener: ol.events.ListenerFunctionType): void; + dispatchEvent(event: {type: string, target?: GlobalEventTarget | ol.events.EventTarget, [x: string]: any}): void | boolean; + dispatchEvent(event: ol.events.Event): void | boolean; + dispatchEvent(event: string): void | boolean; + //getListeners(type: string): ol.events.ListenerFunctionType[]; + //hasListener(opt_type?: string): boolean; + removeEventListener(type: string, listener: ol.events.ListenerFunctionType): void; + } + + interface ListenerFunctionType { + (evt: ol.events.Event): boolean | void; + } + + interface Key extends GlobalObject {} + } + + namespace extent { + + /** + * Apply a transform function to the extent. + * @param extent Extent + * @param transformFn Transform function. Called with [minX, minY, maxX, maxY] extent coordinates. + * @param destinationExtent Destination Extent + * @returns Extent + */ + function applyTransform(extent: ol.Extent, transformFn: ol.TransformFunction, destinationExtent?: ol.Extent): ol.Extent; + + /** + * Build an extent that includes all given coordinates. + * @param coordinates Coordinates + * @returns Bounding extent + */ + function boundingExtent(coordinates: Array): ol.Extent; + + /** + * Return extent increased by the provided value. + * @param extent Extent + * @param value The amount by which the extent should be buffered. + * @param destinationExtent Destination Extent + * @returns Extent + */ + function buffer(extent: ol.Extent, value: number, destinationExtent?: ol.Extent): ol.Extent; + + /** + * Check if the passed coordinate is contained or on the edge of the extent. + * @param extent Extent + * @param coordinate Coordinate + * @returns The coordinate is contained in the extent + */ + function containsCoordinate(extent: ol.Extent, coordinate: ol.Coordinate): boolean; + + /** + * Check if one extent contains another. An extent is deemed contained if it lies completely within the other extent, including if they share one or more edges. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @returns The second extent is contained by or on the edge of the first + */ + function containsExtent(extent1: ol.Extent, extent2: ol.Extent): boolean; + + /** + * Check if the passed coordinate is contained or on the edge of the extent. + * @param extent Extent + * @param x X coordinate + * @param y Y coordinate + * @returns The x, y values are contained in the extent. + */ + function containsXY(extent: ol.Extent, x: number, y: number): boolean; + + /** + * Create an empty extent. + * @returns Empty extent + */ + function createEmpty(): ol.Extent; + + /** + * Determine if two extents are equivalent. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @returns The two extents are equivalent + */ + function equals(extent1: ol.Extent, extent2: ol.Extent): boolean; + + /** + * Modify an extent to include another extent. + * @param extent1 The extent to be modified. + * @param extent2 The extent that will be included in the first. + * @returns A reference to the first (extended) extent. + */ + function extend(extent1: ol.Extent, extent2: ol.Extent): ol.Extent; + + /** + * Get the bottom left coordinate of an extent. + * @param extent Extent + * @returns Bottom left coordinate + */ + function getBottomLeft(extent: ol.Extent): ol.Coordinate; + + /** + * Get the bottom right coordinate of an extent. + * @param extent Extent + * @returns Bottom right coordinate + */ + function getBottomRight(extent: ol.Extent): ol.Coordinate; + + /** + * Get the center coordinate of an extent. + * @param extent Extent + * @returns Center + */ + function getCenter(extent: ol.Extent): ol.Coordinate; + + /** + * Get the height of an extent. + * @param extent Extent + * @returns Height + */ + function getHeight(extent: ol.Extent): number; + + /** + * Get the intersection of two extents. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @param extent Optional extent to populate with intersection. + * @returns Intersecting extent + */ + function getIntersection(extent1: ol.Extent, extent2: ol.Extent, extent?: ol.Extent): ol.Extent; + + /** + * Get the size (width, height) of an extent. + * @param extent Extent + * @returns The extent size + */ + function getSize(extent: ol.Extent): ol.Size; + + /** + * Get the top left coordinate of an extent. + * @param extent Extent + * @returns Top left coordinate + */ + function getTopLeft(extent: ol.Extent): ol.Coordinate; + + /** + * Get the top right coordinate of an extent. + * @param extent Extent + * @returns Top right coordinate + */ + function getTopRight(extent: ol.Extent): ol.Coordinate; + + /** + * Get the width of an extent. + * @param extent Extent + * @returns Width + */ + function getWidth(extent: ol.Extent): number; + + /** + * Determine if one extent intersects another. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @returns The two extents intersects + */ + function intersects(extent1: ol.Extent, extent2: ol.Extent): boolean; + + /** + * Determine if an extent is empty. + * @param extent Extent + * @returns Is empty + */ + function isEmpty(extent: ol.Extent): boolean; + } + + /** + * Loading mechanisms for vector data. + */ + namespace featureloader { + + /** + * Create an XHR feature loader for a url and format. The feature loader loads features (with XHR), parses the features, and adds them to the vector source. + * @param url Feature URL Service + * @param format Feature format + * @returns The feature loader + */ + function xhr(url: string, format: ol.format.Feature): ol.FeatureLoader; + } + + namespace format { + + // Type definitions + interface IGCZ extends String { } + + // Classes + class EsriJSON { + } + + class Feature { + } + + /** + * Feature format for reading and writing data in the GeoJSON format. + */ + class GeoJSON extends ol.format.JSONFeature { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.format.GeoJSONOptions); + + /** + * Read a feature from a GeoJSON Feature source. Only works for Feature, use readFeatures to read FeatureCollection source. + * @param source Source + * @param options Read options + * @returns Feature + */ + readFeature(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): ol.Feature; + + /** + * Read all features from a GeoJSON source. Works with both Feature and FeatureCollection sources. + * @param source Source + * @param options Read options + * @returns Features + */ + readFeatures(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): Array; + + /** + * Read a geometry from a GeoJSON source. + * @param source Source + * @param options Read options + * @returns Geometry + */ + readGeometry(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): ol.geom.Geometry; + + /** + * Read the projection from a GeoJSON source. + * @param source Source + * @returns Projection + */ + readProjection(source: Document | Node | JSON | string): ol.proj.Projection; + + /** + * Encode a feature as a GeoJSON Feature string. + * @param feature Feature + * @param options Write options + * @returns GeoJSON + */ + writeFeature(feature: ol.Feature, options?: olx.format.WriteOptions): string; + + /** + * Encode a feature as a GeoJSON Feature object. + * @param feature Feature + * @param options Write options + * @returns GeoJSON object + */ + writeFeatureObject(feature: ol.Feature, options?: olx.format.WriteOptions): JSON; + + /** + * Encode an array of features as GeoJSON. + * @param features Features + * @param options Write options + * @returns GeoJSON + */ + writeFeatures(features: Array, options?: olx.format.WriteOptions): string; + + /** + * Encode an array of features as a GeoJSON object. + * @param features Features + * @param options Write options + * @returns GeoJSON object + */ + writeFeaturesObject(features: Array, options?: olx.format.WriteOptions): JSON; + + /** + * Encode a geometry as a GeoJSON string. + * @param geometry Geometry + * @param options Write options + * @returns GeoJSON + */ + writeGeometry(geometry: ol.geom.Geometry, options?: olx.format.WriteOptions): string; + + /** + * Encode a geometry as a GeoJSON object. + * @param geometry Geometry + * @param options Options + * @options Write options + * @returns GeoJSON object + */ + writeGeometryObject(geometry: ol.geom.Geometry, options?: olx.format.WriteOptions): JSON; + } + + class GML { + } + + class GML2 { + } + + class GML3 { + } + + class GMLBase { + } + + class GPX { + } + + class IGC { + } + + class JSONFeature { + } + + class KML { + } + + class OSMXML { + } + + class Polyline { + } + + class TextFeature { + } + + class TopoJSON { + } + + class WFS { + readFeatures(source: Document | Node | GlobalObject | string, option?: olx.format.ReadOptions): Array; + } + + class WKT { + constructor(opt_options?: olx.format.WKTOptions); + + /** + * Read a feature from a WKT source. + * @param source Source + * @param opt_options Read options + * @returns Feature + */ + readFeature(source: Document | Node | JSON | string, opt_options?: olx.format.ReadOptions): ol.Feature; + + /** + * Read all features from a WKT source. + * @param source Source + * @param options Read options + * @returns Features + */ + readFeatures(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): Array; + + /** + * Read a geometry from a GeoJSON source. + * @param source Source + * @param options Read options + * @returns Geometry + */ + readGeometry(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): ol.geom.Geometry; + + /** + * Encode a feature as a WKT string. + * @param feature Feature + * @param options Write options + * @returns GeoJSON + */ + writeFeature(feature: ol.Feature, options?: olx.format.WriteOptions): string; + + /** + * Encode an array of features as a WKT string. + * @param features Features + * @param options Write options + * @returns GeoJSON + */ + writeFeatures(features: Array, options?: olx.format.WriteOptions): string; + + /** + * Write a single geometry as a WKT string. + * @param geometry Geometry + * @param options Write options + * @returns GeoJSON + */ + writeGeometry(geometry: ol.geom.Geometry, options?: olx.format.WriteOptions): string; + } + + class WMSCapabilities { + } + + class WMSGetFeatureInfo { + } + + class WMTSCapabilities { + } + + class XML { + } + + class XMLFeature { + } + } + + namespace geom { + + // Type definitions + interface GeometryLayout extends String { } + interface GeometryType extends String { } + + /** + * Abstract base class; only used for creating subclasses; do not instantiate + * in apps, as cannot be rendered. + */ + class Circle extends ol.geom.SimpleGeometry { + + constructor(center: ol.Coordinate, opt_radius?: number, opt_layout?: ol.geom.GeometryLayout); + + clone(): ol.geom.Circle; + + getCenter(): ol.Coordinate; + + getRadius(): number; + + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + setCenter(center: ol.Coordinate): void; + + setCenterAndRadius(center: ol.Coordinate, radius: number, opt_layout?: ol.geom.GeometryLayout): void; + + setFlatCoordinates(layout: ol.geom.GeometryLayout, flatCoordinates: number[]): void; + + setRadius(radius: number): void; + + /** + * Transform each coordinate of the circle from one coordinate reference system + * to another. The geometry is modified in place. + * If you do not want the geometry modified in place, first clone() it and + * then use this function on the clone. + * + * Internally a circle is currently represented by two points: the center of + * the circle `[cx, cy]`, and the point to the right of the circle + * `[cx + r, cy]`. This `transform` function just transforms these two points. + * So the resulting geometry is also a circle, and that circle does not + * correspond to the shape that would be obtained by transforming every point + * of the original circle. + * @param source The current projection. Can be a string identifier or a {@link ol.proj.Projection} object. + * @param destination The desired projection. Can be a string identifier or a {@link ol.proj.Projection} object. + * @returns This geometry. Note that original geometry is modified in place. + */ + transform(source: ol.proj.ProjectionLike, destination: ol.proj.ProjectionLike): ol.geom.Circle; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. Base class for vector geometries. + */ + class Geometry extends ol.Object { + + /** + * Return the closest point of the geometry to the passed point as coordinate. + * @param point Point + * @param closestPoint Closest Point + * @returns Closest Point + */ + getClosestPoint(point: ol.Coordinate, closestPoint?: ol.Coordinate): ol.Coordinate; + + /** + * Get the extent of the geometry. + * @param extent Extent + * @returns Extent + */ + getExtent(extent?: ol.Extent): ol.Extent; + + /** + * Transform each coordinate of the geometry from one coordinate reference system to another. + * The geometry is modified in place. For example, a line will be transformed to a line and a + * circle to a circle. If you do not want the geometry modified in place, first clone() it and + * then use this function on the clone. + * @param source The current projection. Can be a string identifier or a ol.proj.Projection object. + * @param destination The desired projection. Can be a string identifier or a ol.proj.Projection object. + * @return This geometry. Note that original geometry is modified in place. + */ + transform(source: ol.proj.ProjectionLike, destination: ol.proj.ProjectionLike): ol.geom.Geometry; + } + + /** + * An array of ol.geom.Geometry objects. + */ + class GeometryCollection extends ol.geom.Geometry { + + /** + * constructor + * @param geometries Geometries. + */ + constructor(geometries?: Array); + + /** + * Apply a transform function to each coordinate of the geometry. The geometry is modified in place. + * If you do not want the geometry modified in place, first clone() it and then use this function on the clone. + * @param transformFn TransformFunction + */ + applyTransform(transformFn: ol.TransformFunction): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.GeometryCollection; + + /** + * Return the geometries that make up this geometry collection. + * @returns Geometries. + */ + getGeometries(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the geometries that make up this geometry collection. + * @param geometries Geometries. + */ + setGeometries(geometries: Array): void; + + translate(deltaX: number, deltaY: number): void; + + } + + /** + * Linear ring geometry. Only used as part of polygon; cannot be rendered + * on its own. + */ + class LinearRing extends SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array, layout?: ol.geom.GeometryLayout); + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.LinearRing; + + /** + * Return the area of the linear ring on projected plane. + * @returns Area (on projected plane). + */ + getArea(): number; + + /** + * Return the coordinates of the linear ring. + * @returns Coordinates. + */ + getCoordinates(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * @Set the coordinates of the linear ring + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array, layout?: any): void; + + } + + /** + * Linestring geometry. + */ + class LineString extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed coordinate to the coordinates of the linestring. + * @param coordinate Coordinate. + */ + appendCoordinate(coordinate: ol.Coordinate): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.LineString; + + /** + * Returns the coordinate at `m` using linear interpolation, or `null` if no + * such coordinate exists. + * + * `extrapolate` controls extrapolation beyond the range of Ms in the + * MultiLineString. If `extrapolate` is `true` then Ms less than the first + * M will return the first coordinate and Ms greater than the last M will + * return the last coordinate. + * + * @param m M. + * @param extrapolate Extrapolate. Default is `false`. + * @returns Coordinate. + */ + getCoordinateAtM(m: number, extrapolate?: boolean): ol.Coordinate; + + /** + * Return the coordinates of the linestring. + * @returns Coordinates. + */ + getCoordinates(): Array; + + /** + * Return the length of the linestring on projected plane. + * @returns Length (on projected plane). + */ + getLength(): number; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the linestring. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Multi-linestring geometry. + */ + class MultiLineString extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array>, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed linestring to the multilinestring. + * @param lineString LineString. + */ + appendLineString(lineString: ol.geom.LineString): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.MultiLineString; + + /** + * Returns the coordinate at `m` using linear interpolation, or `null` if no + * such coordinate exists. + * + * `extrapolate` controls extrapolation beyond the range of Ms in the + * MultiLineString. If `extrapolate` is `true` then Ms less than the first + * M will return the first coordinate and Ms greater than the last M will + * return the last coordinate. + * + * `interpolate` controls interpolation between consecutive LineStrings + * within the MultiLineString. If `interpolate` is `true` the coordinates + * will be linearly interpolated between the last coordinate of one LineString + * and the first coordinate of the next LineString. If `interpolate` is + * `false` then the function will return `null` for Ms falling between + * LineStrings. + * + * @param m M. + * @param extrapolate Extrapolate. Default is `false`. + * @param interpolate Interpolate. Default is `false`. + * @returns Coordinate. + */ + getCoordinateAtM(m: number, extrapolate?: boolean, interpolate?: boolean): ol.Coordinate; + + /** + * Return the coordinates of the multilinestring. + * @returns Coordinates. + */ + getCoordinates(): Array>; + + /** + * Return the linestring at the specified index. + * @param index Index. + * @returns LineString. + */ + getLineString(index: number): ol.geom.LineString; + + /** + * Return the linestrings of this multilinestring. + * @returns LineStrings. + */ + getLineStrings(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the multilinestring. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array>, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Multi-point geometry. + */ + class MultiPoint extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed point to this multipoint. + * @param {ol.geom.Point} point Point. + */ + appendPoint(point: ol.geom.Point): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.MultiPoint; + + /** + * Return the coordinates of the multipoint. + * @returns Coordinates. + */ + getCoordinates(): Array; + + /** + * Return the point at the specified index. + * @param index Index. + * @returns Point. + */ + getPoint(index: number): ol.geom.Point; + + /** + * Return the points of this multipoint. + * @returns Points. + */ + getPoints(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the multipoint. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Multi-polygon geometry. + */ + class MultiPolygon extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array>>, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed polygon to this multipolygon. + * @param polygon Polygon. + */ + appendPolygon(polygon: ol.geom.Polygon): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.MultiPolygon; + + /** + * Return the area of the multipolygon on projected plane. + * @returns Area (on projected plane). + */ + getArea(): number; + + /** + * Get the coordinate array for this geometry. This array has the structure + * of a GeoJSON coordinate array for multi-polygons. + * + * @param right Orient coordinates according to the right-hand + * rule (counter-clockwise for exterior and clockwise for interior rings). + * If `false`, coordinates will be oriented according to the left-hand rule + * (clockwise for exterior and counter-clockwise for interior rings). + * By default, coordinate orientation will depend on how the geometry was + * constructed. + * @returns Coordinates. + */ + getCoordinates(right?: boolean): Array>>; + + /** + * Return the interior points as {@link ol.geom.MultiPoint multipoint}. + * @returns Interior points. + */ + getInteriorPoints(): ol.geom.MultiPoint; + + /** + * Return the polygon at the specified index. + * @param index Index. + * @returns Polygon. + */ + getPolygon(index: number): ol.geom.Polygon; + + /** + * Return the polygons of this multipolygon. + * @returns Polygons. + */ + getPolygons(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the multipolygon. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array>>, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Point geometry. + */ + class Point extends SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: ol.Coordinate, layout?: ol.geom.GeometryLayout); + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.Point; + + /** + * Return the coordinate of the point. + * @returns Coordinates. + */ + getCoordinates(): ol.Coordinate; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinate of the point. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: ol.Coordinate, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Polygon geometry. + */ + class Polygon extends SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param opt_layout Layout. + */ + constructor(coordinates: Array>, opt_layout?: ol.geom.GeometryLayout); + + /** + * Create an approximation of a circle on the surface of a sphere. + * @param sphere The sphere. + * @param center Center (`[lon, lat]` in degrees). + * @param radius The great-circle distance from the center to the polygon vertices. + * @param opt_n Optional number of vertices for the resulting polygon. Default is `32`. + * @returns The "circular" polygon. + */ + static circular(sphere: ol.Sphere, center: ol.Coordinate, radius: number, opt_n?: number): ol.geom.Polygon; + + static fromCircle(circle: ol.geom.Circle, opt_sides?: number, opt_angle?: number): ol.geom.Polygon; + + static fromExtent(extent: ol.Extent): ol.geom.Polygon; + + /** + * Append the passed linear ring to this polygon. + * @param linearRing Linear ring. + */ + appendLinearRing(linearRing: ol.geom.LinearRing): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.Polygon; + + /** + * Return the area of the polygon on projected plane. + * @returns Area (on projected plane). + */ + getArea(): number; + + /** + * Get the coordinate array for this geometry. This array has the structure + * of a GeoJSON coordinate array for polygons. + * + * @param opt_right Orient coordinates according to the right-hand + * rule (counter-clockwise for exterior and clockwise for interior rings). + * If `false`, coordinates will be oriented according to the left-hand rule + * (clockwise for exterior and counter-clockwise for interior rings). + * By default, coordinate orientation will depend on how the geometry was + * constructed. + * @returns Coordinates. + */ + getCoordinates(opt_right?: boolean): Array>; + + /** + * Return an interior point of the polygon. + * @returns Interior point. + */ + getInteriorPoint(): ol.geom.Point; + + /** + * Return the Nth linear ring of the polygon geometry. Return `null` if the + * given index is out of range. + * The exterior linear ring is available at index `0` and the interior rings + * at index `1` and beyond. + * + * @param index Index. + * @returns Linear ring. + */ + getLinearRing(index: number): ol.geom.LinearRing; + + getLinearRingCount(): number; + + /** + * Return the linear rings of the polygon. + * @returns Linear rings. + */ + getLinearRings(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the polygon. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array>, layout?: ol.geom.GeometryLayout): void; + } + /** + * Abstract base class; only used for creating subclasses; do not instantiate + * in apps, as cannot be rendered. + */ + class SimpleGeometry extends ol.geom.Geometry { + + /** + * Apply a transform function to each coordinate of the geometry. The geometry is modified in place. + * If you do not want the geometry modified in place, first clone() it and then use this function on the clone. + * @param transformFn TransformFunction + */ + applyTransform(transformFn: ol.TransformFunction): void; + + /** + * Return the first coordinate of the geometry. + * @returns First coordinate. + */ + getFirstCoordinate(): ol.Coordinate; + + /** + * Return the last coordinate of the geometry. + * @returns Last point. + */ + getLastCoordinate(): ol.Coordinate; + + /** + * Return the {@link ol.geom.GeometryLayout layout} of the geometry. + * @returns Layout. + */ + getLayout(): ol.geom.GeometryLayout; + + /** + * Translate the geometry. This modifies the geometry coordinates in place. + * If instead you want a new geometry, first clone() this geometry. + * @param deltaX Delta X + * @param deltaY Delta Y + */ + translate(deltaX: number, deltaY: number): void; + } + } + + namespace has { + } + + namespace interaction { + + class DoubleClickZoom extends ol.interaction.Interaction { + } + + class DragAndDrop extends ol.interaction.Interaction { + } + + class DragAndDropEvent extends ol.events.Event { + } + + class DragBox extends ol.interaction.Pointer { + constructor (opt_options?: olx.interaction.DragBoxOptions) + getGeometry (): ol.geom.Polygon + } + + class DragPan extends ol.interaction.Pointer { + } + + class DragRotate extends ol.interaction.Pointer { + } + + class DragRotateAndZoom extends ol.interaction.Pointer { + } + + class DragZoom extends ol.interaction.DragBox { + } + + class Draw extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DrawOptions) + } + + class DrawEvent extends ol.events.Event { + constructor (type: ol.interaction.DrawEventType, feature: ol.Feature) + feature: ol.Feature + } + + class Interaction extends ol.Object { + constructor (options: olx.interaction.InteractionOptions) + handleEvent (e: ol.MapBrowserEvent): boolean + getActive (): boolean; + getMap (): ol.Map; + setActive (active: boolean): void; + } + + class KeyboardPan extends ol.interaction.Interaction { + } + + class KeyboardZoom extends ol.interaction.Interaction { + } + + class Modify extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.ModifyOptions) + } + + class ModifyEvent extends ol.events.Event { + constructor ( + type: ol.ModifyEventType, + features: ol.Collection, + mapBrowserPointerEvent: ol.MapBrowserPointerEvent + ) + features: ol.Collection; + mapBrowserPointerEvent: ol.MapBrowserPointerEvent; + } + + class MouseWheelZoom extends ol.interaction.Interaction { + } + + class PinchRotate extends ol.interaction.Pointer { + } + + class PinchZoom extends ol.interaction.Pointer { + } + + class Pointer extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.PointerOptions) + handleEvent(mapBrowserEvent: ol.MapBrowserEvent): boolean + } + + class Select extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.SelectOptions); + getLayer(): ol.layer.Layer; + getFeatures(): ol.Collection; + } + + class Snap extends ol.interaction.Pointer { + } + + class Translate extends ol.interaction.Pointer { + } + + class TranslateEvent extends ol.events.Event { + } + + function defaults(opts: olx.interaction.DefaultsOptions): ol.Collection; + + interface DragBoxEndConditionType { + (evt: ol.MapBrowserEvent, startPixel: ol.Pixel, endPixel: ol.Pixel): boolean + } + + interface DrawGeometryFunctionType { + (coordinates: ol.Coordinate | Array | Array>, geom?: ol.geom.SimpleGeometry): ol.geom.SimpleGeometry; + } + + interface SelectFilterFunction { (feature: ol.Feature | ol.render.Feature, layer: ol.layer.Layer): boolean; } + + interface DrawEventType extends String { + DRAWSTART: any; + DRAWEND: any; + } + } + + namespace layer { + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. Note that with ol.layer.Base and all its subclasses, any property set in the options is set as a ol.Object property on the layer object, so is observable, and has get/set accessors. + */ + class Base extends ol.Object { + + /** + * @constructor + * @param options Layer options. + */ + constructor(options?: olx.layer.BaseOptions); + + /** + * Return the brightness of the layer. + * @returns The brightness of the layer. + */ + getBrightness(): number; + + /** + * Return the contrast of the layer. + * @returns The contrast of the layer. + */ + getContrast(): number; + + /** + * Return the extent of the layer or undefined if it will be visible regardless of extent. + * @returns The layer extent. + */ + getExtent(): ol.Extent; + + /** + * Return the hue of the layer. + * @returns The hue of the layer + */ + getHue(): number; + + /** + * Return the maximum resolution of the layer. + * @returns The maximum resolution of the layer + */ + getMaxResolution(): number; + + /** + * Return the minimum resolution of the layer. + * @returns The minimum resolution of the layer. + */ + getMinResolution(): number; + + /** + * Return the opacity of the layer (between 0 and 1). + * @returns The opacity of the layer. + */ + getOpacity(): number; + + /** + * Return the saturation of the layer. + * @returns The saturation of the layer. + */ + getSaturation(): number; + + /** + * Return the visibility of the layer (true or false). + * The visibility of the layer + */ + getVisible(): boolean; + + /** + * Adjust the layer brightness. A value of -1 will render the layer completely black. A value of 0 will leave the brightness unchanged. A value of 1 will render the layer completely white. Other values are linear multipliers on the effect (values are clamped between -1 and 1). + * @param brightness The brightness of the layer + */ + setBrightness(brightness: number): void; + + /** + * Adjust the layer contrast. A value of 0 will render the layer completely grey. A value of 1 will leave the contrast unchanged. Other values are linear multipliers on the effect (and values over 1 are permitted). + * @param contrast The contrast of the layer + */ + setContrast(contrast: number): void; + + /** + * Set the extent at which the layer is visible. If undefined, the layer will be visible at all extents. + * @param extent The extent of the layer + */ + setExtent(extent?: ol.Extent): void; + + /** + * Apply a hue-rotation to the layer. A value of 0 will leave the hue unchanged. Other values are radians around the color circle. + * @param hue The hue of the layer + */ + setHue(hue: number): void; + + /** + * Set the maximum resolution at which the layer is visible. + * @param maxResolution The maximum resolution of the layer. + */ + setMaxResolution(maxResolution: number): void; + + /** + * Set the minimum resolution at which the layer is visible. + * @param minResolution The minimum resolution of the layer. + */ + setMinResolution(minResolution: number): void; + + /** + * Set the opacity of the layer, allowed values range from 0 to 1. + * @param opacity The opacity of the layer. + */ + setOpacity(opacity: number): void; + + /** + * Adjust layer saturation. A value of 0 will render the layer completely unsaturated. A value of 1 will leave the saturation unchanged. Other values are linear multipliers of the effect (and values over 1 are permitted). + * @param saturation The saturation of the layer. + */ + setSaturation(saturation: number): void; + + /** + * Set the visibility of the layer (true or false). + * @param visible The visibility of the layer. + */ + setVisible(visible: boolean): void; + } + + /** + * A ol.Collection of layers that are handled together. + */ + class Group extends ol.layer.Base { + + /** + * @constructor + * @param options Layer options. + */ + constructor(options?: olx.layer.GroupOptions); + + /** + * Returns the collection of layers in this group. + * @returns Collection of layers that are part of this group. + */ + getLayers(): ol.Collection; + + /** + * Set the collection of layers in this group. + * @param layers Collection of layers that are part of this group. + */ + setLayers(layers: ol.Collection): void; + } + + /** + * Layer for rendering vector data as a heatmap. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Heatmap extends ol.layer.Vector { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.layer.HeatmapOptions); + + /** + * Return the blur size in pixels. + * @returns Blur size in pixels + */ + getBlur(): number; + + /** + * Return the gradient colors as array of strings. + * @returns Colors + */ + getGradient(): Array; + + /** + * Return the size of the radius in pixels. + * @returns Radius size in pixel + */ + getRadius(): number; + + /** + * Set the blur size in pixels. + * @param blur Blur size in pixels + */ + setBlur(blur: number): void; + + /** + * Set the gradient colors as array of strings. + * @param colors Gradient + */ + setGradient(colors: Array): void; + + /** + * Set the size of the radius in pixels. + * @param radius Radius size in pixels + */ + setRadius(radius: number): void; + } + + /** + * Server-rendered images that are available for arbitrary extents and resolutions. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Image extends ol.layer.Layer { + + /** + * @constructor + * @param options Layer options + */ + constructor(options?: olx.layer.ImageOptions); + + /** + * Return the associated source of the image layer. + * @returns Source. + */ + getSource(): ol.source.Image; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. A visual representation of raster or vector map data. Layers group together those properties that pertain to how the data is to be displayed, irrespective of the source of that data. + */ + class Layer extends ol.layer.Base { + + /** + * @constructor + * @param options Layer options + */ + constructor(options?: olx.layer.LayerOptions); + + /** + * Get the layer source. + * @returns The layer source (or null if not yet set) + */ + getSource(): ol.source.Source; + + /** + * Set the layer source. + * @param source The layer source. + */ + setSource(source: ol.source.Source): void; + } + + /** + * For layer sources that provide pre-rendered, tiled images in grids that are organized by zoom levels for specific resolutions. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Tile extends ol.layer.Layer { + + /** + * @constructor + * @param options Tile layer options. + */ + constructor(options?: olx.layer.TileOptions); + + /** + * Return the level as number to which we will preload tiles up to. + * @retruns The level to preload tiled up to. + */ + getPreload(): number; + + /** + * Return the associated tilesource of the layer. + * @returns Source + */ + getSource(): ol.source.Tile; + + /** + * Whether we use interim tiles on error. + * @returns Use interim tiles on error. + */ + getUseInterimTilesOnError(): boolean; + + /** + * Set the level as number to which we will preload tiles up to. + * @param preload The level to preload tiled up to + */ + setPreload(preload: number): void; + + /** + * Set whether we use interim tiles on error. + * @param useInterimTilesOnError Use interim tiles on error. + */ + setUseInterimTilesOnError(useInterimTilesOnError: boolean): void; + } + + /** + * Vector data that is rendered client-side. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Vector extends ol.layer.Layer { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.layer.VectorOptions); + + /** + * Return the associated vectorsource of the layer. + * @returns Source. + */ + getSource(): ol.source.Vector; + + /** + * Get the style for features. This returns whatever was passed to the style option at construction or to the setStyle method. + */ + getStyle(): ol.style.Style | Array | ol.style.StyleFunction; + + /** + * Get the style function. + * @returns Layer style function + */ + getStyleFunction(): ol.style.StyleFunction; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + */ + setStyle(): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + * @param style Layer style + */ + setStyle(style: ol.style.Style): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + * @param style Layer style + */ + setStyle(style: Array): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + * @param style Layer style + */ + setStyle(style: ol.style.StyleFunction): void; + + /** + * Sets the layer to be rendered on top of other layers on a map. The map will not manage this layer + * in its layers collection, and the callback in ol.Map#forEachLayerAtPixel will receive null as + * layer. This is useful for temporary layers. To remove an unmanaged layer from the map, use #setMap(null). + * To add the layer to a map and have it managed by the map, use ol.Map#addLayer instead. + * @argument map. + */ + setMap(map: ol.Map): void; + } + } + + namespace loadingstrategy { + + /** + * Strategy function for loading all features with a single request. + * @param extent Extent + * @param resolution Resolution + * @returns Extents + */ + function all(extent: ol.Extent, resolution: number): Array; + + /** + * Strategy function for loading features based on the view's extent and resolution. + * @param extent Extent + * @param resolution Resolution + * @returns Extents + */ + function bbox(extent: ol.Extent, resolution: number): Array; + + /** + * Creates a strategy function for loading features based on a tile grid. + * @param tileGrid Tile grid + * @returns Loading strategy + */ + function tile(tileGrid: ol.tilegrid.TileGrid): ol.LoadingStrategy; + } + + namespace pointer { + + class PointerEvent { + constructor (type: string, + originalEvent: Event, + opt_eventDict?: {[x: string]: any}) + originalEvent: Event; + buttons: number; + pressure: number; + bubbles: boolean; + cancelable: boolean; + view: Object; + detail: number; + screenX: number; + screenY: number; + clientX: number; + clientY: number; + ctrlKey: boolean; + altKey: boolean; + shiftKey: boolean; + metaKey: boolean; + button: number; + relatedTarget: Node; + pointerId: number; + width: number; + height: number; + tiltX: number; + tiltY: number; + pointerType: string; + hwTimestamp: number; + isPrimary: boolean; + preventDefault: () => void; + } + + } + + namespace proj { + + // Type definitions + interface ProjectionLike extends String { } + interface Units extends String { } + + // Methods + + /** + * Meters per unit lookup table. + */ + //TODO: validate! + var METERS_PER_UNIT: GlobalObject; + + /** + * Registers coordinate transform functions to convert coordinates between the source projection and the destination projection. The forward and inverse functions convert coordinate pairs; this function converts these into the functions used internally which also handle extents and coordinate arrays. + * @param source Source projection + * @param destination Destination projection + * @param forward The forward transform function (that is, from the source projection to the destination projection) that takes a ol.Coordinate as argument and returns the transformed ol.Coordinate. + * @param inverse The inverse transform function (that is, from the destination projection to the source projection) that takes a ol.Coordinate as argument and returns the transformed ol.Coordinate. + */ + function addCoordinateTransforms(source: ProjectionLike, destination: ProjectionLike, forward: (coordinate: Coordinate) => Coordinate, inverse: (coordinate: Coordinate) => Coordinate): void; + + /** + * Registers transformation functions that don't alter coordinates. Those allow to transform between projections with equal meaning. + * @param projections Projections. + */ + function addEquivalentProjections(projections: Array): void; + + /** + * Add a Projection object to the list of supported projections that can be looked up by their code. + * @param projection Projection instance. + */ + function addProjection(projection: Projection): void; + + /** + * Transforms a coordinate from longitude/latitude to a different projection. + * @param coordinate Coordinate as longitude and latitude, i.e. an array with longitude as 1st and latitude as 2nd element. + * @param opt_projection Target projection. The default is Web Mercator, i.e. 'EPSG:3857'. + */ + function fromLonLat(coordinate: Coordinate, opt_projection: ProjectionLike): Coordinate; + + /** + * Fetches a Projection object for the code specified. + * @param projectionLike Either a code string which is a combination of authority and identifier such as "EPSG:4326", or an existing projection object, or undefined. + * @returns Projection object, or null if not in list. + */ + function get(projectionLike: ProjectionLike): Projection; + + /** + * Given the projection-like objects, searches for a transformation function to convert a coordinates array from the source projection to the destination projection. + * @param source Source. + * @param destination Destination. + * @returns Transform function. + */ + function getTransform(source: ProjectionLike, destination: ProjectionLike): ol.TransformFunction; + + /** + * Transforms a coordinate to longitude/latitude. + * @param coordinate Projected coordinate. + * @param projection Projection of the coordinate. The default is Web Mercator, i.e. 'EPSG:3857'. + * @returns Coordinate as longitude and latitude, i.e. an array with longitude as 1st and latitude as 2nd element. + */ + function toLonLat(coordinate: Coordinate, projection: ProjectionLike): Coordinate; + + /** + * Transforms a coordinate from source projection to destination projection. This returns a new coordinate (and does not modify the original). + * @param coordinate Coordinate. + * @param source Source projection-like. + * @param destination Destination projection-like. + * @returns Coordinate. + */ + function transform(coordinate: Coordinate, source: ProjectionLike, destination: ProjectionLike): Coordinate; + + /** + * Transforms an extent from source projection to destination projection. This returns a new extent (and does not modify the original). + * @param extent The extent to transform. + * @param source Source projection-like. + * @param destination Destination projection-like. + * @returns The transformed extent. + */ + function transformExtent(extent: Extent, source: ProjectionLike, destination: ProjectionLike): Extent; + + class Projection { + constructor(options: olx.Projection); + + getExtent(): Extent; + + /** + * Set the validity extent for this projection. + * @param extent The new extent of the projection. + */ + setExtent(extent: Extent): void; + + getCode(): string; + + getMetersPerUnit(): number; + + getPointResolution(resolution: number, point: ol.Coordinate): number; + + getUnits(): ol.proj.Units; + + getWorldExtent(): ol.Extent; + + isGlobal(): boolean; + + setGetPointResolution(func: (n: number, c: ol.Coordinate) => number): void; + + setGlobal(global: boolean): void; + + setWorldExtent(worldExtent: ol.Extent): void; + } + } + + namespace render { + + class Event { + } + + class VectorContext { + } + class Feature { + get(key: string): any; + getExtent(): ol.Extent; + getGeometry(): ol.geom.Geometry; + getProperties: GlobalObject[]; + getType(): ol.geom.GeometryType; + } + namespace canvas { + class Immediate { + } + } + } + + namespace source { + + class BingMaps extends TileImage { + } + + class CartoDB extends XYZ { + } + + class Cluster extends Vector { + } + + class Image extends Source { + } + + class ImageArcGISRest extends Image { + } + + class ImageCanvas extends Image { + } + + class ImageEvent { + } + + class ImageMapGuide extends Image { + } + + class ImageStatic extends Image { + } + + class ImageVector extends ImageCanvas { + } + + class ImageWMS extends Image { + constructor(options: olx.ImageWMSOptions); + } + + class MapQuest extends XYZ { + constructor(options: any); + } + + class OSM extends XYZ { + } + + class Source extends ol.Object { + getAttributions(): Array; + + getLogo(): string | olx.LogoOptions | void; + + /** + * Get the projection of the source. + * @return Projection. + */ + getProjection(): ol.proj.Projection; + + getState(): ol.source.State; + + setAttributions(attributions: Array): void; + } + + class Stamen extends XYZ { + } + + class Tile extends Source { + } + + class TileArcGISRest extends TileImage { + } + + class TileDebug extends Tile { + } + + class TileEvent { + } + + class TileImage extends UrlTile { + } + + class TileJSON extends TileImage { + } + + class TileUTFGrid extends Tile { + } + + class TileWMS extends TileImage { + constructor(options: olx.TileWMSOptions); + + /** + * Update the user-provided (WMS request) parameters. + */ + updateParams(params: any): void; + + /** + * Get the user-provided (WMS request) params, i.e. those passed to the constructor through the "params" option, and possibly updated using the updateParams method. + */ + getParams(): any; + + /** + * Return the GetFeatureInfo URL for the passed coordinate, resolution, and + * projection. Return `undefined` if the GetFeatureInfo URL cannot be + * constructed. + * @param coordinate Coordinate. + * @param resolution Resolution. + * @param projection Projection. + * @param params GetFeatureInfo params. `INFO_FORMAT` at least should + * be provided. If `QUERY_LAYERS` is not provided then the layers specified + * in the `LAYERS` parameter will be used. `VERSION` should not be + * specified here. + * @return GetFeatureInfo URL. + */ + getGetFeatureInfoUrl(coordinate: ol.Coordinate, resolution: number, projection: ol.proj.ProjectionLike, params: {}): string; + } + + class UrlTile extends Tile { + } + + class Vector extends Source { + constructor(opts?: olx.source.VectorOptions) + /** + * Add a single feature to the source. If you want to add a batch of features at once, + * call source.addFeatures() instead. + */ + addFeature(feature: ol.Feature): void; + + /** + * Add a batch of features to the source. + */ + addFeatures(features: ol.Feature[]): void; + + /** + * Remove all features from the source. + * @param opt_fast Skip dispatching of removefeature events. + */ + clear(opt_fast?: boolean): void; + + forEachFeature(callback: (f: ol.Feature) => any, opt_this?: any): any; + + forEachFeatureInExtent(extent: ol.Extent, callback: (f: ol.Feature) => any, opt_this?: any): any; + + forEachFeatureIntersectingExtent(extent: ol.Extent, callback: (f: ol.Feature) => any, opt_this?: any): any; + + getClosestFeatureToCoordinate(coordinate: ol.Coordinate): ol.Feature; + + /** + * Get the extent of the features currently in the source. + */ + getExtent(): ol.Extent; + + getFeatureById(id: string | number): ol.Feature; + + /** + * Get all features on the source + */ + getFeatures(): ol.Feature[]; + + /** + * Get all features whose geometry intersects the provided coordinate. + */ + getFeaturesAtCoordinate(coordinate: ol.Coordinate): ol.Feature[]; + + getFeaturesCollection(): ol.Collection; + + /** + * Get all features in the provided extent. Note that this returns all features whose bounding boxes + * intersect the given extent (so it may include features whose geometries do not intersect the extent). + * This method is not available when the source is configured with useSpatialIndex set to false. + */ + getFeaturesInExtent(extent: ol.Extent): ol.Feature[]; + + removeFeature(feature: ol.Feature): void; + } + + class VectorEvent { + } + + class VectorTile extends UrlTile { + } + + class WMTS extends TileImage { + constructor(options: olx.source.WMTSOptions); + } + + class XYZ extends TileImage { + } + + class Zoomify extends TileImage { + } + + // Namespaces + namespace wms { + interface ServerType extends String { } + } + + // Type definitions + interface State extends String { } + interface WMTSRequestEncoding extends String { } + } + + namespace style { + + class AtlasManager { + } + + class Circle extends Image { + constructor(opt_options?: olx.style.CircleOptions); + } + + /** + * Set fill style for vector features. + */ + class Fill { + + constructor(opt_options?: olx.style.FillOptions); + + getColor(): ol.Color | string; + + /** + * Set the color. + */ + setColor(color: ol.Color | string): void; + + getChecksum(): string; + } + + class Icon extends Image { + constructor(option: olx.style.IconOptions) + } + + class Image { + getOpacity(): number; + getRotateWithView(): boolean; + getRotation(): number; + getScale(): number; + getSnapToPiexl(): boolean; + + setOpacity(opacity: number): void; + setRotation(rotation: number): void; + setScale(scale: number): void; + } + + interface GeometryFunction { + (feature: Feature): ol.geom.Geometry + } + + class RegularShape { + } + + class Stroke { + constructor(opts?: olx.style.StrokeOptions); + getColor(): ol.Color | string; + getLineCap(): string; + getLineDash(): number[]; + getLineJoin(): string; + getMitterLimit(): number; + getWidth(): number; + setColor(color: ol.Color | string): void; + setLineCap(lineCap: string): void; + setLineDash(lineDash: number[]): void; + setLineJoin(lineJoin: string): void; + setMiterLimit(miterLimit: number): void; + setWidth(width: number): void; + } + + /** + * Container for vector feature rendering styles. Any changes made to the style + * or its children through `set*()` methods will not take effect until the + * feature, layer or FeatureOverlay that uses the style is re-rendered. + */ + class Style { + constructor(opts: olx.style.StyleOptions); + + getFill(): ol.style.Fill; + /*** + * Get the geometry to be rendered. + * @return Feature property or geometry or function that returns the geometry that will + * be rendered with this style. + */ + getGeometry(): string | ol.geom.Geometry | ol.style.GeometryFunction; + getGeometryFunction(): ol.style.GeometryFunction; + getImage(): ol.style.Image; + getStroke(): ol.style.Stroke; + getText(): ol.style.Text; + getZIndex(): number; + + setGeometry(geometry: string | ol.geom.Geometry | ol.style.GeometryFunction): void; + setZIndex(zIndex: number): void; + } + + /** + * Set text style for vector features. + */ + class Text { + constructor(opt?: olx.style.TextOptions); + + getFont(): string; + getOffsetX(): number; + getOffsetY(): number; + getFill(): Fill; + getRotation(): number; + getScale(): number; + getStroke(): Stroke; + getText(): string; + getTextAlign(): string; + getTextBaseline(): string; + + /** + * Set the font. + */ + setFont(font: string): void; + + /** + * Set the x offset. + */ + setOffsetX(offsetX: number): void; + + /** + * Set the y offset. + */ + setOffsetY(offsetY: number): void; + + /** + * Set the fill. + */ + setFill(fill: Fill): void; + + /** + * Set the rotation. + */ + setRotation(rotation: number): void; + + /** + * Set the scale. + */ + setScale(scale: number): void; + + /** + * Set the stroke. + * + */ + setStroke(stroke: Stroke): void; + + /** + * Set the text. + */ + setText(text: string): void; + + /** + * Set the text alignment. + */ + setTextAlign(textAlign: string): void; + + /** + * Set the text baseline. + */ + setTextBaseline(textBaseline: string): void; + } + + /** + * A function that takes an ol.Feature and a {number} representing the view's resolution. The function should return an array of ol.style.Style. This way e.g. a vector layer can be styled. + */ + interface StyleFunction { (feature: ol.Feature, resolution: number): ol.style.Style } + } + + namespace tilegrid { + + /** + * Base class for setting the grid pattern for sources accessing tiled-image servers. + */ + class TileGrid { + + /** + * @constructor + * @param options Tile grid options + */ + constructor(options: olx.tilegrid.TileGridOptions); + + /** + * Creates a TileCoord transform function for use with this tile grid. Transforms the internal tile coordinates with bottom-left origin to the tile coordinates used by the ol.TileUrlFunction. The returned function expects an ol.TileCoord as first and an ol.proj.Projection as second argument and returns a transformed ol.TileCoord. + */ + createTileCoordTransform(): { (tilecoord: ol.TileCoord, projection: ol.proj.Projection): ol.TileCoord }; + + /** + * Get the maximum zoom level for the grid. + * @returns Max zoom + */ + getMaxZoom(): number; + + /** + * Get the minimum zoom level for the grid. + * @returns Min zoom + */ + getMinZoom(): number; + + /** + * Get the origin for the grid at the given zoom level. + * @param z Z + * @returns Origin + */ + getOrigin(z: number): ol.Coordinate; + + /** + * Get the list of resolutions for the tile grid. + * @param z Z + * @returns Resolution + */ + getResolution(z: number): number; + + /** + * Get the list of resolutions for the tile grid. + * @returns Resolutions + */ + getResolutions(): Array; + + /** + * Get the tile coordinate for the given map coordinate and resolution. This method considers that coordinates that intersect tile boundaries should be assigned the higher tile coordinate. + * @param coordinate Coordinate + * @param resolution Resolution + * @param tileCoord Destination ol.TileCoord object. + * @returns Tile coordinate + */ + getTileCoordForCoordAndResolution(coordinate: ol.Coordinate, resolution: number, tileCoord?: ol.TileCoord): ol.TileCoord; + + /** + * Get a tile coordinate given a map coordinate and zoom level. + * @param coordinate Coordinate + * @param z Zoom level + * @param tileCoord Destination ol.TileCoord object + * @returns Tile coordinate + */ + getTileCoordForCoordAndZ(coordinate: ol.Coordinate, z: number, tileCoord?: ol.TileCoord): ol.TileCoord; + + /** + * Get the tile size for a zoom level. The type of the return value matches the tileSize or tileSizes that the tile grid was configured with. To always get an ol.Size, run the result through ol.size.toSize(). + * @param z Z + * @returns Tile size + */ + getTileSize(z: number): number | ol.Size; + } + + /** + * Set the grid pattern for sources accessing WMTS tiled-image servers. + */ + class WMTS extends TileGrid { + + /** + * @constructor + * @param options WMTS options + */ + constructor(options: olx.tilegrid.WMTSOptions); + + /** + * Create a tile grid from a WMTS capabilities matrix set. + * @param matrixSet An object representing a matrixSet in the capabilities document. + * @param extent An optional extent to restrict the tile ranges the server provides. + * @returns WMTS tilegrid instance + */ + createFromCapabilitiesMatrixSet(matrixSet: any, extent: ol.Extent): ol.tilegrid.WMTS; + + /** + * Get the list of matrix identifiers. + * @returns MatrixIds + */ + getMatrixIds(): Array; + } + + /** + * Set the grid pattern for sources accessing Zoomify tiled-image servers. + */ + class Zoomify extends TileGrid { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.tilegrid.ZoomifyOptions); + } + + /** + * Creates a tile grid with a standard XYZ tiling scheme. + * @param options Tile grid options. + * @returns The grid instance + */ + function createXYZ(options?: olx.tilegrid.XYZOptions): ol.tilegrid.TileGrid; + } + + namespace webgl { + + class Context { + + /** + * @constructor + * @param canvas HTML Canvas Element + * @param gl WebGL Rendering context + */ + constructor(canvas: HTMLCanvasElement, gl: WebGLRenderingContext); + + /** + Get the WebGL rendering context + @returns The rendering context. + */ + getGL(): WebGLRenderingContext; + + /** + * Get the frame buffer for hit detection. + * @returns The hit detection frame buffer. + */ + getHitDetectionFramebuffer(): WebGLFramebuffer; + + /** + * Use a program. If the program is already in use, this will return false. + * @param program Program. + * @returns Changed. + */ + useProgram(program: WebGLProgram): boolean; + } + } + + // Type definitions + + /** + * A function returning the canvas element ({HTMLCanvasElement}) used by the source as an image. The arguments passed to the function are: ol.Extent the image extent, {number} the image resolution, {number} the device pixel ratio, ol.Size the image size, and ol.proj.Projection the image projection. The canvas returned by this function is cached by the source. The this keyword inside the function references the ol.source.ImageCanvas. + */ + function CanvasFunctionType(extent: Extent, resolution: number, pixelRatio: number, size: Size, projection: proj.Projection): HTMLCanvasElement; + + /** + * A color represented as a short array [red, green, blue, alpha]. red, green, and blue should be integers in the range 0..255 inclusive. alpha should be a float in the range 0..1 inclusive. + */ + interface Color extends Array { } + + /** + * An array of numbers representing an xy coordinate. Example: [16, 48]. + */ + interface Coordinate extends Array { } + + /** + * An array of numbers representing an extent: [minx, miny, maxx, maxy]. + */ + interface Extent extends Array { } + + /** + * Overlay position: 'bottom-left', 'bottom-center', 'bottom-right', 'center-left', 'center-center', 'center-right', 'top-left', 'top-center', 'top-right' + */ + interface OverlayPositioning extends String { } + + /** + * An array with two elements, representing a pixel. The first element is the x-coordinate, the second the y-coordinate of the pixel. + */ + interface Pixel extends Array { } + + /** + * Available renderers: 'canvas', 'dom' or 'webgl'. + */ + interface RendererType extends String { } + + /** + * An array of numbers representing a size: [width, height]. + */ + interface Size extends Array { } + + /** + * An array of three numbers representing the location of a tile in a tile grid. The order is z, x, and y. z is the zoom level. + */ + interface TileCoord extends Array { } + + // Functions + + /** + * A function that takes a ol.Coordinate and transforms it into a {string}. + */ + interface CoordinateFormatType { (coordinate?: Coordinate): string; } + + /** + * Implementation based on the code of OpenLayers, no documentation available (yet). If it is incorrect, please create an issue and I will change it. + */ + interface FeatureLoader { (extent: ol.Extent, number: number, projection: ol.proj.Projection): string } + + /** + * A function that returns a style given a resolution. The this keyword inside the function references the ol.Feature to be styled. + */ + interface FeatureStyleFunction { (resolution: number): ol.style.Style } + + /** + * Loading strategy + */ + interface LoadingStrategy { (extent: ol.Extent, resolution: number): Array } + + /** + * Function to perform manipulations before rendering. This function is called with the ol.Map as first and an optional olx.FrameState as second argument. Return true to keep this function for the next frame, false to remove it. + */ + interface PreRenderFunction { (map: ol.Map, frameState?: olx.FrameState): boolean } + + /** + * A transform function accepts an array of input coordinate values, an optional output array, and an optional dimension (default should be 2). The function transforms the input coordinate values, populates the output array, and returns the output array. + */ + interface TransformFunction { (input: Array, output?: Array, dimension?: number): Array } +} + +declare module "openlayers" { + export = ol; +} diff --git a/pako/index.d.ts b/pako/index.d.ts index 572fe99c9f..e4f74c1ff0 100644 --- a/pako/index.d.ts +++ b/pako/index.d.ts @@ -7,7 +7,6 @@ export = Pako; export as namespace pako; declare namespace Pako { - /** * Compress data with deflate algorithm and options. */ diff --git a/parse/index.d.ts b/parse/index.d.ts index 1e8bdab69e..29d168c82d 100644 --- a/parse/index.d.ts +++ b/parse/index.d.ts @@ -26,6 +26,10 @@ declare namespace Parse { interface SuccessFailureOptions extends SuccessOption, ErrorOption { } + interface SessionTokenOption { + sessionToken?: string; + } + interface WaitOption { /** * Set to true to wait for the server to confirm success @@ -67,29 +71,30 @@ declare namespace Parse { interface IPromise { - then(resolvedCallback: (value: T) => IPromise, rejectedCallback?: (reason: any) => IPromise): IPromise; - then(resolvedCallback: (value: T) => U, rejectedCallback?: (reason: any) => IPromise): IPromise; - then(resolvedCallback: (value: T) => U, rejectedCallback?: (reason: any) => U): IPromise; + then(resolvedCallback: (...values: T[]) => IPromise, rejectedCallback?: (reason: any) => IPromise): IPromise; + then(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => IPromise): IPromise; + then(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => U): IPromise; } - class Promise { + class Promise implements IPromise { static as(resolvedValue: U): Promise; - static error(error: U): Promise; + static error(error: U): Promise; static is(possiblePromise: any): Boolean; - static when(promises: Promise[]): Promise; + static when(promises: IPromise[]): Promise; + static when(...promises: IPromise[]): Promise; always(callback: Function): Promise; done(callback: Function): Promise; fail(callback: Function): Promise; reject(error: any): void; resolve(result: any): void; - then(resolvedCallback: (value: T) => Promise, - rejectedCallback?: (reason: any) => Promise): IPromise; - then(resolvedCallback: (value: T) => U, - rejectedCallback?: (reason: any) => IPromise): IPromise; - then(resolvedCallback: (value: T) => U, - rejectedCallback?: (reason: any) => U): IPromise; + then(resolvedCallback: (...values: T[]) => IPromise, + rejectedCallback?: (reason: any) => IPromise): IPromise; + then(resolvedCallback: (...values: T[]) => U, + rejectedCallback?: (reason: any) => IPromise): IPromise; + then(resolvedCallback: (...values: T[]) => U, + rejectedCallback?: (reason: any) => U): IPromise; } interface IBaseObject { @@ -306,7 +311,9 @@ declare namespace Parse { */ class Object extends BaseObject { - id: any; + id: string; + createdAt: Date; + updatedAt: Date; attributes: any; cid: string; changed: boolean; @@ -319,7 +326,9 @@ declare namespace Parse { static fetchAll(list: Object[], options: SuccessFailureOptions): Promise; static fetchAllIfNeeded(list: Object[], options: SuccessFailureOptions): Promise; static destroyAll(list: Object[], options?: Object.DestroyAllOptions): Promise; - static saveAll(list: Object[], options?: Object.SaveAllOptions): Promise; + static saveAll(list: T[], options?: Object.SaveAllOptions): Promise; + + static registerSubclass(className: string, clazz: new (options?: any) => T): void; initialize(): void; add(attr: string, item: any): Object; @@ -333,7 +342,7 @@ declare namespace Parse { dirtyKeys(): string[]; escape(attr: string): string; existed(): boolean; - fetch(options?: Object.FetchOptions): Promise; + fetch(options?: Object.FetchOptions): Promise; get(attr: string): any; getACL(): ACL; has(attr: string): boolean; @@ -345,7 +354,8 @@ declare namespace Parse { previousAttributes(): any; relation(attr: string): Relation; remove(attr: string, item: any): any; - save(options?: Object.SaveOptions, arg2?: any, arg3?: any): Promise; + save(attrs?: { [key: string]: any }, options?: Object.SaveOptions): Promise; + save(key: string, value: any, options?: Object.SaveOptions): Promise; set(key: string, value: any, options?: Object.SetOptions): boolean; setACL(acl: ACL, options?: SuccessFailureOptions): boolean; unset(attr: string, options?: any): any; @@ -583,11 +593,11 @@ declare namespace Parse { doesNotExist(key: string): Query; doesNotMatchKeyInQuery(key: string, queryKey: string, query: Query): Query; doesNotMatchQuery(key: string, query: Query): Query; - each(callback: Function, options?: SuccessFailureOptions): Promise; + each(callback: Function, options?: Query.EachOptions): Promise; endsWith(key: string, suffix: string): Query; equalTo(key: string, value: any): Query; exists(key: string): Query; - find(options?: Query.FindOptions): Promise; + find(options?: Query.FindOptions): Promise; first(options?: Query.FirstOptions): Promise; get(objectId: string, options?: Query.GetOptions): Promise; greaterThan(key: string, value: any): Query; @@ -613,6 +623,7 @@ declare namespace Parse { } namespace Query { + interface EachOptions extends SuccessFailureOptions, UseMasterKeyOption { } interface CountOptions extends SuccessFailureOptions, UseMasterKeyOption { } interface FindOptions extends SuccessFailureOptions, UseMasterKeyOption { } interface FirstOptions extends SuccessFailureOptions, UseMasterKeyOption { } @@ -642,6 +653,21 @@ declare namespace Parse { setName(name: string, options?: SuccessFailureOptions): any; } + class Config extends Object { + static get(options?: SuccessFailureOptions): Promise; + static current(): Config; + + get(attr: string): any; + escape(attr: string): any; + } + + class Session extends Object { + static current(): Promise; + + getSessionToken(): string; + isCurrentSessionRevocable(): boolean; + } + /** * Routers map faux-URLs to actions, and fire events when routes are * matched. Creating a new one sets its `routes` hash, if not set statically. @@ -698,11 +724,10 @@ declare namespace Parse { static allowCustomUserClass(isAllowed: boolean): void; static become(sessionToken: string, options?: SuccessFailureOptions): Promise; static requestPasswordReset(email: string, options?: SuccessFailureOptions): Promise; + static extend(protoProps?: any, classProps?: any): any; signUp(attrs: any, options?: SuccessFailureOptions): Promise; logIn(options?: SuccessFailureOptions): Promise; - fetch(options?: SuccessFailureOptions): Promise; - save(arg1: any, arg2: any, arg3: any): Promise; authenticated(): boolean; isCurrent(): boolean; @@ -822,9 +847,9 @@ declare namespace Parse { } interface JobStatus { - error?: Function; - message?: Function; - success?: Function; + error?: (response: any) => void; + message?: (response: any) => void; + success?: (response: any) => void; } interface FunctionRequest { @@ -835,8 +860,8 @@ declare namespace Parse { } interface FunctionResponse { - success?: (response: HttpResponse) => void; - error?: (response: HttpResponse) => void; + success?: (response: any) => void; + error?: (response: any) => void; } interface Cookie { @@ -845,12 +870,18 @@ declare namespace Parse { value?: string; } - interface AfterSaveRequest extends FunctionRequest {} + interface SaveRequest extends FunctionRequest { + object: Object; + } + + interface AfterSaveRequest extends SaveRequest {} interface AfterDeleteRequest extends FunctionRequest {} interface BeforeDeleteRequest extends FunctionRequest {} interface BeforeDeleteResponse extends FunctionResponse {} - interface BeforeSaveRequest extends FunctionRequest {} - interface BeforeSaveResponse extends FunctionResponse {} + interface BeforeSaveRequest extends SaveRequest {} + interface BeforeSaveResponse extends FunctionResponse { + success?: () => void; + } function afterDelete(arg1: any, func?: (request: AfterDeleteRequest) => void): void; function afterSave(arg1: any, func?: (request: AfterSaveRequest) => void): void; @@ -859,9 +890,11 @@ declare namespace Parse { function define(name: string, func?: (request: FunctionRequest, response: FunctionResponse) => void): void; function httpRequest(options: HTTPOptions): Promise; function job(name: string, func?: (request: JobRequest, status: JobStatus) => void): HttpResponse; - function run(name: string, data?: any, options?: SuccessFailureOptions): Promise; + function run(name: string, data?: any, options?: RunOptions): Promise; function useMasterKey(): void; + interface RunOptions extends SuccessFailureOptions, UseMasterKeyOption, SessionTokenOption { } + /** * To use this Cloud Module in Cloud Code, you must require 'buffer' in your JavaScript file. * @@ -911,7 +944,10 @@ declare namespace Parse { } - enum ErrorCode { + /* + * We need to inline the codes in order to make compilation work without this type definition as dependency. + */ + const enum ErrorCode { OTHER_CAUSE = -1, INTERNAL_SERVER_ERROR = 1, @@ -1043,10 +1079,10 @@ declare namespace Parse { * Call this method first to set up your authentication tokens for Parse. * You can get your keys from the Data Browser on parse.com. * @param {String} applicationId Your Parse Application ID. - * @param {String} javaScriptKey Your Parse JavaScript Key. + * @param {String} javaScriptKey (optional) Your Parse JavaScript Key (Not needed for parse-server) * @param {String} masterKey (optional) Your Parse Master Key. (Node.js only!) */ - function initialize(applicationId: string, javaScriptKey: string, masterKey?: string): void; + function initialize(applicationId: string, javaScriptKey?: string, masterKey?: string): void; } diff --git a/passport/index.d.ts b/passport/index.d.ts index de0d4d8e03..0d66436bfe 100644 --- a/passport/index.d.ts +++ b/passport/index.d.ts @@ -8,6 +8,7 @@ declare namespace Express { export interface Request { authInfo?: any; + user?: any; // These declarations are merged into express's Request type login(user: any, done: (err: any) => void): void; @@ -89,4 +90,3 @@ declare module 'passport' { }[]; } } - diff --git a/pixi.js/index.d.ts b/pixi.js/index.d.ts index cf0456e470..6926e9c8e9 100644 --- a/pixi.js/index.d.ts +++ b/pixi.js/index.d.ts @@ -90,10 +90,10 @@ declare namespace PIXI { emit(event: string, ...args: any[]): boolean; on(event: string, fn: Function, context?: any): EventEmitter; once(event: string, fn: Function, context?: any): EventEmitter; - removeListener(event: string, fn: Function, context?: any, once?: boolean): EventEmitter; - removeAllListeners(event: string): EventEmitter; + removeListener(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; + removeAllListeners(event?: string): EventEmitter; - off(event: string, fn: Function, context?: any, once?: boolean): EventEmitter; + off(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; addListener(event: string, fn: Function, context?: any): EventEmitter; } diff --git a/plotly.js/plotly.js-tests.ts b/plotly.js/plotly.js-tests.ts index b5b8b9e275..1ed85371cf 100644 --- a/plotly.js/plotly.js-tests.ts +++ b/plotly.js/plotly.js-tests.ts @@ -1,5 +1,7 @@ /// +import * as Plotly from 'plotly.js'; + var data = [ { x: ['giraffes', 'orangutans', 'monkeys'], diff --git a/plotly.js/plotly.js.d.ts b/plotly.js/plotly.js.d.ts index c28d2ffb0f..863c708abb 100644 --- a/plotly.js/plotly.js.d.ts +++ b/plotly.js/plotly.js.d.ts @@ -28,6 +28,12 @@ interface PlotlyConfig { logging?: boolean } -declare var Plotly: { - newPlot(divid:string, data:any[], layout?:any, config?:PlotlyConfig):void -}; +interface PlotlyStatic { + newPlot(divid:string | HTMLElement, data:any[], layout?:any, config?:PlotlyConfig):void; +} + +declare module "plotly.js" { + export = plotly; +} + +declare var plotly:PlotlyStatic; diff --git a/pouchDB/index.d.ts b/pouchDB/index.d.ts index e601bcaa53..2d40feb2ec 100644 --- a/pouchDB/index.d.ts +++ b/pouchDB/index.d.ts @@ -1,232 +1,24 @@ -// Type definitions for Pouch 0.1 -// Project: http://pouchdb.com -// Definitions by: Bill Sears +// Type definitions for pouchdb v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface PouchError { - status: number; - error: string; - reason: string; -} +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// -interface PouchApi { - type(): string; - id(): string; - close(callback: () => void): void; -} - -interface PouchInfoResponse { - db_name: string; - doc_count: number; - update_seq: string; -} - -interface PouchApi { - info(callback: (err: PouchError, res: PouchInfoResponse) => void): void; -} - -interface PouchGetOptions { - rev?: string; - revs?: boolean; - revs_info?: boolean; - conflicts?: boolean; - attachments?: boolean; -} - -interface PouchGetResponse { - _id: string; - _rev: string; - _attachments: any; -} - -interface PouchAllDocsOptions { - startkey?: string; - endKey?: string; - descending?: boolean; - include_docs?: boolean; - conflicts?: boolean; -} - -interface PouchAllDocsItem { - id: string; - key: string; - value: any; - doc: any; -} - -interface PouchAllDocsResponse { - total_rows: number; - rows: PouchAllDocsItem[]; -} - -interface PouchApi { - // - // get == select by id - // - get(id: string, opts: PouchGetOptions, callback: (err: PouchError, res: PouchGetResponse) => void): void; - get(id: string, callback: (err: PouchError, res: PouchGetResponse) => void): void; - allDocs(opts: PouchAllDocsOptions, callback: (err: PouchError, res: PouchAllDocsResponse) => void): void; - allDocs(callback: (err: PouchError, res: PouchAllDocsResponse) => void): void; -} - -interface PouchBulkDocsRequest { - docs: any[]; -} - -interface PouchUpdateOptions { - new_edits?: boolean; -} - -interface PouchUpdateResponse { - ok: boolean; - id: string; - rev: string; -} - -interface PouchApi { - bulkDocs(req: PouchBulkDocsRequest, opts: PouchUpdateOptions, callback: (err: PouchError, res: PouchUpdateResponse[]) => void): void; - bulkDocs(req: PouchBulkDocsRequest, callback: (err: PouchError, res: PouchUpdateResponse[]) => void): void; - // - // post == insert (doc does not contain an _id) - // - post(doc: any, opts: PouchUpdateOptions, callback: (err: PouchError, res: PouchUpdateResponse) => void): void; - post(doc: any, callback: (err: PouchError, res: PouchUpdateResponse) => void): void; - // - // put == update (doc DOES contain an _id) - // - put(doc: any, opts: PouchUpdateOptions, callback: (err: PouchError, res: PouchUpdateResponse) => void): void; - put(doc: any, callback: (err: PouchError, res: PouchUpdateResponse) => void): void; - // - // remove == delete - // - remove(doc: any, opts: PouchUpdateOptions, callback: (err: PouchError, res: PouchUpdateResponse) => void): void; - remove(doc: any, callback: (err: PouchError, res: PouchUpdateResponse) => void): void; -} - -interface PouchFilter { - map: (doc: any) => void; - reduce?: (key: string, value: any) => any; -} - -interface PouchQueryOptions { - complete?: any; - include_docs?: boolean; - error?: (err: PouchError) => void; - descending?: boolean; - reduce?: boolean; -} - -interface PouchQueryResponse { - rows: any[]; -} - -interface PouchApi { - // - // query == select by other criteria - // - query(fun: string, opts: PouchQueryOptions, callback: (err: PouchError, res: PouchQueryResponse) => void): void; - query(fun: string, callback: (err: PouchError, res: PouchQueryResponse) => void): void; - query(fun: PouchFilter, opts: PouchQueryOptions, callback: (err: PouchError, res: PouchQueryResponse) => void): void; - query(fun: PouchFilter, callback: (err: PouchError, res: PouchQueryResponse) => void): void; -} - -interface PouchAttachmentOptions { - decode?: boolean; -} - -interface PouchApi { - getAttachment(id: string, opts: PouchAttachmentOptions, callback: (err: PouchError, res: any) => void): void; - getAttachment(id: string, callback: (err: PouchError, res: any) => void): void; - putAttachment(id: string, rev: string, doc: any, type: string, callback: (err: PouchError, res: PouchUpdateResponse) => void): void; - removeAttachment(id: string, rev: string, callback: (err: PouchError, res: PouchUpdateResponse) => void): void; -} - -interface PouchCancellable { - cancel: () => void; -} - -interface PouchChangesOptions { - onChange: (change: PouchChange) => void; - complete?: (err: PouchError, res: PouchChanges) => void; - seq?: number; - since?: number; - descending?: boolean; - filter?: PouchFilter; - continuous?: boolean; - include_docs?: boolean; - conflicts?: boolean; -} - -interface PouchChange { - changes: any; - doc: PouchGetResponse; - id: string; - seq: number; -} - -interface PouchChanges { - results: PouchChange[]; -} - -interface PouchApi { - changes(opts: PouchChangesOptions, callback: (err: PouchError, res: PouchChanges) => void): PouchCancellable; - changes(callback: (err: PouchError, res: PouchChanges) => void): PouchCancellable; -} - -interface PouchRevsDiffOptions { -} - -interface PouchReplicateOptions { - continuous?: boolean; - onChange?: (e: any) => void; - filter?: any; // Can be either string or PouchFilter - complete?: (err: PouchError, res: PouchChanges) => void; -} - -interface PouchReplicateResponse { - ok: boolean; - start_time: Date; - end_time: Date; - docs_read: number; - docs_written: number; -} - -interface PouchReplicate { - from(url: string, opts: PouchReplicateOptions, callback: (err: PouchError, res: PouchReplicateResponse) => void): PouchCancellable; - from(url: string, callback: (err: PouchError, res: PouchReplicateResponse) => void): PouchCancellable; - to(dbName: string, opts: PouchReplicateOptions, callback: (err: PouchError, res: PouchReplicateResponse) => void): PouchCancellable; - to(dbName: string, callback: (err: PouchError, res: PouchReplicateResponse) => void): PouchCancellable; -} - -interface PouchApi { - revsDiff(req: any, opts: PouchRevsDiffOptions, callback: (missing: any) => void): void; - revsDiff(req: any, callback: (missing: any) => void): void; - replicate: PouchReplicate; -} - -interface PouchOptions { - name?: string; - adapter?: string; - skip_setup?: boolean; -} - -interface PouchDB extends PouchApi { - new (name: string, opts: PouchOptions, callback: (err: PouchError, res: PouchDB) => void): PouchDB; - new (name: string, callback: (err: PouchError, res: PouchDB) => void): PouchDB; - new (name: string, opts: PouchOptions): PouchDB; - new (name: string): PouchDB; - destroy(name: string, callback: (err: PouchError) => void): void; -} - -declare var PouchDB: PouchDB; - -// Support AMD require declare module 'pouchdb' { - export = PouchDB; + const plugin: PouchDB.Static; + export = plugin; } - -// -// emit is the function that the PouchFilter.map function should call in order to add a particular item to -// a filter view. -// -declare function emit(key: any, value: any): void; diff --git a/pouchDB/pouch-tests.ts b/pouchDB/pouch-tests.ts index dcbdd5c03b..89f1c002db 100644 --- a/pouchDB/pouch-tests.ts +++ b/pouchDB/pouch-tests.ts @@ -1,142 +1,106 @@ +import * as PouchDB from 'pouchdb'; +namespace PouchDBTests { + function isString(someString: string) { + } + function isNumber(someNumber: number) { + } -window.alert = function (thing?: string) { - var div = document.createElement('div'); - div.appendChild(document.createTextNode(thing)); - document.getElementsByTagName('body')[0].appendChild(div); -} - -var pouch: PouchDB; - -function pouchTests() { - new PouchDB('testdb', function (err: PouchError, res: PouchDB) { - if (err) { - alert('Error ' + err.status + ' occurred ' + err.error + ' - ' + err.reason); - } - else { - pouch = res; - alert("database opened"); - runTests(); - } - }); -} - -var tests = [ - setupTests, - testId, - testAllDocs, - testGet, - testUpdate, - testDelete, - deleteDb -]; - -var testIndex; - -var revs: any = {}; - -function runTests() { - testIndex = 0; - tests[testIndex++](); -} - -// each test function except the last one needs to call nextTest when it is finished doing its thing. -function nextTest() { - alert("starting test " + testIndex); - tests[testIndex++](); -} - -function setupTests() { - alert('setupTests'); - pouch.bulkDocs({ - docs: [{ _id: '1', name: 'record 1' }, - { _id: '2', name: 'record 2' }, - { _id: '3', name: 'record 3' } - ] - }, function (err: PouchError, res: PouchUpdateResponse[]) { - if (err) { - alert('Error ' + err.status + ' occurred ' + err.error + ' - ' + err.reason); - } - else { - for (var i = 0; i < res.length; i++) { - if (res[i].ok) { - revs[res[i].id] = res[i].rev; - } - } - alert("test records loaded"); - } - nextTest(); - }); -} - -function testId() { - alert('testId'); - var id = pouch.id(); - alert('Database Id = ' + id); - nextTest(); -} - -function testGet() { - alert('testGet'); - pouch.get('1', function (err: PouchError, res: PouchGetResponse) { - if (err) { - alert('Error ' + err.status + ' occurred ' + err.error + ' - ' + err.reason); - } - else { - alert('Retrieved record with id=1, name=[' + res['name'] + ']'); - } - nextTest(); - }); -} - -function testAllDocs() { - alert('testAllDocs'); - pouch.allDocs(function (err: PouchError, res: PouchAllDocsResponse) { - alert('allDocs resulted in ' + res.total_rows + ' results'); - for (var i = 0; i < res.total_rows; i++) { - alert('Retrieved record with id=' + res.rows[i].id + ', rev=[' + res.rows[i].value.rev + ']'); - } - nextTest(); - }); -} - -function testUpdate() { - alert('testUpdate'); - pouch.put({ _id: '2', _rev: revs['2'], name: 'record 2 updated' }, function (err: PouchError, res: PouchUpdateResponse) { - if (err) { - alert('Error ' + err.status + ' occurred ' + err.error + ' - ' + err.reason); - } - else { - alert('record updated id=' + res.id + ', rev=[' + res.rev + ']'); - } - testAllDocs(); // spit out the db contents and then go on - }); -} - -function testDelete() { - alert('testDelete'); - pouch.remove({ _id: '3', _rev: revs['3'] }, function (err: PouchError, res: PouchUpdateResponse) { - if (err) { - alert('Error ' + err.status + ' occurred ' + err.error + ' - ' + err.reason); - } - else { - alert('record deleted id=' + res.id + ', rev=[' + res.rev + ']'); - } - testAllDocs(); // spit out the db contents and then go on - }); -} - -function deleteDb() { - alert('deleteDb'); - if (pouch) { - pouch = null; - PouchDB.destroy('testdb', function (err: PouchError) { - if (err) { - alert('Error ' + err.status + ' occurred ' + err.error + ' - ' + err.reason); - } - else { - alert("database destroyed"); - } - }); - } + function testAllDocs() { + const db = new PouchDB<{ foo: number }>(); + + db.allDocs().then(({ offset, total_rows, rows }) => { + isNumber(offset); + isNumber(total_rows); + + rows.forEach(({ id, key, value, doc }) => { + isString(id); + isString(key); + isString(value.rev); + + // check document property + isNumber(doc.foo); + }) + }); + + db.allDocs({ startkey: "a", endkey: "b" }); + db.allDocs({ startkey: "a", endkey: "b", inclusive_end: true }); + db.allDocs({ keys: ["a", "b", "c" ]}); + db.allDocs({ key: "a" }); + db.allDocs({ + attachments: true, + binary: true, + conflicts: true, + descending: true, + include_docs: true, + limit: 5, + skip: 1 + }); + } + + function testDestroy() { + const db = new PouchDB<{}>(); + + db.destroy({}, (error) => { + }); + db.destroy().then(() => { + }).catch((error) => { + }); + } + + function testBasics() { + type MyModel = { property: 'someProperty '}; + let model: PouchDB.Core.Document; + const id = 'model'; + + let db = new PouchDB(); + db = new PouchDB(null, { + adapter: 'fruitdown' + }); + db = new PouchDB(null, { + adapter: 'http' + }); + db = new PouchDB(null, { + adapter: 'idb' + }); + db = new PouchDB(null, { + adapter: 'leveldb' + }); + db = new PouchDB(null, { + adapter: 'localstorage' + }); + db = new PouchDB(null, { + adapter: 'memory' + }); + db = new PouchDB(null, { + adapter: 'websql' + }); + db = new PouchDB(null, { + adapter: 'websql', + size: 100 + }); + + db.post(model).then((result) => { + isString(result.id); + }); + db.post(model, null, (error, response) => { + }); + + db.get(id).then((result) => model = result); + db.get(id, null, (error, result) => { + }); + + db.put(model).then((error) => { + }); + db.put(model, null, null, null, (error) => { + }); + + db.info().then((info) => { + }); + db.info({ ajax: { cache: true }}, (error, result) => { + }); + + db.viewCleanup().catch((error) => { + }); + } } diff --git a/pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown-tests.ts b/pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown-tests.ts new file mode 100644 index 0000000000..ee6f70c59b --- /dev/null +++ b/pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown-tests.ts @@ -0,0 +1,18 @@ +/// +/// + +namespace PouchDBAdapterFruitdownTests { + function testConstructor() { + type MyModel = { numericProperty: number }; + let model: PouchDB.Core.Document; + + let db = new PouchDB(null, { + adapter: 'fruitdown', + }); + db.get('model').then((result) => model); + db = new PouchDB('myDb', { + adapter: 'fruitdown', + }); + db.get('model').then((result) => model); + } +} diff --git a/pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown.d.ts b/pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown.d.ts new file mode 100644 index 0000000000..e818121543 --- /dev/null +++ b/pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown.d.ts @@ -0,0 +1,26 @@ +// Type definitions for pouchdb-adapter-fruitdown v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace PouchDB { + namespace FruitDOWNAdapter { + interface FruitDOWNAdapterConfiguration + extends Configuration.LocalDatabaseConfiguration { + adapter: 'fruitdown'; + } + } + + interface Static { + new(name: string | void, + options: FruitDOWNAdapter.FruitDOWNAdapterConfiguration + ): Database; + } +} + +declare module 'pouchdb-adapter-fruitdown' { + const plugin: PouchDB.Plugin; + export = plugin; +} diff --git a/pouchdb-adapter-http/pouchdb-adapter-http-tests.ts b/pouchdb-adapter-http/pouchdb-adapter-http-tests.ts new file mode 100644 index 0000000000..bbd1b5ec69 --- /dev/null +++ b/pouchdb-adapter-http/pouchdb-adapter-http-tests.ts @@ -0,0 +1,8 @@ +/// +/// + +function testHttpDbCreation() { + const basicDB = new PouchDB('basic', { + adapter: 'http' + }); +} diff --git a/pouchdb-adapter-http/pouchdb-adapter-http.d.ts b/pouchdb-adapter-http/pouchdb-adapter-http.d.ts new file mode 100644 index 0000000000..f1a535be5e --- /dev/null +++ b/pouchdb-adapter-http/pouchdb-adapter-http.d.ts @@ -0,0 +1,26 @@ +// Type definitions for pouchdb-http v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace PouchDB { + namespace HttpAdapter { + interface HttpAdapterConfiguration + extends Configuration.RemoteDatabaseConfiguration { + adapter: 'http'; + } + } + + interface Static { + new(name: string | void, + options: HttpAdapter.HttpAdapterConfiguration + ): Database; + } +} + +declare module 'pouchdb-adapter-http' { + const plugin: PouchDB.Plugin; + export = plugin; +} diff --git a/pouchdb-adapter-idb/pouchdb-adapter-idb-tests.ts b/pouchdb-adapter-idb/pouchdb-adapter-idb-tests.ts new file mode 100644 index 0000000000..2256bfc6bc --- /dev/null +++ b/pouchdb-adapter-idb/pouchdb-adapter-idb-tests.ts @@ -0,0 +1,16 @@ +/// +/// + +function testIdbDbCreation() { + const basicDB = new PouchDB('basic', { + adapter: 'idb' + }); + const persistentDb = new PouchDB('persistent', { + adapter: 'idb', + storage: 'persistent' + }); + const temporaryDb = new PouchDB('temporary', { + adapter: 'idb', + storage: 'temporary' + }); +} diff --git a/pouchdb-adapter-idb/pouchdb-adapter-idb.d.ts b/pouchdb-adapter-idb/pouchdb-adapter-idb.d.ts new file mode 100644 index 0000000000..34e75f6bdf --- /dev/null +++ b/pouchdb-adapter-idb/pouchdb-adapter-idb.d.ts @@ -0,0 +1,38 @@ +// Type definitions for pouchdb-adapter-idb v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace PouchDB { + namespace Core { + interface DatabaseInfo { + idb_attachment_format?: 'base64' | 'binary'; + } + } + + namespace IdbAdapter { + interface IdbAdapterConfiguration + extends Configuration.LocalDatabaseConfiguration { + /** + * Configures storage persistence. + * + * Only works in Firefox 26+. + */ + storage?: 'persistent' | 'temporary'; + adapter: 'idb'; + } + } + + interface Static { + new(name: string | void, + options: IdbAdapter.IdbAdapterConfiguration + ): Database; + } +} + +declare module 'pouchdb-adapter-idb' { + const plugin: PouchDB.Plugin; + export = plugin; +} diff --git a/pouchdb-adapter-leveldb/pouchdb-adapter-leveldb-tests.ts b/pouchdb-adapter-leveldb/pouchdb-adapter-leveldb-tests.ts new file mode 100644 index 0000000000..a9a66df854 --- /dev/null +++ b/pouchdb-adapter-leveldb/pouchdb-adapter-leveldb-tests.ts @@ -0,0 +1,15 @@ +/// +/// + +namespace PouchDBAdapterLevelDBTests { + function testConstructor() { + type MyModel = { numericProperty: number }; + + let db = new PouchDB(null, { + adapter: 'leveldb', + }); + db = new PouchDB('myDb', { + adapter: 'leveldb', + }); + } +} diff --git a/pouchdb-adapter-leveldb/pouchdb-adapter-leveldb.d.ts b/pouchdb-adapter-leveldb/pouchdb-adapter-leveldb.d.ts new file mode 100644 index 0000000000..fcdaaea65b --- /dev/null +++ b/pouchdb-adapter-leveldb/pouchdb-adapter-leveldb.d.ts @@ -0,0 +1,25 @@ +// Type definitions for pouchdb-adapter-leveldb v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace PouchDB { + namespace LevelDbAdapter { + interface LevelDbAdapterConfiguration extends Configuration.LocalDatabaseConfiguration { + adapter: 'leveldb'; + } + } + + interface Static { + new(name: string | void, + options: LevelDbAdapter.LevelDbAdapterConfiguration + ): Database; + } +} + +declare module 'pouchdb-adapter-leveldb' { + const plugin: PouchDB.Plugin; + export = plugin; +} diff --git a/pouchdb-adapter-localstorage/pouchdb-adapter-localstorage-tests.ts b/pouchdb-adapter-localstorage/pouchdb-adapter-localstorage-tests.ts new file mode 100644 index 0000000000..06fe1f9a0b --- /dev/null +++ b/pouchdb-adapter-localstorage/pouchdb-adapter-localstorage-tests.ts @@ -0,0 +1,15 @@ +/// +/// + +namespace PouchDBAdapterLocalStorageyTests { + function testConstructor() { + type MyModel = { numericProperty: number }; + + let db = new PouchDB(null, { + adapter: 'localstorage', + }); + db = new PouchDB('myDb', { + adapter: 'localstorage', + }); + } +} diff --git a/pouchdb-adapter-localstorage/pouchdb-adapter-localstorage.d.ts b/pouchdb-adapter-localstorage/pouchdb-adapter-localstorage.d.ts new file mode 100644 index 0000000000..92f9b17752 --- /dev/null +++ b/pouchdb-adapter-localstorage/pouchdb-adapter-localstorage.d.ts @@ -0,0 +1,26 @@ +// Type definitions for pouchdb-adapter-localstorage v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace PouchDB { + namespace LocalStorageAdapter { + interface LocalStorageAdapterConfiguration + extends Configuration.LocalDatabaseConfiguration { + adapter: 'localstorage'; + } + } + + interface Static { + new(name: string | void, + options: LocalStorageAdapter.LocalStorageAdapterConfiguration + ): Database; + } +} + +declare module 'pouchdb-adapter-localstorage' { + const plugin: PouchDB.Plugin; + export = plugin; +} diff --git a/pouchdb-adapter-memory/pouchdb-adapter-memory-tests.ts b/pouchdb-adapter-memory/pouchdb-adapter-memory-tests.ts new file mode 100644 index 0000000000..b234915648 --- /dev/null +++ b/pouchdb-adapter-memory/pouchdb-adapter-memory-tests.ts @@ -0,0 +1,15 @@ +/// +/// + +namespace PouchDBAdapterMemoryTests { + function testConstructor() { + type MyModel = { numericProperty: number }; + + let db = new PouchDB(null, { + adapter: 'memory', + }); + db = new PouchDB('myDb', { + adapter: 'memory', + }); + } +} diff --git a/pouchdb-adapter-memory/pouchdb-adapter-memory.d.ts b/pouchdb-adapter-memory/pouchdb-adapter-memory.d.ts new file mode 100644 index 0000000000..75c89509ba --- /dev/null +++ b/pouchdb-adapter-memory/pouchdb-adapter-memory.d.ts @@ -0,0 +1,26 @@ +// Type definitions for pouchdb-adapter-memory v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace PouchDB { + namespace MemoryAdapter { + interface MemoryAdapterConfiguration + extends Configuration.LocalDatabaseConfiguration { + adapter: 'memory'; + } + } + + interface Static { + new(name: string | void, + options: MemoryAdapter.MemoryAdapterConfiguration + ): Database; + } +} + +declare module 'pouchdb-adapter-memory' { + const plugin: PouchDB.Plugin; + export = plugin; +} diff --git a/pouchdb-adapter-node-websql/pouchdb-adapter-node-websql-tests.ts b/pouchdb-adapter-node-websql/pouchdb-adapter-node-websql-tests.ts new file mode 100644 index 0000000000..4f751d3395 --- /dev/null +++ b/pouchdb-adapter-node-websql/pouchdb-adapter-node-websql-tests.ts @@ -0,0 +1,28 @@ +/// +/// + +namespace PouchDBAdapterNodeWebSQLTests { + function isBoolean(someBoolean: boolean) { + } + function isNumber(someNumber: number) { + } + function isString(someString: string) { + } + + function testConstructor() { + type MyModel = { numericProperty: number }; + + let db = new PouchDB(null, { + adapter: 'websql', + size: 5, + }); + db = new PouchDB('myDb', { + adapter: 'websql', + }); + + db.info().then((info) => { + isBoolean(info.sqlite_plugin); + isString(info.websql_encoding); + }); + } +} diff --git a/pouchdb-adapter-node-websql/pouchdb-adapter-node-websql.d.ts b/pouchdb-adapter-node-websql/pouchdb-adapter-node-websql.d.ts new file mode 100644 index 0000000000..57a0407a5e --- /dev/null +++ b/pouchdb-adapter-node-websql/pouchdb-adapter-node-websql.d.ts @@ -0,0 +1,12 @@ +// Type definitions for pouchdb-adapter-node-websql v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module 'pouchdb-adapter-node-websql' { + const plugin: PouchDB.Plugin; + export = plugin; +} diff --git a/pouchdb-adapter-websql/pouchdb-adapter-websql-tests.ts b/pouchdb-adapter-websql/pouchdb-adapter-websql-tests.ts new file mode 100644 index 0000000000..1c0242a17c --- /dev/null +++ b/pouchdb-adapter-websql/pouchdb-adapter-websql-tests.ts @@ -0,0 +1,29 @@ +/// +/// + +namespace PouchDBAdapterWebSQLTests { + function isBoolean(someBoolean: boolean) { + } + function isNumber(someNumber: number) { + } + function isString(someString: string) { + } + + function testConstructor() { + type MyModel = { numericProperty: number }; + + let db = new PouchDB('basic'); + db = new PouchDB(null, { + adapter: 'websql' + }); + db = new PouchDB('sized', { + adapter: 'websql', + size: 10 + }); + + db.info().then((info) => { + isBoolean(info.sqlite_plugin); + isString(info.websql_encoding); + }); + } +} diff --git a/pouchdb-adapter-websql/pouchdb-adapter-websql.d.ts b/pouchdb-adapter-websql/pouchdb-adapter-websql.d.ts new file mode 100644 index 0000000000..64b732d482 --- /dev/null +++ b/pouchdb-adapter-websql/pouchdb-adapter-websql.d.ts @@ -0,0 +1,36 @@ +// Type definitions for pouchdb-adapter-websql v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace PouchDB { + namespace Core { + interface DatabaseInfo { + sqlite_plugin?: boolean; + websql_encoding?: 'UTF-8' | 'UTF-16'; + } + } + + namespace AdapterWebSql { + interface Configuration + extends Configuration.LocalDatabaseConfiguration { + /** + * Amount in MB to request for storage. + */ + size?: number; + adapter: 'websql'; + } + } + + interface Static { + new(name: string | void, + options: AdapterWebSql.Configuration): Database; + } +} + +declare module 'pouchdb-adapter-websql' { + const plugin: PouchDB.Plugin; + export = plugin; +} diff --git a/pouchdb-browser/pouchdb-browser-tests.ts b/pouchdb-browser/pouchdb-browser-tests.ts new file mode 100644 index 0000000000..82575efada --- /dev/null +++ b/pouchdb-browser/pouchdb-browser-tests.ts @@ -0,0 +1,19 @@ +/// +/// + +namespace PouchDBBrowserTests { + function testConstructor() { + type MyModel = { numericProperty: number }; + let model: PouchDB.Core.Document; + + let db = new PouchDB(null, { + adapter: 'idb', + }); + db = new PouchDB('myDb', { + adapter: 'http', + }); + db.get('model').then((result) => model); + db.viewCleanup().catch((error) => { + }); + } +} diff --git a/pouchdb-browser/pouchdb-browser.d.ts b/pouchdb-browser/pouchdb-browser.d.ts new file mode 100644 index 0000000000..3fb6dc9f2e --- /dev/null +++ b/pouchdb-browser/pouchdb-browser.d.ts @@ -0,0 +1,15 @@ +// Type definitions for pouchdb-browser v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// +/// +/// + +declare module 'pouchdb-browser' { + const PouchDb: PouchDB.Static; + export = PouchDb; +} diff --git a/pouchdb-core/pouchdb-core-tests.ts b/pouchdb-core/pouchdb-core-tests.ts new file mode 100644 index 0000000000..ac7a6c3e69 --- /dev/null +++ b/pouchdb-core/pouchdb-core-tests.ts @@ -0,0 +1,78 @@ +/// + +namespace PouchDBCoreTests { + function isString(someString: string) { + } + function isNumber(someNumber: number) { + } + + function testAllDocs() { + const db = new PouchDB<{ foo: number }>(); + + db.allDocs().then(({ offset, total_rows, rows }) => { + isNumber(offset); + isNumber(total_rows); + + rows.forEach(({ id, key, value, doc }) => { + isString(id); + isString(key); + isString(value.rev); + + // check document property + isNumber(doc.foo); + }) + }); + + db.allDocs({ startkey: "a", endkey: "b" }); + db.allDocs({ startkey: "a", endkey: "b", inclusive_end: true }); + db.allDocs({ keys: ["a", "b", "c" ]}); + db.allDocs({ key: "a" }); + db.allDocs({ + attachments: true, + binary: true, + conflicts: true, + descending: true, + include_docs: true, + limit: 5, + skip: 1 + }); + } + + function testDestroy() { + const db = new PouchDB<{}>(); + + db.destroy({}, (error) => { + }); + db.destroy().then(() => { + }).catch((error) => { + }); + } + + function testBasics() { + type MyModel = { property: 'someProperty '}; + let model: PouchDB.Core.Document; + const id = 'model'; + + const db = new PouchDB(); + + db.post(model).then((result) => { + isString(result.id); + }); + db.post(model, null, (error, response) => { + }); + + db.get(id).then((result) => model = result); + db.get(id, null, (error, result) => { + }); + + db.put(model).then((error) => { + }); + db.put(model, null, null, null, (error) => { + }); + + db.info().then((info) => { + }); + db.info({ ajax: { cache: true }}, (error, result) => { + }); + } +} diff --git a/pouchdb-core/pouchdb-core.d.ts b/pouchdb-core/pouchdb-core.d.ts new file mode 100644 index 0000000000..a8b6418510 --- /dev/null +++ b/pouchdb-core/pouchdb-core.d.ts @@ -0,0 +1,334 @@ +// Type definitions for pouchdb-core v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace PouchDB { + namespace Core { + interface Error { + } + interface Callback { + (error: E | void, result: R | void): void; + } + type AnyCallback = Callback; + type DocumentId = string; + type DocumentKey = string; + type RevisionId = string; + type Availability = 'available' | 'compacted' | 'not compacted' | 'missing'; + type Attachment = string | ArrayBuffer; + type Encodable = { [propertyName: string]: any }; + + interface Options { + ajax?: Configuration.RemoteRequesterConfiguration; + } + + interface BasicResponse { + /** `true` if the operation was successful; `false` otherwise */ + ok: boolean; + } + interface Response extends BasicResponse { + /** id of the targeted document */ + id: DocumentId; + /** resulting revision of the targeted document */ + rev: RevisionId; + } + + interface DatabaseInfo { + } + + interface Revision { + ok: Document & RevisionIdMeta; + } + interface RevisionInfo { + rev: RevisionId; + status: Availability; + } + + interface IdMeta { + _id: DocumentId; + } + interface RevisionIdMeta { + _rev: RevisionId; + } + interface GetMeta { + /** Conflicting leaf revisions. + * + * Only present if `GetOptions.conflicts` is `true` + */ + _conflicts?: RevisionId[]; + _rev?: RevisionId; + /** Only present if `GetOptions.revs` is `true` */ + _revs_info?: RevisionInfo[]; + /** Only present if `GetOptions.revs_info` is `true` */ + _revisions?: { + ids: RevisionId[]; + start: number; + } + } + type NewDocument = Content; + type Document = Content & IdMeta; + type ExistingDocument = + Document & RevisionIdMeta; + + interface AllDocsOptions extends Options { + /** Include attachment data for each document. + * + * Requires `include_docs` to be `true`. + * + * By default, attachments are Base64-encoded. + * @see binary + */ + attachments?: boolean; + /** Return attachments as Buffers. + * + * Requires `include_docs` to be `true`. + * Requires `attachments` to be `true`. */ + binary?: boolean; + /** Include conflict information for each document. + * + * Requires `include_docs` to be `true`. */ + conflicts?: boolean; + /** Reverse ordering of results. */ + descending?: boolean; + /** Include contents for each document. */ + include_docs?: boolean; + /** Maximum number of documents to return. */ + limit?: number; + /** Number of documents to skip before returning. + * + * Causes poor performance on IndexedDB and LevelDB. */ + skip?: number; + } + interface AllDocsWithKeyOptions extends AllDocsOptions { + /** Constrain results to documents matching this key. */ + key: DocumentKey; + } + interface AllDocsWithKeysOptions extends AllDocsOptions { + /** Constrains results to documents matching any of these keys. */ + keys: DocumentId[]; + } + interface AllDocsWithinRangeOptions extends AllDocsOptions { + /** Low end of range, or high end if `descending` is `true`. */ + startkey: DocumentKey; + /** High end of range, or low end if `descending` is `true`. */ + endkey: DocumentKey; + /** Include any documents identified by `endkey`. + * + * Defaults to `true`. */ + inclusive_end?: boolean; + } + interface AllDocsMeta { + _attachments?: { + [attachmentId: string]: Attachment; + }; + } + interface AllDocsResponse { + /** The `skip` if provided, or in CouchDB the actual offset */ + offset: number; + total_rows: number; + rows: { + /** Only present if `include_docs` was `true`. */ + doc?: Document; + id: DocumentId; + key: DocumentKey; + value: { + rev: RevisionId; + } + }[]; + } + + interface DestroyOptions extends Options { + } + + interface GetOptions extends Options { + /** Include list of conflicting leaf revisions. */ + conflicts?: boolean; + /** Specific revision to fetch */ + rev?: RevisionId; + /** Include revision history of the document. */ + revs?: boolean; + /** Include a list of revisions of the document, and their + * availability. */ + revs_info?: boolean; + } + interface GetOpenRevisions extends Options { + /** Fetch all leaf revisions if open_revs="all" or fetch all leaf + * revisions specified in open_revs array. Leaves will be returned + * in the same order as specified in input array. */ + open_revs: 'all' | Core.RevisionId[]; + } + + /** @todo does this have any other properties? */ + interface PutOptions extends Options { + } + interface PostOptions extends PutOptions { + } + + interface InfoOptions extends Options { + } + } + + /** + * Pass this to `PouchDB.plugin()`. + */ + export type Plugin = 'This should be passed to PouchDB.plugin()'; + + namespace Configuration { + interface CommonDatabaseConfiguration { + /** + * Database name. + */ + name?: string; + /** + * Database adapter to use. + * + * If unspecified, PouchDB will infer this automatically, preferring + * IndexedDB to WebSQL in browsers that support both (i.e. Chrome, + * Opera and Android 4.4+). + */ + adapter?: string; + } + + interface LocalDatabaseConfiguration extends CommonDatabaseConfiguration { + /** + * Enables auto compaction, which means compact() is called after + * every change to the database. + * + * Defaults to false. + */ + auto_compaction?: boolean; + /** + * How many old revisions we keep track (not a copy) of. + */ + revs_limit?: number; + } + + interface RemoteRequesterConfiguration { + /** + * Time before HTTP requests time out (in ms). + */ + timeout?: number; + /** + * Appends a random string to the end of all HTTP GET requests to avoid + * them being cached on IE. Set this to true to prevent this happening. + */ + cache?: boolean; + /** + * HTTP headers to add to requests. + */ + headers?: { + [name: string]: string; + } + username?: string; + password?: string; + /** + * Enables transferring cookies and HTTP Authorization information. + * + * Defaults to true. + */ + withCredentials?: boolean; + /** + * Disables automatic creation of databases. + */ + skip_setup?: boolean; + } + + interface RemoteDatabaseConfiguration extends CommonDatabaseConfiguration { + ajax?: RemoteRequesterConfiguration; + } + + type DatabaseConfiguration = LocalDatabaseConfiguration | + RemoteDatabaseConfiguration; + } + + + + interface Static { + plugin(plugin: Plugin): Static; + + new(name?: string, + options?: Configuration.DatabaseConfiguration): Database; + } + + interface Database { + /** Fetch all documents matching the given key. */ + allDocs(options: Core.AllDocsWithKeyOptions): + Promise>; + /** Fetch all documents matching any of the given keys. */ + allDocs(options: Core.AllDocsWithKeysOptions): + Promise>; + /** Fetch all documents matching the given key range. */ + allDocs(options: Core.AllDocsWithinRangeOptions): + Promise>; + /** Fetch all documents. */ + allDocs(options?: Core.AllDocsOptions): + Promise>; + + /** Destroy the database */ + destroy(options: Core.DestroyOptions | void, + callback: Core.AnyCallback): void; + destroy(options?: Core.DestroyOptions | void): Promise; + + /** Fetch a document */ + get(docId: Core.DocumentId, + options: Core.GetOpenRevisions): Promise[]>; + get(docId: Core.DocumentId, + options: Core.GetOpenRevisions, + callback: Core.Callback[]>): void; + get(docId: Core.DocumentId, + options: Core.GetOptions + ): Promise & Core.GetMeta>; + get(docId: Core.DocumentId, + options: Core.GetOptions, + callback: Core.Callback & Core.GetMeta> + ): void; + get(docId: Core.DocumentId, + options: void, + callback: Core.Callback>): void; + get(docId: Core.DocumentId): Promise>; + + /** Create a new document without providing an id. + * + * You should prefer put() to post(), because when you post(), you are + * missing an opportunity to use allDocs() to sort documents by _id + * (because your _ids are random). + * + * @see {@link https://pouchdb.com/2014/06/17/12-pro-tips-for-better-code-with-pouchdb.html|PouchDB Pro Tips} + * */ + post(doc: Core.NewDocument, + options: Core.PostOptions | void, + callback: Core.Callback): void; + post(doc: Core.NewDocument, + options?: Core.PostOptions): Promise; + + /** Create a new document or update an existing document. + * + * If the document already exists, you must specify its revision _rev, + * otherwise a conflict will occur. + * There are some restrictions on valid property names of the documents. + * If you try to store non-JSON data (for instance Date objects) you may + * see inconsistent results. */ + put(doc: Core.Document, + id: Core.DocumentId | void, + revision: Core.RevisionId | void, + options: Core.PutOptions | void, + callback: Core.Callback): void; + put(doc: Core.Document, + id?: Core.DocumentId, + revision?: Core.RevisionId, + options?: Core.PutOptions): Promise; + + /** Get database information */ + info(options: Core.InfoOptions | void, + callback: Core.Callback): void; + info(options?: Core.InfoOptions): Promise; + } +} + +declare module 'pouchdb-core' { + const PouchDb: PouchDB.Static; + export = PouchDb; +} + +declare var PouchDB: PouchDB.Static; diff --git a/pouchdb-http/pouchdb-http-tests.ts b/pouchdb-http/pouchdb-http-tests.ts new file mode 100644 index 0000000000..b3378e68b1 --- /dev/null +++ b/pouchdb-http/pouchdb-http-tests.ts @@ -0,0 +1,14 @@ +/// +/// + +namespace PouchDBHttpTests { + function testConstructor() { + type MyModel = { numericProperty: number }; + let model: PouchDB.Core.Document; + + let db = new PouchDB('myDb', { + adapter: 'http', + }); + db.get('model').then((result) => model); + } +} diff --git a/pouchdb-http/pouchdb-http.d.ts b/pouchdb-http/pouchdb-http.d.ts new file mode 100644 index 0000000000..0fb6d2963c --- /dev/null +++ b/pouchdb-http/pouchdb-http.d.ts @@ -0,0 +1,12 @@ +// Type definitions for pouchdb-http v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module 'pouchdb-http' { + const PouchDb: PouchDB.Static; + export = PouchDb; +} diff --git a/pouchdb-mapreduce/pouchdb-mapreduce-tests.ts b/pouchdb-mapreduce/pouchdb-mapreduce-tests.ts new file mode 100644 index 0000000000..a42f8178ee --- /dev/null +++ b/pouchdb-mapreduce/pouchdb-mapreduce-tests.ts @@ -0,0 +1,12 @@ +/// + +namespace PouchDBBrowserTests { + function testConstructor() { + type MyModel = { numericProperty: number }; + let model: PouchDB.Core.Document; + + let db = new PouchDB('mydb'); + db.viewCleanup().catch((error) => { + }); + } +} diff --git a/pouchdb-mapreduce/pouchdb-mapreduce.d.ts b/pouchdb-mapreduce/pouchdb-mapreduce.d.ts new file mode 100644 index 0000000000..1c04ddceaf --- /dev/null +++ b/pouchdb-mapreduce/pouchdb-mapreduce.d.ts @@ -0,0 +1,26 @@ +// Type definitions for pouchdb-mapreduce v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace PouchDB { + export interface Database { + /** + * Cleans up any stale map/reduce indexes. + * + * As design docs are deleted or modified, their associated index + * files(in CouchDB) or companion databases (in local PouchDBs) continue + * to take up space on disk. viewCleanup() removes these unnecessary + * index files. + */ + viewCleanup(callback: PouchDB.Core.Callback): void; + viewCleanup(): Promise; + } +} + +declare module 'pouchdb-adapter-mapreduce' { + const plugin: PouchDB.Plugin; + export = plugin; +} diff --git a/pouchdb-node/pouchdb-node-tests.ts b/pouchdb-node/pouchdb-node-tests.ts new file mode 100644 index 0000000000..ec9c338092 --- /dev/null +++ b/pouchdb-node/pouchdb-node-tests.ts @@ -0,0 +1,19 @@ +/// +/// + +namespace PouchDBBrowserTests { + function testConstructor() { + type MyModel = { numericProperty: number }; + let model: PouchDB.Core.Document; + + let db = new PouchDB('myDb', { + adapter: 'http', + }); + db = new PouchDB('myDb', { + adapter: 'leveldb', + }); + db.get('model').then((result) => model); + db.viewCleanup().catch((error) => { + }); + } +} diff --git a/pouchdb-node/pouchdb-node.d.ts b/pouchdb-node/pouchdb-node.d.ts new file mode 100644 index 0000000000..deac5a0140 --- /dev/null +++ b/pouchdb-node/pouchdb-node.d.ts @@ -0,0 +1,24 @@ +// Type definitions for pouchdb-node v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// +/// +/// + +declare namespace PouchDB { + namespace Core { + interface DatabaseInfo { + /** The backend *DOWN adapter being used (MemDOWN, RiakDOWN, …). */ + backend_adapter?: string; + } + } +} + +declare module 'pouchdb-node' { + const PouchDb: PouchDB.Static; + export = PouchDb; +} diff --git a/pouchdb-replication/pouchdb-replication-tests.ts b/pouchdb-replication/pouchdb-replication-tests.ts new file mode 100644 index 0000000000..4e51bdea95 --- /dev/null +++ b/pouchdb-replication/pouchdb-replication-tests.ts @@ -0,0 +1 @@ +/// diff --git a/pouchdb-replication/pouchdb-replication.d.ts b/pouchdb-replication/pouchdb-replication.d.ts new file mode 100644 index 0000000000..3dddb04f85 --- /dev/null +++ b/pouchdb-replication/pouchdb-replication.d.ts @@ -0,0 +1,23 @@ +// Type definitions for pouchdb-replication v5.4.4 +// Project: https://pouchdb.com/ +// Definitions by: Andy Brown , Brian Geppert , Frederico Galvão +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace PouchDB { + namespace Replication { + /** @todo When is this present? */ + interface ReplicationMeta { + _replication_id: string; + _replication_state: string; + _replication_state_time: number; + _replication_stats: {}; + } + } +} + +declare module 'pouchdb-replication' { + const plugin: PouchDB.Plugin; + export = plugin; +} diff --git a/promisify-supertest/index.d.ts b/promisify-supertest/index.d.ts index d0c57e3029..5c0ea6251a 100644 --- a/promisify-supertest/index.d.ts +++ b/promisify-supertest/index.d.ts @@ -19,19 +19,18 @@ declare namespace supertest { interface SuperTest extends superagent.SuperAgent { } - interface Test extends superagent.Request { + interface Test extends superagent.Request { url: string; serverAddress(app: any, path: string): string; - expect(status: number, callback?: CallbackHandler): Test; - expect(status: number, body: string, callback?: CallbackHandler): Test; - expect(body: string, callback?: CallbackHandler): Test; - expect(body: RegExp, callback?: CallbackHandler): Test; - expect(body: Object, callback?: CallbackHandler): Test; - expect(field: string, val: string, callback?: CallbackHandler): Test; - expect(field: string, val: RegExp, callback?: CallbackHandler): Test; - expect(checker: (res: Response) => any): Test; - end(callback: CallbackHandler): Test; - end(): Promise; + expect(status: number, callback?: CallbackHandler): this; + expect(status: number, body: string, callback?: CallbackHandler): this; + expect(body: string, callback?: CallbackHandler): this; + expect(body: RegExp, callback?: CallbackHandler): this; + expect(body: Object, callback?: CallbackHandler): this; + expect(field: string, val: string, callback?: CallbackHandler): this; + expect(field: string, val: RegExp, callback?: CallbackHandler): this; + expect(checker: (res: Response) => any): this; + end(callback?: CallbackHandler): this & Promise; } interface Response extends superagent.Response { diff --git a/protobufjs/index.d.ts b/protobufjs/index.d.ts index 75d507f7f9..bc401c9626 100644 --- a/protobufjs/index.d.ts +++ b/protobufjs/index.d.ts @@ -387,3 +387,7 @@ declare namespace ProtoBuf { declare module "protobufjs" { export = ProtoBuf; } + +declare module "protobufjs/dist/protobuf-light" { + export = ProtoBuf; +} diff --git a/qs/index.d.ts b/qs/index.d.ts index 41c7b0da6a..c23c02f871 100644 --- a/qs/index.d.ts +++ b/qs/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for qs +// Type definitions for qs 6.2.0 // Project: https://github.com/hapijs/qs -// Definitions by: Roman Korneev +// Definitions by: Roman Korneev , Leon Yu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = QueryString; @@ -12,14 +12,16 @@ declare namespace QueryString { strictNullHandling?: boolean; skipNulls?: boolean; encode?: boolean; - filter?: any; - arrayFormat?: any; - indices?: string; + encoder?: (str: string) => any; + filter?: Array | ((prefix: string, value: any) => any); + arrayFormat?: 'indices' | 'brackets' | 'repeat'; + indices?: boolean; } interface IParseOptions { - delimiter?: string; + delimiter?: string | RegExp; depth?: number; + decoder?: (str: string) => any; arrayLimit?: number; parseArrays?: boolean; allowDots?: boolean; diff --git a/qs/qs-tests.ts b/qs/qs-tests.ts index aef2ecd2db..1f1ab7dc72 100644 --- a/qs/qs-tests.ts +++ b/qs/qs-tests.ts @@ -1,4 +1,4 @@ - +/// import qs = require('qs'); @@ -7,3 +7,246 @@ qs.stringify({ a: 'b', c: 'd' }, { delimiter: '&' }); qs.parse('a=b'); qs.parse('a=b&c=d', { delimiter: '&' }); + +() => { + var obj = qs.parse('a=c'); + assert.deepEqual(obj, { a: 'c' }); + + var str = qs.stringify(obj); + assert.equal(str, 'a=c'); +} + +() => { + var plainObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true }); + assert.deepEqual(plainObject, { a: { hasOwnProperty: 'b' } }); +} + +() => { + var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }); + assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } }); +} + +() => { + assert.deepEqual(qs.parse('a%5Bb%5D=c'), { + a: { b: 'c' } + }); +} + +() => { + assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), { + foo: { + bar: { + baz: 'foobarbaz' + } + } + }); +} + +() => { + var expected = { + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } + }; + var string = 'a[b][c][d][e][f][g][h][i]=j'; + assert.deepEqual(qs.parse(string), expected); +} + +() => { + var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); + assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }); +} + +() => { + var limited = qs.parse('a=b&c=d', { parameterLimit: 1 }); + assert.deepEqual(limited, { a: 'b' }); +} + +() => { + var delimited = qs.parse('a=b;c=d', { delimiter: ';' }); + assert.deepEqual(delimited, { a: 'b', c: 'd' }); +} + +() => { + var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); + assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' }); +} + +() => { + var withDots = qs.parse('a.b=c', { allowDots: true }); + assert.deepEqual(withDots, { a: { b: 'c' } }); +} + +() => { + var withArray = qs.parse('a[]=b&a[]=c'); + assert.deepEqual(withArray, { a: ['b', 'c'] }); +} + +() => { + var withIndexes = qs.parse('a[1]=c&a[0]=b'); + assert.deepEqual(withIndexes, { a: ['b', 'c'] }); +} + +() => { + var noSparse = qs.parse('a[1]=b&a[15]=c'); + assert.deepEqual(noSparse, { a: ['b', 'c'] }); +} + +() => { + var withEmptyString = qs.parse('a[]=&a[]=b'); + assert.deepEqual(withEmptyString, { a: ['', 'b'] }); + + var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c'); + assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] }); +} + +() => { + var withMaxIndex = qs.parse('a[100]=b'); + assert.deepEqual(withMaxIndex, { a: { '100': 'b' } }); +} + +() => { + var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 }); + assert.deepEqual(withArrayLimit, { a: { '1': 'b' } }); +} + +() => { + var noParsingArrays = qs.parse('a[]=b', { parseArrays: false }); + assert.deepEqual(noParsingArrays, { a: { '0': 'b' } }); +} + +() => { + var mixedNotation = qs.parse('a[0]=b&a[b]=c'); + assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } }); +} + +() => { + var arraysOfObjects = qs.parse('a[][b]=c'); + assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] }); +} + +() => { + assert.equal(qs.stringify({ a: 'b' }), 'a=b'); + assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); +} + +() => { + var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false }); + assert.equal(unencoded, 'a[b]=c'); +} + +() => { + var encoded = qs.stringify({ a: { b: 'c' } }, { + encoder: function (str) { + // Passed in values `a`, `b`, `c` + return // Return encoded string + } + }) +} + +() => { + var decoded = qs.parse('x=z', { + decoder: function (str) { + // Passed in values `x`, `z` + return // Return decoded string + } + }) +} + +() => { + qs.stringify({ a: ['b', 'c', 'd'] }); + // 'a[0]=b&a[1]=c&a[2]=d' +} + +() => { + qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }); + // 'a=b&a=c&a=d' +} + +() => { + qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }) + // 'a[0]=b&a[1]=c' + qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }) + // 'a[]=b&a[]=c' + qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }) + // 'a=b&a=c' +} + +() => { + assert.equal(qs.stringify({ a: '' }), 'a='); +} + +() => { + assert.equal(qs.stringify({ a: null, b: undefined }), 'a='); +} + +() => { + assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); +} + +() => { + qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: function (prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; + } }); + // 'a=b&c=d&e[f]=123&e[g][0]=4' + qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }); + // 'a=b&e=f' + qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }); +} + +() => { + var withNull = qs.stringify({ a: null, b: '' }); + assert.equal(withNull, 'a=&b='); +} + +() => { + var equalsInsensitive = qs.parse('a&b='); + assert.deepEqual(equalsInsensitive, { a: '', b: '' }); +} + +() => { + var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); + assert.equal(strictNull, 'a&b='); +} + +() => { + var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true }); + assert.deepEqual(parsedStrictNull, { a: null, b: '' }); +} + +() => { + var nullsSkipped = qs.stringify({ a: 'b', c: null }, { skipNulls: true }); + assert.equal(nullsSkipped, 'a=b'); +} + +() => { + var encoder = () => {}; + var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder }); + assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I'); +} + +() => { + var decoder = () => {}; + var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder }); + assert.deepEqual(obj, { a: 'こんにちは!' }); +} diff --git a/radium/index.d.ts b/radium/index.d.ts index 96b3a2f3e9..bc238621cd 100644 --- a/radium/index.d.ts +++ b/radium/index.d.ts @@ -1,18 +1,114 @@ // Type definitions for radium 0.17.1 // Project: https://github.com/formidablelabs/radium -// Definitions by: Alex Gorbatchev , Philipp Holzer +// Definitions by: Alex Gorbatchev , Philipp Holzer , Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - import React = require('react'); - -interface ReactComponent { - new (p: P): React.Component; -} - -declare var Radium: { - >(comp: T): T; -}; +import ReactComponent = React.Component; export = Radium; + +// @Radium decorator +declare function Radium(component: TElement): TElement; +declare function Radium(config: Radium.RadiumConfig): (component?: any) => any; +declare namespace Radium { + interface StyleRules { + [index: string]: React.CSSProperties; + } + + /** + * Style component properties + */ + export interface StyleProps { + /** + * An object of CSS rules to render. Each key of the rules object is a CSS selector and the value is an object + * of styles. If rules is empty, the component will render nothing. + */ + rules: StyleRules; + /** + * A string that any included selectors in rules will be appended to. + * Use to scope styles in the component to a particular element. A good use case might be to generate a unique + * ID for a component to scope any styles to the particular component that owns the + + + ) + } +} + + +Radium.TestMode.enable(); diff --git a/rails-actioncable/index.d.ts b/rails-actioncable/index.d.ts index 497583a775..8d42c4d17a 100644 --- a/rails-actioncable/index.d.ts +++ b/rails-actioncable/index.d.ts @@ -8,24 +8,33 @@ declare module ActionCable { unsubscribe(): void; perform(action: string, data: {}): void; } + interface Subscriptions { - create(chan_name: string, obj: {}): Channel; + create(chan_name: string, obj: CreateMixin): Channel; } + interface Cable { subscriptions: Subscriptions; } + + interface CreateMixin { + connected(): void; + disconnected(): void; + received(obj: Object): void; + [key: string]: Function; + } + function createConsumer(): Cable; function createConsumer(url: string): Cable; } declare interface AppInterface { cable?: ActionCable.Cable; - network?: ActionCable.Channel; + network?: ActionCable.Channel; } declare var App: AppInterface; - - - - +declare module 'actioncable' { + export = ActionCable; +} diff --git a/rails-actioncable/rails-actioncable-tests.ts b/rails-actioncable/rails-actioncable-tests.ts index a3fd305cc1..2700638f97 100644 --- a/rails-actioncable/rails-actioncable-tests.ts +++ b/rails-actioncable/rails-actioncable-tests.ts @@ -1,4 +1,22 @@ +interface HelloChannel extends ActionCable.Channel { + hello(world: string, name?: string): void; +} App = {}; App.cable = ActionCable.createConsumer(); -App.cable.subscriptions.create("NetworkChannel", {}); +const helloChannel = App.cable.subscriptions.create('NetworkChannel', { + connected(): void { + console.log('connected'); + }, + disconnected(): void { + console.log('disconnected'); + }, + received(obj: Object): void { + console.log(obj); + }, + hello(world: string, name: string = 'John Doe'): void { + console.log(`Hello, ${world}! name[${name}]`); + } +}) as HelloChannel; + +helloChannel.hello('World'); diff --git a/rc-tooltip/rc-tooltip-tests.tsx b/rc-tooltip/rc-tooltip-tests.tsx index 33816d7949..d1f4db339a 100644 --- a/rc-tooltip/rc-tooltip-tests.tsx +++ b/rc-tooltip/rc-tooltip-tests.tsx @@ -35,3 +35,14 @@ ReactDOM.render( , document.querySelector('.another-app') ); + +ReactDOM.render( + tooltip} + > + hover + , + document.querySelector('.another-app') +); diff --git a/rc-tooltip/rc-tooltip.d.ts b/rc-tooltip/rc-tooltip.d.ts index 317b8d1fc4..a2a5c67314 100644 --- a/rc-tooltip/rc-tooltip.d.ts +++ b/rc-tooltip/rc-tooltip.d.ts @@ -1,4 +1,4 @@ -// Type definitions for rc-tooltip v3.3.2 +// Type definitions for rc-tooltip v3.4.2 // Project: https://github.com/react-component/tooltip // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -27,7 +27,7 @@ declare namespace Tooltip { placement?: Placement | Object; align?: Object; onPopupAlign?: (popupDomNode: Element, align: Object) => void; - overlay: React.ReactElement; + overlay: React.ReactElement | (() => React.ReactElement); arrowContent?: React.ReactNode; getTooltipContainer?: () => Element; destroyTooltipOnHide?: boolean; diff --git a/react-addons-shallow-compare/index.d.ts b/react-addons-shallow-compare/index.d.ts index eeb4935176..7ffca6eefd 100644 --- a/react-addons-shallow-compare/index.d.ts +++ b/react-addons-shallow-compare/index.d.ts @@ -5,9 +5,9 @@ import { Component } from 'react'; +export = shallowCompare; + declare function shallowCompare( component: Component, nextProps: P, nextState: S): boolean; - -export = shallowCompare; diff --git a/react-big-calendar/react-big-calendar-tests.tsx b/react-big-calendar/react-big-calendar-tests.tsx new file mode 100644 index 0000000000..8e7bca7a9d --- /dev/null +++ b/react-big-calendar/react-big-calendar-tests.tsx @@ -0,0 +1,153 @@ +/// +/// +/// +/// + +import * as React from "react"; +import * as ReactDOM from "react-dom"; +import * as ReactDOMServer from "react-dom/server"; +import BigCalendar from 'react-big-calendar'; + +// Init localizer +BigCalendar.momentLocalizer(moment); + +// Testing examples from demos page +// http://intljusticemission.github.io/react-big-calendar/examples/index.html + +// Basic Example Test +const BasicExample = React.createClass({ + render() { + return ( + + ); + } +}); +ReactDOM.render(, document.body); +const basicExampleHtml = ReactDOMServer.renderToString(); +console.log('Test Results -> BasicExample', basicExampleHtml); + +// Full API Example Test - based on API Documentation +// http://intljusticemission.github.io/react-big-calendar/examples/index.html#api +const FullAPIExample = React.createClass({ + render() { + return ( + { } } + onView={() => { } } + onSelectSlot={(slotInfo) => { + const start = slotInfo.start; + const end = slotInfo.end; + const slots = slotInfo.slots; + } } + onSelectEvent={(event) => { } } + onSelecting={(slotInfo) => { + const start = slotInfo.start; + const end = slotInfo.end; + return true; + } } + views={{}} + toolbar={true} + popup={true} + popupOffset={20} + selectable={true} + step={20} + rtl={true} + eventPropGetter={(event, start, end, isSelected) => { } } + titleAccessor={'string'} + allDayAccessor={true} + startAccessor={new Date()} + endAccessor={new Date()} + min={new Date()} + max={new Date()} + scrollToTime={new Date()} + formats={{}} + components={{}} + messages={{}} + /> + ); + } +}); +ReactDOM.render(, document.body); +const fullApiExampleHtml = ReactDOMServer.renderToString(); +console.log('Test Results -> FullAPIExample', fullApiExampleHtml); + +// Test fixtures +function getEvents(): Object[] { + return [ + { + 'title': 'All Day Event', + 'allDay': true, + 'start': new Date(2015, 3, 0), + 'end': new Date(2015, 3, 0) + }, + { + 'title': 'Long Event', + 'start': new Date(2015, 3, 7), + 'end': new Date(2015, 3, 10) + }, + + { + 'title': 'DTS STARTS', + 'start': new Date(2016, 2, 13, 0, 0, 0), + 'end': new Date(2016, 2, 20, 0, 0, 0) + }, + + { + 'title': 'DTS ENDS', + 'start': new Date(2016, 10, 6, 0, 0, 0), + 'end': new Date(2016, 10, 13, 0, 0, 0) + }, + + { + 'title': 'Some Event', + 'start': new Date(2015, 3, 9, 0, 0, 0), + 'end': new Date(2015, 3, 9, 0, 0, 0) + }, + { + 'title': 'Conference', + 'start': new Date(2015, 3, 11), + 'end': new Date(2015, 3, 13), + desc: 'Big conference for important people' + }, + { + 'title': 'Meeting', + 'start': new Date(2015, 3, 12, 10, 30, 0, 0), + 'end': new Date(2015, 3, 12, 12, 30, 0, 0), + desc: 'Pre-meeting meeting, to prepare for the meeting' + }, + { + 'title': 'Lunch', + 'start': new Date(2015, 3, 12, 12, 0, 0, 0), + 'end': new Date(2015, 3, 12, 13, 0, 0, 0), + desc: 'Power lunch' + }, + { + 'title': 'Meeting', + 'start': new Date(2015, 3, 12, 14, 0, 0, 0), + 'end': new Date(2015, 3, 12, 15, 0, 0, 0) + }, + { + 'title': 'Happy Hour', + 'start': new Date(2015, 3, 12, 17, 0, 0, 0), + 'end': new Date(2015, 3, 12, 17, 30, 0, 0), + desc: 'Most important meal of the day' + }, + { + 'title': 'Dinner', + 'start': new Date(2015, 3, 12, 20, 0, 0, 0), + 'end': new Date(2015, 3, 12, 21, 0, 0, 0) + }, + { + 'title': 'Birthday Party', + 'start': new Date(2015, 3, 13, 7, 0, 0), + 'end': new Date(2015, 3, 13, 10, 30, 0) + } + ]; +}; diff --git a/react-big-calendar/react-big-calendar.d.ts b/react-big-calendar/react-big-calendar.d.ts new file mode 100644 index 0000000000..3886a4ca59 --- /dev/null +++ b/react-big-calendar/react-big-calendar.d.ts @@ -0,0 +1,54 @@ +// Type definitions for react-big-calendar v0.10.X +// Project: https://github.com/intljusticemission/react-big-calendar +// Definitions by: Piotr Witek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'react-big-calendar' { + import * as React from 'react'; + + type stringOrDate = string | Date; + + interface BigCalendarProps extends React.Props { + date?: stringOrDate; + view?: string; + events?: Object[]; + onNavigate?: Function; + onView?: Function; + onSelectSlot?: (slotInfo: { start: stringOrDate, end: stringOrDate, slots: Date[] | string[] }) => void; + onSelectEvent?: (event: Object) => void; + onSelecting?: (slotInfo: { start: stringOrDate, end: stringOrDate }) => boolean; + views?: Object; + toolbar?: boolean; + popup?: boolean; + popupOffset?: number | { x: number, y: number }; + selectable?: boolean; + step?: number; + rtl?: boolean; + eventPropGetter?: (event: Object, start: stringOrDate, end: stringOrDate, isSelected: boolean) => void; + titleAccessor?: string; + allDayAccessor?: boolean; + startAccessor?: stringOrDate; + endAccessor?: stringOrDate; + min?: stringOrDate; + max?: stringOrDate; + scrollToTime?: stringOrDate; + formats?: Object; + components?: Object; + messages?: Object; + } + + export class BigCalendar extends React.Component { + /** + * Setup the localizer by providing the moment Object + */ + static momentLocalizer(momentInstance: Object): void; + /** + * Setup the localizer by providing the globalize Object + */ + static globalizeLocalizer(globalizeInstance: Object): void; + } + + export default BigCalendar; +} diff --git a/react-bootstrap/index.d.ts b/react-bootstrap/index.d.ts index c6649ab95d..3641a4c751 100644 --- a/react-bootstrap/index.d.ts +++ b/react-bootstrap/index.d.ts @@ -4,1041 +4,1099 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as React from 'react'; - - -type Sizes = 'xs' | 'xsmall' | 'sm' | 'small' | 'lg' | 'large'; - - -// Change onSelect signature to be (eventKey: any, event: SyntheticEvent) => any on all React-Bootstrap components, instead of the old inconsistent mishmash (#1604, #1677, #1756) -/** ( eventKey:any, e:React.SyntheticEvent ):void */ -interface SelectCallback { - (eventKey: any, e: React.SyntheticEvent): void; - /** - @deprecated - This signature is a hack so can still derive from HTMLProps. - It does not reflect the underlying event and should not be used. - */ - (e: React.MouseEvent): void; -} - - -interface TransitionCallbacks { - onEnter?: Function; - onEntered?: Function; - onEntering?: Function; - onExit?: Function; - onExited?: Function; - onExiting?: Function; -} - - -// -interface AccordionProps extends React.HTMLProps { - bsSize?: Sizes; - bsStyle?: string; - collapsible?: boolean; - defaultExpanded?: boolean; - eventKey?: any; - expanded?: boolean; - footer?: any; // TODO: Add more specific type - header?: any; // TODO: Add more specific type -} -type Accordion = React.ClassicComponent; -export var Accordion: React.ClassicComponentClass; - -// -interface BreadcrumbProps - extends React.Props { - bsClass?: string; -} -interface BreadcrumbClass - extends React.ClassicComponentClass { - Item: typeof BreadcrumbItem; -} -type Breadcrumb = React.ClassicComponent; -export var Breadcrumb: BreadcrumbClass; - - -// -interface BreadcrumbItemProps - extends React.Props { - active?: boolean; - id?: string | number; - linkId?: string | number; - href?: string; - title?: React.ReactNode; - target?: string; -} -type BreadcrumbItem = React.ClassicComponent; -export var BreadcrumbItem: React.ClassicComponentClass; - - -//