diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 7f3c8671de..3938bc24d1 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3009,6 +3009,7 @@ /types/proj4leaflet/ @BendingBender /types/project-oxford/ @scsouthw /types/promise-dag/ @OSjoerdWie +/types/promise-map-limit/ @kohlmannj /types/promise-pg/ @coldacid /types/promise-polyfill/ @skysteve /types/promise-pool/ @vilic diff --git a/README.es.md b/README.es.md index ce94bb0298..c3cff967db 100644 --- a/README.es.md +++ b/README.es.md @@ -87,6 +87,7 @@ Primero, haz un [fork](https://guides.github.com/activities/forking/) en este re * `cd types/my-package-to-edit` * Haz cambios. Recuerda editar las pruebas. + Si realiza cambios importantes, no olvide [actualizar una versión principal](#quiero-actualizar-un-paquete-a-una-nueva-versión-principal). * También puede que quieras añadirte la sección "Definitions by" en el encabezado del paquete. - Esto hará que seas notificado (a través de tu nombre de usuario en GitHub) cada vez que alguien haga un pull request o issue sobre el paquete. - Haz esto añadiendo tu nombre al final de la línea, así como en `// Definitions by: Alice , Bob `. diff --git a/README.md b/README.md index 7c58fe8901..554316e52a 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,7 @@ First, [fork](https://guides.github.com/activities/forking/) this repository, in * `cd types/my-package-to-edit` * Make changes. Remember to edit tests. + If you make breaking changes, do not forget to [update a major version](#i-want-to-update-a-package-to-a-new-major-version). * You may also want to add yourself to "Definitions by" section of the package header. - This will cause you to be notified (via your GitHub username) whenever someone makes a pull request or issue about the package. - Do this by adding your name to the end of the line, as in `// Definitions by: Alice , Bob `. diff --git a/notNeededPackages.json b/notNeededPackages.json index 6f3e4fe093..dd5523d102 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -660,6 +660,12 @@ "sourceRepoURL": "https://github.com/ashtuchkin/iconv-lite", "asOfVersion": "0.4.14" }, + { + "libraryName": "ids", + "typingsPackageName": "ids", + "sourceRepoURL": "https://github.com/bpmn-io/ids", + "asOfVersion": "0.2.2" + }, { "libraryName": "immutability-helper", "typingsPackageName": "immutability-helper", diff --git a/package.json b/package.json index db67595b77..37d1f4d48b 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "private": true, "name": "definitely-typed", - "version": "0.0.1", + "version": "0.0.2", "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped", "repository": { "type": "git", diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts index b1e013bea9..828aab87c2 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -3039,6 +3039,37 @@ declare namespace AceAjax { **/ new(container: HTMLElement, theme?: string): VirtualRenderer; } + + export interface Completer { + /** + * Provides possible completion results asynchronously using the given callback. + * @param editor The editor to associate with + * @param session The `EditSession` to refer to + * @param pos An object containing the row and column + * @param prefix The prefixing string before the current position + * @param callback Function to provide the results or error + */ + getCompletions: (editor: Editor, session: IEditSession, pos: Position, prefix: string, callback: CompletionCallback) => void; + + /** + * Provides tooltip information about a completion result. + * @param item The completion result + */ + getDocTooltip?: (item: Completion) => void; + } + + export interface Completion { + value: string; + meta: string; + type?: string; + caption?: string; + snippet?: any; + score?: number; + exactMatch?: number; + docHTML?: string; + } + + export type CompletionCallback = (error: Error, results: Completion[]) => void; } declare var ace: AceAjax.Ace; diff --git a/types/adone/glosses/application.d.ts b/types/adone/glosses/app.d.ts similarity index 90% rename from types/adone/glosses/application.d.ts rename to types/adone/glosses/app.d.ts index 4c9661843a..1c6dee3369 100644 --- a/types/adone/glosses/application.d.ts +++ b/types/adone/glosses/app.d.ts @@ -1,5 +1,5 @@ declare namespace adone { - namespace application { + namespace app { namespace I { type ArgumentType = ((x: string, index: number) => any) | RegExp; @@ -12,7 +12,7 @@ declare namespace adone { | "append" | "count" | "set"; - nargs?: number | "+" | "*" | "?" + nargs?: number | "+" | "*" | "?"; type?: ArgumentType | ArgumentType[]; verify?: (args: any, opts: any) => boolean; // TODO required?: boolean; @@ -49,7 +49,7 @@ declare namespace adone { name?: string; description?: string; subsystems?: SubsystemInfo[]; - commandsGroups?: Group[] + commandsGroups?: Group[]; } interface SubsystemInfo { @@ -71,24 +71,24 @@ declare namespace adone { namespace I { interface LoadSubsystemOptions { - name?: string, - description?: string, - group?: string, - transpile?: boolean + name?: string; + description?: string; + group?: string; + transpile?: boolean; } interface CommonAddSubsystemInfo { - name?: string, - useFilename?: boolean - description?: string, - group?: string, - configureArgs?: any[] - transpile?: boolean, - bind?: boolean | string + name?: string; + useFilename?: boolean; + description?: string; + group?: string; + configureArgs?: any[]; + transpile?: boolean; + bind?: boolean | string; } interface AddSubsystemInfo extends CommonAddSubsystemInfo { - subsystem: Subsystem | string, + subsystem: Subsystem | string; } interface SysInfo { @@ -109,7 +109,7 @@ declare namespace adone { } interface AddSubsystemsFromOptions extends CommonAddSubsystemInfo { - filter?: string[] | ((file: string) => boolean | Promise) + filter?: string[] | ((file: string) => boolean | Promise); } } @@ -211,25 +211,22 @@ declare namespace adone { _rejectionHandled(p: Promise): void; _signalExit(sigName: string): void; - } namespace I { interface Command { - // ? + names: string[]; + // TODO } interface Argument { - // ? + names: string[]; + // TODO } - interface PositionalArgument extends Argument { - // ? - } + type PositionalArgument = Argument; // TODO - interface OptionalArgument extends Argument { - // ? - } + type OptionalArgument = Argument; // TODO interface DefineCommandFromSubsystemOptions { name?: string; diff --git a/types/adone/glosses/is.d.ts b/types/adone/glosses/is.d.ts index 011b906234..bf8bb0a347 100644 --- a/types/adone/glosses/is.d.ts +++ b/types/adone/glosses/is.d.ts @@ -320,12 +320,12 @@ declare namespace adone { /** * Checks whether the given object is an adone subsystem */ - export function subsystem(obj: any): obj is adone.application.Subsystem; + export function subsystem(obj: any): obj is adone.app.Subsystem; /** * Checks whether the given object is an adone application */ - export function application(obj: any): obj is adone.application.Application; + export function application(obj: any): obj is adone.app.Application; /** * Checks whether the given object is an adone logger diff --git a/types/adone/index.d.ts b/types/adone/index.d.ts index a74641c4df..c6add2eeea 100644 --- a/types/adone/index.d.ts +++ b/types/adone/index.d.ts @@ -5,7 +5,7 @@ // TypeScript Version: 2.4 /// -/// +/// /// /// /// diff --git a/types/adone/test/glosses/application.ts b/types/adone/test/glosses/app.ts similarity index 99% rename from types/adone/test/glosses/application.ts rename to types/adone/test/glosses/app.ts index 38c5b0c8ff..8d74c8093b 100644 --- a/types/adone/test/glosses/application.ts +++ b/types/adone/test/glosses/app.ts @@ -8,7 +8,7 @@ namespace applicationTests { Subsystem, runCli, Application - } = adone.application; + } = adone.app; namespace DApplicationTests { { diff --git a/types/adone/tsconfig.json b/types/adone/tsconfig.json index 3f02029dcc..7194901d7a 100644 --- a/types/adone/tsconfig.json +++ b/types/adone/tsconfig.json @@ -24,6 +24,7 @@ "adone.d.ts", "async.d.ts", "benchmark.d.ts", + "glosses/app.d.ts", "glosses/archives.d.ts", "glosses/assertion.d.ts", "glosses/collections/array_set.d.ts", @@ -95,7 +96,7 @@ "glosses/utils.d.ts", "glosses/vault.d.ts", "index.d.ts", - "test/glosses/application.ts", + "test/glosses/app.ts", "test/glosses/archives.ts", "test/glosses/assertion.ts", "test/glosses/collections/array_set.ts", diff --git a/types/aframe/aframe-tests.ts b/types/aframe/aframe-tests.ts index 5af66a09d1..5e2bd23e36 100644 --- a/types/aframe/aframe-tests.ts +++ b/types/aframe/aframe-tests.ts @@ -21,9 +21,9 @@ type MyEntity = AFrame.Entity<{ material: THREE.Material; sound: { pause(): void }; }>; -const camera = document.querySelector('a-entity[camera]').components.camera; -const material = document.querySelector('a-entity[material]').components.material; -document.querySelector('a-entity[sound]').components.sound.pause(); +const camera = (document.querySelector('a-entity[camera]') as MyEntity).components.camera; +const material = (document.querySelector('a-entity[material]') as MyEntity).components.material; +(document.querySelector('a-entity[sound]') as MyEntity).components.sound.pause(); entity.getDOMAttribute('geometry').primitive; @@ -38,21 +38,82 @@ entity.addEventListener('child-detached', (event) => { }); // Components -const Component = AFRAME.registerComponent('test', {}); + +interface TestComponent extends AFrame.Component { + multiply: (f: number) => number; + + data: { + myProperty: any[], + string: string, + num: number + }; + + system: TestSystem; +} + +const Component = AFRAME.registerComponent('test-component', { + schema: { + myProperty: { + default: [], + parse() { return [true]; }, + }, + string: { type: 'string' }, + num: 0 + }, + init() { + this.data.num = 0; + }, + update() {}, + tick() {}, + remove() {}, + pause() {}, + play() {}, + + multiply(this: TestComponent, f: number) { + // Reference to system because both were registered with the same name. + return f * this.data.num * this.system.data.counter; + } +}); // Scene const scene = document.querySelector('a-scene'); scene.hasLoaded; // System -const system = scene.systems['systemName']; + +interface TestSystem extends AFrame.System { + data: { + counter: number; + }; +} + +const testSystem: AFrame.SystemDefinition = { + schema: { + counter: 0 + }, + + init() { + this.data.counter = 1; + } +}; + +AFRAME.registerSystem('test-component', testSystem); // Register Custom Geometry -AFRAME.registerGeometry('a-test-geometry', { + +interface TestGeometry extends AFrame.Geometry { + schema: AFrame.MultiPropertySchema<{ + groupIndex: number; + }>; +} + +AFRAME.registerGeometry('a-test-geometry', { schema: { groupIndex: { default: 0 } }, init(data) { this.geometry = new THREE.Geometry(); + const temp = data.groupIndex; + temp; } }); diff --git a/types/aframe/index.d.ts b/types/aframe/index.d.ts index 0da1ed0ef5..b405de0273 100644 --- a/types/aframe/index.d.ts +++ b/types/aframe/index.d.ts @@ -2,6 +2,7 @@ // Project: https://aframe.io/ // Definitions by: Paul Shannon // Roberto Ritger +// Trygve Wastvedt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -19,7 +20,7 @@ declare var hasNativeWebVRImplementation: boolean; interface Document { createElement(tagName: string): AFrame.Entity; querySelector(selectors: 'a-scene'): AFrame.Scene; - querySelector>(selectors: string): T; + querySelector(selectors: string): AFrame.Entity; querySelectorAll(selectors: string): NodeListOf | Element>; } @@ -36,15 +37,15 @@ declare namespace AFrame { components: { [ key: string ]: ComponentDescriptor }; geometries: { [ key: string ]: GeometryDescriptor }; primitives: { [ key: string ]: Entity }; - registerComponent(name: string, component: ComponentDefinition): ComponentConstructor; + registerComponent(name: string, component: ComponentDefinition): ComponentConstructor; registerElement(name: string, element: ANode): void; - registerGeometry(name: string, geometry: GeometryDefinition): Geometry; + registerGeometry(name: string, geometry: GeometryDefinition): GeometryConstructor; registerPrimitive(name: string, primitive: PrimitiveDefinition): void; - registerShader(name: string, shader: any): void; - registerSystem(name: string, definition: SystemDefinition): void; + registerShader(name: string, shader: T): ShaderConstructor; + registerSystem(name: string, definition: SystemDefinition): SystemConstructor; schema: SchemaUtils; shaders: { [ key: string ]: ShaderDescriptor }; - systems: { [key: string]: System }; + systems: { [key: string]: SystemConstructor }; THREE: typeof THREE; TWEEN: typeof TWEEN; utils: Utils; @@ -89,54 +90,39 @@ declare namespace AFrame { tick(): void; } - interface Component { + interface Component { attrName?: string; - data?: any; + data: T; dependencies?: string[]; el: Entity; id: string; multiple?: boolean; name: string; - schema: Schema; + schema: Schema; + system: S | undefined; - init(data?: any): void; - pause(): void; - play(): void; - remove(): void; - tick?(time: number, timeDelta: number): void; - update(oldData: any): void; - updateSchema?(): void; + init(this: this, data?: T): void; + pause(this: this): void; + play(this: this): void; + remove(this: this): void; + tick?(this: this, time: number, timeDelta: number): void; + update(this: this, oldData: T): void; + updateSchema?(this: this): void; - extendSchema(update: Schema): void; - flushToDOM(): void; + extendSchema(this: this, update: Schema): void; + flushToDOM(this: this): void; } - interface ComponentConstructor { - new (el: Entity, name: string, id: string): Component; + interface ComponentConstructor { + new (el: Entity, attrValue: string, id: string): T; } - interface ComponentDefinition { - dependencies?: string[]; - el?: Entity; - id?: string; - multiple?: boolean; - schema?: Schema; + type ComponentDefinition = Partial; - init?(data?: any): void; - pause?(): void; - play?(): void; - remove?(): void; - tick?(time: number, timeDelta: number): void; - update?(oldData: any): void; - updateSchema?(): void; - - [ key: string ]: any; - } - - interface ComponentDescriptor { - Component: Component; - dependencies: string[] | null; - multiple: boolean | null; + interface ComponentDescriptor { + Component: ComponentConstructor; + dependencies: string[] | undefined; + multiple: boolean | undefined; // internal APIs2 // parse @@ -144,7 +130,6 @@ declare namespace AFrame { // schema // stringify // type - [ key: string ]: any; } interface Coordinate { @@ -153,8 +138,14 @@ declare namespace AFrame { z: number; } + interface DefaultComponents { + position: Component; + rotation: Component; + scale: Component; + } + interface Entity> extends ANode { - components: C; + components: C & DefaultComponents; isPlaying: boolean; object3D: THREE.Object3D; object3DMap: ObjectMap; @@ -165,8 +156,8 @@ declare namespace AFrame { /** * @deprecated since 0.4.0 */ - getComputedAttribute(attr: string): T; - getDOMAttribute(attr: string): T; + getComputedAttribute(attr: string): Component; + getDOMAttribute(attr: string): any; getObject3D(type: string): THREE.Object3D; getOrCreateObject3D(type: string, construct: any): THREE.Object3D; is(stateName: string): boolean; @@ -179,7 +170,6 @@ declare namespace AFrame { // getAttribute specific usages getAttribute(type: string): any; - getAttribute(attr: string): T; getAttribute(type: 'position' | 'rotation' | 'scale'): Coordinate; // setAttribute specific usages @@ -192,12 +182,18 @@ declare namespace AFrame { addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } - type DetailEvent = Event & { detail: D }; + type DetailEvent = Event & { + detail: D; + target: EventTarget & Entity; + }; interface EntityEventMap { 'child-attached': DetailEvent<{ el: Element | Entity }>; 'child-detached': DetailEvent<{ el: Element | Entity }>; - 'componentchanged': DetailEvent<{ name: string }>; + 'componentchanged': DetailEvent<{ + name: string, + id: string + }>; 'componentremoved': DetailEvent<{ name: string, id: string, @@ -215,23 +211,28 @@ declare namespace AFrame { interface Geometry { name: string; geometry: THREE.Geometry; - schema: Schema; - update(data: object): void; - [ key: string ]: any; + schema: Schema; + + init(this: this, data: { [P in keyof this['schema']]: any }): void; + // Would like the above to be: + // init?(this: this, data?: { [P in keyof T['schema']]: T['schema'][P]['default'] } ): void; + // I think this is prevented by the following issue: https://github.com/Microsoft/TypeScript/issues/21760. } - interface GeometryDefinition extends ComponentDefinition { - geometry?: THREE.Geometry; + interface GeometryConstructor { + new (): T; } - interface GeometryDescriptor { - Geometry: Geometry; + type GeometryDefinition = Partial; + + interface GeometryDescriptor { + Geometry: GeometryConstructor; schema: Schema; } - interface MultiPropertySchema { - [ key: string ]: SinglePropertySchema; - } + type MultiPropertySchema = { + [P in keyof T]: SinglePropertySchema | T[P]; + }; interface PrimitiveDefinition { defaultComponents?: any; // TODO cleanup type @@ -240,8 +241,9 @@ declare namespace AFrame { transforms?: any; // TODO cleanup type } - type PropertyTypes = 'array' | 'boolean' | 'color' | 'int' | 'number' | 'selector' | - 'selectorAll' | 'src' | 'string' | 'vec2' | 'vec3' | 'vec4'; + type PropertyTypes = 'array' | 'asset' | 'audio' | 'boolean' | 'color' | + 'int' | 'map' | 'model' | 'number' | 'selector' | 'selectorAll' | + 'string' | 'vec2' | 'vec3' | 'vec4'; type SceneEvents = 'enter-vr' | 'exit-vr' | 'loaded' | 'renderstart'; @@ -265,7 +267,7 @@ declare namespace AFrame { addEventListener(type: SceneEvents, listener: EventListener, useCapture?: boolean): void; } - type Schema = SinglePropertySchema | MultiPropertySchema; + type Schema = SinglePropertySchema | MultiPropertySchema; interface SchemaUtils { isSingleProperty(schema: Schema): boolean; @@ -274,11 +276,25 @@ declare namespace AFrame { interface Shader { name: string; - schema: Schema; + data: { [key: string]: any }; + schema: Schema; + material: THREE.Material; + vertexShader: string; + fragmentShader: string; + + init(this: this, data?: this['data']): void; + tick?(this: this, time: number, timeDelta: number): void; + update(this: this, oldData: this['data']): void; } - interface ShaderDescriptor { - Shader: Shader; + interface ShaderConstructor { + new (): T; + } + + type ShaderDefinition = Partial; + + interface ShaderDescriptor { + Shader: ShaderConstructor; schema: Schema; } @@ -287,27 +303,23 @@ declare namespace AFrame { 'default'?: T; parse?(value: string): T; stringify?(value: T): string; - [ key: string ]: any; } interface System { - data: any; - schema: Schema; - init(): void; - pause(): void; - play(): void; - tick?(): void; + data: { [key: string]: any }; + schema: Schema; + init(this: this): void; + pause(this: this): void; + play(this: this): void; + tick?(this: this, t: number, dt: number): void; } - interface SystemDefinition { - schema?: Schema; - init?(): void; - pause?(): void; - play?(): void; - tick?(): void; - [ key: string ]: any; + interface SystemConstructor { + new (scene: Scene): T; } + type SystemDefinition = Partial; + interface Utils { coordinates: { isCoordinate(value: string): boolean; @@ -326,5 +338,8 @@ declare namespace AFrame { diff(a: object, b: object): object; extend(target: object, ... source: object[]): object; extendDeep(target: object, ... source: object[]): object; + + throttle(tickFunction: () => void, minimumInterval: number, optionalContext?: {}): (t: number, dt: number) => void; + throttleTick(tickFunction: (t: number, dt: number) => void, minimumInterval: number, optionalContext?: {}): (t: number, dt: number) => void; } } diff --git a/types/aframe/tslint.json b/types/aframe/tslint.json index 71ee04c4e1..495d29983d 100644 --- a/types/aframe/tslint.json +++ b/types/aframe/tslint.json @@ -1,6 +1,5 @@ { "extends": "dtslint/dt.json", "rules": { - "no-unnecessary-generics": false } } diff --git a/types/algoliasearch/algoliasearch-tests.ts b/types/algoliasearch/algoliasearch-tests.ts index 0814b0fc03..2898f889fc 100644 --- a/types/algoliasearch/algoliasearch-tests.ts +++ b/types/algoliasearch/algoliasearch-tests.ts @@ -2,16 +2,16 @@ import * as algoliasearch from 'algoliasearch'; import { ClientOptions, SynonymOption, - AlgoliaApiKeyOptions, + ApiKeyOptions, SearchSynonymOptions, - AlgoliaResponse, - AlgoliaSecuredApiOptions, - AlgoliaIndexSettings, - AlgoliaQueryParameters, - AlgoliaIndex, + SecuredApiOptions, + Index, + Response, + IndexSettings, + QueryParameters, } from 'algoliasearch'; -let _algoliaResponse: AlgoliaResponse = { +let _algoliaResponse: Response = { hits: [{}, {}], page: 0, nbHits: 12, @@ -33,7 +33,7 @@ let _synonymOption: SynonymOption = { replaceExistingSynonyms: false, }; -let _algoliaApiKeyOptions: AlgoliaApiKeyOptions = { +let _algoliaApiKeyOptions: ApiKeyOptions = { validity: 0, maxQueriesPerIPPerHour: 0, indexes: [''], @@ -48,14 +48,14 @@ let _searchSynonymOptions: SearchSynonymOptions = { hitsPerPage: 0, }; -let _algoliaSecuredApiOptions: AlgoliaSecuredApiOptions = { +let _algoliaSecuredApiOptions: SecuredApiOptions = { filters: '', validUntil: 0, restrictIndices: '', userToken: '', }; -let _algoliaIndexSettings: AlgoliaIndexSettings = { +let _algoliaIndexSettings: IndexSettings = { attributesToIndex: [''], attributesForFaceting: [''], unretrievableAttributes: [''], @@ -63,7 +63,7 @@ let _algoliaIndexSettings: AlgoliaIndexSettings = { ranking: [''], customRanking: [''], replicas: [''], - maxValuesPerFacet: '', + maxValuesPerFacet: 100, attributesToHighlight: [''], attributesToSnippet: [''], highlightPreTag: '', @@ -96,13 +96,13 @@ let _algoliaIndexSettings: AlgoliaIndexSettings = { placeholders: '', }; -let _algoliaQueryParameters: AlgoliaQueryParameters = { +let _algoliaQueryParameters: QueryParameters = { query: '', filters: '', attributesToRetrieve: [''], restrictSearchableAttributes: [''], facets: '', - maxValuesPerFacet: '', + maxValuesPerFacet: 2, attributesToHighlight: [''], attributesToSnippet: [''], highlightPreTag: '', @@ -147,7 +147,20 @@ let _algoliaQueryParameters: AlgoliaQueryParameters = { minProximity: 0, }; -let index: AlgoliaIndex = algoliasearch('', '').initIndex(''); +let index: Index = algoliasearch('', '').initIndex(''); let search = index.search({ query: '' }); + index.search({ query: '' }, (err, res) => {}); + +// partialUpdateObject +index.partialUpdateObject({}, () => {}); +index.partialUpdateObject({}, false, () => {}); +index.partialUpdateObject({}).then(() => {}); +index.partialUpdateObject({}, false).then(() => {}); + +// partialUpdateObjects +index.partialUpdateObjects([{}], () => {}); +index.partialUpdateObjects([{}], false, () => {}); +index.partialUpdateObjects([{}]).then(() => {}); +index.partialUpdateObjects([{}], false).then(() => {}); diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index 3304ad579d..87c1f79a0e 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for algoliasearch-client-js 3.24.8 +// Type definitions for algoliasearch-client-js 3.27.0 // Project: https://github.com/algolia/algoliasearch-client-js // Definitions by: Baptiste Coquelle // Haroen Viaene @@ -7,87 +7,44 @@ // TypeScript Version: 2.2 declare namespace algoliasearch { - interface AlgoliaResponse { - /** - * Contains all the hits matching the query - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - hits: any[]; - /** - * Current page - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - page: number; - /** - * Number of total hits matching the query - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - nbHits: number; - /** - * Number of pages - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - nbPages: number; - /** - * Number of hits per pages - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - hitsPerPage: number; - /** - * Engine processing time (excluding network transfer) - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - processingTimeMS: number; - /** - * Query used to perform the search - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - query: string; - /** - * GET parameters used to perform the search - * https://github.com/algolia/algoliasearch-client-js#response-format - */ - params: string; - } - interface AlgoliaMultiResponse { - results: AlgoliaResponse[]; - } - /* - Interface for the algolia client object - */ - interface AlgoliaClient { + /** + * Interface for the algolia client object + */ + interface Client { /** * Initialization of the index - * @param name: index name - * return algolia index object * https://github.com/algolia/algoliasearch-client-js#init-index---initindex */ - initIndex(name: string): AlgoliaIndex; + initIndex(indexName: string): Index; /** * Query on multiple index - * @param queries index name, query and query parameters - * @param cb callback(err, res) * https://github.com/algolia/algoliasearch-client-js#multiple-queries---multiplequeries */ search( queries: { indexName: string; query: string; - params: AlgoliaQueryParameters; + params: QueryParameters; }[], - cb: (err: Error, res: AlgoliaMultiResponse) => void + cb: (err: Error, res: MultiResponse) => void ): void; /** * Query on multiple index - * @param queries index name, query and query parameters - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#multiple-queries---multiplequeries */ - search(queries: { - indexName: string; - query: string; - params: AlgoliaQueryParameters; - }[]): Promise; + search( + queries: { + indexName: string; + query: string; + params: QueryParameters; + }[] + ): Promise; + /** + * Query for facet values of a specific facet + */ + searchForFacetValues( + queries: [{ indexName: string; params: SearchForFacetValues.Parameters }] + ): Promise; /** * clear browser cache * https://github.com/algolia/algoliasearch-client-js#cache @@ -107,336 +64,255 @@ declare namespace algoliasearch { */ getExtraHeader(name: string): string; /** - * remove an extra header for all upcoming requests + * Remove an extra header for all upcoming requests */ unsetExtraHeader(name: string): void; /** * List all your indices along with their associated information (number of entries, disk size, etc.) - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#list-indices---listindexes */ listIndexes(cb: (err: Error, res: any) => void): void; /** * List all your indices along with their associated information (number of entries, disk size, etc.) - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#list-indices---listindexes */ listIndexes(): Promise; /** * Delete a specific index - * @param name - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-index---deleteindex */ - deleteIndex(name: string, cb: (err: Error, res: any) => void): void; + deleteIndex(name: string, cb: (err: Error, res: Task) => void): void; /** * Delete a specific index - * @param name - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#delete-index---deleteindex */ - deleteIndex(name: string): Promise; + deleteIndex(name: string): Promise; /** * Copy an index from a specific index to a new one - * @param from origin index - * @param to destination index - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#copy-index---copyindex */ copyIndex( from: string, to: string, - cb: (err: Error, res: any) => void + scope: ('settings' | 'synonyms' | 'rules')[], + cb: (err: Error, res: Task) => void ): void; /** * Copy an index from a specific index to a new one - * @param from origin index - * @param to destination index - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#copy-index---copyindex */ - copyIndex(from: string, to: string): Promise; + copyIndex( + from: string, + to: string, + scope: ('settings' | 'synonyms' | 'rules')[] + ): Promise; /** * Move index to a new one (and will overwrite the original one) - * @param from origin index - * @param to destination index - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#move-index---moveindex */ moveIndex( from: string, to: string, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Move index to a new one (and will overwrite the original one) - * @param from origin index - * @param to destination index - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#move-index---moveindex */ - moveIndex(from: string, to: string): Promise; + moveIndex(from: string, to: string): Promise; /** * Generate a public API key - * @param key api key - * @param filters * https://github.com/algolia/algoliasearch-client-js#generate-key---generatesecuredapikey */ - generateSecuredApiKey( - key: string, - filters: AlgoliaSecuredApiOptions - ): string; + generateSecuredApiKey(key: string, filters: SecuredApiOptions): string; /** * Perform multiple operations with one API call to reduce latency - * @param action - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch */ - batch(action: AlgoliaAction[], cb: (err: Error, res: any) => void): void; + batch(action: Action[], cb: (err: Error, res: Task) => void): void; /** * Perform multiple operations with one API call to reduce latency - * @param action - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch */ - batch(action: AlgoliaAction[]): Promise; + batch(action: Action[]): Promise; /** * Lists global API Keys - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ listApiKeys(cb: (err: Error, res: any) => void): void; /** * Lists global API Keys - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ listApiKeys(): Promise; /** * Add global API Keys - * @param scopes - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ - addApiKey(scopes: string[], cb: (err: Error, res: any) => void): void; + addApiKey(scopes: string[], cb: (err: Error, res: Task) => void): void; /** * Add global API Key - * @param scopes - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ addApiKey( scopes: string[], - options: AlgoliaApiKeyOptions, - cb: (err: Error, res: any) => void + options: ApiKeyOptions, + cb: (err: Error, res: Task) => void ): void; /** * Add global API Keys - * @param scopes - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ - addApiKey(scopes: string[], options?: AlgoliaApiKeyOptions): Promise; + addApiKey(scopes: string[], options?: ApiKeyOptions): Promise; /** * Update global API key - * @param key - * @param scopes - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ updateApiKey( key: string, scopes: string[], - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Update global API key - * @param key - * @param scopes - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ updateApiKey( key: string, scopes: string[], - options: AlgoliaApiKeyOptions, - cb: (err: Error, res: any) => void + options: ApiKeyOptions, + cb: (err: Error, res: Task) => void ): void; /** * Update global API key - * @param key - * @param scopes - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ updateApiKey( key: string, scopes: string[], - options?: AlgoliaApiKeyOptions - ): Promise; + options?: ApiKeyOptions + ): Promise; /** * Gets the rights of a global key - * @param key - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ getApiKey(key: string, cb: (err: Error, res: any) => void): void; /** * Gets the rights of a global key - * @param key - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ getApiKey(key: string): Promise; /** * Deletes a global key - * @param key - * @param cb(err,res) * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteapikey */ - deleteApiKey(key: string, cb: (err: Error, res: any) => void): void; + deleteApiKey(key: string, cb: (err: Error, res: Task) => void): void; /** * Deletes a global key - * @param key - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteapikey */ - deleteApiKey(key: string): Promise; + deleteApiKey(key: string): Promise; /** * Get 1000 last events - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs */ - getLogs(options: LogsOptions, cb: (err: Error, res: any) => void): void; + getLogs( + options: LogsOptions, + cb: (err: Error, res: { logs: Log[] }) => void + ): void; /** * Get 1000 last events - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs */ - getLogs(options: LogsOptions): Promise; + getLogs(options: LogsOptions): Promise<{ logs: Log[] }>; } /** * Interface for the index algolia object */ - interface AlgoliaIndex { + interface Index { /** * Gets a specific object - * @param objectID - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects */ - getObject(objectID: string, cb: (err: Error, res: any) => void): void; + getObject(objectID: string, cb: (err: Error, res: {}) => void): void; /** * Gets specific attributes from an object - * @param objectID - * @param attributes - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects */ getObject( objectID: string, attributes: string[], - cb: (err: Error, res: any) => void + cb: (err: Error, res: {}) => void ): void; /** * Gets a list of objects - * @param objectIDs - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects */ - getObjects(objectIDs: string[], cb: (err: Error, res: any) => void): void; + getObjects( + objectIDs: string[], + cb: (err: Error, res: { results: {}[] }) => void + ): void; /** * Add a specific object - * @param object without objectID - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects */ - addObject(object: {}, cb: (err: Error, res: any) => void): void; + addObject(object: {}, cb: (err: Error, res: Task) => void): void; /** * Add a list of objects - * @param object with objectID - * @param objectID - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects */ addObject( object: {}, objectID: string, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Add list of objects - * @param objects - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects */ - addObjects(objects: {}[], cb: (err: Error, res: any) => void): void; + addObjects(objects: {}[], cb: (err: Error, res: Task) => void): void; /** * Add or replace a specific object - * @param object - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - saveObject(object: {}, cb: (err: Error, res: any) => void): void; + saveObject(object: {}, cb: (err: Error, res: Task) => void): void; /** * Add or replace several objects - * @param objects - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - saveObjects(objects: object[], cb: (err: Error, res: any) => void): void; + saveObjects(objects: object[], cb: (err: Error, res: Task) => void): void; /** * Update parameters of a specific object - * @param object - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - partialUpdateObject(object: {}, cb: (err: Error, res: any) => void): void; + partialUpdateObject(object: {}, cb: (err: Error, res: Task) => void): void; + partialUpdateObject(object: {}, createIfNotExists: boolean, cb: (err: Error, res: Task) => void): void; /** * Update parameters of a list of objects - * @param objects - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - partialUpdateObjects( - objects: {}[], - cb: (err: Error, res: any) => void - ): void; + partialUpdateObjects(objects: {}[], cb: (err: Error, res: Task) => void): void; + partialUpdateObjects(objects: {}[], createIfNotExists: boolean, cb: (err: Error, res: Task) => void): void; /** * Delete a specific object - * @param objectID - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects */ - deleteObject(objectID: string, cb: (err: Error, res: any) => void): void; + deleteObject(objectID: string, cb: (err: Error, res: Task) => void): void; /** * Delete a list of objects - * @param objectIDs - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects */ deleteObjects( objectIDs: string[], - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Delete objects that matches the query - * @param query - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-by-query---deletebyquery */ deleteByQuery(query: string, cb: (err: Error, res: any) => void): void; /** * Delete objects that matches the query - * @param query - * @param params of the object - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-by-query---deletebyquery */ deleteByQuery( @@ -446,34 +322,26 @@ declare namespace algoliasearch { ): void; /** * Delete objects that matches the query - * @param query - * @param params of the object - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-by-query---deleteby */ - deleteBy(params: {}, cb: (err: Error, res: any) => void): void; + deleteBy(params: {}, cb: (err: Error, res: Task) => void): void; /** * Wait for an indexing task to be compete - * @param taskID - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#wait-for-operations---waittask */ waitTask(taskID: number, cb: (err: Error, res: any) => void): void; /** * Get an index settings - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#get-settings---getsettings */ - getSettings(cb: (err: Error, res: any) => void): void; + getSettings(cb: (err: Error, res: IndexSettings) => void): void; /** * Set an index settings - * @param settings - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#set-settings---setsettings */ setSettings( - settings: AlgoliaIndexSettings, - cb: (err: Error, res: any) => void + settings: IndexSettings, + cb: (err: Error, res: Task) => void ): void; /** * Clear cache of an index @@ -482,66 +350,53 @@ declare namespace algoliasearch { clearCache(): void; /** * Clear an index content - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#clear-index---clearindex */ - clearIndex(cb: (err: Error, res: any) => void): void; + clearIndex(cb: (err: Error, res: Task) => void): void; /** * Save a synonym object - * @param synonym - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym */ saveSynonym( - synonym: AlgoliaSynonym, + synonym: Synonym, options: SynonymOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Save a synonym object - * @param synonyms - * @param options - * @param cb(err, res) */ batchSynonyms( - synonyms: AlgoliaSynonym[], + synonyms: Synonym[], options: SynonymOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Delete a specific synonym - * @param identifier - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#batch-synonyms---batchsynonyms */ deleteSynonym( identifier: string, options: SynonymOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Clear all synonyms of an index - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#clear-all-synonyms---clearsynonyms */ clearSynonyms( options: SynonymOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Get a specific synonym - * @param identifier - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#get-synonym---getsynonym */ - getSynonym(identifier: string, cb: (err: Error, res: any) => void): void; + getSynonym( + identifier: string, + cb: (err: Error, res: Synonym) => void + ): void; /** * Search a synonyms - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms */ searchSynonyms( @@ -550,57 +405,42 @@ declare namespace algoliasearch { ): void; /** * Save a rule object - * @param rule - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#save-rule---saverule */ saveRule( - rule: AlgoliaRule, + rule: Rule, options: RuleOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Save a rule object - * @param rules - * @param options - * @param cb(err, res) */ batchRules( - rules: AlgoliaRule[], + rules: Rule[], options: RuleOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Delete a specific rule - * @param identifier - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#batch-rules---batchrules */ deleteRule( identifier: string, options: RuleOption, - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Clear all rules of an index - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#clear-all-rules---clearrules */ - clearRules(options: RuleOption, cb: (err: Error, res: any) => void): void; + clearRules(options: RuleOption, cb: (err: Error, res: Task) => void): void; /** * Get a specific rule - * @param identifier - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#get-rule---getrule */ - getRule(identifier: string, cb: (err: Error, res: any) => void): void; + getRule(identifier: string, cb: (err: Error, res: Rule) => void): void; /** * Search a rules - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#search-rules---searchrules */ searchRules( @@ -609,403 +449,286 @@ declare namespace algoliasearch { ): void; /** * List index user keys - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#list-api-keys---listapikeys */ listApiKeys(cb: (err: Error, res: any) => void): void; /** * Add key for this index - * @param scopes - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ - addApiKey(scopes: string[], cb: (err: Error, res: any) => void): void; + addApiKey(scopes: string[], cb: (err: Error, res: Task) => void): void; /** * Add key for this index - * @param scopes - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ addApiKey( scopes: string[], - options: AlgoliaApiKeyOptions, - cb: (err: Error, res: any) => void + options: ApiKeyOptions, + cb: (err: Error, res: Task) => void ): void; /** * Update a key for this index - * @param key - * @param scopes - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ updateApiKey( key: string, scopes: string[], - cb: (err: Error, res: any) => void + cb: (err: Error, res: Task) => void ): void; /** * Update a key for this index - * @param key - * @param scopes - * @param options - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ updateApiKey( key: string, scopes: string[], - options: AlgoliaApiKeyOptions, - cb: (err: Error, res: any) => void + options: ApiKeyOptions, + cb: (err: Error, res: Task) => void ): void; /** * Gets the rights of an index specific key - * @param key - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#get-key-permissions---getapikeyacl */ getApiKey(key: string, cb: (err: Error, res: any) => void): void; /** * Deletes an index specific key - * @param key - * @param cb(err, res) * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteapikey */ - deleteApiKey(key: string, cb: (err: Error, res: any) => void): void; + deleteApiKey(key: string, cb: (err: Error, res: Task) => void): void; /** * Gets specific attributes from an object - * @param objectID - * @param attributes - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects */ - getObject(objectID: string, attributes?: string[]): Promise; + getObject(objectID: string, attributes?: string[]): Promise<{}>; /** * Gets a list of objects - * @param objectIDs - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects */ - getObjects(objectIDs: string[]): Promise; + getObjects(objectIDs: string[]): Promise<{ results: {}[] }>; /** * Add a list of objects - * @param object with objectID - * @param objectID - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects */ - addObject(object: {}, objectID?: string): Promise; + addObject(object: {}, objectID?: string): Promise; /** * Add list of objects - * @param objects - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects */ - addObjects(objects: {}[]): Promise; + addObjects(objects: {}[]): Promise; /** * Add or replace a specific object - * @param object - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - saveObject(object: {}): Promise; + saveObject(object: {}): Promise; /** * Add or replace several objects - * @param objects - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - saveObjects(objects: object[]): Promise; + saveObjects(objects: object[]): Promise; /** * Update parameters of a specific object - * @param object - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - partialUpdateObject(object: {}): Promise; + partialUpdateObject(object: {}): Promise; + partialUpdateObject(object: {}, createIfNotExists: boolean): Promise; /** * Update parameters of a list of objects - * @param objects - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects */ - partialUpdateObjects(objects: {}[]): Promise; + partialUpdateObjects(objects: {}[]): Promise; + partialUpdateObjects(objects: {}[], createIfNotExists?: boolean): Promise; /** * Delete a specific object - * @param objectID - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects */ - deleteObject(objectID: string): Promise; + deleteObject(objectID: string): Promise; /** * Delete a list of objects - * @param objectIDs - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects */ - deleteObjects(objectIDs: string[]): Promise; + deleteObjects(objectIDs: string[]): Promise; /** * Delete objects that matches the query - * @param query - * @param params of the object - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#delete-by-query---deletebyquery */ deleteByQuery(query: string, params?: {}): Promise; /** * Delete objects that matches the query - * @param params of the search - * return {Promise} * https://www.algolia.com/doc/api-reference/api-methods/delete-by-query/ */ - deleteBy(params: {}): Promise; + deleteBy(params: {}): Promise; /** * Wait for an indexing task to be compete - * @param taskID - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#wait-for-operations---waittask */ waitTask(taskID: number): Promise; /** * Get an index settings - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#get-settings---getsettings */ - getSettings(): Promise; + getSettings(): Promise; /** * Set an index settings - * @param settings - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#set-settings---setsettings */ - setSettings(settings: AlgoliaIndexSettings): Promise; + setSettings(settings: IndexSettings): Promise; /** * Search in an index - * @param params query parameter - * return {Promise} - * @param err() error callback * https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search */ - search(params: AlgoliaQueryParameters): Promise; + search(params: QueryParameters): Promise; /** * Search in an index - * @param params query parameter - * @param cb(err, res) - * @param err() error callback * https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search */ search( - params: AlgoliaQueryParameters, - cb: (err: Error, res: AlgoliaResponse) => void + params: QueryParameters, + cb: (err: Error, res: Response) => void ): void; /** * Search in an index - * @param params query parameter - * return {Promise} - * @param err() error callback * https://www.algolia.com/doc/api-reference/api-methods/search-for-facet-values/ */ - searchForFacetValues(options: { - facetName: string; - facetQuery: string; - } & AlgoliaQueryParameters): Promise; + searchForFacetValues( + options: SearchForFacetValues.Parameters + ): Promise; /** * Search in an index - * @param params query parameter - * @param cb(err, res) - * @param err() error callback * https://www.algolia.com/doc/api-reference/api-methods/search-for-facet-values/ */ - searchForFacetValues(options: { - facetName: string; - facetQuery: string; - } & AlgoliaQueryParameters, - cb: (err: Error, res: any) => void + searchForFacetValues( + options: SearchForFacetValues.Parameters, + cb: (err: Error, res: SearchForFacetValues.Response) => void ): void; /** * Browse an index - * @param query - * @param cb(err, content) * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browse(query: string, cb: (err: Error, res: any) => void): void; + browse(query: string, cb: (err: Error, res: BrowseResponse) => void): void; /** * Browse an index - * @param query - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browse(query: string): Promise; + browse(query: string): Promise; /** * Browse an index from a cursor - * @param cursor - * @param cb(err, content) * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browseFrom(cursor: string, cb: (err: Error, res: any) => void): void; + browseFrom( + cursor: string, + cb: (err: Error, res: BrowseResponse) => void + ): void; /** * Browse an index from a cursor - * @param cursor - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browseFrom(cursor: string): Promise; + browseFrom(cursor: string): Promise; /** * Browse an entire index - * return Promise * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browseAll(): Promise; + browseAll(): Promise; /** * Clear an index content - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#clear-index---clearindex */ - clearIndex(): Promise; + clearIndex(): Promise; /** * Save a synonym object - * @param synonym - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym */ - saveSynonym(synonym: AlgoliaSynonym, options: SynonymOption): Promise; + saveSynonym(synonym: Synonym, options: SynonymOption): Promise; /** * Save a synonym object - * @param synonyms - * @param options - * return {Promise} */ - batchSynonyms( - synonyms: AlgoliaSynonym[], - options: SynonymOption - ): Promise; + batchSynonyms(synonyms: Synonym[], options: SynonymOption): Promise; /** * Delete a specific synonym - * @param identifier - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#batch-synonyms---batchsynonyms */ - deleteSynonym(identifier: string, options: SynonymOption): Promise; + deleteSynonym(objectID: string, options: SynonymOption): Promise; /** * Clear all synonyms of an index - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#clear-all-synonyms---clearsynonyms */ - clearSynonyms(options: SynonymOption): Promise; + clearSynonyms(options: SynonymOption): Promise; /** * Get a specific synonym - * @param identifier - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#get-synonym---getsynonym */ - getSynonym(identifier: string): Promise; + getSynonym(objectID: string): Promise; /** * Search a synonyms - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms */ searchSynonyms(options: SearchSynonymOptions): Promise; /** * Save a rule object - * @param rule - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#save-rule---saverule */ - saveRule(rule: AlgoliaRule, options: RuleOption): Promise; + saveRule(rule: Rule, options: RuleOption): Promise; /** * Save a rule object - * @param rules - * @param options - * return {Promise} */ - batchRules(rules: AlgoliaRule[], options: RuleOption): Promise; + batchRules(rules: Rule[], options: RuleOption): Promise; /** * Delete a specific rule - * @param identifier - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#batch-rules---batchrules */ - deleteRule(identifier: string, options: RuleOption): Promise; + deleteRule(identifier: string, options: RuleOption): Promise; /** * Clear all query rules of an index - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#clear-all-rules---clearrules */ - clearRules(options: RuleOption): Promise; + clearRules(options: RuleOption): Promise; /** * Get a specific query rule - * @param identifier - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#get-rule---getrule */ - getRule(identifier: string): Promise; + getRule(identifier: string): Promise; /** * Search for query rules - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#search-rules---searchrules */ searchRules(options: SearchRuleOptions): Promise; /** * List index user keys - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#list-api-keys---listapikeys */ listApiKeys(): Promise; /** * Add key for this index - * @param scopes - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ - addApiKey(scopes: string[], options?: AlgoliaApiKeyOptions): Promise; + addApiKey(scopes: string[], options?: ApiKeyOptions): Promise; /** * Update a key for this index - * @param key - * @param scopes - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ - updateApiKey(key: string, scopes: string[]): Promise; + updateApiKey(key: string, scopes: string[]): Promise; /** * Update a key for this index - * @param key - * @param scopes - * @param options - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateapikey */ updateApiKey( key: string, scopes: string[], - options: AlgoliaApiKeyOptions - ): Promise; + options: ApiKeyOptions + ): Promise; /** * Gets the rights of an index specific key - * @param key - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#get-key-permissions---getapikeyacl */ getApiKey(key: string): Promise; /** * Deletes an index specific key - * @param key - * return {Promise} * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteapikey */ - deleteApiKey(key: string): Promise; + deleteApiKey(key: string): Promise; } - /* -Interface describing available options when initializing a client -*/ + /** + * Interface describing available options when initializing a client + */ interface ClientOptions { /** * Timeout for requests to our servers, in milliseconds @@ -1020,20 +743,20 @@ Interface describing available options when initializing a client */ protocol?: string; /** - * (node only) httpAgent instance to use when communicating with Algolia servers. + * (node only) httpAgent instance to use when communicating with servers. * https://github.com/algolia/algoliasearch-client-js#client-options */ httpAgent?: any; /** - * read: array of read hosts to use to call Algolia servers, computed automatically - * write: array of read hosts to use to call Algolia servers, computed automatically + * read: array of read hosts to use to call servers, computed automatically + * write: array of read hosts to use to call servers, computed automatically * https://github.com/algolia/algoliasearch-client-js#client-options */ hosts?: { read?: string[]; write?: string[] }; } - /* -Interface describing options available for gettings the logs -*/ + /** + * Interface describing options available for gettings the logs + */ interface LogsOptions { /** * Specify the first entry to retrieve (0-based, 0 is the most recent log entry). @@ -1062,11 +785,15 @@ Interface describing options available for gettings the logs * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs */ type?: string; + /** + * The index to request logs from + */ + indexName?: string; } /** * Describe the action object used for batch operation */ - interface AlgoliaAction { + interface Action { /** * Type of the batch action * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch @@ -1093,7 +820,7 @@ Interface describing options available for gettings the logs /** * Describes the option used when creating user key */ - interface AlgoliaApiKeyOptions { + interface ApiKeyOptions { /** * Add a validity period. The key will be valid for a specific period of time (in seconds). * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey @@ -1123,7 +850,7 @@ Interface describing options available for gettings the logs * Specify the list of query parameters * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey */ - queryParameters?: AlgoliaQueryParameters; + queryParameters?: QueryParameters; /** * Specify a description to describe where the key is used. * https://github.com/algolia/algoliasearch-client-js#add-user-key---addapikey @@ -1216,9 +943,9 @@ Interface describing options available for gettings the logs */ hitsPerPage?: number; } - interface AlgoliaBrowseResponse { + interface BrowseResponse { cursor?: string; - hits: any[]; + hits: {}[]; params: string; query: string; processingTimeMS: number; @@ -1226,7 +953,7 @@ Interface describing options available for gettings the logs /** * Describes a synonym object */ - interface AlgoliaSynonym { + interface Synonym { /** * ObjectID of the synonym * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym @@ -1246,7 +973,7 @@ Interface describing options available for gettings the logs /** * Describes a query rule object */ - interface AlgoliaRule { + interface Rule { /** * ObjectID of the synonym * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym @@ -1332,7 +1059,7 @@ Interface describing options available for gettings the logs /** * Describes the options used when generating new api keys */ - interface AlgoliaSecuredApiOptions { + interface SecuredApiOptions { /** * Filter the query with numeric, facet or/and tag filters * default: "" @@ -1355,266 +1082,7 @@ Interface describing options available for gettings the logs */ userToken?: string; } - - /** - * Describes the settings available for configure your index - */ - interface AlgoliaIndexSettings { - /** - * The list of attributes you want index - * default: * - * https://github.com/algolia/algoliasearch-client-js#attributestoindex - */ - attributesToIndex?: string[]; - /** - * The list of attributes you want to use for faceting - * default: null - * https://github.com/algolia/algoliasearch-client-js#attributesforfaceting - */ - attributesForFaceting?: string[]; - /** - * The list of attributes that cannot be retrieved at query time - * default: null - * https://github.com/algolia/algoliasearch-client-js#unretrievableattributes - */ - unretrievableAttributes?: string[]; - /** - * List of attributes you want to use for textual search - * default: [] - * https://github.com/algolia/algoliasearch-client-js#searchableattributes - */ - searchableAttributes?: string[]; - /** - * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer - * default: * - * https://github.com/algolia/algoliasearch-client-js#attributestoretrieve - */ - attributesToRetrieve?: string[]; - /** - * Controls the way results are sorted - * default: ['typo', 'geo', 'words', 'filters', 'proximity', 'attribute', 'exact', 'custom'] - * https://github.com/algolia/algoliasearch-client-js#ranking - */ - ranking?: string[]; - /** - * Lets you specify part of the ranking - * default: [] - * https://github.com/algolia/algoliasearch-client-js#customranking - */ - customRanking?: string[]; - /** - * The list of indices on which you want to replicate all write operations - * default: [] - * https://github.com/algolia/algoliasearch-client-js#replicas - */ - replicas?: string[]; - /** - * Limit the number of facet values returned for each facet - * default: "" - * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet - */ - maxValuesPerFacet?: string; - /** - * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted. - * default: null - * https://github.com/algolia/algoliasearch-client-js#attributestohighlight - */ - attributesToHighlight?: string[]; - /** - * Default list of attributes to snippet alongside the number of words to return - * default: null - * https://github.com/algolia/algoliasearch-client-js#attributestosnippet - */ - attributesToSnippet?: string[]; - /** - * Specify the string that is inserted before the highlighted parts in the query result - * default: - * https://github.com/algolia/algoliasearch-client-js#highlightpretag - */ - highlightPreTag?: string; - /** - * Specify the string that is inserted after the highlighted parts in the query result - * default: - * https://github.com/algolia/algoliasearch-client-js#highlightposttag - */ - highlightPostTag?: string; - /** - * String used as an ellipsis indicator when a snippet is truncated. - * default: … - * https://github.com/algolia/algoliasearch-client-js#snippetellipsistext - */ - snippetEllipsisText?: string; - /** - * If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets - * default: false - * https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays - */ - restrictHighlightAndSnippetArrays?: boolean; - /** - * Pagination parameter used to select the number of hits per page - * default: 20 - * https://github.com/algolia/algoliasearch-client-js#hitsperpage - */ - hitsPerPage?: number; - /** - * The minimum number of characters needed to accept one typo - * default: 4 - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo - */ - minWordSizefor1Typo?: number; - /** - * The minimum number of characters needed to accept two typos. - * default: 8 - * https://github.com/algolia/algoliasearch-client-js#highlightposttag - */ - minWordSizefor2Typos?: number; - /** - * This option allows you to control the number of typos allowed in the result set - * default: true - * 'true' The typo tolerance is enabled and all matching hits are retrieved (default behavior). - * 'false' The typo tolerance is disabled. All results with typos will be hidden. - * 'min' Only keep results with the minimum number of typos. For example, if one result matches without typos, then all results with typos will be hidden. - * 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos. - * https://github.com/algolia/algoliasearch-client-js#typotolerance - */ - typoTolerance?: any; - /** - * If set to false, disables typo tolerance on numeric tokens (numbers). - * default: true - * https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens - */ - allowTyposOnNumericTokens?: boolean; - /** - * If set to true, plural won't be considered as a typo - * default: false - * https://github.com/algolia/algoliasearch-client-js#ignoreplurals - */ - ignorePlurals?: boolean; - /** - * List of attributes on which you want to disable typo tolerance - * default: "" - * https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes - */ - disableTypoToleranceOnAttributes?: string; - /** - * Specify the separators (punctuation characters) to index. - * default: "" - * https://github.com/algolia/algoliasearch-client-js#separatorstoindex - */ - separatorsToIndex?: string; - /** - * Selects how the query words are interpreted - * default: 'prefixLast' - * 'prefixAll' All query words are interpreted as prefixes. This option is not recommended. - * 'prefixLast' Only the last word is interpreted as a prefix (default behavior). - * 'prefixNone' No query word is interpreted as a prefix. This option is not recommended. - * https://github.com/algolia/algoliasearch-client-js#querytype - */ - queryType?: any; - /** - * This option is used to select a strategy in order to avoid having an empty result page - * default: 'none' - * 'lastWords' When a query does not return any results, the last word will be added as optional - * 'firstWords' When a query does not return any results, the first word will be added as optional - * 'allOptional' When a query does not return any results, a second trial will be made with all words as optional - * 'none' No specific processing is done when a query does not return any results - * https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults - */ - removeWordsIfNoResults?: string; - /** - * Enables the advanced query syntax - * default: false - * https://github.com/algolia/algoliasearch-client-js#advancedsyntax - */ - advancedSyntax?: boolean; - /** - * A string that contains the comma separated list of words that should be considered as optional when found in the query - * default: [] - * https://github.com/algolia/algoliasearch-client-js#optionalwords - */ - optionalWords?: string[]; - /** - * Remove stop words from the query before executing it - * default: false - * true|false: enable or disable stop words for all 41 supported languages; or - * a list of language ISO codes (as a comma-separated string) for which stop words should be enable - * https://github.com/algolia/algoliasearch-client-js#removestopwords - */ - removeStopWords?: string[]; - /** - * List of attributes on which you want to disable prefix matching - * default: [] - * https://github.com/algolia/algoliasearch-client-js#disableprefixonattributes - */ - disablePrefixOnAttributes?: string[]; - /** - * List of attributes on which you want to disable the computation of exact criteria - * default: [] - * https://github.com/algolia/algoliasearch-client-js#disableexactonattributes - */ - disableExactOnAttributes?: string[]; - /** - * This parameter control how the exact ranking criterion is computed when the query contains one word - * default: attribute - * 'none': no exact on single word query - * 'word': exact set to 1 if the query word is found in the record - * 'attribute': exact set to 1 if there is an attribute containing a string equals to the query - * https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery - */ - exactOnSingleWordQuery?: string; - /** - * Specify the list of approximation that should be considered as an exact match in the ranking formula - * default: ['ignorePlurals', 'singleWordSynonym'] - * 'ignorePlurals': alternative words added by the ignorePlurals feature - * 'singleWordSynonym': single-word synonym (For example "NY" = "NYC") - * 'multiWordsSynonym': multiple-words synonym - * https://github.com/algolia/algoliasearch-client-js#alternativesasexact - */ - alternativesAsExact?: any; - /** - * The name of the attribute used for the Distinct feature - * default: null - * https://github.com/algolia/algoliasearch-client-js#attributefordistinct - */ - attributeForDistinct?: string; - /** - * If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set. - * https://github.com/algolia/algoliasearch-client-js#distinct - */ - distinct?: any; - /** - * All numerical attributes are automatically indexed as numerical filters - * default '' - * https://github.com/algolia/algoliasearch-client-js#numericattributestoindex - */ - numericAttributesToIndex?: string[]; - /** - * Allows compression of big integer arrays. - * default: false - * https://github.com/algolia/algoliasearch-client-js#allowcompressionofintegerarray - */ - allowCompressionOfIntegerArray?: boolean; - /** - * Specify alternative corrections that you want to consider. - * default: [] - * https://github.com/algolia/algoliasearch-client-js#altcorrections - */ - altCorrections?: {}[]; - /** - * Configure the precision of the proximity ranking criterion - * default: 1 - * https://github.com/algolia/algoliasearch-client-js#minproximity - */ - minProximity?: number; - /** - * This is an advanced use-case to define a token substitutable by a list of words without having the original token searchable - * default: '' - * https://github.com/algolia/algoliasearch-client-js#placeholders - */ - placeholders?: any; - } - - interface AlgoliaQueryParameters { + interface QueryParameters { /** * Query string used to perform the search * default: '' @@ -1650,7 +1118,7 @@ Interface describing options available for gettings the logs * default: "" * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet */ - maxValuesPerFacet?: string; + maxValuesPerFacet?: number; /** * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted. * default: null @@ -1922,6 +1390,408 @@ Interface describing options available for gettings the logs * https://github.com/algolia/algoliasearch-client-js#minproximity */ minProximity?: number; + + nbShards?: number; + userData?: string | object; + } + + interface AlgoliaResponse { + /** + * Contains all the hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hits: any[]; + /** + * Current page + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + page: number; + /** + * Number of total hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbHits: number; + /** + * Number of pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbPage: number; + /** + * Number of hits per pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hitsPerPage: number; + /** + * Engine processing time (excluding network transfer) + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + processingTimeMS: number; + /** + * Query used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + query: string; + /** + * GET parameters used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + params: string; + facets: { + [facetName: string]: { [facetValue: string]: number }; + }; + } + + namespace SearchForFacetValues { + interface Parameters extends QueryParameters { + /** + * The facet to search in + */ + facetName: string; + /** + * The query for the search in this facet + */ + facetQuery: string; + } + + interface Response { + facetHits: { value: string; highlighted: string; count: number }[]; + exhaustiveFacetsCount: boolean; + processingTimeMS: number; + } + } + + interface Log { + timestamp: string; + method: string; + answer_code: number; + query_body: string; + answer: string; + url: string; + ip: string; + query_headers: string; + sha1: string; + nb_api_calls: string; + index: string; + query_params: string; + query_nb_hits: string; + processing_time_ms: string; + exhaustive_faceting?: false; + exhaustive_nb_hits?: false; + } + + interface Task { + taskID: number; + } + + interface IndexSettings { + /** + * The list of attributes you want index + * default: * + * https://github.com/algolia/algoliasearch-client-js#attributestoindex + */ + attributesToIndex?: string[]; + /** + * The list of attributes you want to use for faceting + * default: null + * https://github.com/algolia/algoliasearch-client-js#attributesforfaceting + */ + attributesForFaceting?: string[]; + /** + * The list of attributes that cannot be retrieved at query time + * default: null + * https://github.com/algolia/algoliasearch-client-js#unretrievableattributes + */ + unretrievableAttributes?: string[]; + /** + * List of attributes you want to use for textual search + * default: [] + * https://github.com/algolia/algoliasearch-client-js#searchableattributes + */ + searchableAttributes?: string[]; + /** + * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer + * default: * + * https://github.com/algolia/algoliasearch-client-js#attributestoretrieve + */ + attributesToRetrieve?: string[]; + /** + * Controls the way results are sorted + * default: ['typo', 'geo', 'words', 'filters', 'proximity', 'attribute', 'exact', 'custom'] + * https://github.com/algolia/algoliasearch-client-js#ranking + */ + ranking?: string[]; + /** + * Lets you specify part of the ranking + * default: [] + * https://github.com/algolia/algoliasearch-client-js#customranking + */ + customRanking?: string[]; + /** + * The list of indices on which you want to replicate all write operations + * default: [] + * https://github.com/algolia/algoliasearch-client-js#replicas + */ + replicas?: string[]; + /** + * Limit the number of facet values returned for each facet + * default: "" + * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet + */ + maxValuesPerFacet?: number; + /** + * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted. + * default: null + * https://github.com/algolia/algoliasearch-client-js#attributestohighlight + */ + attributesToHighlight?: string[]; + /** + * Default list of attributes to snippet alongside the number of words to return + * default: null + * https://github.com/algolia/algoliasearch-client-js#attributestosnippet + */ + attributesToSnippet?: string[]; + /** + * Specify the string that is inserted before the highlighted parts in the query result + * default: + * https://github.com/algolia/algoliasearch-client-js#highlightpretag + */ + highlightPreTag?: string; + /** + * Specify the string that is inserted after the highlighted parts in the query result + * default: + * https://github.com/algolia/algoliasearch-client-js#highlightposttag + */ + highlightPostTag?: string; + /** + * String used as an ellipsis indicator when a snippet is truncated. + * default: … + * https://github.com/algolia/algoliasearch-client-js#snippetellipsistext + */ + snippetEllipsisText?: string; + /** + * If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets + * default: false + * https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays + */ + restrictHighlightAndSnippetArrays?: boolean; + /** + * Pagination parameter used to select the number of hits per page + * default: 20 + * https://github.com/algolia/algoliasearch-client-js#hitsperpage + */ + hitsPerPage?: number; + /** + * The minimum number of characters needed to accept one typo + * default: 4 + * https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo + */ + minWordSizefor1Typo?: number; + /** + * The minimum number of characters needed to accept two typos. + * default: 8 + * https://github.com/algolia/algoliasearch-client-js#highlightposttag + */ + minWordSizefor2Typos?: number; + /** + * This option allows you to control the number of typos allowed in the result set + * default: true + * 'true' The typo tolerance is enabled and all matching hits are retrieved (default behavior). + * 'false' The typo tolerance is disabled. All results with typos will be hidden. + * 'min' Only keep results with the minimum number of typos. For example, if one result matches without typos, then all results with typos will be hidden. + * 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos. + * https://github.com/algolia/algoliasearch-client-js#typotolerance + */ + typoTolerance?: any; + /** + * If set to false, disables typo tolerance on numeric tokens (numbers). + * default: true + * https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens + */ + allowTyposOnNumericTokens?: boolean; + /** + * If set to true, plural won't be considered as a typo + * default: false + * https://github.com/algolia/algoliasearch-client-js#ignoreplurals + */ + ignorePlurals?: boolean; + /** + * List of attributes on which you want to disable typo tolerance + * default: "" + * https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes + */ + disableTypoToleranceOnAttributes?: string; + /** + * Specify the separators (punctuation characters) to index. + * default: "" + * https://github.com/algolia/algoliasearch-client-js#separatorstoindex + */ + separatorsToIndex?: string; + /** + * Selects how the query words are interpreted + * default: 'prefixLast' + * 'prefixAll' All query words are interpreted as prefixes. This option is not recommended. + * 'prefixLast' Only the last word is interpreted as a prefix (default behavior). + * 'prefixNone' No query word is interpreted as a prefix. This option is not recommended. + * https://github.com/algolia/algoliasearch-client-js#querytype + */ + queryType?: any; + /** + * This option is used to select a strategy in order to avoid having an empty result page + * default: 'none' + * 'lastWords' When a query does not return any results, the last word will be added as optional + * 'firstWords' When a query does not return any results, the first word will be added as optional + * 'allOptional' When a query does not return any results, a second trial will be made with all words as optional + * 'none' No specific processing is done when a query does not return any results + * https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults + */ + removeWordsIfNoResults?: string; + /** + * Enables the advanced query syntax + * default: false + * https://github.com/algolia/algoliasearch-client-js#advancedsyntax + */ + advancedSyntax?: boolean; + /** + * A string that contains the comma separated list of words that should be considered as optional when found in the query + * default: [] + * https://github.com/algolia/algoliasearch-client-js#optionalwords + */ + optionalWords?: string[]; + /** + * Remove stop words from the query before executing it + * default: false + * true|false: enable or disable stop words for all 41 supported languages; or + * a list of language ISO codes (as a comma-separated string) for which stop words should be enable + * https://github.com/algolia/algoliasearch-client-js#removestopwords + */ + removeStopWords?: string[]; + /** + * List of attributes on which you want to apply word-splitting ("decompounding") for + * each of the languages supported (German, Dutch, and Finnish as of 05/2018) + * default: {de: [], nl: [], fi: []} + */ + decompoundedAttributes?: { [key in Partial<'nl' | 'de' | 'fi'>]: string[] }; + /** + * List of attributes on which you want to disable prefix matching + * default: [] + * https://github.com/algolia/algoliasearch-client-js#disableprefixonattributes + */ + disablePrefixOnAttributes?: string[]; + /** + * List of attributes on which you want to disable the computation of exact criteria + * default: [] + * https://github.com/algolia/algoliasearch-client-js#disableexactonattributes + */ + disableExactOnAttributes?: string[]; + /** + * This parameter control how the exact ranking criterion is computed when the query contains one word + * default: attribute + * 'none': no exact on single word query + * 'word': exact set to 1 if the query word is found in the record + * 'attribute': exact set to 1 if there is an attribute containing a string equals to the query + * https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery + */ + exactOnSingleWordQuery?: string; + /** + * Specify the list of approximation that should be considered as an exact match in the ranking formula + * default: ['ignorePlurals', 'singleWordSynonym'] + * 'ignorePlurals': alternative words added by the ignorePlurals feature + * 'singleWordSynonym': single-word synonym (For example "NY" = "NYC") + * 'multiWordsSynonym': multiple-words synonym + * https://github.com/algolia/algoliasearch-client-js#alternativesasexact + */ + alternativesAsExact?: any; + /** + * The name of the attribute used for the Distinct feature + * default: null + * https://github.com/algolia/algoliasearch-client-js#attributefordistinct + */ + attributeForDistinct?: string; + /** + * If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set. + * https://github.com/algolia/algoliasearch-client-js#distinct + */ + distinct?: any; + /** + * All numerical attributes are automatically indexed as numerical filters + * default '' + * https://github.com/algolia/algoliasearch-client-js#numericattributestoindex + */ + numericAttributesToIndex?: string[]; + /** + * Allows compression of big integer arrays. + * default: false + * https://github.com/algolia/algoliasearch-client-js#allowcompressionofintegerarray + */ + allowCompressionOfIntegerArray?: boolean; + /** + * Specify alternative corrections that you want to consider. + * default: [] + * https://github.com/algolia/algoliasearch-client-js#altcorrections + */ + altCorrections?: {}[]; + /** + * Configure the precision of the proximity ranking criterion + * default: 1 + * https://github.com/algolia/algoliasearch-client-js#minproximity + */ + minProximity?: number; + /** + * This is an advanced use-case to define a token substitutable by a list of words without having the original token searchable + * default: '' + * https://github.com/algolia/algoliasearch-client-js#placeholders + */ + placeholders?: any; + } + + interface Response { + /** + * Contains all the hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hits: any[]; + /** + * Current page + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + page: number; + /** + * Number of total hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbHits: number; + /** + * Number of pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbPages: number; + /** + * Number of hits per pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hitsPerPage: number; + /** + * Engine processing time (excluding network transfer) + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + processingTimeMS: number; + /** + * Query used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + query: string; + /** + * GET parameters used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + params: string; + facets?: { + [facetName: string]: { [facetValue: string]: number }; + }; + } + + interface MultiResponse { + results: Response[]; } } @@ -1929,5 +1799,5 @@ declare function algoliasearch( applicationId: string, apiKey: string, options?: algoliasearch.ClientOptions -): algoliasearch.AlgoliaClient; +): algoliasearch.Client; export = algoliasearch; diff --git a/types/algoliasearch/lite/index.d.ts b/types/algoliasearch/lite/index.d.ts new file mode 100644 index 0000000000..588e2ac543 --- /dev/null +++ b/types/algoliasearch/lite/index.d.ts @@ -0,0 +1,624 @@ +// Type definitions for algoliasearch-client-js 3.27.0 +// Project: https://github.com/algolia/algoliasearch-client-js +// Definitions by: Baptiste Coquelle +// Haroen Viaene +// Aurélien Hervé +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare namespace algoliasearch { + /* + Interface for the algolia client object + */ + interface Client { + /** + * Initialization of the index + * https://github.com/algolia/algoliasearch-client-js#init-index---initindex + */ + initIndex(indexName: string): Index; + /** + * Query on multiple index + * https://github.com/algolia/algoliasearch-client-js#multiple-queries---multiplequeries + */ + search( + queries: { + indexName: string; + query: string; + params: QueryParameters; + }[], + cb: (err: Error, res: MultiResponse) => void + ): void; + /** + * Query on multiple index + * https://github.com/algolia/algoliasearch-client-js#multiple-queries---multiplequeries + */ + search( + queries: { + indexName: string; + query: string; + params: QueryParameters; + }[] + ): Promise; + /** + * Query for facet values of a specific facet + */ + searchForFacetValues( + queries: [{ indexName: string; params: SearchForFacetValues.Parameters }] + ): Promise; + /** + * clear browser cache + * https://github.com/algolia/algoliasearch-client-js#cache + */ + clearCache(): void; + /** + * Add a header to be sent with all upcoming requests + */ + setExtraHeader(name: string, value: string): void; + /** + * Get the value of an extra header + */ + getExtraHeader(name: string): string; + /** + * remove an extra header for all upcoming requests + */ + unsetExtraHeader(name: string): void; + } + /** + * Interface for the index algolia object + */ + interface Index { + /** + * Gets a specific object + * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects + */ + getObject(objectID: string, cb: (err: Error, res: {}) => void): void; + /** + * Gets specific attributes from an object + * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects + */ + getObject( + objectID: string, + attributes: string[], + cb: (err: Error, res: {}) => void + ): void; + /** + * Gets a list of objects + * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects + */ + getObjects( + objectIDs: string[], + cb: (err: Error, res: { results: {}[] }) => void + ): void; + /** + * Gets a list of objects + * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects + */ + getObjects(objectIDs: string[]): Promise<{ results: {}[] }>; + /** + * Clear cache of an index + * https://github.com/algolia/algoliasearch-client-js#cache + */ + clearCache(): void; + /** + * Search in an index + * https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search + */ + search( + params: QueryParameters, + cb: (err: Error, res: Response) => void + ): void; + /** + * Search in an index + * https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search + */ + search(params: QueryParameters): Promise; + /** + * Search in an index + * https://www.algolia.com/doc/api-reference/api-methods/search-for-facet-values/ + */ + searchForFacetValues( + options: SearchForFacetValues.Parameters + ): Promise; + /** + * Search in an index + * https://www.algolia.com/doc/api-reference/api-methods/search-for-facet-values/ + */ + searchForFacetValues( + options: SearchForFacetValues.Parameters, + cb: (err: Error, res: SearchForFacetValues.Response) => void + ): void; + /** + * Browse an index + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + browse(query: string, cb: (err: Error, res: BrowseResponse) => void): void; + /** + * Browse an index + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + browse(query: string): Promise; + /** + * Browse an index from a cursor + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + browseFrom( + cursor: string, + cb: (err: Error, res: BrowseResponse) => void + ): void; + /** + * Browse an index from a cursor + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + browseFrom(cursor: string): Promise; + } + /** + * Interface describing available options when initializing a client + */ + interface ClientOptions { + /** + * Timeout for requests to our servers, in milliseconds + * default: 15s (node), 2s (browser) + * https://github.com/algolia/algoliasearch-client-js#client-options + */ + timeout?: number; + /** + * Protocol to use when communicating with algolia + * default: current protocol(browser), https(node) + * https://github.com/algolia/algoliasearch-client-js#client-options + */ + protocol?: string; + /** + * (node only) httpAgent instance to use when communicating with servers. + * https://github.com/algolia/algoliasearch-client-js#client-options + */ + httpAgent?: any; + /** + * read: array of read hosts to use to call servers, computed automatically + * write: array of read hosts to use to call servers, computed automatically + * https://github.com/algolia/algoliasearch-client-js#client-options + */ + hosts?: { read?: string[]; write?: string[] }; + } + interface BrowseResponse { + cursor?: string; + hits: {}[]; + params: string; + query: string; + processingTimeMS: number; + } + + interface QueryParameters { + /** + * Query string used to perform the search + * default: '' + * https://github.com/algolia/algoliasearch-client-js#query + */ + query?: string; + /** + * Filter the query with numeric, facet or/and tag filters + * default: "" + * https://github.com/algolia/algoliasearch-client-js#filters + */ + filters?: string; + /** + * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer. + * default: * + * https://github.com/algolia/algoliasearch-client-js#attributestoretrieve + */ + attributesToRetrieve?: string[]; + /** + * List of attributes you want to use for textual search + * default: attributeToIndex + * https://github.com/algolia/algoliasearch-client-js#restrictsearchableattributes + */ + restrictSearchableAttributes?: string[]; + /** + * You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes + * default: "" + * https://github.com/algolia/algoliasearch-client-js#facets + */ + facets?: string; + /** + * Limit the number of facet values returned for each facet. + * default: "" + * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet + */ + maxValuesPerFacet?: number; + /** + * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted. + * default: null + * https://github.com/algolia/algoliasearch-client-js#attributestohighlight + */ + attributesToHighlight?: string[]; + /** + * Default list of attributes to snippet alongside the number of words to return + * default: null + * https://github.com/algolia/algoliasearch-client-js#attributestosnippet + */ + attributesToSnippet?: string[]; + /** + * Specify the string that is inserted before the highlighted parts in the query result + * default: + * https://github.com/algolia/algoliasearch-client-js#highlightpretag + */ + highlightPreTag?: string; + /** + * Specify the string that is inserted after the highlighted parts in the query result + * default: + * https://github.com/algolia/algoliasearch-client-js#highlightposttag + */ + highlightPostTag?: string; + /** + * String used as an ellipsis indicator when a snippet is truncated. + * default: … + * https://github.com/algolia/algoliasearch-client-js#snippetellipsistext + */ + snippetEllipsisText?: string; + /** + * If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets + * default: false + * https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays + */ + restrictHighlightAndSnippetArrays?: boolean; + /** + * Pagination parameter used to select the number of hits per page + * default: 20 + * https://github.com/algolia/algoliasearch-client-js#hitsperpage + */ + hitsPerPage?: number; + /** + * Pagination parameter used to select the page to retrieve. + * default: 0 + * https://github.com/algolia/algoliasearch-client-js#page + */ + page?: number; + /** + * Offset of the first hit to return + * default: null + * https://github.com/algolia/algoliasearch-client-js#offset + */ + offset?: number; + /** + * Number of hits to return. + * default: null + * https://github.com/algolia/algoliasearch-client-js#length + */ + length?: number; + /** + * The minimum number of characters needed to accept one typo. + * default: 4 + * https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo + */ + minWordSizefor1Typo?: number; + /** + * The minimum number of characters needed to accept two typo. + * fault: 8 + * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos + */ + minWordSizefor2Typos?: number; + /** + * This option allows you to control the number of typos allowed in the result set: + * default: true + * 'true' The typo tolerance is enabled and all matching hits are retrieved + * 'false' The typo tolerance is disabled. All results with typos will be hidden. + * 'min' Only keep results with the minimum number of typos + * 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos. + * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos + */ + typoTolerance?: boolean; + /** + * If set to false, disables typo tolerance on numeric tokens (numbers). + * default: + * https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens + */ + allowTyposOnNumericTokens?: boolean; + /** + * If set to true, plural won't be considered as a typo + * default: false + * https://github.com/algolia/algoliasearch-client-js#ignoreplurals + */ + ignorePlurals?: boolean; + /** + * List of attributes on which you want to disable typo tolerance + * default: "" + * https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes + */ + disableTypoToleranceOnAttributes?: string; + /** + * Search for entries around a given location + * default: "" + * https://github.com/algolia/algoliasearch-client-js#aroundlatlng + */ + aroundLatLng?: string; + /** + * Search for entries around a given latitude/longitude automatically computed from user IP address. + * default: "" + * https://github.com/algolia/algoliasearch-client-js#aroundlatlngviaip + */ + aroundLatLngViaIP?: string; + /** + * Control the radius associated with a geo search. Defined in meters. + * default: null + * You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area + * https://github.com/algolia/algoliasearch-client-js#aroundradius + */ + aroundRadius?: number | 'all'; + /** + * Control the precision of a geo search + * default: null + * https://github.com/algolia/algoliasearch-client-js#aroundprecision + */ + aroundPrecision?: number; + /** + * Define the minimum radius used for a geo search when aroundRadius is not set. + * default: null + * https://github.com/algolia/algoliasearch-client-js#minimumaroundradius + */ + minimumAroundRadius?: number; + /** + * Search entries inside a given area defined by the two extreme points of a rectangle + * default: null + * https://github.com/algolia/algoliasearch-client-js#insideboundingbox + */ + insideBoundingBox?: number[][]; + /** + * Selects how the query words are interpreted + * default: 'prefixLast' + * 'prefixAll' All query words are interpreted as prefixes. This option is not recommended. + * 'prefixLast' Only the last word is interpreted as a prefix (default behavior). + * 'prefixNone' No query word is interpreted as a prefix. This option is not recommended. + * https://github.com/algolia/algoliasearch-client-js#querytype + */ + queryType?: any; + /** + * Search entries inside a given area defined by a set of points + * defauly: '' + * https://github.com/algolia/algoliasearch-client-js#insidepolygon + */ + insidePolygon?: number[][]; + /** + * This option is used to select a strategy in order to avoid having an empty result page + * default: 'none' + * 'lastWords' When a query does not return any results, the last word will be added as optional + * 'firstWords' When a query does not return any results, the first word will be added as optional + * 'allOptional' When a query does not return any results, a second trial will be made with all words as optional + * 'none' No specific processing is done when a query does not return any results + * https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults + */ + removeWordsIfNoResults?: string; + /** + * Enables the advanced query syntax + * default: false + * https://github.com/algolia/algoliasearch-client-js#advancedsyntax + */ + advancedSyntax?: boolean; + /** + * A string that contains the comma separated list of words that should be considered as optional when found in the query + * default: [] + * https://github.com/algolia/algoliasearch-client-js#optionalwords + */ + optionalWords?: string[]; + /** + * Remove stop words from the query before executing it + * default: false + * true|false: enable or disable stop words for all 41 supported languages; or + * a list of language ISO codes (as a comma-separated string) for which stop words should be enable + * https://github.com/algolia/algoliasearch-client-js#removestopwords + */ + removeStopWords?: string[]; + /** + * List of attributes on which you want to disable the computation of exact criteria + * default: [] + * https://github.com/algolia/algoliasearch-client-js#disableexactonattributes + */ + disableExactOnAttributes?: string[]; + /** + * This parameter control how the exact ranking criterion is computed when the query contains one word + * default: attribute + * 'none': no exact on single word query + * 'word': exact set to 1 if the query word is found in the record + * 'attribute': exact set to 1 if there is an attribute containing a string equals to the query + * https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery + */ + exactOnSingleWordQuery?: string; + /** + * Specify the list of approximation that should be considered as an exact match in the ranking formula + * default: ['ignorePlurals', 'singleWordSynonym'] + * 'ignorePlurals': alternative words added by the ignorePlurals feature + * 'singleWordSynonym': single-word synonym (For example "NY" = "NYC") + * 'multiWordsSynonym': multiple-words synonym + * https://github.com/algolia/algoliasearch-client-js#alternativesasexact + */ + alternativesAsExact?: any; + /** + * If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set. + * https://github.com/algolia/algoliasearch-client-js#distinct + */ + distinct?: any; + /** + * If set to true, the result hits will contain ranking information in the _rankingInfo attribute. + * default: false + * https://github.com/algolia/algoliasearch-client-js#getrankinginfo + */ + getRankingInfo?: boolean; + /** + * All numerical attributes are automatically indexed as numerical filters + * default: '' + * https://github.com/algolia/algoliasearch-client-js#numericattributestoindex + */ + numericAttributesToIndex?: string[]; + /** + * @deprecated please use filters instead + * A string that contains the comma separated list of numeric filters you want to apply. + * https://github.com/algolia/algoliasearch-client-js#numericfilters-deprecated + */ + numericFilters?: string[]; + /** + * @deprecated + * Filter the query by a set of tags. + * https://github.com/algolia/algoliasearch-client-js#tagfilters-deprecated + */ + tagFilters?: string; + /** + * @deprecated + * Filter the query by a set of facets. + * https://github.com/algolia/algoliasearch-client-js#facetfilters-deprecated + */ + facetFilters?: string; + /** + * If set to false, this query will not be taken into account in the analytics feature. + * default true + * https://github.com/algolia/algoliasearch-client-js#analytics + */ + analytics?: boolean; + /** + * If set, tag your query with the specified identifiers + * default: null + * https://github.com/algolia/algoliasearch-client-js#analyticstags + */ + analyticsTags?: string[]; + /** + * If set to false, the search will not use the synonyms defined for the targeted index. + * default: true + * https://github.com/algolia/algoliasearch-client-js#synonyms + */ + synonyms?: boolean; + /** + * If set to false, words matched via synonym expansion will not be replaced by the matched synonym in the highlighted result. + * default: true + * https://github.com/algolia/algoliasearch-client-js#replacesynonymsinhighlight + */ + replaceSynonymsInHighlight?: boolean; + /** + * Configure the precision of the proximity ranking criterion + * default: 1 + * https://github.com/algolia/algoliasearch-client-js#minproximity + */ + minProximity?: number; + + nbShards?: number; + userData?: string | object; + } + + interface AlgoliaResponse { + /** + * Contains all the hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hits: any[]; + /** + * Current page + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + page: number; + /** + * Number of total hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbHits: number; + /** + * Number of pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbPage: number; + /** + * Number of hits per pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hitsPerPage: number; + /** + * Engine processing time (excluding network transfer) + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + processingTimeMS: number; + /** + * Query used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + query: string; + /** + * GET parameters used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + params: string; + facets: { + [facetName: string]: { [facetValue: string]: number }; + }; + } + + namespace SearchForFacetValues { + interface Parameters extends QueryParameters { + /** + * The facet to search in + */ + facetName: string; + /** + * The query for the search in this facet + */ + facetQuery: string; + } + + interface Response { + facetHits: { value: string; highlighted: string; count: number }[]; + exhaustiveFacetsCount: boolean; + processingTimeMS: number; + } + } + + interface Response { + /** + * Contains all the hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hits: any[]; + /** + * Current page + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + page: number; + /** + * Number of total hits matching the query + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbHits: number; + /** + * Number of pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + nbPages: number; + /** + * Number of hits per pages + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + hitsPerPage: number; + /** + * Engine processing time (excluding network transfer) + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + processingTimeMS: number; + /** + * Query used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + query: string; + /** + * GET parameters used to perform the search + * https://github.com/algolia/algoliasearch-client-js#response-format + */ + params: string; + facets?: { + [facetName: string]: { [facetValue: string]: number }; + }; + } + + interface MultiResponse { + results: Response[]; + } +} + +declare function algoliasearch( + applicationId: string, + apiKey: string, + options?: algoliasearch.ClientOptions +): algoliasearch.Client; +export = algoliasearch; diff --git a/types/algoliasearch/tsconfig.json b/types/algoliasearch/tsconfig.json index 3358732ba3..9a8a2a623c 100644 --- a/types/algoliasearch/tsconfig.json +++ b/types/algoliasearch/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "lite/index.d.ts", "algoliasearch-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/amazon-cognito-auth-js/index.d.ts b/types/amazon-cognito-auth-js/index.d.ts new file mode 100644 index 0000000000..d828fccfc8 --- /dev/null +++ b/types/amazon-cognito-auth-js/index.d.ts @@ -0,0 +1,577 @@ +// Type definitions for amazon-cognito-auth-js 1.2 +// Project: https://github.com/aws/amazon-cognito-auth-js +// Definitions by: Scott Escue +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/* + * Create global variable to provide access to types when used without module + * loading. + */ +export as namespace AmazonCognitoIdentity; + +// Stubs the XDomainRequest built-in from older IE browsers, does not follow the project's interface naming convention +export interface XDomainRequest { + readonly responseText: string; + timeout: number; + onprogress: () => void; + ontimeout: () => void; + onerror: () => void; + onload: () => void; + + open(method: string, url: string): void; + send(data: string): void; + abort(): void; +} + +export interface CognitoSessionData { + /** + * The session's Id token. + */ + IdToken?: CognitoIdToken; + + /** + * The session's refresh token. + */ + RefreshToken?: CognitoRefreshToken; + + /** + * The session's access token. + */ + AccessToken?: CognitoAccessToken; + + /** + * The session's token scopes. + */ + TokenScopes?: CognitoTokenScopes; + + /** + * The session's state. + */ + State?: string; +} + +export interface CognitoAuthOptions { + /** + * Required: User pool application client id. + */ + ClientId: string; + + /** + * Required: The application/user-pools Cognito web hostname,this is set at the Cognito console. + */ + AppWebDomain: string; + + /** + * Optional: The token scopes + */ + TokenScopesArray?: ReadonlyArray; + + /** + * Required: Required: The redirect Uri, which will be launched after authentication as signed in. + */ + RedirectUriSignIn: string; + + /** + * Required: The redirect Uri, which will be launched when signed out. + */ + RedirectUriSignOut: string; + + /** + * Optional: Pre-selected identity provider (this allows to automatically trigger social provider authentication flow). + */ + IdentityProvider?: string; + + /** + * Optional: UserPoolId for the configured cognito userPool. + */ + UserPoolId?: string; + + /** + * Optional: boolean flag indicating if the data collection is enabled to support cognito advanced security features. By default, this flag is set to true. + */ + AdvancedSecurityDataCollectionFlag?: boolean; +} + +export interface CognitoAuthUserHandler { + onSuccess: (authSession: CognitoAuthSession) => void; + onFailure: (err: any) => void; +} + +export interface CognitoConstants { + DOMAIN_SCHEME: string; + DOMAIN_PATH_SIGNIN: string; + DOMAIN_PATH_TOKEN: string; + DOMAIN_PATH_SIGNOUT: string; + DOMAIN_QUERY_PARAM_REDIRECT_URI: string; + DOMAIN_QUERY_PARAM_SIGNOUT_URI: string; + DOMAIN_QUERY_PARAM_RESPONSE_TYPE: string; + DOMAIN_QUERY_PARAM_IDENTITY_PROVIDER: string; + DOMAIN_QUERY_PARAM_USERCONTEXTDATA: string; + CLIENT_ID: string; + STATE: string; + SCOPE: string; + TOKEN: string; + CODE: string; + POST: string; + PARAMETERERROR: string; + SCOPETYPEERROR: string; + QUESTIONMARK: string; + POUNDSIGN: string; + COLONDOUBLESLASH: string; + SLASH: string; + AMPERSAND: string; + EQUALSIGN: string; + SPACE: string; + CONTENTTYPE: string; + CONTENTTYPEVALUE: string; + AUTHORIZATIONCODE: string; + IDTOKEN: string; + ACCESSTOKEN: string; + REFRESHTOKEN: string; + ERROR: string; + ERROR_DESCRIPTION: string; + STRINGTYPE: string; + STATELENGTH: number; + STATEORIGINSTRING: string; + WITHCREDENTIALS: string; + UNDEFINED: string; + SELF: string; + HOSTNAMEREGEX: RegExp; + QUERYPARAMETERREGEX1: RegExp; + QUERYPARAMETERREGEX2: RegExp; + HEADER: { 'Content-Type': string }; +} + +export class CognitoIdToken { + /** + * Constructs a new CognitoIdToken object + * @param IdToken The JWT Id token + */ + constructor(IdToken: string); + + /** + * @returns the record's token. + */ + getJwtToken(): string; + + /** + * Sets new value for id token. + * @param idToken The JWT Id token + */ + setJwtToken(idToken: string): void; + + /** + * @returns the token's expiration (exp member). + */ + getExpiration(): number; + + /** + * @returns the token's payload. + */ + decodePayload(): object; +} + +export class CognitoRefreshToken { + /** + * Constructs a new CognitoRefreshToken object + * @param RefreshToken The JWT refresh token. + */ + constructor(RefreshToken: string); + + /** + * @returns the record's token. + */ + getToken(): string; + + /** + * Sets new value for refresh token. + * @param refreshToken The JWT refresh token. + */ + setToken(refreshToken: string): void; +} + +export class CognitoAccessToken { + /** + * Constructs a new CognitoAccessToken object + * @param AccessToken The JWT access token. + */ + constructor(AccessToken: string); + + /** + * @returns the record's token. + */ + getJwtToken(): string; + + /** + * Sets new value for access token. + * @param accessToken The JWT access token. + */ + setJwtToken(accessToken: string): void; + + /** + * @returns the token's expiration (exp member). + */ + getExpiration(): number; + + /** + * @returns the username from payload. + */ + getUsername(): string; + + /** + * @returns the token's payload. + */ + decodePayload(): object; +} + +export class CognitoTokenScopes { + /** + * Constructs a new CognitoTokenScopes object + * @param TokenScopesArray The token scopes + */ + constructor(TokenScopesArray: ReadonlyArray); + + /** + * @returns the token scopes. + */ + getScopes(): string[]; + + /** + * Sets new value for token scopes. + * @param tokenScopes The token scopes + */ + setTokenScopes(tokenScopes: ReadonlyArray): void; +} + +export class CognitoAuthSession { + /** + * Constructs a new CognitoUserSession object + * @param sessionData The session's tokens, scopes, and state. + */ + constructor(sessionData: CognitoSessionData); + + /** + * @returns the session's Id token + */ + getIdToken(): CognitoIdToken; + + /** + * Set a new Id token + * @param IdToken The session's Id token. + */ + setIdToken(IdToken: CognitoIdToken): void; + + /** + * @returns the session's refresh token + */ + getRefreshToken(): CognitoRefreshToken; + + /** + * Set a new Refresh token + * @param RefreshToken The session's refresh token. + */ + setRefreshToken(RefreshToken: CognitoRefreshToken): void; + + /** + * @returns the session's access token + */ + getAccessToken(): CognitoAccessToken; + + /** + * Set a new Access token + * @param AccessToken The session's access token. + */ + setAccessToken(AccessToken: CognitoAccessToken): void; + + /** + * @returns the session's token scopes + */ + getTokenScopes(): CognitoTokenScopes; + + /** + * Set new token scopes + * @param tokenScopes The session's token scopes. + */ + setTokenScopes(tokenScopes: CognitoTokenScopes): void; + + /** + * @returns the session's state + */ + getState(): string; + + /** + * Set new state + * @param state The session's state. + */ + setState(State: string): void; + + /** + * Checks to see if the session is still valid based on session expiry information found + * in Access and Id Tokens and the current time + * @returns if the session is still valid + */ + isValid(): boolean; +} + +export class CognitoAuth { + /** + * Called on success or error. + */ + userhandler: CognitoAuthUserHandler; + + /** + * Constructs a new CognitoAuth object + * @param options Creation options + */ + constructor(options: CognitoAuthOptions); + + /** + * @returns the constants + */ + getCognitoConstants(): CognitoConstants; + + /** + * @returns the client id + */ + getClientId(): string; + + /** + * @returns the app web domain + */ + getAppWebDomain(): string; + + /** + * method for getting the current user of the application from the local storage + * + * @returns the user retrieved from storage + */ + getCurrentUser(): string; + + /** + * method for setting the current user's name + * @param Username the user's name + */ + setUser(Username: string): void; + + /** + * sets response type to 'code' + */ + useCodeGrantFlow(): void; + + /** + * sets response type to 'token' + */ + useImplicitFlow(): void; + + /** + * @returns the current session for this user + */ + getSignInUserSession(): CognitoAuthSession; + + /** + * @returns the user's username + */ + getUsername(): string; + + /** + * @param Username the user's username + */ + setUsername(Username: string): void; + + /** + * @returns the user's state + */ + getState(): string; + + /** + * @param State the user's state + */ + setState(State: string): void; + + /** + * This is used to get a session, either from the session object or from the local storage, or by using a refresh token + * @param RedirectUriSignIn Required: The redirect Uri, which will be launched after authentication. + * @param TokenScopesArray Required: The token scopes, it is an array of strings specifying all scopes for the tokens. + */ + getSession(): void; + + /** + * Parse the http request response and proceed according to different response types. + * @param httpRequestResponse the http request response + */ + parseCognitoWebResponse(httpRequestResponse: string): void; + + /** + * Get the query parameter map and proceed according to code response type. + * @param Query parameter map + */ + getCodeQueryParameter(map: ReadonlyMap): void; + + /** + * Get the query parameter map and proceed according to token response type. + * @param Query parameter map + */ + getTokenQueryParameter(map: ReadonlyMap): void; + + /** + * Get cached tokens and scopes and return a new session using all the cached data. + * @returns the auth session + */ + getCachedSession(): CognitoAuthSession; + + /** + * This is used to get last signed in user from local storage + * @returns the last user name + */ + getLastUser(): string; + + /** + * This is used to save the session tokens and scopes to local storage. + */ + cacheTokensScopes(): void; + + /** + * Compare two sets if they are identical. + * @param set1 one set + * @param set2 the other set + * @returns boolean value is true if two sets are identical + */ + compareSets(set1: ReadonlySet, set2: ReadonlySet): boolean; + + /** + * Get the hostname from url. + * @param url the url string + * @returns hostname string + */ + getHostName(url: string): string; + + /** + * Get http query parameters and return them as a map. + * @param url the url string + * @param splitMark query parameters split mark (prefix) + * @returns map + */ + getQueryParameters(url: string, splitMark: string): Map; + + /** + * helper function to generate a random string + * @param length the length of string + * @param chars a original string + * @returns a random value. + */ + generateRandomString(length: number, chars: string): string; + + /** + * This is used to clear the session tokens and scopes from local storage + */ + clearCachedTokensScopes(): void; + + /** + * This is used to build a user session from tokens retrieved in the authentication result + * @param refreshToken Successful auth response from server. + */ + refreshSession(refreshToken: string): void; + + /** + * Make the http POST request. + * @param header header JSON object + * @param body body JSON object + * @param url string + * @param onSuccess callback + * @param onFailure callback + */ + makePOSTRequest(header: object, body: object, url: string, + onSuccess: (responseText: string) => void, + onFailure: (responseText: string) => void): void; + + /** + * Create the XHR object + * @param method which method to call + * @param url the url string + * @returns xhr + */ + createCORSRequest(method: string, url: string): XMLHttpRequest | XDomainRequest; + + /** + * The http POST request onFailure callback. + * @param err the error object + */ + onFailure(err: any): void; + + /** + * The http POST request onSuccess callback when refreshing tokens. + * @param jsonData tokens + */ + onSuccessRefreshToken(jsonData: string): void; + + /** + * The http POST request onSuccess callback when exchanging code for tokens. + * @param jsonData tokens + */ + onSuccessExchangeForToken(jsonData: string): void; + + /** + * Launch Cognito Auth UI page. + * @param URL the url to launch + */ + launchUri(URL: string): void; + + /** + * @returns scopes string + */ + getSpaceSeperatedScopeString(): string; + + /** + * Create the FQDN(fully qualified domain name) for authorization endpoint. + * @returns url + */ + getFQDNSignIn(): string; + + /** + * Sign out the user. + */ + signOut(): void; + + /** + * Create the FQDN(fully qualified domain name) for signout endpoint. + * @returns url + */ + getFQDNSignOut(): string; + + /** + * This method returns the encoded data string used for cognito advanced security feature. + * This would be generated only when developer has included the JS used for collecting the + * data on their client. Please refer to documentation to know more about using AdvancedSecurity + * features + */ + getUserContextData(): string; + + /** + * Helper method to let the user know if he has either a valid cached session + * or a valid authenticated session from the app integration callback. + * @returns userSignedIn + */ + isUserSignedIn(): boolean; +} + +export class DateHelper { + /** + * @returns The current time in "ddd MMM D HH:mm:ss UTC YYYY" format. + */ + getNowString(): string; +} + +export class StorageHelper { + /** + * This is used to get a storage object + * @returns the storage + */ + constructor(); + + /** + * This is used to return the storage + * @returns the storage + */ + getStorage(): Storage; +} diff --git a/types/amazon-cognito-auth-js/test/amazon-cognito-auth-js-tests.ts b/types/amazon-cognito-auth-js/test/amazon-cognito-auth-js-tests.ts new file mode 100644 index 0000000000..42e58185e4 --- /dev/null +++ b/types/amazon-cognito-auth-js/test/amazon-cognito-auth-js-tests.ts @@ -0,0 +1,162 @@ +import * as lib from 'amazon-cognito-auth-js'; + +const idToken: lib.CognitoIdToken = new lib.CognitoIdToken('fak3T0ken1=='); +idToken.decodePayload(); // $ExpectType object +idToken.setJwtToken('fak3T0ken2=='); // $ExpectType void +idToken.getJwtToken(); // $ExpectType string +idToken.getExpiration(); // $ExpectType number + +const refreshToken: lib.CognitoRefreshToken = new lib.CognitoRefreshToken('refreshplease=='); +refreshToken.setToken('refreshagainplease=='); // $ExpectType void +refreshToken.getToken(); // $ExpectType string + +const accessToken: lib.CognitoAccessToken = new lib.CognitoAccessToken('fak3T0ken3=='); +accessToken.decodePayload(); // $ExpectType object +accessToken.setJwtToken('fak3T0ken4=='); // $ExpectType void +accessToken.getJwtToken(); // $ExpectType string +accessToken.getExpiration(); // $ExpectType number +accessToken.getUsername(); // $ExpectType string + +const tokenScopes: lib.CognitoTokenScopes = new lib.CognitoTokenScopes(['email', 'custom1']); +tokenScopes.setTokenScopes(['openid']); // $ExpectType void +tokenScopes.getScopes(); // $ExpectType string[] + +let sessionData: lib.CognitoSessionData = {}; +let authSession: lib.CognitoAuthSession = new lib.CognitoAuthSession(sessionData); + +sessionData = { + IdToken: idToken, + RefreshToken: refreshToken, + AccessToken: accessToken, + TokenScopes: tokenScopes, + State: '/myapp/home' +}; +authSession = new lib.CognitoAuthSession(sessionData); + +authSession.setIdToken(new lib.CognitoIdToken('fak3T0ken5==')); // $ExpectType void +authSession.setRefreshToken(new lib.CognitoRefreshToken('refreshmeyetagain==')); // $ExpectType void +authSession.setAccessToken(new lib.CognitoAccessToken('fak3T0ken6==')); // $ExpectType void +authSession.setTokenScopes(new lib.CognitoTokenScopes(['email'])); // $ExpectType void +authSession.setState('/myapp/login'); // $ExpectType void +authSession.getIdToken(); // $ExpectType CognitoIdToken +authSession.getRefreshToken(); // $ExpectType CognitoRefreshToken +authSession.getAccessToken(); // $ExpectType CognitoAccessToken +authSession.getTokenScopes(); // $ExpectType CognitoTokenScopes +authSession.getState(); // $ExpectType string + +let authOptions: lib.CognitoAuthOptions = { + ClientId: '1a2b3c4d5e6f7g', + AppWebDomain: 'myapp.auth.us-east-1.amazoncognito.com', + RedirectUriSignIn: 'https://myapp.com/login', + RedirectUriSignOut: 'https://myapp.com/logout' +}; +let auth: lib.CognitoAuth = new lib.CognitoAuth(authOptions); + +authOptions = { + ClientId: '1a2b3c4d5e6f7g', + AppWebDomain: 'myapp.auth.us-east-1.amazoncognito.com', + TokenScopesArray: ['email', 'openid'], + RedirectUriSignIn: 'https://myapp.com/login', + RedirectUriSignOut: 'https://myapp.com/logout', + IdentityProvider: 'Facebook', + UserPoolId: 'us-east-1_faKE4ReAl', + AdvancedSecurityDataCollectionFlag: true +}; +auth = new lib.CognitoAuth(authOptions); + +auth.getClientId(); // $ExpectType string +auth.getAppWebDomain(); // $ExpectType string +auth.getCurrentUser(); // $ExpectType string +auth.setUser('jane.doe'); // $ExpectType void +auth.useCodeGrantFlow(); // $ExpectType void +auth.useImplicitFlow(); // $ExpectType void +auth.getSignInUserSession(); // $ExpectType CognitoAuthSession +auth.getUsername(); // $ExpectType string +auth.setUsername('john.doe'); // $ExpectType void +auth.getState(); // $ExpectType string +auth.setState('/myhost/default.htm'); // $ExpectType void +auth.getSession(); // $ExpectType void +auth.parseCognitoWebResponse('url&stuff=true'); // $ExpectType void +auth.getCodeQueryParameter(new Map()); // $ExpectType void +auth.getTokenQueryParameter(new Map()); // $ExpectType void +auth.getCachedSession(); // $ExpectType CognitoAuthSession +auth.getLastUser(); // $ExpectType string +auth.cacheTokensScopes(); // $ExpectType void +auth.compareSets(new Set(['1']), new Set(['1'])); // $ExpectType boolean +auth.getHostName('https://site.com/page?size=10'); // $ExpectType string +auth.getQueryParameters('http://site.com?1=1&2=2', '?'); // $ExpectType Map +auth.generateRandomString(5, '159erf'); // $ExpectType string +auth.clearCachedTokensScopes(); // $ExpectType void +auth.refreshSession('refreshToken=='); // $ExpectType void +// $ExpectType void +auth.makePOSTRequest({ 'Content-Type': 'application/json' }, { pool: '2' }, + 'https://auth.com/signin', + (data) => console.log(data), + (error) => console.log(error)); +auth.createCORSRequest('POST', '/myapp/login'); // $ExpectType XMLHttpRequest | XDomainRequest +auth.onFailure('request failed'); // $ExpectType void +auth.onSuccessRefreshToken('{"name":"John", "age":31}'); // $ExpectType void +auth.onSuccessExchangeForToken('{"name":"Jane", "age":30}'); // $ExpectType void +auth.launchUri('https://auth.com/login'); // $ExpectType void +auth.getSpaceSeperatedScopeString(); // $ExpectType string +auth.getFQDNSignIn(); // $ExpectType string +auth.signOut(); // $ExpectType void +auth.getFQDNSignOut(); // $ExpectType string +auth.getUserContextData(); // $ExpectType string +auth.isUserSignedIn(); // $ExpectType boolean + +const userHandler: lib.CognitoAuthUserHandler = { + onSuccess: (authSession: lib.CognitoAuthSession) => console.log(authSession), + onFailure: (error: any) => console.log(error) +}; +auth.userhandler = userHandler; + +const constants: lib.CognitoConstants = auth.getCognitoConstants(); +constants.DOMAIN_SCHEME; // $ExpectType string +constants.DOMAIN_PATH_SIGNIN; // $ExpectType string +constants.DOMAIN_PATH_TOKEN; // $ExpectType string +constants.DOMAIN_PATH_SIGNOUT; // $ExpectType string +constants.DOMAIN_QUERY_PARAM_REDIRECT_URI; // $ExpectType string +constants.DOMAIN_QUERY_PARAM_SIGNOUT_URI; // $ExpectType string +constants.DOMAIN_QUERY_PARAM_RESPONSE_TYPE; // $ExpectType string +constants.DOMAIN_QUERY_PARAM_IDENTITY_PROVIDER; // $ExpectType string +constants.DOMAIN_QUERY_PARAM_USERCONTEXTDATA; // $ExpectType string +constants.CLIENT_ID; // $ExpectType string +constants.STATE; // $ExpectType string +constants.SCOPE; // $ExpectType string +constants.TOKEN; // $ExpectType string +constants.CODE; // $ExpectType string +constants.POST; // $ExpectType string +constants.PARAMETERERROR; // $ExpectType string +constants.SCOPETYPEERROR; // $ExpectType string +constants.QUESTIONMARK; // $ExpectType string +constants.POUNDSIGN; // $ExpectType string +constants.COLONDOUBLESLASH; // $ExpectType string +constants.SLASH; // $ExpectType string +constants.AMPERSAND; // $ExpectType string +constants.EQUALSIGN; // $ExpectType string +constants.SPACE; // $ExpectType string +constants.CONTENTTYPE; // $ExpectType string +constants.CONTENTTYPEVALUE; // $ExpectType string +constants.AUTHORIZATIONCODE; // $ExpectType string +constants.IDTOKEN; // $ExpectType string +constants.ACCESSTOKEN; // $ExpectType string +constants.REFRESHTOKEN; // $ExpectType string +constants.ERROR; // $ExpectType string +constants.ERROR_DESCRIPTION; // $ExpectType string +constants.STRINGTYPE; // $ExpectType string +constants.STATELENGTH; // $ExpectType number +constants.STATEORIGINSTRING; // $ExpectType string +constants.WITHCREDENTIALS; // $ExpectType string +constants.UNDEFINED; // $ExpectType string +constants.SELF; // $ExpectType string +constants.HOSTNAMEREGEX; // $ExpectType RegExp +constants.QUERYPARAMETERREGEX1; // $ExpectType RegExp +constants.QUERYPARAMETERREGEX2; // $ExpectType RegExp +constants.HEADER['Content-Type']; // $ExpectType string + +const dateHelper: lib.DateHelper = new lib.DateHelper(); +dateHelper.getNowString(); // $ExpectType string + +const storageHelper: lib.StorageHelper = new lib.StorageHelper(); +storageHelper.getStorage(); // $ExpectType Storage diff --git a/types/amazon-cognito-auth-js/test/amazon-cognito-auth-js-umd-tests.ts b/types/amazon-cognito-auth-js/test/amazon-cognito-auth-js-umd-tests.ts new file mode 100644 index 0000000000..1e30dbbeb8 --- /dev/null +++ b/types/amazon-cognito-auth-js/test/amazon-cognito-auth-js-umd-tests.ts @@ -0,0 +1,22 @@ +AmazonCognitoIdentity.CognitoIdToken; // $ExpectType typeof CognitoIdToken +AmazonCognitoIdentity.CognitoRefreshToken; // $ExpectType typeof CognitoRefreshToken +AmazonCognitoIdentity.CognitoAccessToken; // $ExpectType typeof CognitoAccessToken +AmazonCognitoIdentity.CognitoTokenScopes; // $ExpectType typeof CognitoTokenScopes +AmazonCognitoIdentity.CognitoAuthSession; // $ExpectType typeof CognitoAuthSession +AmazonCognitoIdentity.CognitoAuth; // $ExpectType typeof CognitoAuth +AmazonCognitoIdentity.DateHelper; // $ExpectType typeof DateHelper +AmazonCognitoIdentity.StorageHelper; // $ExpectType typeof StorageHelper + +const sessionData: AmazonCognitoIdentity.CognitoSessionData = {}; +new AmazonCognitoIdentity.CognitoAuthSession(sessionData); + +const authOptions: AmazonCognitoIdentity.CognitoAuthOptions = { + ClientId: '1a2b3c4d5e6f7g', + AppWebDomain: 'myapp.auth.us-east-1.amazoncognito.com', + RedirectUriSignIn: 'https://myapp.com/login', + RedirectUriSignOut: 'https://myapp.com/logout' +}; +const auth = new AmazonCognitoIdentity.CognitoAuth(authOptions); +auth.userhandler; // $ExpectType CognitoAuthUserHandler +auth.getCognitoConstants(); // $ExpectType CognitoConstants +auth.createCORSRequest('', ''); // $ExpectType XMLHttpRequest | XDomainRequest diff --git a/types/amazon-cognito-auth-js/tsconfig.json b/types/amazon-cognito-auth-js/tsconfig.json new file mode 100644 index 0000000000..df5a9f2d73 --- /dev/null +++ b/types/amazon-cognito-auth-js/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "test/amazon-cognito-auth-js-tests.ts", + "test/amazon-cognito-auth-js-umd-tests.ts" + ] +} diff --git a/types/amazon-cognito-auth-js/tslint.json b/types/amazon-cognito-auth-js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/amazon-cognito-auth-js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/angular-translate/index.d.ts b/types/angular-translate/index.d.ts index 69b1f63d72..719fcb5d5c 100644 --- a/types/angular-translate/index.d.ts +++ b/types/angular-translate/index.d.ts @@ -1,11 +1,9 @@ // Type definitions for Angular Translate (pascalprecht.translate module) 2.15 // Project: https://github.com/PascalPrecht/angular-translate -// Definitions by: Michel Salib +// Definitions by: Michel Salib , Gabriel Gil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/// - declare var _: string; export = _; @@ -69,7 +67,7 @@ declare module 'angular' { versionInfo(): string; loaderCache(): any; isReady(): boolean; - onReady(): angular.IPromise; + onReady(fn?: () => void): angular.IPromise; resolveClientLocale(): string; getAvailableLanguageKeys(): string[]; } diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index ca9d2c7568..1dff1a0451 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -1138,7 +1138,8 @@ angular.module('multiSlotTranscludeExample', []) }; }); -angular.module('componentExample', []) +// $ExpectType IModule +const componentModule = angular.module('componentExample', []) .component('counter', { require: {ctrl: '^ctrl'}, bindings: { @@ -1160,6 +1161,16 @@ angular.module('componentExample', []) }, template: '', transclude: true + }) + .component({ + aThirdComponent: { + controller: class AThirdComponentController { + count: number; + }, + bindings: { + count: '=' + } + } }); interface ICopyExampleUser { diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 4c896eb430..6dccefc926 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -196,6 +196,12 @@ declare namespace angular { * @param options A definition object passed into the component. */ component(name: string, options: IComponentOptions): IModule; + /** + * Use this method to register a component. + * + * @param object Object map of components where the keys are the names and the values are the component definition objects + */ + component(object: {[componentName: string]: IComponentOptions}): IModule; /** * Use this method to register work which needs to be performed on module loading. * @@ -1028,7 +1034,7 @@ declare namespace angular { all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise ]): IPromise<[T1, T2, T3, T4]>; all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise]): IPromise<[T1, T2, T3]>; all(values: [T1 | IPromise, T2 | IPromise]): IPromise<[T1, T2]>; - all(promises: Array>): IPromise; + all(promises: Array>): IPromise; /** * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. * @@ -1273,6 +1279,7 @@ declare namespace angular { directive(object: {[directiveName: string]: Injectable>}): ICompileProvider; component(name: string, options: IComponentOptions): ICompileProvider; + component(object: {[componentName: string]: IComponentOptions}): ICompileProvider; aHrefSanitizationWhitelist(): RegExp; aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; diff --git a/types/ansi-styles/ansi-styles-tests.ts b/types/ansi-styles/ansi-styles-tests.ts index 235f98dce1..d1d21719b4 100644 --- a/types/ansi-styles/ansi-styles-tests.ts +++ b/types/ansi-styles/ansi-styles-tests.ts @@ -1,53 +1,52 @@ +import { EscapeCode } from './escape-code'; +import AnsiStyles = require('ansi-styles'); -import ansi = require('ansi-styles'); +let ansiStyles = AnsiStyles as any, + nsNames = ['modifier', 'color', 'bgColor'], + namespaces = { + modifier: ['reset', 'bold', 'dim', 'italic', 'underline', 'inverse', 'hidden', 'strikethrough'], + color: ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray', + 'redBright', 'greenBright', 'yellowBright', 'blueBright', 'magentaBright', 'cyanBright', 'whiteBright'], + bgColor: ['bgBlack', 'bgRed', 'bgGreen', 'bgYellow', 'bgBlue', 'bgMagenta', 'bgCyan', + 'bgBlackBright', 'bgRedBright', 'bgGreenBright', 'bgYellowBright', 'bgBlueBright', 'bgMagentaBright', 'bgCyanBright', 'bgWhiteBright'], + } as any, + styles = [...namespaces.modifier, ...namespaces.color, ...namespaces.bgColor], + codePair = ['open', 'close'], + codeTypes = ['ansi', 'ansi256', 'ansi16m'], + colorFormats = ['ansi', 'rgb', 'hsl', 'hsv', 'hwb', 'cmyk', 'xyz', 'lab', 'lch', 'hex', 'keyword', 'ansi256', 'hcg', 'apple', 'gray'], + codesMap = 'codes'; -var styles = [ - ansi.reset, +checkStyle(ansiStyles, styles); +nsNames.forEach(ns => checkStyle(ansiStyles[ns], namespaces[ns])); - ansi.bold, - ansi.dim, - ansi.italic, - ansi.underline, - ansi.inverse, - ansi.hidden, - ansi.strikethrough, +checkIsMap(ansiStyles[codesMap], `ansiStyles.${codesMap} not a Map.`); +nsNames.forEach(ns => checkExist(ansiStyles[ns], `ansiStyles.${ns} is not exist.`)); - ansi.black, - ansi.red, - ansi.green, - ansi.yellow, - ansi.blue, - ansi.magenta, - ansi.cyan, - ansi.white, - ansi.gray, +['color', 'bgColor'].forEach(ns => checkConverter(ns, ansiStyles[ns], colorFormats)); - ansi.bgBlack, - ansi.bgRed, - ansi.bgGreen, - ansi.bgYellow, - ansi.bgBlue, - ansi.bgMagenta, - ansi.bgCyan, - ansi.bgWhite -] -for (var key in styles) { - check(key, styles[key]) +function checkStyle(namespace: any, styles: string[]) { + styles.forEach(s => checkCodePair(s, namespace[s])); +} +function checkCodePair(styleName: string, pair: any): void { + codePair.forEach(p => checkIsString(pair[p], `${styleName}.${p} is not a string.`)); } -function check(key:string, escapeCodes:ansi.EscapeCodePair): void { - if (uninitialized(escapeCodes.open)) { - throw new Error('key not found ~> ' + key + '.open') - } - if (uninitialized(escapeCodes.close)) { - throw new Error('key not found ~> ' + key + '.close') - } +function checkConverter(nsName: string, namespace: any, formats: string[]) { + formats.forEach(f => codeTypes.forEach(t => checkIsFunction(namespace[t][f], `ansiStyles.${nsName}.${t}.${f} is not a function.`))); + checkIsString(namespace.close, `${namespace}.close is not a string.`); } -function uninitialized(val:any): boolean { - return val === null || val === undefined +function checkExist(val: any, failMsg: string): void { + if (val == null) throw new Error(failMsg); +} +function checkIsString(val: any, failMsg: string): void { + if(typeof val != 'string') throw new Error(failMsg); +} +function checkIsFunction(fn: any, failMsg: string): void { + if (typeof fn != 'function') throw new Error(failMsg); +} +function checkIsMap(map: any, failMsg: string): void { + if (!(map instanceof Map)) throw new Error(failMsg); } - - diff --git a/types/ansi-styles/escape-code.d.ts b/types/ansi-styles/escape-code.d.ts new file mode 100644 index 0000000000..e9b1fe9d42 --- /dev/null +++ b/types/ansi-styles/escape-code.d.ts @@ -0,0 +1,106 @@ +import * as cssKeywords from 'color-name'; + + +export namespace EscapeCode { + export interface CodePair { + open: string; + close: string; + } + + interface Modifier { + reset: CodePair; + bold: CodePair; + dim: CodePair; + /** + * Not widely supported + */ + italic: CodePair; + underline: CodePair; + inverse: CodePair; + hidden: CodePair; + /** + * Not widely supported + */ + strikethrough: CodePair; + } + interface Color { + black: CodePair; + red: CodePair; + green: CodePair; + yellow: CodePair; + blue: CodePair; + magenta: CodePair; + cyan: CodePair; + white: CodePair; + /** + * bright black + */ + gray: CodePair; + grey: CodePair; + + redBright: CodePair; + greenBright: CodePair; + yellowBright: CodePair; + blueBright: CodePair; + magentaBright: CodePair; + cyanBright: CodePair; + whiteBright: CodePair; + } + interface BackgroundColor { + bgBlack: CodePair; + bgRed: CodePair; + bgGreen: CodePair; + bgYellow: CodePair; + bgBlue: CodePair; + bgMagenta: CodePair; + bgCyan: CodePair; + bgWhite: CodePair; + + bgBlackBright: CodePair; + bgRedBright: CodePair; + bgGreenBright: CodePair; + bgYellowBright: CodePair; + bgBlueBright: CodePair; + bgMagentaBright: CodePair; + bgCyanBright: CodePair; + bgWhiteBright: CodePair; + } + + interface Conversions { + ansi: (ansi: number) => string + rgb: (r: number, g: number, b: number) => string + hsl: (h: number, s: number, l: number) => string + hsv: (h: number, s: number, v: number) => string + hwb: (h: number, w: number, b: number) => string + cmyk: (c: number, m: number, y: number, k: number) => string + xyz: (x: number, y: number, z: number) => string + lab: (l: number, a: number, b: number) => string + lch: (l: number, c: number, h: number) => string + hex: (hex: string) => string + /** + * color keyword in css to ansi code + */ + keyword: (keyword: keyof typeof cssKeywords) => string + ansi256: (ansi256: number) => string + hcg: (h: number, c: number, g: number) => string + /** + * apple RGB to ansi code + */ + apple: (r: number, g: number, b: number) => string + gray: (grayscale: number) => string + } + interface ColorType { + /** + * 16 color ansi code + */ + ansi: Conversions + /** + * 256 color ansi code + */ + ansi256: Conversions + /** + * truecolor(16 million color) ansi code + */ + ansi16m: Conversions + } +} diff --git a/types/ansi-styles/index.d.ts b/types/ansi-styles/index.d.ts index 4522ece77a..a07ac962ab 100644 --- a/types/ansi-styles/index.d.ts +++ b/types/ansi-styles/index.d.ts @@ -1,40 +1,74 @@ -// Type definitions for ansi-styles 2.0.1 +// Type definitions for ansi-styles 3.2.1 // Project: https://github.com/sindresorhus/ansi-styles // Definitions by: bryn austin bellomy +// plylrnsdy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import { EscapeCode } from './escape-code'; -export interface EscapeCodePair { - open: string; - close: string; -} -export declare var reset: EscapeCodePair; +export const reset: EscapeCode.CodePair; +export const bold: EscapeCode.CodePair; +export const dim: EscapeCode.CodePair; +/** + * Not widely supported + */ +export const italic: EscapeCode.CodePair; +export const underline: EscapeCode.CodePair; +export const inverse: EscapeCode.CodePair; +export const hidden: EscapeCode.CodePair; +/** + * Not widely supported + */ +export const strikethrough: EscapeCode.CodePair; -export declare var bold: EscapeCodePair; -export declare var dim: EscapeCodePair; -export declare var italic: EscapeCodePair; -export declare var underline: EscapeCodePair; -export declare var inverse: EscapeCodePair; -export declare var hidden: EscapeCodePair; -export declare var strikethrough: EscapeCodePair; +export const black: EscapeCode.CodePair; +export const red: EscapeCode.CodePair; +export const green: EscapeCode.CodePair; +export const yellow: EscapeCode.CodePair; +export const blue: EscapeCode.CodePair; +export const magenta: EscapeCode.CodePair; +export const cyan: EscapeCode.CodePair; +export const white: EscapeCode.CodePair; +/** + * bright black + */ +export const gray: EscapeCode.CodePair; +export const grey: EscapeCode.CodePair; -export declare var black: EscapeCodePair; -export declare var red: EscapeCodePair; -export declare var green: EscapeCodePair; -export declare var yellow: EscapeCodePair; -export declare var blue: EscapeCodePair; -export declare var magenta: EscapeCodePair; -export declare var cyan: EscapeCodePair; -export declare var white: EscapeCodePair; -export declare var gray: EscapeCodePair; +export const redBright: EscapeCode.CodePair; +export const greenBright: EscapeCode.CodePair; +export const yellowBright: EscapeCode.CodePair; +export const blueBright: EscapeCode.CodePair; +export const magentaBright: EscapeCode.CodePair; +export const cyanBright: EscapeCode.CodePair; +export const whiteBright: EscapeCode.CodePair; -export declare var bgBlack: EscapeCodePair; -export declare var bgRed: EscapeCodePair; -export declare var bgGreen: EscapeCodePair; -export declare var bgYellow: EscapeCodePair; -export declare var bgBlue: EscapeCodePair; -export declare var bgMagenta: EscapeCodePair; -export declare var bgCyan: EscapeCodePair; -export declare var bgWhite: EscapeCodePair; +export const bgBlack: EscapeCode.CodePair; +export const bgRed: EscapeCode.CodePair; +export const bgGreen: EscapeCode.CodePair; +export const bgYellow: EscapeCode.CodePair; +export const bgBlue: EscapeCode.CodePair; +export const bgMagenta: EscapeCode.CodePair; +export const bgCyan: EscapeCode.CodePair; +export const bgWhite: EscapeCode.CodePair; + +export const bgBlackBright: EscapeCode.CodePair; +export const bgRedBright: EscapeCode.CodePair; +export const bgGreenBright: EscapeCode.CodePair; +export const bgYellowBright: EscapeCode.CodePair; +export const bgBlueBright: EscapeCode.CodePair; +export const bgMagentaBright: EscapeCode.CodePair; +export const bgCyanBright: EscapeCode.CodePair; +export const bgWhiteBright: EscapeCode.CodePair; + +/** + * Raw escape codes (i.e. without the CSI escape prefix \u001B[ and render mode postfix m) are available. + * + * This is a Map with the open codes as keys and close codes as values. + */ +export const codes: Map +export const modifier: EscapeCode.Modifier +export const color: EscapeCode.Color & EscapeCode.ColorType & { close: string } +export const bgColor: EscapeCode.BackgroundColor & EscapeCode.ColorType & { close: string } diff --git a/types/arangodb/arangodb-tests.ts b/types/arangodb/arangodb-tests.ts index b498caf6af..7e0fd6383e 100644 --- a/types/arangodb/arangodb-tests.ts +++ b/types/arangodb/arangodb-tests.ts @@ -1,4 +1,4 @@ -import { db, aql } from "@arangodb"; +import { aql, db, query } from "@arangodb"; import { md5 } from "@arangodb/crypto"; import { createRouter } from "@arangodb/foxx"; import sessionsMiddleware = require("@arangodb/foxx/sessions"); @@ -21,15 +21,40 @@ const admin = users.firstExample({ username: "admin" })!; users.update(admin, { password: md5("hunter2") }); console.logLines("user", admin._key, admin.username); -const query = aql` +db._query(aql` FOR u IN ${users} RETURN u -`; +`); -db._createDocumentCollection("bananas").ensureIndex({ +interface Banana { + color: string; + shape: { + type: string; + coords: string[]; + }; +} + +const bananas = db._createDocumentCollection("bananas", { + waitForSync: false, + keyOptions: { + type: "autoincrement", + increment: 11, + offset: 23 + } +}) as ArangoDB.Collection; +bananas.ensureIndex({ type: "hash", unique: true, - fields: ["color", "shape"] + fields: ["color", "shape.type"] +}); +bananas.updateByExample( + bananas.any(), + { shape: { type: "round" } }, + { mergeObjects: true } +); +bananas.ensureIndex({ + type: "geo", + fields: ["latLng"] }); const router = createRouter(); @@ -61,3 +86,13 @@ router.use( transport: cookieTransport({ secret: "banana", algorithm: "sha256" }) }) ); + +console.log( + query` + FOR u IN users + ${aql.literal( + Math.random() < 0.5 ? "FILTER u.admin" : "FILTER !u.admin" + )} + RETURN u + `.toArray() +); diff --git a/types/arangodb/index.d.ts b/types/arangodb/index.d.ts index 34cf3ef99e..5c3f56020f 100644 --- a/types/arangodb/index.d.ts +++ b/types/arangodb/index.d.ts @@ -89,8 +89,9 @@ declare namespace ArangoDB { | "network authentication required"; type EdgeDirection = "any" | "inbound" | "outbound"; type EngineType = "mmfiles" | "rocksdb"; - type IndexType = "hash" | "skiplist" | "fulltext" | "geo1" | "geo2"; + type IndexType = "hash" | "skiplist" | "fulltext" | "geo"; type ViewType = "arangosearch"; + type KeyGeneratorType = "traditional" | "autoincrement"; type ErrorName = | "ERROR_NO_ERROR" | "ERROR_FAILED" @@ -463,12 +464,29 @@ declare namespace ArangoDB { replicationFactor?: number; } + interface CreateCollectionOptions { + waitForSync?: boolean; + journalSize?: number; + isVolatile?: boolean; + isSystem?: boolean; + keyOptions?: { + type?: KeyGeneratorType; + allowUserKeys?: boolean; + increment?: number; + offset?: number; + }; + numberOfShards?: number; + shardKeys?: string[]; + replicationFactor?: number; + } + interface CollectionProperties { waitForSync: boolean; journalSize: number; + isSystem: boolean; isVolatile: boolean; keyOptions?: { - type: string; + type: KeyGeneratorType; allowUserKeys: boolean; increment?: number; offset?: number; @@ -488,7 +506,7 @@ declare namespace ArangoDB { interface IndexDescription { type: IndexType; - fields: ReadonlyArray; + fields: ReadonlyArray; sparse?: boolean; unique?: boolean; deduplicate?: boolean; @@ -497,7 +515,7 @@ declare namespace ArangoDB { interface Index { id: string; type: IndexType; - fields: Array; + fields: Array; sparse: boolean; unique: boolean; deduplicate: boolean; @@ -520,6 +538,8 @@ declare namespace ArangoDB { type DocumentLike = ObjectWithId | ObjectWithKey; + type Patch = { [K in keyof T]?: T[K] | Patch }; + interface DocumentMetadata { _key: string; _id: string; @@ -572,6 +592,7 @@ declare namespace ArangoDB { keepNull?: boolean; waitForSync?: boolean; limit?: number; + mergeObjects?: boolean; } interface RemoveOptions { @@ -706,24 +727,24 @@ declare namespace ArangoDB { ): InsertResult; update( selector: string | DocumentLike, - data: Partial>, + data: Patch>, options?: UpdateOptions ): UpdateResult; update( selectors: ReadonlyArray, - data: ReadonlyArray>>, + data: ReadonlyArray>>, options?: UpdateOptions ): Array>; updateByExample( example: Partial>, - newValue: Partial>, + newValue: Patch>, keepNull?: boolean, waitForSync?: boolean, limit?: number ): number; updateByExample( example: Partial>, - newValue: Partial>, + newValue: Patch>, options?: UpdateByExampleOptions ): number; } @@ -745,6 +766,10 @@ declare namespace ArangoDB { options?: QueryOptions; } + interface AqlLiteral { + toAQL: () => string; + } + interface Cursor { toArray(): T[]; hasNext(): boolean; @@ -862,14 +887,14 @@ declare namespace ArangoDB { // Collection _collection(name: string): Collection; _collections(): Collection[]; - _create(name: string, properties?: CollectionProperties): Collection; + _create(name: string, properties?: CreateCollectionOptions): Collection; _createDocumentCollection( name: string, - properties?: CollectionProperties + properties?: CreateCollectionOptions ): Collection; _createEdgeCollection( name: string, - properties?: CollectionProperties + properties?: CreateCollectionOptions ): Collection; _drop(name: string): void; _truncate(name: string): void; @@ -930,8 +955,26 @@ declare namespace Foxx { set?: (res: Response, sid: string) => void; clear?: (res: Response) => void; } + interface CollectionSessionStorage extends SessionStorage { + new: () => Session; + save: (session: Session) => Session; + clear: (session: Session) => boolean; + prune: () => string[]; + } + interface SessionsMiddleware extends DelegateMiddleware { + storage: SessionStorage; + transport: SessionTransport[]; + } - type Middleware = (req: Request, res: Response, next: NextFunction) => void; + type SimpleMiddleware = ( + req: Request, + res: Response, + next: NextFunction + ) => void; + interface DelegateMiddleware { + register: (endpoint: Endpoint) => SimpleMiddleware; + } + type Middleware = SimpleMiddleware | DelegateMiddleware; type Handler = ((req: Request, res: Response) => void); type NextFunction = () => void; @@ -1214,97 +1257,97 @@ declare namespace Foxx { function route(handler: Handler, name?: string): Endpoint; function route( - pathOrMiddleware: string | Middleware, + pathOrMiddleware: string | SimpleMiddleware, handler: Handler, name?: string ): Endpoint; function route( - pathOrMiddleware: string | Middleware, - middleware: Middleware, + pathOrMiddleware: string | SimpleMiddleware, + middleware: SimpleMiddleware, handler: Handler, name?: string ): Endpoint; function route( - pathOrMiddleware: string | Middleware, - middleware1: Middleware, - middleware2: Middleware, + pathOrMiddleware: string | SimpleMiddleware, + middleware1: SimpleMiddleware, + middleware2: SimpleMiddleware, handler: Handler, name?: string ): Endpoint; function route( - pathOrMiddleware: string | Middleware, - middleware1: Middleware, - middleware2: Middleware, - middleware3: Middleware, + pathOrMiddleware: string | SimpleMiddleware, + middleware1: SimpleMiddleware, + middleware2: SimpleMiddleware, + middleware3: SimpleMiddleware, handler: Handler, name?: string ): Endpoint; function route( - pathOrMiddleware: string | Middleware, - middleware1: Middleware, - middleware2: Middleware, - middleware3: Middleware, - middleware4: Middleware, + pathOrMiddleware: string | SimpleMiddleware, + middleware1: SimpleMiddleware, + middleware2: SimpleMiddleware, + middleware3: SimpleMiddleware, + middleware4: SimpleMiddleware, handler: Handler, name?: string ): Endpoint; function route( - pathOrMiddleware: string | Middleware, - middleware1: Middleware, - middleware2: Middleware, - middleware3: Middleware, - middleware4: Middleware, - middleware5: Middleware, + pathOrMiddleware: string | SimpleMiddleware, + middleware1: SimpleMiddleware, + middleware2: SimpleMiddleware, + middleware3: SimpleMiddleware, + middleware4: SimpleMiddleware, + middleware5: SimpleMiddleware, handler: Handler, name?: string ): Endpoint; function route( - pathOrMiddleware: string | Middleware, - middleware1: Middleware, - middleware2: Middleware, - middleware3: Middleware, - middleware4: Middleware, - middleware5: Middleware, - middleware6: Middleware, + pathOrMiddleware: string | SimpleMiddleware, + middleware1: SimpleMiddleware, + middleware2: SimpleMiddleware, + middleware3: SimpleMiddleware, + middleware4: SimpleMiddleware, + middleware5: SimpleMiddleware, + middleware6: SimpleMiddleware, handler: Handler, name?: string ): Endpoint; function route( - pathOrMiddleware: string | Middleware, - middleware1: Middleware, - middleware2: Middleware, - middleware3: Middleware, - middleware4: Middleware, - middleware5: Middleware, - middleware6: Middleware, - middleware7: Middleware, + pathOrMiddleware: string | SimpleMiddleware, + middleware1: SimpleMiddleware, + middleware2: SimpleMiddleware, + middleware3: SimpleMiddleware, + middleware4: SimpleMiddleware, + middleware5: SimpleMiddleware, + middleware6: SimpleMiddleware, + middleware7: SimpleMiddleware, handler: Handler, name?: string ): Endpoint; function route( - pathOrMiddleware: string | Middleware, - middleware1: Middleware, - middleware2: Middleware, - middleware3: Middleware, - middleware4: Middleware, - middleware5: Middleware, - middleware6: Middleware, - middleware7: Middleware, - middleware8: Middleware, + pathOrMiddleware: string | SimpleMiddleware, + middleware1: SimpleMiddleware, + middleware2: SimpleMiddleware, + middleware3: SimpleMiddleware, + middleware4: SimpleMiddleware, + middleware5: SimpleMiddleware, + middleware6: SimpleMiddleware, + middleware7: SimpleMiddleware, + middleware8: SimpleMiddleware, handler: Handler, name?: string ): Endpoint; function route( - pathOrMiddleware: string | Middleware, - middleware1: Middleware, - middleware2: Middleware, - middleware3: Middleware, - middleware4: Middleware, - middleware5: Middleware, - middleware6: Middleware, - middleware7: Middleware, - middleware8: Middleware, - middleware9: Middleware, + pathOrMiddleware: string | SimpleMiddleware, + middleware1: SimpleMiddleware, + middleware2: SimpleMiddleware, + middleware3: SimpleMiddleware, + middleware4: SimpleMiddleware, + middleware5: SimpleMiddleware, + middleware6: SimpleMiddleware, + middleware7: SimpleMiddleware, + middleware8: SimpleMiddleware, + middleware9: SimpleMiddleware, handler: Handler, name?: string ): Endpoint; @@ -1327,6 +1370,13 @@ declare namespace Foxx { declare module "@arangodb" { function aql(strings: TemplateStringsArray, ...args: any[]): ArangoDB.Query; + namespace aql { + function literal(value: any): ArangoDB.AqlLiteral; + } + function query( + strings: TemplateStringsArray, + ...args: any[] + ): ArangoDB.Cursor; function time(): number; const db: ArangoDB.Database & { [key: string]: ArangoDB.Collection | undefined; @@ -1362,10 +1412,6 @@ declare module "@arangodb/foxx/graphql" { } declare module "@arangodb/foxx/sessions" { - interface SessionsMiddleware extends Foxx.Middleware { - storage: Foxx.SessionStorage; - transport: Foxx.SessionTransport[]; - } interface SessionsOptions { storage: Foxx.SessionStorage | string | ArangoDB.Collection; transport: @@ -1375,7 +1421,9 @@ declare module "@arangodb/foxx/sessions" { | "header"; autoCreate?: boolean; } - function sessionsMiddleware(options: SessionsOptions): Foxx.Middleware; + function sessionsMiddleware( + options: SessionsOptions + ): Foxx.SessionsMiddleware; export = sessionsMiddleware; } @@ -1386,14 +1434,11 @@ declare module "@arangodb/foxx/sessions/storages/collection" { pruneExpired?: boolean; autoUpdate?: boolean; } - interface CollectionStorage extends Foxx.SessionStorage { - prune: () => string[]; - } function collectionStorage( options: | CollectionStorageOptions | CollectionStorageOptions["collection"] - ): CollectionStorage; + ): Foxx.CollectionSessionStorage; export = collectionStorage; } diff --git a/types/arrify/arrify-tests.ts b/types/arrify/arrify-tests.ts index 12995781bf..3fee89133d 100644 --- a/types/arrify/arrify-tests.ts +++ b/types/arrify/arrify-tests.ts @@ -1,5 +1,6 @@ import * as arrify from 'arrify'; +/***************** arrify *****************/ arrify(null); arrify(null); @@ -12,3 +13,74 @@ arrify([2, 3]); function test(val?: string | string[]) { arrify(val); } +/***************** arrify *****************/ + +/***************** arrify *****************/ +arrify(undefined); // returns [] + +arrify(null); // returns [] + +{ + const value: number | string[] = 2018; + arrify(value); // returns [2018] +} + +{ + const value: number[] | string | string[] = ['a', 'b']; + arrify(value); // returns ['a', 'b'] +} +/***************** arrify *****************/ + +/***************** arrify *****************/ +arrify(undefined); + +arrify(null); + +{ + const value: boolean | number[] | string[] = true; + // returns [true] + arrify(value); +} + +{ + const value: boolean[] | number | string[] = ['a', 'b']; + // returns ['a', 'b'] + arrify(value); +} +/***************** arrify *****************/ + +/***************** arrify *****************/ +arrify(undefined); + +arrify(null); + +{ + const value: boolean | Date | number[] | string[] = new Date(2018); + // returns [ new Date(2018) ] + arrify(value); +} + +{ + const value: boolean[] | Date[] | number | string = [true, false]; + // returns [true, false] + arrify(value); +} +/***************** arrify *****************/ + +/***************** arrify *****************/ +arrify(undefined); + +arrify(null); + +{ + const value: boolean | Date | number[] | RegExp | string[] = /test/; + // returns [ /test/ ] + arrify(value); +} + +{ + const value: boolean[] | Date[] | number | RegExp[] | string = [/test1/, /test2/]; + // returns [/test1/, /test2/] + arrify(value); +} +/***************** arrify *****************/ diff --git a/types/arrify/index.d.ts b/types/arrify/index.d.ts index 43c06af05f..7c3c588ea6 100644 --- a/types/arrify/index.d.ts +++ b/types/arrify/index.d.ts @@ -14,5 +14,78 @@ * arrify([2, 3]) // returns [2, 3] */ declare function arrify(val: undefined | null | T | T[]): T[]; + +/** + * @example + * // returns [] + * arrify(undefined); + * @example + * // returns [] + * arrify(null); + * @example + * let value: number | string[] = 2018; + * // returns [2018] + * arrify(value); + * @example + * let value: number[] | string | string[] = ['a', 'b']; + * // returns ['a', 'b'] + * arrify(value); + */ +declare function arrify(val: undefined | null | T1 | T2 | T1[] | T2[]): T1[] | T2[]; + +/** + * @example + * // returns [] + * arrify(undefined); + * @example + * // returns [] + * arrify(null); + * @example + * let value: boolean | number[] | string[] = true; + * // returns [true] + * arrify(value); + * @example + * let value: boolean[] | number | string[] = ['a', 'b']; + * // returns ['a', 'b'] + * arrify(value); + */ +declare function arrify(val: undefined | null | T1 | T2 | T3 | T1[] | T2[] | T3[]): T1[] | T2[] | T3[]; + +/** + * @example + * // returns [] + * arrify(undefined); + * @example + * // returns [] + * arrify(null); + * @example + * let value: boolean | Date | number[] | string[] = new Date(2018); + * // returns [ new Date(2018) ] + * arrify(value); + * @example + * let value: boolean[] | Date[] | number | string = [true, false]; + * // returns [true, false] + * arrify(value); + */ +declare function arrify(val: undefined | null | T1 | T2 | T3 | T4 | T1[] | T2[] | T3[] | T4[]): T1[] | T2[] | T3[] | T4[]; + +/** + * @example + * // returns [] + * arrify(undefined); + * @example + * // returns [] + * arrify(null); + * @example + * let value: boolean | Date | number[] | RegExp | string[] = /test/; + * // returns [ /test/ ] + * arrify(value); + * @example + * let value: boolean[] | Date[] | number | RegExp[] | string = [/test1/, /test2/]; + * // returns [/test1/, /test2/] + * arrify(value); + */ +declare function arrify(val: undefined | null | T1 | T2 | T3 | T4 | T5 | T1[] | T2[] | T3[] | T4[] | T5[]): T1[] | T2[] | T3[] | T4[] | T5[]; + declare namespace arrify {} export = arrify; diff --git a/types/atob/atob-tests.ts b/types/atob/atob-tests.ts new file mode 100644 index 0000000000..e2e2618387 --- /dev/null +++ b/types/atob/atob-tests.ts @@ -0,0 +1,3 @@ +import atob from 'atob'; + +atob('foo'); diff --git a/types/atob/index.d.ts b/types/atob/index.d.ts new file mode 100644 index 0000000000..632880f7a6 --- /dev/null +++ b/types/atob/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for atob 2.1 +// Project: https://git.coolaj86.com/coolaj86/atob.js.git +// Definitions by: John Wright +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export default function(str: string): string; diff --git a/types/atob/tsconfig.json b/types/atob/tsconfig.json new file mode 100644 index 0000000000..70dd7f0fdc --- /dev/null +++ b/types/atob/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "lib": ["es6"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "atob-tests.ts" + ] +} diff --git a/types/atob/tslint.json b/types/atob/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/atob/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index 516e2cc368..aa82e908e5 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -33,8 +33,13 @@ export interface RetryOptions { maxRetries?: number; } -export interface UserMetadata { } -export interface AppMetadata { } +export interface UserMetadata { + [propName: string]: string +} + +export interface AppMetadata { + [propName: string]: any +} export interface UserData { email?: string; @@ -513,9 +518,72 @@ export interface EmailVerificationTicketOptions { result_url: string; } +export interface BaseClientOptions { + baseUrl: string; + clientId?: string; +} + +export interface OAuthClientOptions extends BaseClientOptions { + clientSecret?: string; +} + +export interface DatabaseClientOptions extends BaseClientOptions { +} + +export interface PasswordLessClientOptions extends BaseClientOptions { +} + +export interface TokenManagerOptions extends BaseClientOptions { + headers?: any; +} +export interface UsersOptions extends BaseClientOptions { + headers?: any; +} + +export interface SignInOptions extends VerifyOptions { + connection?: string; +} + +export interface SocialSignInOptions { + access_token: string; + connection: string; +} + +export interface SignInToken { + access_token: string; + id_token?: string; + token_type?: string; + expiry: number; +} + +export interface RequestSMSCodeOptions extends RequestSMSOptions { + client_id: string; +} + +export type SendType = 'link' | 'code'; +export interface RequestEmailCodeOrLinkOptions { + email: string; + send: SendType +} + +export interface ImpersonateSettingOptions { + impersonator_id: string; + protocol: string; + token: string; + clientId?: string; +} + export class AuthenticationClient { + + // Members + database?: DatabaseAuthenticator; + oauth?: OAuthAuthenticator; + passwordless?: PasswordlessAuthenticator; + tokens?: TokenManager; + users?: UsersManager; + constructor(options: AuthenticationClientOptions); getClientInfo(): ClientInfo; @@ -755,3 +823,63 @@ export class ManagementClient { updateResourceServer(params: ObjectWithId, data: ResourceServer): Promise; updateResourceServer(params: ObjectWithId, data: ResourceServer, cb?: (err: Error, data: ResourceServer) => void): void; } + + +export class DatabaseAuthenticator { + constructor(options: DatabaseClientOptions, oauth: OAuthAuthenticator); + + changePassword(data: ResetPasswordOptions): Promise; + changePassword(data: ResetPasswordOptions, cb: (err: Error, message: string) => void): void; + + requestChangePasswordEmail(data: ResetPasswordEmailOptions): Promise; + requestChangePasswordEmail(data: ResetPasswordEmailOptions, cb: (err: Error, message: string) => void): void; + + signIn(data: SignInOptions): Promise; + signIn(data: SignInOptions, cb: (err: Error, data: SignInToken) => void): void; + + signUp(data: CreateUserData): Promise; + signIn(data: CreateUserData, cb: (err: Error, data: User) => void): void; + +} + +export class OAuthAuthenticator { + constructor(options: OAuthClientOptions); + + passwordGrant(options: PasswordGrantOptions): Promise; + passwordGrant(options: PasswordGrantOptions, cb: (err: Error, response: SignInToken) => void): void; + + signIn(data: SignInOptions): Promise; + signIn(data: SignInOptions, cb: (err: Error, data: SignInToken) => void): void; + + + socialSignIn(data: SocialSignInOptions): Promise; + socialSignIn(data: SocialSignInOptions, cb: (err: Error, data: SignInToken) => void): void; +} + +export class PasswordlessAuthenticator { + constructor(options: PasswordLessClientOptions, oauth: OAuthAuthenticator); + + signIn(data: SignInOptions): Promise; + signIn(data: SignInOptions, cb: (err: Error, data: SignInToken) => void): void; + + sendEmail(data: RequestEmailCodeOrLinkOptions): Promise; + sendEmail(data: RequestEmailCodeOrLinkOptions, cb: (err: Error, message: string) => void): void; + + sendSMS(data: RequestSMSCodeOptions): Promise; + sendSMS(data: RequestSMSCodeOptions, cb: (err: Error, message: string) => void): void; +} + +export class TokenManager { + constructor(options: TokenManagerOptions); + +} + +export class UsersManager { + constructor(options: UsersOptions); + + getInfo(accessToken: string): Promise; + getInfo(accessToken: string, cb: (err: Error, user: User) => void): void; + + impersonate(userId: string, settings: ImpersonateSettingOptions): Promise; + impersonate(userId: string, settings: ImpersonateSettingOptions, cb: (err: Error, data: any) => void): void; +} \ No newline at end of file diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index b1de338923..8c892a3ca0 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -46,7 +46,7 @@ export interface Node { export interface ArrayExpression extends Node { type: "ArrayExpression"; - elements: Array; + elements: Array; } export interface AssignmentExpression extends Node { @@ -1306,7 +1306,7 @@ export type TSEntityName = Identifier | TSQualifiedName; export type TSTypeElement = TSCallSignatureDeclaration | TSConstructSignatureDeclaration | TSIndexSignature | TSMethodSignature | TSPropertySignature; -export function arrayExpression(elements?: Array): ArrayExpression; +export function arrayExpression(elements?: Array): ArrayExpression; export function assignmentExpression(operator?: string, left?: LVal, right?: Expression): AssignmentExpression; export function binaryExpression( operator?: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<=", diff --git a/types/behavior3/behavior3-tests.ts b/types/behavior3/behavior3-tests.ts new file mode 100644 index 0000000000..b612209a09 --- /dev/null +++ b/types/behavior3/behavior3-tests.ts @@ -0,0 +1,73 @@ +import '../behavior3'; + +// Test decode +const blackboard = new b3.Blackboard(); +const behaviorTree = new b3.BehaviorTree(); +behaviorTree.load({ + version: "0.3.0", + scope: "tree", + id: "6bc03cd0-38ef-4a3e-8e08-54c412491525", + title: "A behavior tree", + description: "", + root: "607d29f5-9dbc-4cc4-8ebb-e57c4908d87b", + properties: {}, + nodes: { + "607d29f5-9dbc-4cc4-8ebb-e57c4908d87b": { + id: "607d29f5-9dbc-4cc4-8ebb-e57c4908d87b", + name: "Sequence", + title: "Sequence", + description: "", + properties: {}, + display: { + x: -216, + y: -36 + }, + children: [ + "09f04185-205b-40c0-8494-ffd53ffd0820", + "df7366f8-999a-4971-872c-cef57607f99f" + ] + }, + "df7366f8-999a-4971-872c-cef57607f99f": { + id: "df7366f8-999a-4971-872c-cef57607f99f", + name: "Runner", + title: "Runner", + description: "", + properties: {}, + display: { + x: -12, + y: -36 + } + }, + "e498e1a5-5295-43c3-8716-20dd6d3407f2": { + id: "e498e1a5-5295-43c3-8716-20dd6d3407f2", + name: "Succeeder", + title: "Succeeder", + description: "", + properties: {}, + display: { + x: 192, + y: -96 + } + }, + "09f04185-205b-40c0-8494-ffd53ffd0820": { + id: "09f04185-205b-40c0-8494-ffd53ffd0820", + name: "Inverter", + title: "Inverter", + description: "", + properties: {}, + display: { + x: -36, + y: -108 + }, + child: "e498e1a5-5295-43c3-8716-20dd6d3407f2" + } + }, + display: { + camera_x: 640, + camera_y: 324, + camera_z: 1, + x: -324, + y: -36 + } + }); +behaviorTree.tick(null, blackboard); diff --git a/types/behavior3/index.d.ts b/types/behavior3/index.d.ts new file mode 100644 index 0000000000..7cb3ad9deb --- /dev/null +++ b/types/behavior3/index.d.ts @@ -0,0 +1,908 @@ +// Type definitions for behavior3 0.2 +// Project: https://github.com/behavior3/behavior3js +// Definitions by: carry.wu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Behavior3JS + * =========== + * + * * * * + * + * **Behavior3JS** is a Behavior Tree library written in JavaScript. It + * provides structures and algorithms that assist you in the task of creating + * intelligent agents for your game or application. Check it out some features + * of Behavior3JS: + * + * - Based on the work of (Marzinotto et al., 2014), in which they propose a + * **formal**, **consistent** and **general** definition of Behavior Trees; + * - **Optimized to control multiple agents**: you can use a single behavior + * tree instance to handle hundreds of agents; + * - It was **designed to load and save trees in a JSON format**, in order to + * use, edit and test it in multiple environments, tools and languages; + * - A **cool visual editor** which you can access online; + * - Several **composite, decorator and action nodes** available within the + * library. You still can define your own nodes, including composites and + * decorators; + * - **Completely free**, the core module and the visual editor are all + * published under the MIT License, which means that you can use them for + * your open source and commercial projects; + * - **Lightweight**! + * + * Visit http://behavior3.com to know more! + * + * + * ## Core Classes and Functions + * + * This library include the following core structures... + * + * + * **Public:** + * + * - **BehaviorTree**: the structure that represents a Behavior Tree; + * - **Blackboard**: represents a "memory" in an agent and is required to to + * run a `BehaviorTree`; + * - **Composite**: base class for all composite nodes; + * - **Decorator**: base class for all decorator nodes; + * - **Action**: base class for all action nodes; + * - **Condition**: base class for all condition nodes; + * + * + * **Internal:** + * + * - **Tick**: used as container and tracking object through the tree during + * the tick signal; + * - **BaseNode**: the base class that provide all common node features; + * + * *Some classes are used internally on Behavior3JS, but you may need to access + * its functionalities eventually, specially the `Tick` object.* + * + * + * **Nodes:** + * + * - **Composite Nodes**: Sequence, Priority, MemSequence, MemPriority. + * - **Decorators**: Inverter, Limiter, MaxTime, Repeater, + * RepeaterUntilFailure, RepeaterUntilSuccess. + * - **Actions**: Succeeder, Failer, Error, Runner, Wait. + * + * ## The list of all constants in B3. + * + * NAME | VALUE + * ------------------- | ---------------------- + * VERSION | depends on the version + * | + * **Node State** | + * SUCCESS | 1 + * FAILURE | 2 + * RUNNING | 3 + * ERROR | 4 + * | + * **Node categories** | + * COMPOSITE | 'composite' + * DECORATOR | 'decorator' + * ACTION | 'action' + * CONDITION | 'condition' + * + */ +declare namespace b3 { + /** + * This function is used to create unique IDs for trees and nodes. + * + * (consult http://www.ietf.org/rfc/rfc4122.txt). + * + */ + function createUUID(): string; + + /** + * The BaseNode class is used as super class to all nodes in BehaviorJS. It + * comprises all common variables and methods that a node must have to + * execute. + * + * **IMPORTANT:** Do not inherit from this class, use `Composite`, + * `Decorator`, `Action` or `Condition`, instead. + * + * The attributes are specially designed to serialization of the node in a + * JSON format. In special, the `parameters` attribute can be set into the + * visual editor (thus, in the JSON file), and it will be used as parameter + * on the node initialization at `BehaviorTree.load`. + * + * BaseNode also provide 5 callback methods, which the node implementations + * can override. They are `enter`, `open`, `tick`, `close` and `exit`. See + * their documentation to know more. These callbacks are called inside the + * `_execute` method, which is called in the tree traversal. + * + */ + class BaseNode { + /** + * Initialization method. + */ + constructor({category, name, title, description, properties}?: {category?: string, name?: string, title?: string, description?: string, properties?: any}); + + /** + * This is the main method to propagate the tick signal to this node. This + * method calls all callbacks: `enter`, `open`, `tick`, `close`, and + * `exit`. It only opens a node if it is not already open. In the same + * way, this method only close a node if the node returned a status + * different of `RUNNING`. + * + */ + _execute(tick: Tick): number; + + /** + * Wrapper for enter method. + */ + _enter(tick: Tick): void; + + /** + * Wrapper for open method. + */ + _open(tick: Tick): void; + + /** + * Wrapper for tick method. + */ + _tick(tick: Tick): number; + + /** + * Wrapper for close method. + */ + _close(tick: Tick): void; + + /** + * Wrapper for exit method. + */ + _exit(tick: Tick): void; + + /** + * Enter method, override this to use. It is called every time a node is + * asked to execute, before the tick itself. + */ + enter(tick: Tick): void; + + /** + * Open method, override this to use. It is called only before the tick + * callback and only if the not isn't closed. + * + * Note: a node will be closed if it returned `RUNNING` in the tick. + * + */ + open(tick: Tick): void; + + /** + * Tick method, override this to use. This method must contain the real + * execution of node (perform a task, call children, etc.). It is called + * every time a node is asked to execute. + * + */ + tick(tick: Tick): void; + + /** + * Close method, override this to use. This method is called after the tick + * callback, and only if the tick return a state different from + * `RUNNING`. + * + */ + close(tick: Tick): void; + + /** + * Exit method, override this to use. Called every time in the end of the + * execution. + * + */ + exit(tick: Tick): void; + } + + /** + * Action is the base class for all action nodes. Thus, if you want to create + * new custom action nodes, you need to inherit from this class. For example, + * take a look at the Runner action: + * + * class Runner extends b3.Action { + * constructor(){ + * super({name: 'Runner'}); + * } + * tick(tick) { + * return b3.RUNNING; + * } + * }; + * + */ + class Action extends BaseNode { + /** + * Creates an instance of Action. + */ + constructor({name, title, properties}?: {name?: string, title?: string, properties?: any}); + } + + /** + * The BehaviorTree class, as the name implies, represents the Behavior Tree + * structure. + * + * There are two ways to construct a Behavior Tree: by manually setting the + * root node, or by loading it from a data structure (which can be loaded + * from a JSON). Both methods are shown in the examples below and better + * explained in the user guide. + * + * The tick method must be called periodically, in order to send the tick + * signal to all nodes in the tree, starting from the root. The method + * `BehaviorTree.tick` receives a target object and a blackboard as + * parameters. The target object can be anything: a game agent, a system, a + * DOM object, etc. This target is not used by any piece of Behavior3JS, + * i.e., the target object will only be used by custom nodes. + * + * The blackboard is obligatory and must be an instance of `Blackboard`. This + * requirement is necessary due to the fact that neither `BehaviorTree` or + * any node will store the execution variables in its own object (e.g., the + * BT does not store the target, information about opened nodes or number of + * times the tree was called). But because of this, you only need a single + * tree instance to control multiple (maybe hundreds) objects. + * + * Manual construction of a Behavior Tree + * -------------------------------------- + * + * var tree = new b3.BehaviorTree(); + * + * tree.root = new b3.Sequence({children:[ + * new b3.Priority({children:[ + * new MyCustomNode(), + * new MyCustomNode() + * ]}), + * ... + * ]}); + * + * + * Loading a Behavior Tree from data structure + * ------------------------------------------- + * + * var tree = new b3.BehaviorTree(); + * + * tree.load({ + * 'title' : 'Behavior Tree title' + * 'description' : 'My description' + * 'root' : 'node-id-1' + * 'nodes' : { + * 'node-id-1' : { + * 'name' : 'Priority', // this is the node type + * 'title' : 'Root Node', + * 'description' : 'Description', + * 'children' : ['node-id-2', 'node-id-3'], + * }, + * ... + * } + * }) + * + */ + class BehaviorTree { + /** + * Initialization method. + */ + constructor(); + + /** + * This method loads a Behavior Tree from a data structure, populating this + * object with the provided data. Notice that, the data structure must + * follow the format specified by Behavior3JS. Consult the guide to know + * more about this format. + * + * You probably want to use custom nodes in your BTs, thus, you need to + * provide the `names` object, in which this method can find the nodes by + * `names[NODE_NAME]`. This variable can be a namespace or a dictionary, + * as long as this method can find the node by its name, for example: + * + * //json + * ... + * 'node1': { + * 'name': MyCustomNode, + * 'title': ... + * } + * ... + * + * //code + * var bt = new b3.BehaviorTree(); + * bt.load(data, {'MyCustomNode':MyCustomNode}) + * + * + */ + load(data: any, names?: any): void; + + /** + * This method dump the current BT into a data structure. + * + * Note: This method does not record the current node parameters. Thus, + * it may not be compatible with load for now. + * + */ + dump(): any; + + /** + * Propagates the tick signal through the tree, starting from the root. + * + * This method receives a target object of any type (Object, Array, + * DOMElement, whatever) and a `Blackboard` instance. The target object has + * no use at all for all Behavior3JS components, but surely is important + * for custom nodes. The blackboard instance is used by the tree and nodes + * to store execution variables (e.g., last node running) and is obligatory + * to be a `Blackboard` instance (or an object with the same interface). + * + * Internally, this method creates a Tick object, which will store the + * target and the blackboard objects. + * + * Note: BehaviorTree stores a list of open nodes from last tick, if these + * nodes weren't called after the current tick, this method will close them + * automatically. + * + */ + tick(target: any, blackboard: Blackboard): string; + } + + /** + * The Blackboard is the memory structure required by `BehaviorTree` and its + * nodes. It only have 2 public methods: `set` and `get`. These methods works + * in 3 different contexts: global, per tree, and per node per tree. + * + * Suppose you have two different trees controlling a single object with a + * single blackboard, then: + * + * - In the global context, all nodes will access the stored information. + * - In per tree context, only nodes sharing the same tree share the stored + * information. + * - In per node per tree context, the information stored in the blackboard + * can only be accessed by the same node that wrote the data. + * + * The context is selected indirectly by the parameters provided to these + * methods, for example: + * + * // getting/setting variable in global context + * blackboard.set('testKey', 'value'); + * var value = blackboard.get('testKey'); + * + * // getting/setting variable in per tree context + * blackboard.set('testKey', 'value', tree.id); + * var value = blackboard.get('testKey', tree.id); + * + * // getting/setting variable in per node per tree context + * blackboard.set('testKey', 'value', tree.id, node.id); + * var value = blackboard.get('testKey', tree.id, node.id); + * + * Note: Internally, the blackboard store these memories in different + * objects, being the global on `_baseMemory`, the per tree on `_treeMemory` + * and the per node per tree dynamically create inside the per tree memory + * (it is accessed via `_treeMemory[id].nodeMemory`). Avoid to use these + * variables manually, use `get` and `set` instead. + * + */ + class Blackboard { + /** + * Initialization method. + */ + constructor(); + + /** + * Internal method to retrieve the tree context memory. If the memory does + * not exist, this method creates it. + * + */ + _getTreeMemory(treeScope: string): any; + + /** + * Internal method to retrieve the node context memory, given the tree + * memory. If the memory does not exist, this method creates is. + * + */ + _getNodeMemory(treeMemory: string, nodeScope: string): any; + + /** + * Internal method to retrieve the context memory. If treeScope and + * nodeScope are provided, this method returns the per node per tree + * memory. If only the treeScope is provided, it returns the per tree + * memory. If no parameter is provided, it returns the global memory. + * Notice that, if only nodeScope is provided, this method will still + * return the global memory. + * + */ + _getMemory(treeScope: string, nodeScope: string): any; + + /** + * Stores a value in the blackboard. If treeScope and nodeScope are + * provided, this method will save the value into the per node per tree + * memory. If only the treeScope is provided, it will save the value into + * the per tree memory. If no parameter is provided, this method will save + * the value into the global memory. Notice that, if only nodeScope is + * provided (but treeScope not), this method will still save the value into + * the global memory. + * + */ + set(key: string, value: string, treeScope: string, nodeScope: string): void; + + /** + * Retrieves a value in the blackboard. If treeScope and nodeScope are + * provided, this method will retrieve the value from the per node per tree + * memory. If only the treeScope is provided, it will retrieve the value + * from the per tree memory. If no parameter is provided, this method will + * retrieve from the global memory. If only nodeScope is provided (but + * treeScope not), this method will still try to retrieve from the global + * memory. + * + */ + get(key: string, treeScope: string, nodeScope: string): any; + } + + /** + * Composite is the base class for all composite nodes. Thus, if you want to + * create new custom composite nodes, you need to inherit from this class. + * + * When creating composite nodes, you will need to propagate the tick signal + * to the children nodes manually. To do that, override the `tick` method and + * call the `_execute` method on all nodes. For instance, take a look at how + * the Sequence node inherit this class and how it call its children: + * + * // Inherit from Composite, using the util function Class. + * class Sequence extends Composite { + * + * constructor(){ + * // Remember to set the name of the node. + * super({name: 'Sequence'}); + * } + * + * // Override the tick function + * tick(tick) { + * + * // Iterates over the children + * for (var i=0; i +bidirectionalMap.has("one"); // $ExpectType boolean +bidirectionalMap.hasValue(2); // $ExpectType boolean +bidirectionalMap.keys(); // $ExpectType IterableIterator +bidirectionalMap.values(); // $ExpectType IterableIterator diff --git a/types/bidirectional-map/index.d.ts b/types/bidirectional-map/index.d.ts new file mode 100644 index 0000000000..67662d3441 --- /dev/null +++ b/types/bidirectional-map/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for bidirectional-map 1.0 +// Project: https://github.com/educastellano/bidirectional-map +// Definitions by: Helen Anderson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export default class BiMap { + constructor(object?: { [i: string]: TValue }); + size: number; + + set(key: string, value: TValue): void; + get(key: string): TValue; + getKey(value: TValue): string; + clear(): void; + delete(key: string): void; + deleteValue(value: TValue): void; + entries(): IterableIterator<[string, TValue]>; + has(key: string): boolean; + hasValue(value: TValue): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} diff --git a/types/bidirectional-map/tsconfig.json b/types/bidirectional-map/tsconfig.json new file mode 100644 index 0000000000..0c3b3a1cac --- /dev/null +++ b/types/bidirectional-map/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bidirectional-map-tests.ts" + ] +} diff --git a/types/bidirectional-map/tslint.json b/types/bidirectional-map/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bidirectional-map/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/blocked/blocked-tests.ts b/types/blocked/blocked-tests.ts new file mode 100644 index 0000000000..f43eb82cba --- /dev/null +++ b/types/blocked/blocked-tests.ts @@ -0,0 +1,7 @@ +import * as blocked from 'blocked'; + +blocked((ms: number) => { + // todo: show warning +}, { + threshold: 10 +}); diff --git a/types/blocked/index.d.ts b/types/blocked/index.d.ts new file mode 100644 index 0000000000..5292011f23 --- /dev/null +++ b/types/blocked/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for blocked 1.2 +// Project: https://github.com/visionmedia/node-blocked#readme +// Definitions by: Jonas Lochmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/*~ Note that ES6 modules cannot directly export callable functions. + *~ This file should be imported using the CommonJS-style: + *~ import x = require('someLibrary'); + *~ + *~ Refer to the documentation to understand common + *~ workarounds for this limitation of ES6 modules. + */ + +export = Blocked; + +declare function Blocked(callback: (ms: number) => void, options?: Blocked.Options): NodeJS.Timer; + +declare namespace Blocked { + interface Options { + threshold: number; // in milliseconds + } +} diff --git a/types/blocked/tsconfig.json b/types/blocked/tsconfig.json new file mode 100644 index 0000000000..3b110548b0 --- /dev/null +++ b/types/blocked/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "blocked-tests.ts" + ] +} diff --git a/types/blocked/tslint.json b/types/blocked/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/blocked/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bluebird-retry/bluebird-retry-tests.ts b/types/bluebird-retry/bluebird-retry-tests.ts index e9beaf5562..45a665c969 100644 --- a/types/bluebird-retry/bluebird-retry-tests.ts +++ b/types/bluebird-retry/bluebird-retry-tests.ts @@ -30,3 +30,10 @@ const options: retry.Options = { }; retry(logFail, options); + +function stopErrorExample() { + console.log('retrying\n'); + throw new retry.StopError('stop retrying'); +} + +retry(stopErrorExample); diff --git a/types/bluebird-retry/index.d.ts b/types/bluebird-retry/index.d.ts index 358c75936d..b7ba96495d 100644 --- a/types/bluebird-retry/index.d.ts +++ b/types/bluebird-retry/index.d.ts @@ -20,6 +20,8 @@ declare namespace retry { context?: any; args?: any; } + + class StopError extends Error {} } export = retry; diff --git a/types/browser-sync/browser-sync-tests.ts b/types/browser-sync/browser-sync-tests.ts index 613f8aee25..c63cb0c862 100644 --- a/types/browser-sync/browser-sync-tests.ts +++ b/types/browser-sync/browser-sync-tests.ts @@ -167,8 +167,8 @@ browserSync({ browserSync({ proxy: { target: "http://yourlocal.dev", - proxyRes: function (proxyRes, req, res) { - console.log(proxyRes); + proxyRes: function (proxyResponse, req, res) { + console.log(proxyResponse); } } }); @@ -177,8 +177,28 @@ browserSync({ proxy: { target: "http://yourlocal.dev", proxyRes: [ - function (proxyRes, req, res) { - console.log(proxyRes); + function (proxyResponse, req, res) { + console.log(proxyResponse); + } + ] + } +}); + +browserSync({ + proxy: { + target: "http://yourlocal.dev", + proxyRes: function (res) { + console.log(res); + } + } +}); + +browserSync({ + proxy: { + target: "http://yourlocal.dev", + proxyRes: [ + function (res) { + console.log(res); } ] } diff --git a/types/browser-sync/index.d.ts b/types/browser-sync/index.d.ts index 3b97fc8616..de0a457266 100644 --- a/types/browser-sync/index.d.ts +++ b/types/browser-sync/index.d.ts @@ -39,7 +39,7 @@ declare namespace browserSync { * Specify which file events to respond to. * Available events: `add`, `change`, `unlink`, `addDir`, `unlinkDir` */ - watchEvents?: string[]; + watchEvents?: WatchEvents | string[]; /** * Watch files automatically. */ @@ -72,7 +72,7 @@ declare namespace browserSync { * ws - Default: undefined * middleware - Default: undefined * reqHeaders - Default: undefined - * proxyRes - Default: undefined + * proxyRes - Default: undefined (http.ServerResponse if expecting single parameter) * proxyReq - Default: undefined */ proxy?: string | ProxyOptions; @@ -91,7 +91,7 @@ declare namespace browserSync { * Default: [] * Note: Requires at least version 2.8.0. */ - serveStatic?: (string | { route?: string | string[], dir?: string | string[]})[]; + serveStatic?: StaticOptions[] | string[]; /** * Options that are passed to the serve-static middleware when you use the * string[] syntax: eg: `serveStatic: ['./app']`. @@ -120,7 +120,7 @@ declare namespace browserSync { * Can be either "info", "debug", "warn", or "silent" * Default: info */ - logLevel?: string; + logLevel?: LogLevel; /** * Change the console logging prefix. Useful if you're creating your own project based on Browsersync * Default: BS @@ -170,7 +170,7 @@ declare namespace browserSync { * Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. * Can be true, local, external, ui, ui-external, tunnel or false */ - open?: string | boolean; + open?: OpenOptions | boolean; /** * The browser(s) to open * Default: default @@ -320,6 +320,12 @@ declare namespace browserSync { excludeFileTypes?: string[]; } + type WatchEvents = "add" | "change" | "unlink" | "addDir" | "unlinkDir"; + + type LogLevel = "info" | "debug" | "warn" | "silent"; + + type OpenOptions = "local" | "external" | "ui" | "ui-external" | "tunnel"; + interface Hash { [path: string]: T; } @@ -353,16 +359,21 @@ declare namespace browserSync { routes?: Hash; /** configure custom middleware */ middleware?: (MiddlewareHandler | PerRouteMiddleware)[]; - serveStaticOptions?: ServeStaticOptions + serveStaticOptions?: ServeStaticOptions; } interface ProxyOptions { target?: string; middleware?: MiddlewareHandler; ws?: boolean; - reqHeaders?: (config: any) => Hash; - proxyRes?: ((res: http.ServerResponse, req: http.IncomingMessage, next: Function) => any)[] | ((res: http.ServerResponse, req: http.IncomingMessage, next: Function) => any); - proxyReq?: ((res: http.ServerRequest) => any)[] | ((res: http.ServerRequest) => any); + reqHeaders?: (config: object) => Hash; + proxyRes?: ProxyResponseMiddleware | ProxyResponseMiddleware[]; + proxyReq?: ((res: http.ServerRequest) => void)[] | ((res: http.ServerRequest) => void); + error?: (err: NodeJS.ErrnoException, req: http.IncomingMessage, res: http.ServerResponse) => void; + } + + interface ProxyResponseMiddleware { + (proxyRes: http.ServerResponse | http.IncomingMessage, res: http.ServerResponse, req: http.IncomingMessage): void; } interface HttpsOptions { @@ -370,11 +381,17 @@ declare namespace browserSync { cert?: string; } + interface StaticOptions { + route: string | string[], + dir: string | string[] + } + interface MiddlewareHandler { - (req: http.IncomingMessage, res: http.ServerResponse, next: Function): any; + (req: http.IncomingMessage, res: http.ServerResponse, next: () => void): any; } interface PerRouteMiddleware { + id?: string; route: string; handle: MiddlewareHandler; } @@ -382,18 +399,23 @@ declare namespace browserSync { interface GhostOptions { clicks?: boolean; scroll?: boolean; - forms?: boolean | { - submit?: boolean; - inputs?: boolean; - toggles?: boolean; - }; + forms?: FormsOptions | boolean; + } + + interface FormsOptions { + inputs: boolean, + submit: boolean, + toggles: boolean } interface SnippetOptions { - async?: boolean, + async?: boolean; whitelist?: string[], blacklist?: string[], - rule?: { match?: RegExp; fn?: (snippet: string, match: string) => any }; + rule?: { + match?: RegExp; + fn?: (snippet: string, match: string) => any + }; } interface SocketOptions { diff --git a/types/btoa/btoa-tests.ts b/types/btoa/btoa-tests.ts new file mode 100644 index 0000000000..d09cdad23a --- /dev/null +++ b/types/btoa/btoa-tests.ts @@ -0,0 +1,3 @@ +import btoa from 'btoa'; + +btoa('foo'); diff --git a/types/btoa/index.d.ts b/types/btoa/index.d.ts new file mode 100644 index 0000000000..cc311ed836 --- /dev/null +++ b/types/btoa/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for btoa 1.2 +// Project: https://git.coolaj86.com/coolaj86/btoa.js +// Definitions by: John Wright +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export default function(str: string): string; diff --git a/types/btoa/tsconfig.json b/types/btoa/tsconfig.json new file mode 100644 index 0000000000..da4e373e68 --- /dev/null +++ b/types/btoa/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "lib": ["es6"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "btoa-tests.ts" + ] +} diff --git a/types/btoa/tslint.json b/types/btoa/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/btoa/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/chai-spies/chai-spies-tests.ts b/types/chai-spies/chai-spies-tests.ts index 1d99f0add2..f5247ba13f 100644 --- a/types/chai-spies/chai-spies-tests.ts +++ b/types/chai-spies/chai-spies-tests.ts @@ -88,6 +88,27 @@ spyStringArg('foo'); expect(spyStringArg).to.have.been.called.always.with.exactly('foo'); spyStringArg.should.have.been.called.always.with.exactly('foo'); +// .first / .second / .third +const spyStringIteratedArg = chai.spy((arg: string) => arg); +spyStringIteratedArg('foo'); +spyStringIteratedArg('bar'); +spyStringIteratedArg('baz'); +expect(spyStringIteratedArg).to.have.been.first.called.with('foo'); +spyStringIteratedArg.should.have.been.first.called.with('foo'); +expect(spyStringIteratedArg).to.have.been.first.called.with('bar'); +spyStringIteratedArg.should.have.been.first.called.with('bar'); +expect(spyStringIteratedArg).to.have.been.first.called.with('baz'); +spyStringIteratedArg.should.have.been.first.called.with('baz'); + +// .nth +const spyStringNthArg = chai.spy((arg: string) => arg); +spyStringNthArg('foo'); +spyStringNthArg('bar'); +expect(spyStringNthArg).on.nth(1).be.called.with('foo'); +spyStringNthArg.should.on.nth(1).be.called.with('foo'); +expect(spyStringNthArg).on.nth(2).be.called.with('bar'); +spyStringNthArg.should.on.nth(2).be.called.with('bar'); + // .once expect(spy).to.have.been.called.once; expect(spy).to.not.have.been.called.once; diff --git a/types/chai-spies/index.d.ts b/types/chai-spies/index.d.ts index ffed6e594b..75f702ca37 100644 --- a/types/chai-spies/index.d.ts +++ b/types/chai-spies/index.d.ts @@ -10,6 +10,10 @@ declare namespace Chai { spy: ChaiSpies.Spy; } + interface LanguageChains { + on: Assertion; + } + interface Assertion { /** * ####.spy @@ -31,6 +35,28 @@ declare namespace Chai { * Note that ```called``` can be used as a chainable method. */ called: ChaiSpies.Called; + + /** + * * ####.been + * * Assert that something has been spied on. Negation passes through. + * * ```ts + * * expect(spy).to.have.been.called(); + * * spy.should.have.been.called(); + * ``` + * Note that ```been``` can be used as a chainable method. + */ + been: ChaiSpies.Been; + + /** + * * ####.nth (function) + * * Assert that something has been spied on on a certain index. Negation passes through. + * * ```ts + * * expect(spy).on.nth(5).be.called.with('foobar'); + * * spy.should.on.nth(5).be.called.with('foobar'); + * ``` + * Note that ```nth``` can be used as a chainable method. + */ + nth(index: number): Assertion; } } @@ -224,6 +250,47 @@ declare namespace ChaiSpies { lt(n: number): Chai.Assertion; } + interface Been extends Chai.Assertion { + (): Chai.Assertion; + called: Called; + + /** + * ####.first + * Assert that a spy has been called first. + * ```ts + * expect(spy).to.have.been.called.first; + * expect(spy).to.not.have.been.called.first; + * spy.should.have.been.called.first; + * spy.should.not.have.been.called.first; + * ``` + */ + first: Chai.Assertion; + + /** + * ####.second + * Assert that a spy has been called second. + * ```ts + * expect(spy).to.have.been.called.second; + * expect(spy).to.not.have.been.called.second; + * spy.should.have.been.called.second; + * spy.should.not.have.been.called.second; + * ``` + */ + second: Chai.Assertion; + + /** + * ####.third + * Assert that a spy has been called third. + * ```ts + * expect(spy).to.have.been.called.third; + * expect(spy).to.not.have.been.called.third; + * spy.should.have.been.called.third; + * spy.should.not.have.been.called.third; + * ``` + */ + third: Chai.Assertion; + } + interface With { /** * ####.with diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 621152162a..04d2e182ee 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -10,6 +10,7 @@ // Guillaume Rodriguez // Sergey Rubanov // Simon Archer +// Ken Elkabany // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -168,6 +169,7 @@ declare namespace Chart { x?: number | string | Date; y?: number | string | Date; r?: number; + t?: number | string | Date; } interface ChartConfiguration { @@ -219,7 +221,7 @@ declare namespace Chart { interface ChartTitleOptions { display?: boolean; position?: PositionType; - fullWdith?: boolean; + fullWidth?: boolean; fontSize?: number; fontFamily?: string; fontColor?: ChartColor; @@ -422,6 +424,7 @@ declare namespace Chart { padding?: number; reverse?: boolean; showLabelBackdrop?: boolean; + source?: 'auto' | 'data' | 'labels'; } interface AngleLineOptions { @@ -510,6 +513,7 @@ declare namespace Chart { gridLines?: GridLineOptions; barThickness?: number; scaleLabel?: ScaleTitleOptions; + offset?: boolean; beforeUpdate?(scale?: any): void; beforeSetDimension?(scale?: any): void; beforeDataLimits?(scale?: any): void; @@ -529,6 +533,7 @@ declare namespace Chart { interface ChartXAxe extends CommonAxe { categoryPercentage?: number; barPercentage?: number; + distribution?: 'linear' | 'series'; time?: TimeScale; } diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index 466f09107d..d2b92e4b22 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -263,6 +263,7 @@ declare namespace chrome.bookmarks { export interface BookmarkRemoveInfo { index: number; parentId: string; + node: BookmarkTreeNode; } export interface BookmarkMoveInfo { diff --git a/types/cli-progress/cli-progress-tests.ts b/types/cli-progress/cli-progress-tests.ts new file mode 100644 index 0000000000..b9fa6d5057 --- /dev/null +++ b/types/cli-progress/cli-progress-tests.ts @@ -0,0 +1,92 @@ +import progress = require('cli-progress'); + +function test0() { + // Usage + // Multiple examples are available e.g.example.js - just try it $ node example.js + + const _cliProgress = require('cli-progress'); + + // create a new progress bar instance and use shades_classic theme + const bar1 = new _cliProgress.Bar({}, _cliProgress.Presets.shades_classic); + + // start the progress bar with a total value of 200 and start value of 0 + bar1.start(200, 0); + + // update the current value in your application.. + bar1.update(100); + + // stop the progress bar + bar1.stop(); +} + +function test1() { + // Examples + // Example 1 - Set Options + + // change the progress characters + // set fps limit to 5 + // change the output stream and barsize + const bar = new progress.Bar({ + barCompleteChar: '#', + barIncompleteChar: '.', + fps: 5, + stream: process.stdout, + barsize: 65 + }); +} + +function test2() { + // Example 2 - Change Styles defined by Preset + // uee shades preset + // change the barsize + const bar = new progress.Bar({ + barsize: 65 + }, progress.Presets.shades_grey); +} + +function test3() { + // Example 3 - Custom Payload + // create new progress bar with custom token "speed" + const bar = new progress.Bar({ + format: 'progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit' + }); + + // initialize the bar - set payload token "speed" with the default value "N/A" + bar.start(200, 0, { + speed: "N/A" + }); + + // some code/update loop + // ... + + // update bar value. set custom token "speed" to 125 + bar.update(5, { + speed: '125' + }); + + // process finished + bar.stop(); +} + +function test4() { + // Example 4 - Custom Presets + // File mypreset.js + + const _colors = require('colors'); + + module.exports = { + format: _colors.red(' {bar}') + ' {percentage}% | ETA: {eta}s | {value}/{total} | Speed: {speed} kbit', + barCompleteChar: '\u2588', + barIncompleteChar: '\u2591' + }; +} + +function test5() { + // Application + + const _mypreset = require('./mypreset.js'); + + const bar = new progress.Bar({ + barsize: 65 + }, _mypreset); +} diff --git a/types/cli-progress/index.d.ts b/types/cli-progress/index.d.ts new file mode 100644 index 0000000000..3ac9dfe8a3 --- /dev/null +++ b/types/cli-progress/index.d.ts @@ -0,0 +1,114 @@ +// Type definitions for cli-progress 1.8 +// Project: https://github.com/AndiDittrich/Node.CLI-Progress +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +export interface Options { + /** + * progress bar output format. + * The progressbar can be customized by using the following build-in placeholders. They can be combined in any order. + * {bar} - the progress bar, customizable by the options barsize, barCompleteString and barIncompleteString + * {percentage} - the current progress in percent (0-100) + * {total} - the end value + * {value} - the current value set by last update() call + * {eta} - expected time of accomplishment in seconds + * {duration} - elapsed time in seconds + * {eta_formatted} - expected time of accomplishment formatted into appropriate units + * {duration_formatted} - elapsed time formatted into appropriate units + * + * Example: + * progress [{bar}] {percentage}% | ETA: {eta}s | {value}/{total} + * is rendered as + * progress [========================================] 100% | ETA: 0s | 200/200 + */ + format?: string; + + /** the maximum update rate (default: 10) */ + fps?: number; + + /** output stream to use (default: process.stderr) */ + stream?: NodeJS.WritableStream; + + /** automatically call stop() when the value reaches the total (default: false) */ + stopOnComplete?: boolean; + + /** clear the progress bar on complete / stop() call (default: false) */ + clearOnComplete?: boolean; + + /** the length of the progress bar in chars (default: 40) */ + barsize?: number; + + /** character to use as "complete" indicator in the bar (default: "=") */ + barCompleteString?: string; + + /** character to use as "incomplete" indicator in the bar (default: "-") */ + barIncompleteString?: string; + + /** character to use as "complete" indicator in the bar (default: "=") */ + barCompleteChar?: string; + + /** character to use as "incomplete" indicator in the bar (default: "-") */ + barIncompleteChar?: string; + + /** hide the cursor during progress operation; restored on complete (default: false) */ + hideCursor?: boolean; + + /** number of updates with which to calculate the eta; higher numbers give a more stable eta (default: 10) */ + etaBuffer?: number; + + /** disable line wrapping (default: false) - pass null to keep terminal settings; pass true to trim the output to terminal width */ + linewrap?: boolean | null; +} + +export interface Preset { + barCompleteChar: string; + barIncompleteChar: string; + format: string; +} + +export class Bar { + /** Initialize a new Progress bar. An instance can be used multiple times! it's not required to re-create it! */ + constructor(opt: Options, preset?: Preset); + + calculateETA(): void; + + formatTime(t: any, roundToMultipleOf: any): any; + + getTotal(): any; + + /** Increases the current progress value by a specified amount (default +1). Update payload optionally */ + increment(step: number, payload?: object): void; + + render(): void; + + /** Sets the total progress value while progressbar is active. Especially useful handling dynamic tasks. */ + setTotal(total: number): void; + + /** Starts the progress bar and set the total and initial value */ + start(total: number, startValue: number, payload?: object): void; + + /** Stops the progress bar and go to next line */ + stop(): void; + + stopTimer(): void; + + /** Sets the current progress value and optionally the payload with values of custom tokens as a second parameter */ + update(current: number, payload?: object): void; +} + +export const Presets: { + /** Styles as of cli-progress v1.3.0 */ + legacy: Preset; + + /** Unicode Rectangles */ + rect: Preset; + + /** Unicode background shades are used for the bar */ + shades_classic: Preset; + + /** Unicode background shades with grey bar */ + shades_grey: Preset; +}; diff --git a/types/cli-progress/tsconfig.json b/types/cli-progress/tsconfig.json new file mode 100644 index 0000000000..be8771c6c5 --- /dev/null +++ b/types/cli-progress/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "cli-progress-tests.ts" + ] +} diff --git a/types/cli-progress/tslint.json b/types/cli-progress/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cli-progress/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cloneable-readable/cloneable-readable-tests.ts b/types/cloneable-readable/cloneable-readable-tests.ts new file mode 100644 index 0000000000..d6cf68f33d --- /dev/null +++ b/types/cloneable-readable/cloneable-readable-tests.ts @@ -0,0 +1,11 @@ +import { PassThrough } from 'stream'; +import cloneable = require('cloneable-readable'); + +const ps = new PassThrough(); // $ExpectType PassThrough +const cl = cloneable(ps); // $ExpectType Cloneable + +process.stdin.pipe(cl.clone()).pipe(process.stderr); +process.stdin.pipe(cl).pipe(process.stdout); + +cloneable.isCloneable(ps); // $ExpectType boolean +cloneable.isCloneable(cl); // $ExpectType boolean diff --git a/types/cloneable-readable/index.d.ts b/types/cloneable-readable/index.d.ts new file mode 100644 index 0000000000..49f7c89ffd --- /dev/null +++ b/types/cloneable-readable/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for cloneable-readable 1.1 +// Project: https://github.com/mcollina/cloneable-readable#readme +// Definitions by: Nikita Volodin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +import { Readable } from 'stream'; + +type Cloneable = T & { clone(): Cloneable }; +interface CloneableFn { + (x: T): Cloneable; + isCloneable(x: Readable): boolean; +} +declare const cloneable: CloneableFn; +export = cloneable; diff --git a/types/cloneable-readable/tsconfig.json b/types/cloneable-readable/tsconfig.json new file mode 100644 index 0000000000..86b9886f7d --- /dev/null +++ b/types/cloneable-readable/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cloneable-readable-tests.ts" + ] +} diff --git a/types/cloneable-readable/tslint.json b/types/cloneable-readable/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cloneable-readable/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/command-line-args/command-line-args-tests.ts b/types/command-line-args/command-line-args-tests.ts index 11848ee202..89d310cb14 100644 --- a/types/command-line-args/command-line-args-tests.ts +++ b/types/command-line-args/command-line-args-tests.ts @@ -1,10 +1,24 @@ import commandLineArgs = require('command-line-args'); -const optionDefinitions = [ - { name: 'verbose', alias: 'v', type: Boolean }, - { name: 'src', type: String, multiple: true, defaultOption: true }, - { name: 'timeout', alias: 't', type: Number } +const optionDefinitions: commandLineArgs.OptionDefinition[] = [ + { + name: 'something', + alias: 's', + type: String, + defaultValue: '1', + multiple: true, + lazyMultiple: true, + defaultOption: true, + group: 'one' + } ]; -const options = commandLineArgs(optionDefinitions); +const options = commandLineArgs(optionDefinitions, { + argv: [ '--one', '1' ], + partial: true, + stopAtFirstUnknown: true, + camelCase: true +}); +const unknown = options._unknown; +const something = options.something; diff --git a/types/command-line-args/index.d.ts b/types/command-line-args/index.d.ts index 332368d827..5172a2f74a 100644 --- a/types/command-line-args/index.d.ts +++ b/types/command-line-args/index.d.ts @@ -1,87 +1,90 @@ -// Type definitions for command-line-args 4.0.7 +// Type definitions for command-line-args 5.0 // Project: https://github.com/75lb/command-line-args -// Definitions by: CzBuCHi +// Definitions by: Lloyd Brookes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /** - * Returns an object containing all options set on the command line. By default it parses the global [`process.argv`](https://nodejs.org/api/process.html#process_process_argv) array. - * - * By default, an exception is thrown if the user sets an unknown option (one without a valid [definition](#exp_module_definition--OptionDefinition)). To enable __partial parsing__, invoke `commandLineArgs` with the `partial` option - all unknown arguments will be returned in the `_unknown` property. - * - * - * @param {module:definition[]} - An array of [OptionDefinition](#exp_module_definition--OptionDefinition) objects - * @param [options] {object} - Options. - * @param [options.argv] {string[]} - An array of strings, which if passed will be parsed instead of `process.argv`. - * @param [options.partial] {boolean} - If `true`, an array of unknown arguments is returned in the `_unknown` property of the output. - * @returns {object} - * @throws `UNKNOWN_OPTION` if `options.partial` is false and the user set an undefined option - * @throws `NAME_MISSING` if an option definition is missing the required `name` property - * @throws `INVALID_TYPE` if an option definition has a `type` value that's not a function - * @throws `INVALID_ALIAS` if an alias is numeric, a hyphen or a length other than 1 - * @throws `DUPLICATE_NAME` if an option definition name was used more than once - * @throws `DUPLICATE_ALIAS` if an option definition alias was used more than once - * @throws `DUPLICATE_DEFAULT_OPTION` if more than one option definition has `defaultOption: true` - * @alias module:command-line-args + * Returns an object containing option values parsed from the command line. By default it parses the global `process.argv` array. + * Parsing is strict by default. To be more permissive, enable `partial` or `stopAtFirstUnknown` modes. */ -declare function commandLineArgs(optionDefinitions: commandLineArgs.OptionDefinition[], options?: commandLineArgs.Options): any; +declare function commandLineArgs(optionDefinitions: commandLineArgs.OptionDefinition[], options?: commandLineArgs.ParseOptions): commandLineArgs.CommandLineOptions; -declare module commandLineArgs { +declare namespace commandLineArgs { + interface CommandLineOptions { + /** + * Command-line arguments not parsed by `commandLineArgs`. + */ + _unknown?: string[]; + [propName: string]: any; + } - export interface OptionDefinition { - /** - * The only required definition property is name, the value of each option will be either a Boolean or string. - */ - name: string, - /** - * The type value is a setter function (you receive the output from this), - * enabling you to be specific about the type and value received. - */ - type?: (arg: string) => any, - /** - * getopt-style short option names. Can be any single character (unicode included) except a digit or hypen. - */ - alias?: string, - /** - * Set this flag if the option takes a list of values. You will receive an array of values, each passed - * through the type function (if specified). - */ - multiple?: boolean, - /** - * Any unclaimed command-line args will be set on this option. This flag is typically set on - * the most commonly-used option to make for more concise usage - * (i.e. $ myapp *.js instead of $ myapp --files *.js). - */ - defaultOption?: boolean, - /** - * An initial value for the option. - */ - defaultValue?: any, - /** - * When your app has a large amount of options it makes sense to organise them in groups. - * There are two automatic groups: _all (contains all options) and _none (contains options - * without a group specified in their definition). - */ - group?: string | string[], - /** - * Describes the option. - */ - description?: string, - /** - * A label for the type, e.g. . - */ - typeLabel?: string; - } + interface ParseOptions { + /** + * An array of strings which if present will be parsed instead of `process.argv`. + */ + argv?: string[]; - export interface Options { - /** - * An array of strings, which if passed will be parsed instead of `process.argv`. - */ - argv?: string[]; - /** - * If `true`, an array of unknown arguments is returned in the `_unknown` property of the output. - */ - partial?: boolean; - } + /** + * If `true`, `commandLineArgs` will not throw on unknown options or values, instead returning them in the `_unknown` property of the output. + */ + partial?: boolean; + + /** + * If `true`, `commandLineArgs` will not throw on unknown options or values. Instead, parsing will stop at the first unknown argument + * and the remaining arguments returned in the `_unknown` property of the output. If set, `partial: true` is implied. + */ + stopAtFirstUnknown?: boolean; + + /** + * If `true`, options with hypenated names (e.g. `move-to`) will be returned in camel-case (e.g. `moveTo`). + */ + camelCase?: boolean; + } + + interface OptionDefinition { + /** + * The long option name. + */ + name: string; + + /** + * A setter function (you receive the output from this) enabling you to be specific about the type and value received. Typical values + * are `String` (the default), `Number` and `Boolean` but you can use a custom function. If no option value was set you will receive `null`. + */ + type?: (input: string) => any; + + /** + * A getopt-style short option name. Can be any single character except a digit or hyphen. + */ + alias?: string; + + /** + * Set this flag if the option accepts multiple values. In the output, you will receive an array of values each passed through the `type` function. + */ + multiple?: boolean; + + /** + * Identical to `multiple` but with greedy parsing disabled. + */ + lazyMultiple?: boolean; + + /** + * Any values unaccounted for by an option definition will be set on the `defaultOption`. This flag is typically set + * on the most commonly-used option to enable more concise usage. + */ + defaultOption?: boolean; + + /** + * An initial value for the option. + */ + defaultValue?: any; + + /** + * One or more group names the option belongs to. + */ + group?: string | string[]; + } } export = commandLineArgs; diff --git a/types/command-line-args/tslint.json b/types/command-line-args/tslint.json index a41bf5d19a..495d29983d 100644 --- a/types/command-line-args/tslint.json +++ b/types/command-line-args/tslint.json @@ -1,79 +1,5 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false } } diff --git a/types/command-line-args/v4/command-line-args-tests.ts b/types/command-line-args/v4/command-line-args-tests.ts new file mode 100644 index 0000000000..c99d64b1a2 --- /dev/null +++ b/types/command-line-args/v4/command-line-args-tests.ts @@ -0,0 +1,21 @@ +import commandLineArgs = require('command-line-args'); + +const optionDefinitions: commandLineArgs.OptionDefinition[] = [ + { + name: 'something', + alias: 's', + type: String, + defaultValue: '1', + multiple: true, + defaultOption: true, + group: 'one' + } +]; + +const options = commandLineArgs(optionDefinitions, { + argv: [ '--one', '1' ], + partial: true +}); + +const unknown = options._unknown; +const something = options.something; diff --git a/types/command-line-args/v4/index.d.ts b/types/command-line-args/v4/index.d.ts new file mode 100644 index 0000000000..a5c8250827 --- /dev/null +++ b/types/command-line-args/v4/index.d.ts @@ -0,0 +1,73 @@ +// Type definitions for command-line-args 4.0 +// Project: https://github.com/75lb/command-line-args +// Definitions by: CzBuCHi , Lloyd Brookes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/** + * Returns an object containing option values parsed from the command line. By default it parses the global `process.argv` array. + */ +declare function commandLineArgs(optionDefinitions: commandLineArgs.OptionDefinition[], options?: commandLineArgs.ParseOptions): commandLineArgs.CommandLineOptions; + +declare namespace commandLineArgs { + interface CommandLineOptions { + /** + * Command-line arguments not parsed by `commandLineArgs`. + */ + _unknown?: string[]; + [propName: string]: any; + } + + interface ParseOptions { + /** + * An array of strings which if present will be parsed instead of `process.argv`. + */ + argv?: string[]; + + /** + * If `true`, `commandLineArgs` will not throw on unknown options or values, instead returning them in the `_unknown` property of the output. + */ + partial?: boolean; + } + + interface OptionDefinition { + /** + * The long option name. + */ + name: string; + + /** + * A setter function (you receive the output from this) enabling you to be specific about the type and value received. Typical values + * are `String` (the default), `Number` and `Boolean` but you can use a custom function. If no option value was set you will receive `null`. + */ + type?: (input: string) => any; + + /** + * A getopt-style short option name. Can be any single character except a digit or hyphen. + */ + alias?: string; + + /** + * Set this flag if the option accepts multiple values. In the output, you will receive an array of values each passed through the `type` function. + */ + multiple?: boolean; + + /** + * Any values unaccounted for by an option definition will be set on the `defaultOption`. This flag is typically set + * on the most commonly-used option to enable more concise usage. + */ + defaultOption?: boolean; + + /** + * An initial value for the option. + */ + defaultValue?: any; + + /** + * One or more group names the option belongs to. + */ + group?: string | string[]; + } +} + +export = commandLineArgs; diff --git a/types/command-line-args/v4/tsconfig.json b/types/command-line-args/v4/tsconfig.json new file mode 100644 index 0000000000..3517f0823e --- /dev/null +++ b/types/command-line-args/v4/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "command-line-args": [ "command-line-args/v4" ] + } + }, + "files": [ + "index.d.ts", + "command-line-args-tests.ts" + ] +} diff --git a/types/command-line-args/v4/tslint.json b/types/command-line-args/v4/tslint.json new file mode 100644 index 0000000000..495d29983d --- /dev/null +++ b/types/command-line-args/v4/tslint.json @@ -0,0 +1,5 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + } +} diff --git a/types/core-js/core-js-tests.ts b/types/core-js/core-js-tests.ts index ab11eab409..476c97348f 100644 --- a/types/core-js/core-js-tests.ts +++ b/types/core-js/core-js-tests.ts @@ -418,7 +418,7 @@ log.disable(); // Non-standard point = dictOfPoint[s]; point = dictOfPoint[i]; -point = dictOfPoint[sym]; +// point = dictOfPoint[sym]; dictOfPoint = new Dict(dictOfPoint); dictOfAny = new Dict(point); dictOfPoint = Dict(dictOfPoint); diff --git a/types/d3-hsv/d3-hsv-tests.ts b/types/d3-hsv/d3-hsv-tests.ts index 0d3e564360..7aa6fb7817 100644 --- a/types/d3-hsv/d3-hsv-tests.ts +++ b/types/d3-hsv/d3-hsv-tests.ts @@ -6,19 +6,23 @@ * are not intended as functional tests. */ -import { hsv, HSVColor } from 'd3-hsv'; -import { rgb, RGBColor } from 'd3-color'; +import { hsv, HSVColor, interpolateHsv, interpolateHsvLong } from 'd3-hsv'; +import { rgb, hcl, RGBColor } from 'd3-color'; -let c: RGBColor; +let cRGB: RGBColor; let cHSV: HSVColor; let displayable: boolean; let cString: string; +let iString: (t: number) => string; +let nil: null; + +// Hsv signature -// hsv signature cHSV = hsv(120, 0.4, 0.5); cHSV = hsv(120, 0.4, 0.5, 0.5); -// specifier signature +// Specifier signature + cHSV = hsv('rgb(255, 255, 255)'); cHSV = hsv('rgb(10%, 20%, 30%)'); cHSV = hsv('rgba(255, 255, 255, 0.4)'); @@ -28,13 +32,16 @@ cHSV = hsv('hsla(120, 50%, 20%, 0.4)'); cHSV = hsv('#ffeeaa'); cHSV = hsv('#fea'); cHSV = hsv('steelblue'); +cHSV = hsv(''); -// color signature -c = rgb('steelblue'); -cHSV = hsv(c); +// Color signature + +cRGB = rgb('steelblue'); +cHSV = hsv(cRGB); cHSV = hsv(cHSV); -// method signatures +// Method signatures + cHSV = cHSV.brighter(); cHSV = cHSV.brighter(0.2); cHSV = cHSV.darker(); @@ -43,3 +50,25 @@ displayable = cHSV.displayable(); cString = cHSV.toString(); console.log('Channels = (h : %d, s: %d, v: %d)', cHSV.h, cHSV.s, cHSV.v); console.log('Opacity = %d', cHSV.opacity); + +// Interpolater + +iString = interpolateHsv('seagreen', 'steelblue'); +iString = interpolateHsv(rgb('seagreen'), hcl('steelblue')); +iString = interpolateHsv(rgb('seagreen'), hsv('steelblue')); + +iString = interpolateHsvLong('seagreen', 'steelblue'); +iString = interpolateHsvLong(rgb('seagreen'), hcl('steelblue')); +iString = interpolateHsvLong(rgb('seagreen'), hsv('steelblue')); + +// Prototype, instanceof and typeguard + +declare let color: RGBColor | HSVColor | null; + +if (color instanceof rgb) { + cRGB = color; +} else if (color instanceof hsv) { + cHSV = color; +} else { + nil = color; +} diff --git a/types/d3-hsv/index.d.ts b/types/d3-hsv/index.d.ts index 6a7a2c8560..1728af0874 100644 --- a/types/d3-hsv/index.d.ts +++ b/types/d3-hsv/index.d.ts @@ -1,28 +1,89 @@ -// Type definitions for D3JS d3-hsv module 0.0 +// Type definitions for D3JS d3-hsv module 0.1 // Project: https://github.com/d3/d3-hsv/ -// Definitions by: Yuri Feldman +// Definitions by: Yuri Feldman , denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 0.0.3 +// Last module patch version validated against: 0.1.0 import { Color, RGBColor, ColorSpaceObject, ColorCommonInstance } from 'd3-color'; export type ColorSpaceObjectWithHSV = ColorSpaceObject | HSVColor; export interface HSVColorFactory extends Function { + /** + * Constructs a new HSV color. + * @param h The hue of the returned color. + * @param s The saturation of the returned color. + * @param v The value of the returned color. + * @param opacity The opacity of the returned color. + */ (h: number, s: number, v: number, opacity?: number): HSVColor; + /** + * Constructs a new HSV color. + * @param cssColorSpecifier A CSS Color Module Level 3 specifier string, + * it is parsed and then converted to the HSV color space. + */ (cssColorSpecifier: string): HSVColor; + /** + * Constructs a new HSV color. + * @param color A color instance, it will be converted to the RGB color space + * using `color.rgb` and then converted to HSV. + */ (color: HSVColor | ColorSpaceObject | ColorCommonInstance): HSVColor; + + readonly prototype: HSVColor; } export interface HSVColor extends Color { + /** + * The color hue. + */ h: number; + /** + * The color saturation. + */ s: number; + /** + * The color value. + */ v: number; + /** + * The color opacity. + */ opacity: number; + + /** + * Returns a brighter copy of this color. + * @param k Controls how much brighter the returned color should be (defaults to 1). + */ brighter(k?: number): this; + + /** + * Returns a darker copy of this color. + * @param k Controls how much darker the returned color should be (defaults to 1). + */ darker(k?: number): this; + + /** + * Returns the RGB equivalent of this color. + */ rgb(): RGBColor; } export const hsv: HSVColorFactory; + +/** + * Returns an HSV color space interpolator between the two colors a and b. + * If either color’s hue or chroma is NaN, the opposing color’s channel value is used. + * The shortest path between hues is used. The return value of the interpolator is an RGB string. + * @param a The starting color; it will be converted to HSV using `d3.hsv`. + * @param b The ending color; it will be converted to HSV using `d3.hsv`. + */ +export function interpolateHsv(a: string | ColorCommonInstance, b: string | ColorCommonInstance): (t: number) => string; + +/** + * Like `interpolateHsv`, but does not use the shortest path between hues. + * @param a The starting color; it will be converted to HSV using `d3.hsv`. + * @param b The ending color; it will be converted to HSV using `d3.hsv`. + */ +export function interpolateHsvLong(a: string | ColorCommonInstance, b: string | ColorCommonInstance): (t: number) => string; diff --git a/types/d3-hsv/tsconfig.json b/types/d3-hsv/tsconfig.json index c92ce346b2..0f7de85da1 100644 --- a/types/d3-hsv/tsconfig.json +++ b/types/d3-hsv/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/d3-polygon/d3-polygon-tests.ts b/types/d3-polygon/d3-polygon-tests.ts index 28e1e464e1..c4aac0b900 100644 --- a/types/d3-polygon/d3-polygon-tests.ts +++ b/types/d3-polygon/d3-polygon-tests.ts @@ -17,7 +17,7 @@ let containsFlag: boolean; let point: [number, number] = [15, 15]; const polygon: Array<[number, number]> = [[10, 10], [20, 20], [10, 30]]; const pointArray: Array<[number, number]> = [[10, 10], [20, 20], [10, 30], [15, 15]]; -let hull: Array<[number, number]>; +let hullOrNothing: Array<[number, number]> | null; // ----------------------------------------------------------------------------- // Tests @@ -27,7 +27,7 @@ num = d3Polygon.polygonArea(polygon); point = d3Polygon.polygonCentroid(polygon); -hull = d3Polygon.polygonHull(pointArray); +hullOrNothing = d3Polygon.polygonHull(pointArray); containsFlag = d3Polygon.polygonContains(polygon, point); diff --git a/types/d3-polygon/index.d.ts b/types/d3-polygon/index.d.ts index 64e1d2c9b9..b9f8711335 100644 --- a/types/d3-polygon/index.d.ts +++ b/types/d3-polygon/index.d.ts @@ -3,11 +3,11 @@ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.0.1 +// Last module patch version validated against: 1.0.3 /** - * Returns the signed area of the specified polygon. If the vertices of the polygon are in counterclockwise order ( - * assuming a coordinate system where the origin ⟨0,0⟩ is in the top-left corner), the returned area is positive; + * Returns the signed area of the specified polygon. If the vertices of the polygon are in counterclockwise order + * (assuming a coordinate system where the origin <0,0> is in the top-left corner), the returned area is positive; * otherwise it is negative, or zero. * * @param polygon Array of coordinates , and so on. @@ -34,7 +34,7 @@ export function polygonHull(points: Array<[number, number]>): Array<[number, num * Returns true if and only if the specified point is inside the specified polygon. * * @param polygon Array of coordinates , and so on. - * @param point Coordinates of point + * @param point Coordinates of point . */ export function polygonContains(polygon: Array<[number, number]>, point: [number, number]): boolean; diff --git a/types/d3-polygon/tsconfig.json b/types/d3-polygon/tsconfig.json index 79bd8a43b8..1444a903df 100644 --- a/types/d3-polygon/tsconfig.json +++ b/types/d3-polygon/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/d3-polygon/tslint.json b/types/d3-polygon/tslint.json index 604d5950cf..f93cf8562a 100644 --- a/types/d3-polygon/tslint.json +++ b/types/d3-polygon/tslint.json @@ -1,7 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "unified-signatures": false, - "callable-types": false - } + "extends": "dtslint/dt.json" } diff --git a/types/daterangepicker/daterangepicker-tests.ts b/types/daterangepicker/daterangepicker-tests.ts index db79671721..2f8ab867e4 100644 --- a/types/daterangepicker/daterangepicker-tests.ts +++ b/types/daterangepicker/daterangepicker-tests.ts @@ -1,80 +1,116 @@ -import moment = require("moment") -import daterangepicker = require("daterangepicker"); +import moment = require('moment'); +import daterangepicker = require('daterangepicker'); function tests_simple() { $('#daterange').daterangepicker(); - $('input[name="daterange"]').daterangepicker({ - timePicker: true, - timePickerIncrement: 30, - locale: { - format: 'MM/DD/YYYY h:mm A' - } - }); + $('input[name="daterange"]') + .daterangepicker({ + timePicker: true, + timePickerIncrement: 30, + locale: { + format: 'MM/DD/YYYY h:mm A' + }, + maxSpan: { days: 10 }, + applyButtonClasses: 'my-apply-class', + cancelButtonClasses: 'my-cancel-class', + showDropdowns: true, + maxYear: 3000, + minYear: 2000 + }) + .data('daterangepicker') + .remove(); $('#reportrange').daterangepicker({ ranges: { - 'Today': [moment(), moment()], - 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + Today: [moment(), moment()], + Yesterday: [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], - 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] + 'Last Month': [ + moment() + .subtract(1, 'month') + .startOf('month'), + moment() + .subtract(1, 'month') + .endOf('month') + ] } }); - $('input[name="datefilter"]').on('apply.daterangepicker', function (ev, picker) { - $(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY')); + $('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) { + $(this).val( + `${picker.startDate.format('MM/DD/YYYY')} - ${picker.endDate.format('MM/DD/YYYY')}` + ); }); - - $('input[name="datefilter"]').on('cancel.daterangepicker', function (ev, picker) { + $('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) { $(this).val(''); }); - $('#demo').daterangepicker({ - "startDate": "05/06/2016", - "endDate": "05/12/2016" - }, function (start: moment.Moment, end: moment.Moment, label: string) { - console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')"); - }); - - $(function() { - - function cb(start: moment.Moment, end: moment.Moment) { - $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); - } - cb(moment().subtract(29, 'days'), moment()); - - $('#reportrange').daterangepicker({ - ranges: { - 'Today': [moment(), moment()], - 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], - 'Last 7 Days': [moment().subtract(6, 'days'), moment()], - 'Last 30 Days': [moment().subtract(29, 'days'), moment()], - 'This Month': [moment().startOf('month'), moment().endOf('month')], - 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] - } - }, cb); - - $('#reportrange').daterangepicker({ - ranges: { - 'Today': [moment(), moment()], - 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], - 'Last 7 Days': [moment().subtract(6, 'days'), moment()], - 'Last 30 Days': [moment().subtract(29, 'days'), moment()] + $('#demo').daterangepicker( + { + startDate: '05/06/2016', + endDate: '05/12/2016' }, - showCustomRangeLabel: false - }, cb); + (start: moment.Moment, end: moment.Moment, label: string) => { + console.log( + "New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')" + ); + } + ); - $('#endDate').daterangepicker({ - singleDatePicker: true, - startDate: moment() + $(() => { + function cb(start: moment.Moment, end: moment.Moment) { + $('#reportrange span').html( + `${start.format('MMMM D, YYYY')} - ${end.format('MMMM D, YYYY')}` + ); + } + cb(moment().subtract(29, 'days'), moment()); + + $('#reportrange').daterangepicker( + { + ranges: { + Today: [moment(), moment()], + Yesterday: [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + 'Last 7 Days': [moment().subtract(6, 'days'), moment()], + 'Last 30 Days': [moment().subtract(29, 'days'), moment()], + 'This Month': [moment().startOf('month'), moment().endOf('month')], + 'Last Month': [ + moment() + .subtract(1, 'month') + .startOf('month'), + moment() + .subtract(1, 'month') + .endOf('month') + ] + } + }, + cb + ); + + $('#reportrange').daterangepicker( + { + ranges: { + Today: [moment(), moment()], + Yesterday: [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + 'Last 7 Days': [moment().subtract(6, 'days'), moment()], + 'Last 30 Days': [moment().subtract(29, 'days'), moment()] + }, + showCustomRangeLabel: false + }, + cb + ); + + $('#endDate').daterangepicker({ + singleDatePicker: true, + startDate: moment() + }); }); -}); } declare const host: HTMLElement; function test_from_amd() { - var picker = new daterangepicker(host); - console.log(picker.startDate.format("YYYY-MM-DD")); + const picker = new daterangepicker(host); + console.log(picker.startDate.format('YYYY-MM-DD')); } diff --git a/types/daterangepicker/index.d.ts b/types/daterangepicker/index.d.ts index 5a82950ca9..9267a801b2 100644 --- a/types/daterangepicker/index.d.ts +++ b/types/daterangepicker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Date Range Picker v2.1.30 +// Type definitions for Date Range Picker 3.0 // Project: http://www.daterangepicker.com/ // Definitions by: SirMartin // Steven Masala @@ -7,62 +7,81 @@ // TypeScript Version: 2.3 /// -import moment = require("moment"); +import moment = require('moment'); declare global { interface JQuery { - daterangepicker(settings?: daterangepicker.Settings): JQuery; - daterangepicker(settings?: daterangepicker.Settings, callback?: daterangepicker.DataRangePickerCallback): JQuery; + daterangepicker: (( + options?: daterangepicker.Options, + callback?: daterangepicker.DataRangePickerCallback + ) => JQuery) & { defaultOptions?: daterangepicker.Options }; + data(key: 'daterangepicker'): daterangepicker | undefined; } } -declare const daterangepicker: daterangepicker.DateRangePicker; +declare class daterangepicker { + constructor( + element: HTMLElement, + options?: daterangepicker.Options, + callback?: daterangepicker.DataRangePickerCallback + ); + + startDate: moment.Moment; + endDate: moment.Moment; + container: JQuery; + + setStartDate(date: daterangepicker.DateOrString): void; + setEndDate(date: daterangepicker.DateOrString): void; + remove(): void; +} declare namespace daterangepicker { - type DataRangePickerCallback = (start: moment.Moment, end: moment.Moment, label: string | null) => any; + type DataRangePickerCallback = ( + start: moment.Moment, + end: moment.Moment, + label: string | null + ) => void; - interface DateRangePicker { - new (element: HTMLElement, settings?: daterangepicker.Settings, callback?: DataRangePickerCallback): DateRangePicker; - - startDate: moment.Moment; - endDate: moment.Moment; - container: JQuery; - - setStartDate(date: Date | moment.Moment | string): void; - setEndDate(date: Date | moment.Moment | string): void; - remove(): void; - } + type DateOrString = string | moment.Moment | Date; interface DatepickerEventObject extends JQueryEventObject { date: Date; format(format?: string): string; } - interface Settings { + interface Options { /** * The start of the initially selected date range */ - startDate?: string | moment.Moment | Date; + startDate?: DateOrString; /** * The end of the initially selected date range */ - endDate?: string | moment.Moment | Date; + endDate?: DateOrString; /** - * The earliest date a user may select + * The earliest date a user may select */ - minDate?: string | moment.Moment | Date; + minDate?: DateOrString; /** * The latest date a user may select */ - maxDate?: string | moment.Moment | Date; + maxDate?: DateOrString; /** * The maximum span between the selected start and end dates. Can have any property you can add to a moment object (i.e. days, months) */ - dateLimit?: any; + maxSpan?: moment.MomentInput | moment.Duration; /** * Show year and month select boxes above calendars to jump to a specific month and year */ showDropdowns?: boolean; + /** + * The minimum year shown in the dropdowns when `showDropdowns` is set to true. + */ + minYear?: number; + /** + * The maximum year shown in the dropdowns when `showDropdowns` is set to true. + */ + maxYear?: number; /** * Show localized week numbers at the start of each week on the calendars */ @@ -90,15 +109,25 @@ declare namespace daterangepicker { /** * Set predefined date ranges the user can select from.Each key is the label for the range, and its value an array with two dates representing the bounds of the range. */ - ranges?: any; + ranges?: { [name: string]: [DateOrString, DateOrString] }; /** - * (string: 'left'/'right'/'center') Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to + * Whether to show the 'Custom Range' label or just pre-defined ranges */ - opens?: string; + showCustomRangeLabel?: boolean; /** - * (string: 'down' or 'up') Whether the picker appears below (default) or above the HTML element it's attached to + * Normally, if you use the `ranges` option to specify pre-defined date ranges, calendars + * for choosing a custom date range are not shown until the user clicks "Custom Range". + * When this option is set to true, the calendars for choosing a custom date range are always shown instead. */ - drops?: string; + alwaysShowCalendars?: boolean; + /** + * Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to + */ + opens?: 'left' | 'right' | 'center'; + /** + * Whether the picker appears below (default) or above the HTML element it's attached to + */ + drops?: 'down' | 'up'; /** * CSS class names that will be added to all buttons in the picker */ @@ -106,11 +135,11 @@ declare namespace daterangepicker { /** * CSS class string that will be added to the apply button */ - applyClass?: string; + applyButtonClasses?: string; /** - * CSS class string that will be added to the cancel button - */ - cancelClass?: string; + * CSS class string that will be added to the cancel button + */ + cancelButtonClasses?: string; /** * Allows you to provide localized strings for buttons and labels, customize the date display format, and change the first day of week for the calendars. */ @@ -124,33 +153,28 @@ declare namespace daterangepicker { */ autoApply?: boolean; /** - * When enabled, the two calendars displayed will always be for two sequential months (i.e.January and February), and both will be advanced when clicking the left or right arrows above the calendars.When disabled, the two calendars can be individually advanced and display any month/ year. + * When enabled, the two calendars displayed will always be for two sequential months (i.e. + * January and February), and both will be advanced when clicking the left or right arrows + * above the calendars.When disabled, the two calendars can be individually advanced and + * display any month/ year. */ linkedCalendars?: boolean; - /** - * jQuery selector of the parent element that the date range picker will be added to, if not provided this will be 'body' - */ - parentEl?: string; /** * A function that is passed each date in the two calendars before they are displayed, and may return true or false to indicate whether that date should be available for selection or not. */ - isInvalidDate?(startDate: string | moment.Moment | Date, endDate?: string | moment.Moment | Date): boolean; + isInvalidDate?(startDate: DateOrString, endDate?: DateOrString): boolean; /** * A function that is passed each date in the two calendars before they are displayed, and may return a string or array of CSS class names to apply to that date's calendar cell. */ - isCustomDate?(date: string | moment.Moment | Date): string | string[] | undefined; + isCustomDate?(date: DateOrString): string | string[] | undefined; /** * Indicates whether the date range picker should automatically update the value of an < input > element it's attached to at initialization and when the selected dates change. */ autoUpdateInput?: boolean; /** - * Normally, if you use the ranges option to specify pre- defined date ranges, calendars for choosing a custom date range are not shown until the user clicks "Custom Range".When this option is set to true, the calendars for choosing a custom date range are always shown instead. - */ - alwaysShowCalendars?: boolean; - /** - * Whether to show the 'Custom Range' label or just pre-defined ranges - */ - showCustomRangeLabel?: boolean; + * jQuery selector of the parent element that the date range picker will be added to, if not provided this will be 'body' + */ + parentEl?: string; } interface Locale { diff --git a/types/daterangepicker/tslint.json b/types/daterangepicker/tslint.json index a41bf5d19a..3db14f85ea 100644 --- a/types/daterangepicker/tslint.json +++ b/types/daterangepicker/tslint.json @@ -1,79 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/deline/deline-tests.ts b/types/deline/deline-tests.ts new file mode 100644 index 0000000000..35f1696484 --- /dev/null +++ b/types/deline/deline-tests.ts @@ -0,0 +1,13 @@ +import * as dl from "deline"; + +const moduleName = "deline"; + +dl.deline(`deline`); // $ExpectType string +dl.deline(`module name: ${moduleName}`); // $ExpectType string +dl.deline`deline`; // $ExpectType string +dl.deline`tagged template: ${moduleName}`; // $ExpectType string +dl.deline` +tagged template: + +${moduleName} +`; diff --git a/types/deline/index.d.ts b/types/deline/index.d.ts new file mode 100644 index 0000000000..b65cd80d5e --- /dev/null +++ b/types/deline/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for deline 1.0 +// Project: https://github.com/airbnb/deline#readme +// Definitions by: Inaki Arroyo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function deline(strings: string | TemplateStringsArray, ...values: any[]): string; diff --git a/types/ids/tsconfig.json b/types/deline/tsconfig.json similarity index 87% rename from types/ids/tsconfig.json rename to types/deline/tsconfig.json index 1c739774db..ae8ad2e876 100644 --- a/types/ids/tsconfig.json +++ b/types/deline/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "ids-tests.ts" + "deline-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/deline/tslint.json b/types/deline/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/deline/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dom-to-image/index.d.ts b/types/dom-to-image/index.d.ts new file mode 100644 index 0000000000..b6e186f53b --- /dev/null +++ b/types/dom-to-image/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for dom-to-image 2.6 +// Project: https://github.com/tsayen/dom-to-image +// Definitions by: Jip Sterk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +export interface DomToImage { + toSvg(node: Node, options?: Options): Promise; + toPng(node: Node, options?: Options): Promise; + toJpeg(node: Node, options?: Options): Promise; + toBlob(node: Node, options?: Options): Promise; + toPixelData(node: Node, options?: Options): Promise; +} + +export interface Options { + filter?: (node: Node) => boolean; + bgcolor?: string; + width?: number; + height?: number; + style?: {}; + quality?: number; + imagePlaceholder?: string; + cachebust?: boolean; +} + +export const DomToImage: DomToImage; + +type DomToImage_ = DomToImage; +type Options_ = Options; + +export default DomToImage; + +declare global { + namespace DomToImage { + type Options = Options_; + type DomToImage = DomToImage_; + } + + const DomToImage: DomToImage.DomToImage; +} diff --git a/types/dom-to-image/test/dom-to-image-global-tests.ts b/types/dom-to-image/test/dom-to-image-global-tests.ts new file mode 100644 index 0000000000..a21be8bd01 --- /dev/null +++ b/types/dom-to-image/test/dom-to-image-global-tests.ts @@ -0,0 +1,38 @@ +const node = new Node(); + +const options: DomToImage.Options = { + filter, + bgcolor: '#24292e', + style: { + width: '100px' + }, + width: 100, + height: 100, + quality: 0.1, + imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAIAAAP', + cachebust: true +}; + +function filter(node: Node): boolean { + return true; +} + +async function testToSvg() { + const svg = await DomToImage.toSvg(node, { filter }); +} + +async function testToPng() { + const png = await DomToImage.toPng(node, { bgcolor: '#24292e', style: { width: '100px' } }); +} + +async function testToJpeg() { + const jpeg = await DomToImage.toJpeg(node, { width: 100, height: 100 }); +} + +async function testToBlob() { + const blob = await DomToImage.toBlob(node, { quality: 0.1, }); +} + +async function testToPixelData() { + const pixelData = await DomToImage.toPixelData(node, { imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAIAAAP', cachebust: true }); +} diff --git a/types/dom-to-image/test/dom-to-image-import-default-tests.ts b/types/dom-to-image/test/dom-to-image-import-default-tests.ts new file mode 100644 index 0000000000..0f300ffa38 --- /dev/null +++ b/types/dom-to-image/test/dom-to-image-import-default-tests.ts @@ -0,0 +1,40 @@ +import domToImage, { Options } from 'dom-to-image'; + +const node = new Node(); + +const options: Options = { + filter, + bgcolor: '#24292e', + style: { + width: '100px' + }, + width: 100, + height: 100, + quality: 0.1, + imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAIAAAP', + cachebust: true +}; + +function filter(node: Node): boolean { + return true; +} + +async function testToSvg() { + const svg = await domToImage.toSvg(node, { filter }); +} + +async function testToPng() { + const png = await domToImage.toPng(node, { bgcolor: '#24292e', style: { width: '100px' } }); +} + +async function testToJpeg() { + const jpeg = await domToImage.toJpeg(node, { width: 100, height: 100 }); +} + +async function testToBlob() { + const blob = await domToImage.toBlob(node, { quality: 0.1, }); +} + +async function testToPixelData() { + const pixelData = await domToImage.toPixelData(node, { imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAIAAAP', cachebust: true }); +} diff --git a/types/dom-to-image/test/dom-to-image-module-tests.ts b/types/dom-to-image/test/dom-to-image-module-tests.ts new file mode 100644 index 0000000000..571a28f5b6 --- /dev/null +++ b/types/dom-to-image/test/dom-to-image-module-tests.ts @@ -0,0 +1,40 @@ +import { Options, DomToImage } from 'dom-to-image'; + +const node = new Node(); + +const options: Options = { + filter, + bgcolor: '#24292e', + style: { + width: '100px' + }, + width: 100, + height: 100, + quality: 0.1, + imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAIAAAP', + cachebust: true +}; + +function filter(node: Node): boolean { + return true; +} + +async function testToSvg() { + const svg = await DomToImage.toSvg(node, { filter }); +} + +async function testToPng() { + const png = await DomToImage.toPng(node, { bgcolor: '#24292e', style: { width: '100px' } }); +} + +async function testToJpeg() { + const jpeg = await DomToImage.toJpeg(node, { width: 100, height: 100 }); +} + +async function testToBlob() { + const blob = await DomToImage.toBlob(node, { quality: 0.1, }); +} + +async function testToPixelData() { + const pixelData = await DomToImage.toPixelData(node, { imagePlaceholder: 'data:image/gif;base64,R0lGODlhAQABAIAAAP', cachebust: true }); +} diff --git a/types/dom-to-image/tsconfig.json b/types/dom-to-image/tsconfig.json new file mode 100644 index 0000000000..10fc769913 --- /dev/null +++ b/types/dom-to-image/tsconfig.json @@ -0,0 +1,27 @@ + +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "test/dom-to-image-module-tests.ts", + "test/dom-to-image-global-tests.ts", + "test/dom-to-image-import-default-tests.ts" + ] +} \ No newline at end of file diff --git a/types/dom-to-image/tslint.json b/types/dom-to-image/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/dom-to-image/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index e83de2b303..4064c9b8a0 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -610,6 +610,7 @@ declare namespace Draft { import DraftBlockType = Draft.Model.Constants.DraftBlockType; import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; import DraftEntityType = Draft.Model.Constants.DraftEntityType; + import DraftEntityInstance = Draft.Model.Entity.DraftEntityInstance; import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; @@ -754,6 +755,8 @@ declare namespace Draft { getEntity(key: string): EntityInstance; getLastCreatedEntityKey(): string; mergeEntityData(key: string, toMerge: { [key: string]: any }): ContentState; + replaceEntityData(key: string, toMerge: { [key: string]: any }): ContentState; + addEntity(instance: DraftEntityInstance): ContentState; getBlockMap(): BlockMap; diff --git a/types/ember-data/index.d.ts b/types/ember-data/index.d.ts index a5918f9375..b891bbe1d1 100644 --- a/types/ember-data/index.d.ts +++ b/types/ember-data/index.d.ts @@ -52,25 +52,27 @@ declare module 'ember-data' { * Convert an array of errors in JSON-API format into an object. */ function errorsArrayToHash(errors: any[]): {}; + + interface RelationshipOptions { + async?: boolean; + inverse?: RelationshipsFor | null; + polymorphic?: boolean; + } + + interface Sync { async: false; } + interface Async { async?: true; } + /** * `DS.belongsTo` is used to define One-To-One and One-To-Many * relationships on a [DS.Model](/api/data/classes/DS.Model.html). */ function belongsTo( modelName: K, - options: { - async: false; - inverse?: string | null; - polymorphic?: boolean; - } + options: RelationshipOptions & Sync ): Ember.ComputedProperty; function belongsTo( modelName: K, - options?: { - async?: true; - inverse?: string | null; - polymorphic?: boolean; - } + options?: RelationshipOptions & Async ): Ember.ComputedProperty, ModelRegistry[K]>; /** * `DS.hasMany` is used to define One-To-Many and Many-To-Many @@ -78,19 +80,11 @@ declare module 'ember-data' { */ function hasMany( type: K, - options: { - async: false; - inverse?: string | null; - polymorphic?: boolean; - } + options: RelationshipOptions & Sync ): Ember.ComputedProperty>; function hasMany( type: K, - options?: { - async?: true; - inverse?: string | null; - polymorphic?: boolean; - } + options?: RelationshipOptions & Async ): Ember.ComputedProperty, Ember.Array>; /** * This method normalizes a modelName into the format Ember Data uses @@ -101,6 +95,7 @@ declare module 'ember-data' { interface AttrOptions { defaultValue?: T | (() => T); + allowNull?: boolean; // TODO: restrict to boolean transform (TS 2.8) } /** diff --git a/types/ember-data/test/model.ts b/types/ember-data/test/model.ts index 63bda2588e..2085daf90a 100644 --- a/types/ember-data/test/model.ts +++ b/types/ember-data/test/model.ts @@ -17,6 +17,7 @@ const User = DS.Model.extend({ username: DS.attr('string'), email: DS.attr('string'), verified: DS.attr('boolean', { defaultValue: false }), + canBeNull: DS.attr('boolean', { allowNull: true }), createdAt: DS.attr('date', { defaultValue() { return new Date(); } }) diff --git a/types/es6-shim/es6-shim-tests.ts b/types/es6-shim/es6-shim-tests.ts index 87f6fba0e5..7d7fdc6db2 100644 --- a/types/es6-shim/es6-shim-tests.ts +++ b/types/es6-shim/es6-shim-tests.ts @@ -17,7 +17,7 @@ let r: RegExp = /a/; let sym: symbol = {} as symbol; let e: Error = new Error(); let date: Date; -let key: PropertyKey; +let key: KeyOfProperty; let point: Point = { x: 1, y: 2 }; let point3d: Point3D = { x: 1, y: 2, z: 3 }; let point3dOrUndef: Point3D | undefined; @@ -25,7 +25,7 @@ let pointOrUndef: Point | undefined; let arrayOfPoint: Point[] = []; let arrayOfPoint3D: Point3D[]; let arrayOfSymbol: symbol[]; -let arrayOfPropertyKey: PropertyKey[]; +let arrayOfPropertyKey: KeyOfProperty[]; let arrayOfAny: any[]; let arrayOfStringAny: [string, any][]; let arrayLikeOfAny: ArrayLike = []; @@ -40,8 +40,8 @@ let iterableIteratorOfPointPoint: IterableIteratorShim<[Point, Point]>; let iterableIteratorOfNode: IterableIteratorShim; let iterableIteratorOfStringPoint: IterableIteratorShim<[string, Point]>; let iterableIteratorOfAny: IterableIteratorShim; -let iterableIteratorOfPropertyKey: IterableIteratorShim; -let iterableIteratorOfPropertyKeyPoint: IterableIteratorShim<[PropertyKey, Point]>; +let iterableIteratorOfPropertyKey: IterableIteratorShim; +let iterableIteratorOfPropertyKeyPoint: IterableIteratorShim<[KeyOfProperty, Point]>; let nodeList: NodeList; let pd: PropertyDescriptor = {}; let pdm: PropertyDescriptorMap = {}; diff --git a/types/es6-shim/index.d.ts b/types/es6-shim/index.d.ts index 2cf61a9362..e2c1a01f3d 100644 --- a/types/es6-shim/index.d.ts +++ b/types/es6-shim/index.d.ts @@ -4,7 +4,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -declare type PropertyKey = string | number | symbol; +// TODO: As of TypeScript@2.9 there is a global type PropertyKey that should be used instead of this. +declare type KeyOfProperty = string | number | symbol; interface IteratorResult { done: boolean; @@ -625,17 +626,17 @@ declare var WeakSet: WeakSetConstructor; declare namespace Reflect { function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; function construct(target: Function, argumentsList: ArrayLike): any; - function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; - function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function defineProperty(target: any, propertyKey: KeyOfProperty, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: KeyOfProperty): boolean; function enumerate(target: any): IterableIteratorShim; - function get(target: any, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function get(target: any, propertyKey: KeyOfProperty, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: KeyOfProperty): PropertyDescriptor; function getPrototypeOf(target: any): any; - function has(target: any, propertyKey: PropertyKey): boolean; + function has(target: any, propertyKey: KeyOfProperty): boolean; function isExtensible(target: any): boolean; - function ownKeys(target: any): Array; + function ownKeys(target: any): Array; function preventExtensions(target: any): boolean; - function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function set(target: any, propertyKey: KeyOfProperty, value: any, receiver?: any): boolean; function setPrototypeOf(target: any, proto: any): boolean; } @@ -653,17 +654,17 @@ declare module "es6-shim" { namespace Reflect { function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; function construct(target: Function, argumentsList: ArrayLike): any; - function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; - function deleteProperty(target: any, propertyKey: PropertyKey): boolean; + function defineProperty(target: any, propertyKey: KeyOfProperty, attributes: PropertyDescriptor): boolean; + function deleteProperty(target: any, propertyKey: KeyOfProperty): boolean; function enumerate(target: any): Iterator; - function get(target: any, propertyKey: PropertyKey, receiver?: any): any; - function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor; + function get(target: any, propertyKey: KeyOfProperty, receiver?: any): any; + function getOwnPropertyDescriptor(target: any, propertyKey: KeyOfProperty): PropertyDescriptor; function getPrototypeOf(target: any): any; - function has(target: any, propertyKey: PropertyKey): boolean; + function has(target: any, propertyKey: KeyOfProperty): boolean; function isExtensible(target: any): boolean; - function ownKeys(target: any): Array; + function ownKeys(target: any): Array; function preventExtensions(target: any): boolean; - function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + function set(target: any, propertyKey: KeyOfProperty, value: any, receiver?: any): boolean; function setPrototypeOf(target: any, proto: any): boolean; } } diff --git a/types/eslint/eslint-tests.ts b/types/eslint/eslint-tests.ts index a281991918..6a81d69c8a 100644 --- a/types/eslint/eslint-tests.ts +++ b/types/eslint/eslint-tests.ts @@ -336,6 +336,7 @@ rule = { onCodePathSegmentStart(segment, node) {}, onCodePathSegmentEnd(segment, node) {}, onCodePathSegmentLoop(fromSegment, toSegment, node) {}, + IfStatement(node) {}, 'Program:exit'() {}, }; }, diff --git a/types/eslint/index.d.ts b/types/eslint/index.d.ts index 76f04617d8..89067f97c8 100644 --- a/types/eslint/index.d.ts +++ b/types/eslint/index.d.ts @@ -241,7 +241,10 @@ export namespace Rule { meta?: RuleMetaData; } - interface RuleListener { + type NodeTypes = ESTree.Node['type']; + type NodeListener = { [T in NodeTypes]?: (node: ESTree.Node) => void }; + + interface RuleListener extends NodeListener { onCodePathStart?(codePath: CodePath, node: ESTree.Node): void; onCodePathEnd?(codePath: CodePath, node: ESTree.Node): void; diff --git a/types/evaporate/evaporate-tests.ts b/types/evaporate/evaporate-tests.ts index ea4a4ac9bf..3140cd9ea9 100644 --- a/types/evaporate/evaporate-tests.ts +++ b/types/evaporate/evaporate-tests.ts @@ -1,7 +1,27 @@ -import Evaporate = require("evaporate"); +import Evaporate = require('evaporate'); -function test_upload() { - var evaporate = new Evaporate({}); - var uploadId = evaporate.add({}); - evaporate.cancel(uploadId); -} +const newEvaporate = new Evaporate({ + bucket: 'abc', +}); + +Evaporate.create({ + bucket: 'abc', +}) + .then((evaporate) => { + evaporate.add({ + name: 'gwejlf', + file: new File(['abcd'], 'efg'), + started: (file_key) => { + evaporate.pause(file_key); + }, + paused: (file_key) => { + evaporate.resume(file_key); + }, + resumed: (file_key) => { + evaporate.cancel(file_key); + } + }) + .then((awsS3ObjectKey) => { + console.log(awsS3ObjectKey + '!!!'); + }); + }); diff --git a/types/evaporate/index.d.ts b/types/evaporate/index.d.ts index bf4b52aae3..1c415769b8 100644 --- a/types/evaporate/index.d.ts +++ b/types/evaporate/index.d.ts @@ -1,12 +1,112 @@ -// Type definitions for EvaporateJS +// Type definitions for EvaporateJS 2.1 // Project: https://github.com/TTLabs/EvaporateJS -// Definitions by: Andrew Kuklewicz , Chris Rhoden +// Definitions by: Andrew Kuklewicz +// Chris Rhoden +// Junyoung Clare Jang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 export = Evaporate; declare class Evaporate { - cancel(id:string): boolean; - constructor(config:any); - add(config:any): string; + constructor(config: Evaporate.CreateConfig); + supported: boolean; + add(config: Evaporate.AddConfig, options?: Evaporate.AddOverrideOptions): Promise; + pause(file_key?: string, options?: object): Promise; + resume(file_key?: string): Promise; + cancel(file_key?: string): Promise; +} + +declare namespace Evaporate { + function create(config: CreateConfig): Promise; + + interface CreateConfig { + readableStreams?: boolean; + readableStreamPartMethod?: null | ((file: File, start: number, end: number) => ReadableStream); + bucket: string; + logging?: boolean; + maxConcurrentParts?: number; + partSize?: number; + retryBackoffPower?: number; + maxRetryBackoffSecs?: number; + progressIntervalMS?: number; + cloudfront?: boolean; + s3Acceleration?: boolean; + mockLocalStorage?: boolean; + encodeFilename?: boolean; + computeContentMd5?: false; + allowS3ExistenceOptimization?: boolean; + onlyRetryForSameFileName?: boolean; + timeUrl?: string; + cryptoMd5Method?: null | ((data: ArrayBuffer) => string); + cryptoHexEncodedHash256?: null | ((data: ArrayBuffer) => string); + aws_url?: string; + aws_key?: string; + awsRegion?: string; + awsSignatureVersion?: '2' | '4'; + signerUrl?: string; + sendCanonicalRequestToSignerUrl?: boolean; + s3FileCacheHoursAgo?: null | number; + signParams?: object; + signHeaders?: object; + customAuthMethod?: null | (( + signParams: string, + signHeaders: string, + stringToSign: () => string | undefined, + signatureDateTime: string, + canonicalRequest: string + ) => Promise); + maxFileSize?: number; + signResponseHandler?: null | ((response: any, stringToSign: string, signatureDateTime: string) => Promise); + xhrWithCredentials?: boolean; + localTimeOffset?: number; + evaporateChanged?: (evaporate: Evaporate, evaporatingCount: number) => void; + abortCompletionThrottlingMs?: number; + } + + interface TransferStats { + speed: number; + readableSpeed: string; + loaded: number; + totalUploaded: number; + remainingSize: number; + secondsLeft: number; + fileSize: number; + } + + interface AddConfig { + name: string; + file: File; + xAmzHeadersAtInitiate?: { [key: string]: string }; + notSignedHeadersAtInitiate?: { [key: string]: string }; + xAmzHeadersAtUpload?: { [key: string]: string }; + xAmzHeadersAtComplete?: { [key: string]: string }; + xAmzHeadersCommon?: { [key: string]: string }; + started?: (file_key: string) => void; + uploadInitiated?: (s3UploadId?: string) => void; + paused?: (file_key: string) => void; + resumed?: (file_key: string) => void; + pausing?: (file_key: string) => void; + cancelled?: () => void; + complete?: (xhr: XMLHttpRequest, awsObjectKey: string, stats: TransferStats) => void; + nameChanged?: (awsObjectKey: string) => void; + info?: (msg: string) => void; + warn?: (msg: string) => void; + error?: (msg: string) => void; + progress?: (p: number, stats: TransferStats) => void; + contentType?: string; + beforeSigner?: (xhr: XMLHttpRequest, url: string) => void; + } + + type ImmutableOptionKeys = + | 'maxConcurrentParts' | 'logging' | 'cloudfront' | 'encodeFilename' + | 'computeContentMd5' | 'allowS3ExistenceOptimization' | 'onlyRetryForSameFileName' + | 'timeUrl' | 'cryptoMd5Method' | 'cryptoHexEncodedHash256' | 'awsRegion' | 'awsSignatureVersion' + | 'evaporateChanged'; + type AddOverrideOptionKeys = Exclude; + interface AddOverrideOptions extends Pick {} + + interface PauseConfig { + force?: boolean; + } } diff --git a/types/evaporate/tsconfig.json b/types/evaporate/tsconfig.json index 9164730455..c932b3ca2f 100644 --- a/types/evaporate/tsconfig.json +++ b/types/evaporate/tsconfig.json @@ -1,23 +1,24 @@ { "compilerOptions": { - "module": "commonjs", + "baseUrl": "../", + "forceConsistentCasingInFileNames": true, "lib": [ - "es6" + "es6", + "dom" ], + "module": "commonjs", + "noEmit": true, "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, - "baseUrl": "../", "typeRoots": [ "../" ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true + "types": [] }, "files": [ "index.d.ts", "evaporate-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/evaporate/tslint.json b/types/evaporate/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/evaporate/tslint.json +++ b/types/evaporate/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/event-stream/index.d.ts b/types/event-stream/index.d.ts index f7b10b34a2..35fb2c8b4c 100644 --- a/types/event-stream/index.d.ts +++ b/types/event-stream/index.d.ts @@ -36,7 +36,7 @@ export declare function mapSync(syncFunction: Function): MapStream; * * @param matcher */ -export declare function split(matcher: string | RegExp): MapStream; +export declare function split(matcher?: string | RegExp): MapStream; /** * Create a through stream that emits separator between each chunk, just like Array#join diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 5df51127da..fd0d7ad973 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -36,7 +36,8 @@ import { SQLite, Calendar, MailComposer, - Location + Location, + Updates } from 'expo'; const reverseGeocode: Promise = Location.reverseGeocodeAsync({ @@ -600,6 +601,8 @@ Permissions.CONTACTS === 'contacts'; Permissions.NOTIFICATIONS === 'remoteNotifications'; Permissions.REMOTE_NOTIFICATIONS === 'remoteNotifications'; Permissions.SYSTEM_BRIGHTNESS === 'systemBrightness'; +Permissions.USER_FACING_NOTIFICATIONS === 'userFacingNotifications'; +Permissions.REMINDERS === 'reminders'; async () => { const result = await Permissions.askAsync(Permissions.CAMERA); @@ -742,3 +745,36 @@ async () => { result.status === 'saved'; }; + +async () => { + const updateEventListener: Updates.UpdateEventListener = ({ type, manifest, message }) => { + switch (type) { + case Updates.EventType.DOWNLOAD_STARTED: + case Updates.EventType.DOWNLOAD_PROGRESS: + case Updates.EventType.DOWNLOAD_FINISHED: + case Updates.EventType.NO_UPDATE_AVAILABLE: + case Updates.EventType.ERROR: + return true; + } + }; + + Updates.reload(); + + Updates.reloadFromCache(); + + Updates.addListener(updateEventListener); + + const updateCheckResult = await Updates.checkForUpdateAsync(); + + if (updateCheckResult.isAvailable) { + console.log(updateCheckResult.manifest); + } + + Updates.fetchUpdateAsync(updateEventListener); + + const bundleFetchResult = await Updates.fetchUpdateAsync(); + + if (bundleFetchResult.isNew) { + console.log(bundleFetchResult.manifest); + } +}; diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index e660a4e582..f51d2d13b6 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -1778,8 +1778,9 @@ export namespace Pedometer { * Permissions */ export namespace Permissions { - type PermissionType = 'remoteNotifications' | 'location' | - 'camera' | 'contacts' | 'audioRecording' | 'calendar'; + type PermissionType = 'audioRecording' | 'calendar' | + 'cameraRoll' | 'camera' | 'contacts' | 'location' | 'reminders' | + 'remoteNotifications' | 'systemBrightness' | 'userFacingNotifications'; type PermissionStatus = 'undetermined' | 'granted' | 'denied'; type PermissionExpires = 'never'; @@ -1803,15 +1804,17 @@ export namespace Permissions { type RemoteNotificationPermission = 'remoteNotifications'; - const CAMERA: 'camera'; - const CAMERA_ROLL: 'cameraRoll'; const AUDIO_RECORDING: 'audioRecording'; - const LOCATION: 'location'; - const REMOTE_NOTIFICATIONS: RemoteNotificationPermission; - const NOTIFICATIONS: RemoteNotificationPermission; - const CONTACTS: 'contacts'; - const SYSTEM_BRIGHTNESS: 'systemBrightness'; const CALENDAR: 'calendar'; + const CAMERA_ROLL: 'cameraRoll'; + const CAMERA: 'camera'; + const CONTACTS: 'contacts'; + const LOCATION: 'location'; + const NOTIFICATIONS: RemoteNotificationPermission; + const REMINDERS = 'reminders'; + const REMOTE_NOTIFICATIONS: RemoteNotificationPermission; + const SYSTEM_BRIGHTNESS: 'systemBrightness'; + const USER_FACING_NOTIFICATIONS = 'userFacingNotifications'; } /** @@ -2761,3 +2764,91 @@ export namespace MailComposer { ): Promise<{ status: 'sent' | 'saved' | 'cancelled' }>; } // #endregion + +export namespace Updates { + namespace EventType { + /** A new update is available and has started downloading. */ + type DownloadStart = 'downloadStart'; + /** A new update is currently being downloaded and will be stored in the device's cache. */ + type DownloadProgress = 'downloadProgress'; + /** A new update has finished downloading and is now stored in the device's cache. */ + type DownloadFinished = 'downloadFinished'; + /** No updates are available, and the most up-to-date bundle of this experience is already running. */ + type NoUpdateAvailable = 'noUpdateAvailable'; + /** An error occurred trying to fetch the latest update. */ + type Error = 'error'; + + /** A new update is available and has started downloading. */ + const DOWNLOAD_STARTED: DownloadStart; + /** A new update is currently being downloaded and will be stored in the device's cache. */ + const DOWNLOAD_PROGRESS: DownloadProgress; + /** A new update has finished downloading and is now stored in the device's cache. */ + const DOWNLOAD_FINISHED: DownloadFinished; + /** No updates are available, and the most up-to-date bundle of this experience is already running. */ + const NO_UPDATE_AVAILABLE: NoUpdateAvailable; + /** An error occurred trying to fetch the latest update. */ + const ERROR: Error; + } + + interface UpdateCheck { + /** True if an update is available, false if you're already running the most up-to-date JS bundle. */ + isAvailable: boolean; + /** If `isAvailable` is true, the manifest of the available update. Undefined otherwise. */ + manifest?: Constants.Manifest; + } + + interface UpdateBundle { + /** True if the fetched bundle is new (i.e. a different version that the what's currently running). */ + isNew: boolean; + /** Manifest of the fetched update. */ + manifest: Constants.Manifest; + } + + /** An object that is passed into each event listener when a new version is available. */ + interface UpdateEvent { + /** Type of the event */ + type: EventType.DownloadStart + | EventType.DownloadProgress + | EventType.DownloadFinished + | EventType.NoUpdateAvailable + | EventType.Error; + /** If `type === Expo.Updates.EventType.DOWNLOAD_FINISHED`, the manifest of the newly downloaded update. Undefined otherwise. */ + manifest?: Constants.Manifest; + /** If `type === Expo.Updates.EventType.ERROR`, the error message. Undefined otherwise. */ + message?: string; + } + + type UpdateEventListener = (event: UpdateEvent) => any; + + /** + * Invokes a callback when updates-related events occur, + * either on the initial app load or as a result of a call to `Expo.Updates.fetchUpdateAsync`. + */ + function addListener(listener: UpdateEventListener): EventSubscription; + + /** + * Check if a new published version of your project is available. + * Does not actually download the update. + * Rejects if `updates.enabled` is `false` in app.json. + */ + function checkForUpdateAsync(): Promise; + + /** + * Downloads the most recent published version of your experience to the device's local cache. + * Rejects if `updates.enabled` is `false` in app.json. + */ + function fetchUpdateAsync(listener?: UpdateEventListener): Promise; + + /** + * Immediately reloads the current experience. + * This will use your app.json updates configuration to fetch and load the newest available JS supported by the device's Expo environment. + * This is useful for triggering an update of your experience if you have published a new version. + */ + function reload(): void; + + /** + * Immediately reloads the current experience using the most recent cached version. + * This is useful for triggering an update of your experience if you have published and already downloaded a new version. + */ + function reloadFromCache(): void; +} diff --git a/types/extract-text-webpack-plugin/index.d.ts b/types/extract-text-webpack-plugin/index.d.ts index 61b381d253..f0cc7bf65c 100644 --- a/types/extract-text-webpack-plugin/index.d.ts +++ b/types/extract-text-webpack-plugin/index.d.ts @@ -4,16 +4,10 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { Plugin, NewLoader, OldLoader } from 'webpack'; +import { Plugin, Loader } from 'webpack'; export = ExtractTextPlugin; -/** - * extract-text-webpack-plugin has no support for .options instead of .query yet. - * See https://github.com/webpack/extract-text-webpack-plugin/issues/281 - */ -type Loader = string | OldLoader | NewLoader; - /** * Use an `ExtractTextPlugin` instance and a loader returned by `extract` in concert to write files to disk instead of loading them into others. * Usage example at https://github.com/webpack/extract-text-webpack-plugin#usage-example-with-css diff --git a/types/feather-icons/feather-icons-tests.ts b/types/feather-icons/feather-icons-tests.ts new file mode 100644 index 0000000000..fc71f25798 --- /dev/null +++ b/types/feather-icons/feather-icons-tests.ts @@ -0,0 +1,7 @@ +import * as feather from "feather-icons"; + +feather.replace(); // $ExpectType void +feather.icons[""].toSvg(); // $ExpectType string +feather.icons[""].name; // $ExpectType string +feather.icons[""].contents; // $ExpectType string +feather.icons[""].tags; // $ExpectType string[] diff --git a/types/feather-icons/index.d.ts b/types/feather-icons/index.d.ts new file mode 100644 index 0000000000..34acfb80aa --- /dev/null +++ b/types/feather-icons/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for feather-icons 4.7 +// Project: https://github.com/feathericons/feather#readme +// Definitions by: Jinesh Shah +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace feather; + +export interface FeatherAttributes { + [key: string]: string | number; +} + +export function replace(options?: FeatherAttributes): void; + +export const icons: { + [key: string]: { + name: string; + contents: string; + tags: string[]; + attrs: FeatherAttributes; + toSvg: (options?: FeatherAttributes) => string; + }; +}; diff --git a/types/feather-icons/tsconfig.json b/types/feather-icons/tsconfig.json new file mode 100644 index 0000000000..ab8237b4de --- /dev/null +++ b/types/feather-icons/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "feather-icons-tests.ts"] +} diff --git a/types/feather-icons/tslint.json b/types/feather-icons/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/feather-icons/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/firefox-webext-browser/firefox-webext-browser-tests.ts b/types/firefox-webext-browser/firefox-webext-browser-tests.ts index 38169d573a..53f3b5a928 100644 --- a/types/firefox-webext-browser/firefox-webext-browser-tests.ts +++ b/types/firefox-webext-browser/firefox-webext-browser-tests.ts @@ -12,3 +12,5 @@ browser._manifest.NativeManifest; // $ExpectError // browser.runtime const port = browser.runtime.connect(); port.postMessage(); // $ExpectError + +browser.bookmarks.getTree(); diff --git a/types/firefox-webext-browser/index.d.ts b/types/firefox-webext-browser/index.d.ts index d04b7f6aca..1ce4024f4d 100644 --- a/types/firefox-webext-browser/index.d.ts +++ b/types/firefox-webext-browser/index.d.ts @@ -3915,10 +3915,6 @@ declare namespace browser.bookmarks { type?: BookmarkTreeNodeType; } - export {_import as import}; - - export {_export as export}; - /* bookmarks functions */ /** * Retrieves the specified BookmarkTreeNode(s). @@ -3986,18 +3982,6 @@ declare namespace browser.bookmarks { /** Recursively removes a bookmark folder. */ function removeTree(id: string): Promise; - /** - * Imports bookmarks from an html bookmark file - * @deprecated Unsupported on Firefox at this time. - */ - function _import(): Promise; - - /** - * Exports bookmarks to an html bookmark file - * @deprecated Unsupported on Firefox at this time. - */ - function _export(): Promise; - /* bookmarks events */ /** Fired when a bookmark or folder is created. */ const onCreated: WebExtEvent<(id: string, bookmark: BookmarkTreeNode) => void>; diff --git a/types/fork-ts-checker-webpack-plugin/fork-ts-checker-webpack-plugin-tests.ts b/types/fork-ts-checker-webpack-plugin/fork-ts-checker-webpack-plugin-tests.ts new file mode 100644 index 0000000000..78ead793b4 --- /dev/null +++ b/types/fork-ts-checker-webpack-plugin/fork-ts-checker-webpack-plugin-tests.ts @@ -0,0 +1,24 @@ +import { Configuration } from 'webpack'; +import * as ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'; + +let config: Configuration = { + plugins: [ + new ForkTsCheckerWebpackPlugin() + ] +}; + +config = { + plugins: [ + new ForkTsCheckerWebpackPlugin({}) + ] +}; + +config = { + plugins: [ + new ForkTsCheckerWebpackPlugin({ + vue: true + }) + ] +}; + +export default config; diff --git a/types/fork-ts-checker-webpack-plugin/index.d.ts b/types/fork-ts-checker-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..ace3db5b24 --- /dev/null +++ b/types/fork-ts-checker-webpack-plugin/index.d.ts @@ -0,0 +1,104 @@ +// Type definitions for fork-ts-checker-webpack-plugin 0.4 +// Project: https://github.com/Realytics/fork-ts-checker-webpack-plugin#readme +// Definitions by: JounQin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { RuleFailure } from 'tslint'; +import { Diagnostic } from 'typescript'; +import { Plugin } from 'webpack'; + +declare namespace ForkTsCheckerWebpackPlugin { + type ErrorType = 'diagnostic' | 'lint'; + type Severity = 'error' | 'warning'; + + interface NormalizedMessageJson { + type: ErrorType; + code: string | number; + severity: Severity; + content: string; + file: string; + line: number; + character: number; + } + + class NormalizedMessage { + static TYPE_DIAGNOSTIC: ErrorType; + static TYPE_LINT: ErrorType; + static SEVERITY_ERROR: Severity; + static SEVERITY_WARNING: Severity; + type: ErrorType; + code: string | number; + severity: Severity; + content: string; + file: string; + line: number; + character: number; + constructor(data: NormalizedMessageJson); + static createFromDiagnostic(diagnostic: Diagnostic): NormalizedMessage; + static createFromLint(lint: RuleFailure): NormalizedMessage; + static createFromJSON(json: NormalizedMessageJson): NormalizedMessage; + static compare( + messageA: NormalizedMessage, + messageB: NormalizedMessage, + ): number; + static equals( + messageA: NormalizedMessage, + messageB: NormalizedMessage, + ): boolean; + static deduplicate(messages: NormalizedMessage[]): NormalizedMessage[]; + static compareTypes(typeA: ErrorType, typeB: ErrorType): number; + static compareSeverities( + severityA: Severity, + severityB: Severity, + ): number; + static compareOptionalStrings(stringA: string, stringB: string): number; + static compareNumbers(numberA: number, numberB: number): number; + toJSON(): NormalizedMessageJson; + getType(): ErrorType; + isDiagnosticType(): boolean; + isLintType(): boolean; + getCode(): string | number; + getFormattedCode(): string | number; + getSeverity(): Severity; + isErrorSeverity(): boolean; + isWarningSeverity(): boolean; + getContent(): string; + getFile(): string; + getLine(): number; + getCharacter(): number; + } + + type Formatter = (message: NormalizedMessage, useColors: boolean) => string; + + interface Options { + tsconfig?: string; + tslint?: string | true; + watch?: string | string[]; + async?: boolean; + ignoreDiagnostics?: number[]; + ignoreLints?: string[]; + colors?: boolean; + logger?: Console; + formatter?: 'default' | 'codeframe' | Formatter; + formatterOptions?: { + highlightCode?: boolean + linesAbove?: number + linesBelow?: number + forceColor?: boolean + }; + silent?: boolean; + checkSyntacticErrors?: boolean; + memoryLimit?: number; + workers?: number; + vue?: boolean; + } +} + +declare class ForkTsCheckerWebpackPlugin extends Plugin { + constructor(options?: ForkTsCheckerWebpackPlugin.Options); +} + +export = ForkTsCheckerWebpackPlugin; diff --git a/types/fork-ts-checker-webpack-plugin/tsconfig.json b/types/fork-ts-checker-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..cfd6ee81db --- /dev/null +++ b/types/fork-ts-checker-webpack-plugin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fork-ts-checker-webpack-plugin-tests.ts" + ] +} diff --git a/types/fork-ts-checker-webpack-plugin/tslint.json b/types/fork-ts-checker-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fork-ts-checker-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/freshy/freshy-tests.ts b/types/freshy/freshy-tests.ts new file mode 100644 index 0000000000..406791d0eb --- /dev/null +++ b/types/freshy/freshy-tests.ts @@ -0,0 +1,21 @@ +import { unload, reload, freshy } from 'freshy'; +import minimist = require('minimist'); + +declare function require(x: string): any; + +unload('minimist'); // $ExpectType boolean + +const reloaded = reload('minimist'); // $ExpectType any +minimist === reloaded; // false + +const freshlyLoaded = freshy('minimist'); // $ExpectType any +minimist === freshlyLoaded; // false + +let alsofresh: any; +// $ExpectType any +const fresh = freshy('minimist', (fresh) => { + alsofresh = require('minimist'); + fresh === alsofresh; // true +}); +minimist === fresh; // false +fresh === alsofresh; // true diff --git a/types/freshy/index.d.ts b/types/freshy/index.d.ts new file mode 100644 index 0000000000..93b424143a --- /dev/null +++ b/types/freshy/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for freshy 1.0 +// Project: https://github.com/krakenjs/freshy#readme +// Definitions by: Nikita Volodin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function unload(module: string): boolean; +export function reload(module: string): any; +export function freshy(module: string, cb?: (module: any) => any): any; diff --git a/types/freshy/tsconfig.json b/types/freshy/tsconfig.json new file mode 100644 index 0000000000..7cc3f4d9f4 --- /dev/null +++ b/types/freshy/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "freshy-tests.ts" + ] +} diff --git a/types/freshy/tslint.json b/types/freshy/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/freshy/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts b/types/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts index 337dd1ca0f..bdff193912 100644 --- a/types/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts +++ b/types/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts @@ -14,7 +14,7 @@ declare const dir: string; declare const path: string; declare const data: any; declare const object: any; -let buffer: NodeBuffer; +let buffer: Buffer; declare const modeNum: number; declare const modeStr: string; declare const encoding: string; @@ -148,19 +148,19 @@ fs.futimes(fd, atime, mtime, errorCallback); fs.futimesSync(fd, atime, mtime); fs.fsync(fd, errorCallback); fs.fsyncSync(fd); -fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: NodeBuffer) => { +fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: Buffer) => { }); num = fs.writeSync(fd, buffer, offset, length, position); -fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: NodeBuffer) => { +fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: Buffer) => { }); num = fs.readSync(fd, buffer, offset, length, position); -fs.readFile(filename, (err: Error, data: NodeBuffer) => { +fs.readFile(filename, (err: Error, data: Buffer) => { }); fs.readFile(filename, encoding, (err: Error, data: string) => { }); fs.readFile(filename, openOpts, (err: Error, data: string) => { }); -fs.readFile(filename, (err: Error, data: NodeBuffer) => { +fs.readFile(filename, (err: Error, data: Buffer) => { }); buffer = fs.readFileSync(filename); str = fs.readFileSync(filename, encoding); diff --git a/types/fs-extra-promise-es6/index.d.ts b/types/fs-extra-promise-es6/index.d.ts index 0f52b5c02e..2b7dacd108 100644 --- a/types/fs-extra-promise-es6/index.d.ts +++ b/types/fs-extra-promise-es6/index.d.ts @@ -113,13 +113,13 @@ export function futimes(fd: number, atime: number, mtime: number, callback?: (er export function futimesSync(fd: number, atime: number, mtime: number): void; export function fsync(fd: number, callback?: (err: Error) => void): void; export function fsyncSync(fd: number): void; -export function write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: NodeBuffer) => void): void; -export function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; -export function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: NodeBuffer) => void): void; -export function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; +export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: Error, 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: Error, bytesRead: number, buffer: Buffer) => void): void; +export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; export function readFile(filename: string, options: OpenOptions | string, callback: (err: Error, data: string) => void): void; -export function readFile(filename: string, callback: (err: Error, data: NodeBuffer) => void): void; -export function readFileSync(filename: string): NodeBuffer; +export function readFile(filename: string, callback: (err: Error, data: Buffer) => void): void; +export function readFileSync(filename: string): Buffer; export function readFileSync(filename: string, options: OpenOptions | string): string; export function writeFile(filename: string, data: any, callback?: (err: Error) => void): void; export function writeFile(filename: string, data: any, options: OpenOptions | string, callback?: (err: Error) => void): void; @@ -201,10 +201,10 @@ export function openAsync(path: string, flags: string, mode?: string): Promise; export function futimesAsync(fd: number, atime: number, mtime: number): Promise; export function fsyncAsync(fd: number): Promise; -export function writeAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; -export function readAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; +export function writeAsync(fd: number, buffer: Buffer, offset: number, length: number, position: number): Promise<[number, Buffer]>; +export function readAsync(fd: number, buffer: Buffer, offset: number, length: number, position: number): Promise<[number, Buffer]>; export function readFileAsync(filename: string, options: OpenOptions | string): Promise; -export function readFileAsync(filename: string): Promise; +export function readFileAsync(filename: string): Promise; export function writeFileAsync(filename: string, data: any, options?: OpenOptions | string): Promise; export function appendFileAsync(filename: string, data: any, option?: OpenOptions | string): Promise; diff --git a/types/fs-extra-promise/fs-extra-promise-tests.ts b/types/fs-extra-promise/fs-extra-promise-tests.ts index f273d6efb6..61549a55ad 100644 --- a/types/fs-extra-promise/fs-extra-promise-tests.ts +++ b/types/fs-extra-promise/fs-extra-promise-tests.ts @@ -16,7 +16,7 @@ declare const data: any; declare const object: object; declare const buf: Buffer; let strOrBuf: string | Buffer; -let buffer: NodeBuffer; +let buffer: Buffer; declare const modeNum: number; declare const modeStr: string; declare const encoding: string; @@ -148,19 +148,19 @@ fs.futimes(fd, atime, mtime, errorCallback); fs.futimesSync(fd, atime, mtime); fs.fsync(fd, errorCallback); fs.fsyncSync(fd); -fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: NodeBuffer) => { +fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: Buffer) => { }); num = fs.writeSync(fd, buffer, offset, length, position); -fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: NodeBuffer) => { +fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: Buffer) => { }); num = fs.readSync(fd, buffer, offset, length, position); -fs.readFile(filename, (err: Error, data: NodeBuffer) => { +fs.readFile(filename, (err: Error, data: Buffer) => { }); fs.readFile(filename, encoding, (err: Error, data: string) => { }); fs.readFile(filename, openOpts, (err: NodeJS.ErrnoException, data: Buffer) => { }); -fs.readFile(filename, (err: Error, data: NodeBuffer) => { +fs.readFile(filename, (err: Error, data: Buffer) => { }); buffer = fs.readFileSync(filename); str = fs.readFileSync(filename, encoding); diff --git a/types/fs-extra-promise/index.d.ts b/types/fs-extra-promise/index.d.ts index de47c81a1e..b4ac5be133 100644 --- a/types/fs-extra-promise/index.d.ts +++ b/types/fs-extra-promise/index.d.ts @@ -65,10 +65,10 @@ export function openAsync(path: string, flags: string, mode?: string): Promise; export function futimesAsync(fd: number, atime: number, mtime: number): Promise; export function fsyncAsync(fd: number): Promise; -export function writeAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; -export function readAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; +export function writeAsync(fd: number, buffer: Buffer, offset: number, length: number, position: number): Promise<[number, Buffer]>; +export function readAsync(fd: number, buffer: Buffer, offset: number, length: number, position: number): Promise<[number, Buffer]>; export function readFileAsync(filename: string, options: string | ReadOptions): Promise; -export function readFileAsync(filename: string): Promise; +export function readFileAsync(filename: string): Promise; export function writeFileAsync(filename: string, data: any, options?: string | WriteOptions): Promise; export function appendFileAsync(filename: string, data: any, option?: string | WriteOptions): Promise; diff --git a/types/gm/gm-tests.ts b/types/gm/gm-tests.ts index 9f59854467..b2efd9505a 100644 --- a/types/gm/gm-tests.ts +++ b/types/gm/gm-tests.ts @@ -62,6 +62,7 @@ declare const font: string; declare const quality: number; declare const align: string; declare const depth: number; +declare const defineValue: string; let readStream: stream.PassThrough; gm(src) @@ -104,7 +105,7 @@ gm(src) .crop(width, height, x, y, usePercent) .cycle(factor) .deconstruct() - .define() + .define(defineValue) .delay(time) .density(width, height) .despeckle() diff --git a/types/gm/index.d.ts b/types/gm/index.d.ts index 0670f0ae0f..5e8853efce 100644 --- a/types/gm/index.d.ts +++ b/types/gm/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for gm 1.17 +// Type definitions for gm 1.18 // Project: https://github.com/aheckmann/gm // Definitions by: Joel Spadin , Maarten van Vliet // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -123,7 +123,7 @@ declare namespace m { crop(width: number, height: number, x?: number, y?: number, percent?: boolean): State; cycle(amount: number): State; deconstruct(): State; - define(): State; + define(value: string): State; delay(milliseconds: number): State; density(width: number, height: number): State; despeckle(): State; diff --git a/types/google-apps-script/google-apps-script.calendar.d.ts b/types/google-apps-script/google-apps-script.calendar.d.ts index 34a3d46a11..21770b6efb 100644 --- a/types/google-apps-script/google-apps-script.calendar.d.ts +++ b/types/google-apps-script/google-apps-script.calendar.d.ts @@ -1,6 +1,7 @@ -// Type definitions for Google Apps Script 2017-05-12 +// Type definitions for Google Apps Script 2018-05-03 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen +// linlex // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -24,6 +25,7 @@ declare namespace GoogleAppsScript { deleteCalendar(): void; getColor(): string; getDescription(): string; + getEventById(iCalId: string): CalendarEvent; getEventSeriesById(iCalId: string): CalendarEventSeries; getEvents(startTime: Date, endTime: Date): CalendarEvent[]; getEvents(startTime: Date, endTime: Date, options: Object): CalendarEvent[]; diff --git a/types/google-apps-script/google-apps-script.spreadsheet.d.ts b/types/google-apps-script/google-apps-script.spreadsheet.d.ts index 7cd1cb8946..b656032a96 100644 --- a/types/google-apps-script/google-apps-script.spreadsheet.d.ts +++ b/types/google-apps-script/google-apps-script.spreadsheet.d.ts @@ -1,6 +1,7 @@ -// Type definitions for Google Apps Script 2017-05-12 +// Type definitions for Google Apps Script 2018-05-03 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen +// linlex // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -11,7 +12,7 @@ declare namespace GoogleAppsScript { /** * This service allows scripts to create, access, and modify Google Sheets files. See also the guide to storing data in spreadsheets. - * + * * https://developers.google.com/apps-script/guides/sheets */ export module Spreadsheet { @@ -858,6 +859,7 @@ declare namespace GoogleAppsScript { autoResizeColumn(columnPosition: Integer): Sheet; clear(): Sheet; clear(options: Object): Sheet; + clearConditionalFormatRules(): void; clearContents(): Sheet; clearFormats(): Sheet; clearNotes(): Sheet; @@ -870,6 +872,7 @@ declare namespace GoogleAppsScript { getActiveRange(): Range; getCharts(): EmbeddedChart[]; getColumnWidth(columnPosition: Integer): Integer; + getConditionalFormatRules(): ConditionalFormatRule[]; getDataRange(): Range; getFrozenColumns(): Integer; getFrozenRows(): Integer; @@ -923,6 +926,8 @@ declare namespace GoogleAppsScript { setActiveSelection(range: Range): Range; setActiveSelection(a1Notation: string): Range; setColumnWidth(columnPosition: Integer, width: Integer): Sheet; + setConditionalFormatRules(rules: ReadonlyArray): void; + setCurrentCell(cell: Range): void; setFrozenColumns(columns: Integer): void; setFrozenRows(rows: Integer): void; setName(name: string): Sheet; @@ -1066,6 +1071,14 @@ declare namespace GoogleAppsScript { * An enumeration representing the data-validation criteria that can be set on a range. */ DataValidationCriteria: typeof DataValidationCriteria; + /** + * An enumeration representing the interpolation options for calculating a value to be used in a GradientCondition in a ConditionalFormatRule. + */ + InterpolationType: typeof InterpolationType; + /** + * An enumeration representing the boolean criteria that can be used in conditional format or filter. + */ + BooleanCriteria: typeof BooleanCriteria; /** * An enumeration representing the parts of a spreadsheet that can be protected from edits. */ @@ -1111,27 +1124,408 @@ declare namespace GoogleAppsScript { */ open(file: Drive.File): Spreadsheet; /** - * Opens the spreadsheet with the given ID. + * Opens the spreadsheet with the given ID. */ openById(id: string): Spreadsheet; /** - * Opens the spreadsheet with the given url. + * Opens the spreadsheet with the given url. */ openByUrl(url: string): Spreadsheet; /** - * Sets the active range for the application. + * Sets the active range for the application. */ setActiveRange(range: Range): Range; /** - * Sets the active sheet in a spreadsheet. + * Sets the active sheet in a spreadsheet. */ setActiveSheet(sheet: Sheet): Sheet; /** - * Sets the active spreadsheet. + * Sets the active spreadsheet. */ setActiveSpreadsheet(newActiveSpreadsheet: Spreadsheet): void; + /** + * Creates a builder for a conditional formatting rule. + */ + newConditionalFormatRule(): ConditionalFormatRuleBuilder; } + /** + * Access conditional formatting rules. To create a new rule, use SpreadsheetApp.newConditionalFormatRule() and + * ConditionalFormatRuleBuilder. You can use Sheet.setConditionalFormatRules(rules) to set the rules for a given + * sheet. + */ + export interface ConditionalFormatRule { + /** + * Returns a rule builder preset with this rule's settings. + */ + copy(): ConditionalFormatRuleBuilder; + + /** + * Retrieves the rule's BooleanCondition information if this rule uses boolean condition criteria. + */ + getBooleanCondition(): BooleanCondition; + + /** + * Retrieves the rule's GradientCondition information, if this rule uses gradient condition criteria. + */ + getGradientCondition(): GradientCondition; + + /** + * Retrieves the ranges to which this conditional format rule is applied. + */ + getRanges(): Range[]; + } + + /** + * Builder for conditional format rules. + */ + export interface ConditionalFormatRuleBuilder { + + /** + * Constructs a conditional format rule from the settings applied to the builder. + */ + build(): ConditionalFormatRule; + + /** + * Returns a rule builder preset with this rule's settings. + */ + copy(): ConditionalFormatRuleBuilder; + + /** + * Retrieves the rule's BooleanCondition information if this rule uses boolean condition criteria. + */ + getBooleanCondition(): BooleanCondition; + + /** + * Retrieves the rule's GradientCondition information, if this rule uses gradient condition criteria. + */ + getGradientCondition(): GradientCondition; + + /** + * Retrieves the ranges to which this conditional format rule is applied. + */ + getRanges(): Range[]; + + /** + * Sets the background color for the conditional format rule's format. + */ + setBackground(color: string): ConditionalFormatRuleBuilder; + + /** + * Sets text bolding for the conditional format rule's format. + */ + setBold(bold: boolean): ConditionalFormatRuleBuilder; + + /** + * Sets the font color for the conditional format rule's format. + */ + setFontColor(color: string): ConditionalFormatRuleBuilder; + + /** + * Clears the conditional format rule's gradient maxpoint value, and instead uses the maximum value in the rule's ranges. + */ + setGradientMaxpoint(color: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule's gradient maxpoint fields. + */ + setGradientMaxpointWithValue(color: string, type: InterpolationType, value: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule's gradient midpoint fields. + */ + setGradientMidpointWithValue(color: string, type: InterpolationType, value: string): ConditionalFormatRuleBuilder; + + /** + * Clears the conditional format rule's gradient minpoint value, and instead uses the minimum value in the rule's ranges. + */ + setGradientMinpoint(color: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule's gradient minpoint fields. + */ + setGradientMinpointWithValue(color: string, type: SpreadsheetApp.InterpolationType, value: string): ConditionalFormatRuleBuilder; + + /** + * Sets text italics for the conditional format rule's format. + */ + setItalic(italic: boolean): ConditionalFormatRuleBuilder; + + /** + * Sets one or more ranges to which this conditional format rule is applied. + */ + setRanges(ranges: ReadonlyArray): ConditionalFormatRuleBuilder; + + /** + * Sets text strikethrough for the conditional format rule's format. + */ + setStrikethrough(strikethrough: boolean): ConditionalFormatRuleBuilder; + + /** + * Sets text underlining for the conditional format rule's format. + */ + setUnderline(underline: boolean): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when the cell is empty. + */ + whenCellEmpty(): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when the cell is not empty. + */ + whenCellNotEmpty(): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a date is after the given value. + */ + whenDateAfter(date: Date): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a date is after the given relative date. + */ + whenDateAfter(date: Date): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a date is before the given date. + */ + whenDateBefore(date: Date): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a date is before the given relative date. + */ + whenDateBefore(date: Date): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a date is equal to the given date. + */ + whenDateEqualTo(date: Date): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a date is equal to the given relative date. + */ + whenDateEqualTo(date: Date): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when that the given formula evaluates to true. + */ + whenFormulaSatisfied(formula: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number falls between, or is either of, two specified values. + */ + whenNumberBetween(start: number, end: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number is equal to the given value. + */ + whenNumberEqualTo(number: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number is greater than the given value. + */ + whenNumberGreaterThan(number: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number is greater than or equal to the given value. + */ + whenNumberGreaterThanOrEqualTo(number: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional conditional format rule to trigger when a number less than the given value. + */ + whenNumberLessThan(number: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number less than or equal to the given value. + */ + whenNumberLessThanOrEqualTo(number: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number does not fall between, and is neither of, two specified values. + */ + whenNumberNotBetween(start: number, end: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when a number is not equal to the given value. + */ + whenNumberNotEqualTo(number: number): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when that the input contains the given value. + */ + whenTextContains(text: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when that the input does not contain the given value. + */ + whenTextDoesNotContain(text: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when that the input ends with the given value. + */ + whenTextEndsWith(text: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when that the input is equal to the given value. + */ + whenTextEqualTo(text: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to trigger when that the input starts with the given value. + */ + whenTextStartsWith(text: string): ConditionalFormatRuleBuilder; + + /** + * Sets the conditional format rule to criteria defined by BooleanCriteria values, typically taken from the criteria and arguments of an existing rule. + */ + withCriteria(criteria: BooleanCriteria, args: ReadonlyArray): ConditionalFormatRuleBuilder; + } + + /** + * An enumeration representing the boolean criteria that can be used in conditional format or filter. + */ + export enum BooleanCriteria { + /** + * The criteria is met when a cell is empty. + */ + CELL_EMPTY, + + /** + * The criteria is met when a cell is not empty. + */ + CELL_NOT_EMPTY, + + /** + * The criteria is met when a date is after the given value. + */ + DATE_AFTER, + + /** + * The criteria is met when a date is before the given value. + */ + DATE_BEFORE, + + /** + * The criteria is met when a date is equal to the given value. + */ + DATE_EQUAL_TO, + + /** + * The criteria is met when a date is after the relative date value. + */ + DATE_AFTER_RELATIVE, + + /** + * The criteria is met when a date is before the relative date value. + */ + DATE_BEFORE_RELATIVE, + + /** + * The criteria is met when a date is equal to the relative date value. + */ + DATE_EQUAL_TO_RELATIVE, + + /** + * The criteria is met when a number that is between the given values. + */ + NUMBER_BETWEEN, + + /** + * The criteria is met when a number that is equal to the given value. + */ + NUMBER_EQUAL_TO, + + /** + * The criteria is met when a number that is greater than the given value. + */ + NUMBER_GREATER_THAN, + + /** + * The criteria is met when a number that is greater than or equal to the given value. + */ + NUMBER_GREATER_THAN_OR_EQUAL_TO, + + /** + * The criteria is met when a number that is less than the given value. + */ + NUMBER_LESS_THAN, + + /** + * The criteria is met when a number that is less than or equal to the given value. + */ + NUMBER_LESS_THAN_OR_EQUAL_TO, + + /** + * The criteria is met when a number that is not between the given values. + */ + NUMBER_NOT_BETWEEN, + + /** + * The criteria is met when a number that is not equal to the given value. + */ + NUMBER_NOT_EQUAL_TO, + + /** + * The criteria is met when the input contains the given value. + */ + TEXT_CONTAINS, + + /** + * The criteria is met when the input does not contain the given value. + */ + TEXT_DOES_NOT_CONTAIN, + + /** + * The criteria is met when the input is equal to the given value. + */ + TEXT_EQUAL_TO, + + /** + * The criteria is met when the input begins with the given value. + */ + TEXT_STARTS_WITH, + + /** + * The criteria is met when the input ends with the given value. + */ + TEXT_ENDS_WITH, + + /** + * The criteria is met when the input makes the given formula evaluate to true. + */ + CUSTOM_FORMULA + } + + /** + * An enumeration representing the interpolation options for calculating a value to be used in a GradientCondition in a ConditionalFormatRule. + */ + export enum InterpolationType { + /** + * Use the number as as specific interpolation point for a gradient condition. + */ + NUMBER, + + /** + * Use the number as a percentage interpolation point for a gradient condition. + */ + PERCENT, + + /** + * Use the number as a percentile interpolation point for a gradient condition. + */ + PERCENTILE, + + /** + * Infer the minimum number as a specific interpolation point for a gradient condition. + */ + MIN, + + /** + * Infer the maximum number as a specific interpolation point for a gradient condition. + */ + MAX + } } } diff --git a/types/google-libphonenumber/index.d.ts b/types/google-libphonenumber/index.d.ts index 9a46ac69a6..dd73c56790 100644 --- a/types/google-libphonenumber/index.d.ts +++ b/types/google-libphonenumber/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for libphonenumber v7.4.3 // Project: https://github.com/googlei18n/libphonenumber, https://github.com/seegno/google-libphonenumber // Definitions by: Leon Yu +// Roman Jurkov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace libphonenumber { @@ -112,6 +113,7 @@ declare namespace libphonenumber { export class PhoneNumberUtil { static getInstance(): PhoneNumberUtil format(phoneNumber: PhoneNumber, format: PhoneNumberFormat): string; + formatOutOfCountryCallingNumber(phoneNumber: PhoneNumber, regionDialingFrom?: string): string; getNddPrefixForRegion(regionCode?: string, stripNonDigits?: boolean): string | undefined; getNumberType(phoneNumber: PhoneNumber): PhoneNumberType; getCountryCodeForRegion(supportedRegion:string):string; diff --git a/types/google-map-react/google-map-react-tests.tsx b/types/google-map-react/google-map-react-tests.tsx index 464f840658..552e75d362 100644 --- a/types/google-map-react/google-map-react-tests.tsx +++ b/types/google-map-react/google-map-react-tests.tsx @@ -1,9 +1,20 @@ -import GoogleMapReact, { BootstrapURLKeys } from 'google-map-react'; +import GoogleMapReact, { BootstrapURLKeys, MapOptions } from 'google-map-react'; import * as React from 'react'; const center = { lat: 0, lng: 0 }; const key: BootstrapURLKeys = { key: 'my-google-maps-key' }; const client: BootstrapURLKeys = { client: 'my-client-identifier', v: '3.28' , language: 'en' }; +const options: MapOptions = { + zoomControl: false, + gestureHandling: 'cooperative', + styles: [ + { + featureType: "administrative", + elementType: "all", + stylers: [ {saturation: "-100"} ] + } + ], +}; -; +; diff --git a/types/google-map-react/index.d.ts b/types/google-map-react/index.d.ts index 7f34a68cc4..ca5348323a 100644 --- a/types/google-map-react/index.d.ts +++ b/types/google-map-react/index.d.ts @@ -8,15 +8,48 @@ import * as React from 'react'; export type BootstrapURLKeys = ({ key: string; } | { client: string; v: string; }) & { language?: string }; -export interface Options { - styles?: any[]; - scrollwheel?: boolean; - panControl?: boolean; +export interface MapTypeStyle { + elementType: string; + featureType: string; + stylers: any[]; +} + +export interface MapOptions { + // Any options from https://developers.google.com/maps/documentation/javascript/reference/3/#MapOptions + // excluding 'zoom' and 'center' which get set via props. + backgroundColor?: string; + clickableIcons?: boolean; + disableDefaultUI?: boolean; + disableDoubleClickZoom?: boolean; + draggable?: boolean; + draggableCursor?: string; + draggingCursor?: string; + fullscreenControl?: boolean; + fullscreenControlOptions?: {position: number}; + gestureHandling?: string; + heading?: number; + keyboardShortcuts?: boolean; mapTypeControl?: boolean; - minZoomOverride?: boolean; + mapTypeControlOptions?: any; + mapTypeId?: string; minZoom?: number; maxZoom?: number; - gestureHandling?: string; + noClear?: boolean; + panControl?: boolean; + panControlOptions?: {position: number}; + rotateControl?: boolean; + rotateControlOptions?: {position: number}; + scaleControl?: boolean; + scaleControlOptions?: any; + scrollwheel?: boolean; + streetView?: any; + streetViewControl?: boolean; + streetViewControlOptions?: {position: number}; + styles?: MapTypeStyle[]; + tilt?: number; + zoomControl?: boolean; + zoomControlOptions?: {position: number}; + minZoomOverride?: boolean; // Not a standard option; specific to google-map-react: https://github.com/google-map-react/google-map-react/pull/154 } export interface Maps { @@ -87,7 +120,7 @@ export interface Props { defaultZoom?: number; zoom?: number; hoverDistance?: number; - options?: Options | ((maps: Maps) => Options); + options?: MapOptions | ((maps: Maps) => MapOptions); margin?: any[]; debounced?: boolean; draggable?: boolean; diff --git a/types/got/got-tests.ts b/types/got/got-tests.ts index 8c88cef3bc..1eb2d89aa8 100644 --- a/types/got/got-tests.ts +++ b/types/got/got-tests.ts @@ -1,10 +1,12 @@ import got = require('got'); import cookie = require('cookie'); import FormData = require('form-data'); +import Keyv = require('keyv'); import * as fs from 'fs'; import * as http from 'http'; import * as https from 'https'; import * as url from 'url'; +import QuickLRU = require('quick-lru'); let str: string; let buf: Buffer; @@ -242,7 +244,15 @@ got('todomvc', { }); got('todomvc', { - cache: new Map() + cache: new Map(), +}).then(res => res.fromCache); + +got('todomvc', { + cache: new Keyv(), +}).then(res => res.fromCache); + +got('todomvc', { + cache: new QuickLRU(), }).then(res => res.fromCache); got(new url.URL('http://todomvc.com')); diff --git a/types/got/index.d.ts b/types/got/index.d.ts index 47c281fb53..f786af118e 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -119,7 +119,7 @@ declare namespace got { followRedirect?: boolean; decompress?: boolean; useElectronNet?: boolean; - cache?: Map; + cache?: Cache; agent?: http.Agent | boolean | AgentOptions; throwHttpErrors?: boolean; } @@ -137,6 +137,12 @@ declare namespace got { type RetryFunction = (retry: number, error: any) => number; + interface Cache { + set(key: string, value: any, ttl?: number): any; + get(key: string): any; + delete(key: string): any; + } + interface Response extends http.IncomingMessage { body: B; url: string; diff --git a/types/graphql-depth-limit/graphql-depth-limit-tests.ts b/types/graphql-depth-limit/graphql-depth-limit-tests.ts new file mode 100644 index 0000000000..68a5aa51f9 --- /dev/null +++ b/types/graphql-depth-limit/graphql-depth-limit-tests.ts @@ -0,0 +1,29 @@ +import graphqlDepthLimit = require('graphql-depth-limit'); +import { + GraphQLSchema, + DocumentNode, + buildSchema, + Source, + parse, + validate, + specifiedRules +} from 'graphql'; + +const schema: GraphQLSchema = buildSchema(` + # graphql schema goes here... +`); +const document: DocumentNode = parse(new Source(` + # graphql query goes here... +`, 'GraphQL request')); + +validate(schema, document, [ graphqlDepthLimit(5) ]); + +validate(schema, document, [ ...specifiedRules, graphqlDepthLimit(10) ]); + +validate(schema, document, [ graphqlDepthLimit( + 10, + { ignore: [ /_trusted$/, 'idontcare' ] }, + (depths: any) => { + // do something.... + }, +)]); diff --git a/types/graphql-depth-limit/index.d.ts b/types/graphql-depth-limit/index.d.ts new file mode 100644 index 0000000000..281f8fdaff --- /dev/null +++ b/types/graphql-depth-limit/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for graphql-depth-limit 1.1 +// Project: https://github.com/stems/graphql-depth-limit#readme +// Definitions by: Siim Tiilen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +declare function depthLimit(depthLimit: number, options?: depthLimit.Options, callback?: (obj: any) => void): any; +export = depthLimit; + +declare namespace depthLimit { + interface Options { + ignore: Array boolean)>; + } +} diff --git a/types/graphql-depth-limit/tsconfig.json b/types/graphql-depth-limit/tsconfig.json new file mode 100644 index 0000000000..5c59137102 --- /dev/null +++ b/types/graphql-depth-limit/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "graphql-depth-limit-tests.ts" + ] +} diff --git a/types/graphql-depth-limit/tslint.json b/types/graphql-depth-limit/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/graphql-depth-limit/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/graphql/error/GraphQLError.d.ts b/types/graphql/error/GraphQLError.d.ts index 0be931bee0..ce31564fb1 100644 --- a/types/graphql/error/GraphQLError.d.ts +++ b/types/graphql/error/GraphQLError.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { getLocation } from "../language"; import { ASTNode } from "../language/ast"; import { Source } from "../language/source"; @@ -58,7 +59,7 @@ export class GraphQLError extends Error { /** * The original error thrown from a field resolver during execution. */ - readonly originalError: Error | void; + readonly originalError: Maybe; /** * Extension fields to add to the formatted error. @@ -68,10 +69,10 @@ export class GraphQLError extends Error { constructor( message: string, nodes?: ReadonlyArray | ASTNode | undefined, - source?: Source | void, - positions?: ReadonlyArray | void, - path?: ReadonlyArray | void, - originalError?: Error | void, - extensions?: { [key: string]: any } | void + source?: Maybe, + positions?: Maybe>, + path?: Maybe>, + originalError?: Maybe, + extensions?: Maybe<{ [key: string]: any }> ); } diff --git a/types/graphql/execution/execute.d.ts b/types/graphql/execution/execute.d.ts index 424bb62b5a..7ef4d5ce63 100644 --- a/types/graphql/execution/execute.d.ts +++ b/types/graphql/execution/execute.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLError, locatedError } from "../error"; import { GraphQLSchema } from "../type/schema"; import { @@ -51,9 +52,9 @@ export type ExecutionArgs = { document: DocumentNode; rootValue?: any; contextValue?: any; - variableValues?: { [key: string]: any } | void; - operationName?: string | void; - fieldResolver?: GraphQLFieldResolver | void; + variableValues?: Maybe<{ [key: string]: any }>; + operationName?: Maybe; + fieldResolver?: Maybe>; }; /** @@ -74,9 +75,9 @@ export function execute( document: DocumentNode, rootValue?: any, contextValue?: any, - variableValues?: { [key: string]: any } | void, - operationName?: string | void, - fieldResolver?: GraphQLFieldResolver | void + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe, + fieldResolver?: Maybe> ): MaybePromise; /** @@ -101,7 +102,7 @@ export function addPath( export function assertValidExecutionArguments( schema: GraphQLSchema, document: DocumentNode, - rawVariableValues: { [key: string]: any } | void + rawVariableValues: Maybe<{ [key: string]: any }> ): void; /** @@ -115,9 +116,9 @@ export function buildExecutionContext( document: DocumentNode, rootValue: any, contextValue: any, - rawVariableValues: { [key: string]: any } | void, - operationName: string | void, - fieldResolver: GraphQLFieldResolver | void + rawVariableValues: Maybe<{ [key: string]: any }>, + operationName: Maybe, + fieldResolver: Maybe> ): ReadonlyArray | ExecutionContext; /** @@ -181,4 +182,4 @@ export function getFieldDef( schema: GraphQLSchema, parentType: GraphQLObjectType, fieldName: string -): GraphQLField | void; +): Maybe>; diff --git a/types/graphql/execution/values.d.ts b/types/graphql/execution/values.d.ts index fb629325e8..e3cb7eb4bc 100644 --- a/types/graphql/execution/values.d.ts +++ b/types/graphql/execution/values.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLError } from "../error"; import { GraphQLInputType, GraphQLField, GraphQLArgument } from "../type/definition"; import { GraphQLDirective } from "../type/directives"; @@ -35,7 +36,7 @@ export function getVariableValues( export function getArgumentValues( def: GraphQLField | GraphQLDirective, node: FieldNode | DirectiveNode, - variableValues?: { [key: string]: any } | void + variableValues?: Maybe<{ [key: string]: any }> ): { [key: string]: any }; /** @@ -54,5 +55,5 @@ export function getDirectiveValues( node: { readonly directives?: ReadonlyArray; }, - variableValues?: { [key: string]: any } | void + variableValues?: Maybe<{ [key: string]: any }> ): undefined | { [key: string]: any }; diff --git a/types/graphql/graphql.d.ts b/types/graphql/graphql.d.ts index 7282ea80f2..59dc3918f1 100644 --- a/types/graphql/graphql.d.ts +++ b/types/graphql/graphql.d.ts @@ -1,3 +1,4 @@ +import Maybe from "./tsutils/Maybe"; import { Source } from "./language/source"; import { GraphQLFieldResolver } from "./type/definition"; import { GraphQLSchema } from "./type/schema"; @@ -38,9 +39,9 @@ export interface GraphQLArgs { source: Source | string; rootValue?: any; contextValue?: any; - variableValues?: { [key: string]: any } | void; - operationName?: string | void; - fieldResolver?: GraphQLFieldResolver | void; + variableValues?: Maybe<{ [key: string]: any }>; + operationName?: Maybe; + fieldResolver?: Maybe>; } export function graphql(args: GraphQLArgs): Promise; @@ -49,9 +50,9 @@ export function graphql( source: Source | string, rootValue?: any, contextValue?: any, - variableValues?: { [key: string]: any } | void, - operationName?: string | void, - fieldResolver?: GraphQLFieldResolver | void + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe, + fieldResolver?: Maybe> ): Promise; /** @@ -66,7 +67,7 @@ export function graphqlSync( source: Source | string, rootValue?: any, contextValue?: any, - variableValues?: { [key: string]: any } | void, - operationName?: string | void, - fieldResolver?: GraphQLFieldResolver | void + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe, + fieldResolver?: Maybe> ): ExecutionResult; diff --git a/types/graphql/index.d.ts b/types/graphql/index.d.ts index 68e04d104d..ba9213b7c4 100644 --- a/types/graphql/index.d.ts +++ b/types/graphql/index.d.ts @@ -13,6 +13,7 @@ // Dylan Stewart // Alessio Dionisi // Divyendu Singh +// Brad Zacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/graphql/language/visitor.d.ts b/types/graphql/language/visitor.d.ts index a137fa318e..be50e6e02e 100644 --- a/types/graphql/language/visitor.d.ts +++ b/types/graphql/language/visitor.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { ASTNode, ASTKindToNode } from "./ast"; import { TypeInfo } from "../utilities/TypeInfo"; @@ -157,4 +158,4 @@ export function visitWithTypeInfo(typeInfo: TypeInfo, visitor: Visitor, kind: string, isLeaving: boolean): VisitFn | void; +export function getVisitFn(visitor: Visitor, kind: string, isLeaving: boolean): Maybe>; diff --git a/types/graphql/subscription/subscribe.d.ts b/types/graphql/subscription/subscribe.d.ts index a9fe6b565e..f5b29ebbb8 100644 --- a/types/graphql/subscription/subscribe.d.ts +++ b/types/graphql/subscription/subscribe.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLSchema } from "../type/schema"; import { DocumentNode } from "../language/ast"; import { GraphQLFieldResolver } from "../type/definition"; @@ -28,10 +29,10 @@ export function subscribe(args: { document: DocumentNode; rootValue?: any; contextValue?: any; - variableValues?: { [key: string]: any } | void; - operationName?: string | void; - fieldResolver?: GraphQLFieldResolver | void; - subscribeFieldResolver?: GraphQLFieldResolver | void; + variableValues?: Maybe<{ [key: string]: any }>; + operationName?: Maybe; + fieldResolver?: Maybe>; + subscribeFieldResolver?: Maybe>; }): Promise | ExecutionResult>; export function subscribe( @@ -39,10 +40,10 @@ export function subscribe( document: DocumentNode, rootValue?: any, contextValue?: any, - variableValues?: { [key: string]: any } | void, - operationName?: string | void, - fieldResolver?: GraphQLFieldResolver | void, - subscribeFieldResolver?: GraphQLFieldResolver | void + variableValues?: Maybe<{ [key: string]: any }>, + operationName?: Maybe, + fieldResolver?: Maybe>, + subscribeFieldResolver?: Maybe> ): Promise | ExecutionResult>; /** @@ -69,6 +70,6 @@ export function createSourceEventStream( rootValue?: any, contextValue?: any, variableValues?: { [key: string]: any }, - operationName?: string | void, - fieldResolver?: GraphQLFieldResolver | void + operationName?: Maybe, + fieldResolver?: Maybe> ): Promise | ExecutionResult>; diff --git a/types/graphql/tsconfig.json b/types/graphql/tsconfig.json index 72f0de0665..3bc66f8bea 100644 --- a/types/graphql/tsconfig.json +++ b/types/graphql/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "index.d.ts", "graphql-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/graphql/tsutils/Maybe.d.ts b/types/graphql/tsutils/Maybe.d.ts new file mode 100644 index 0000000000..7ad0bc85a4 --- /dev/null +++ b/types/graphql/tsutils/Maybe.d.ts @@ -0,0 +1,4 @@ +// Conveniently represents flow's "Maybe" type https://flow.org/en/docs/types/maybe/ +type Maybe = null | undefined | T + +export default Maybe diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index ed87af50ad..b078acccb1 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { MaybePromise } from "../jsutils/MaybePromise"; import { ScalarTypeDefinitionNode, @@ -254,8 +255,8 @@ export type Thunk = (() => T) | T; */ export class GraphQLScalarType { name: string; - description: string | void; - astNode?: ScalarTypeDefinitionNode | void; + description: Maybe; + astNode?: Maybe; constructor(config: GraphQLScalarTypeConfig); // Serializes an internal value to include in a response. @@ -265,7 +266,7 @@ export class GraphQLScalarType { parseValue(value: any): any; // Parses an externally provided literal value to use as an input. - parseLiteral(valueNode: ValueNode, variables?: { [key: string]: any } | void): any; + parseLiteral(valueNode: ValueNode, variables?: Maybe<{ [key: string]: any }>): any; toString(): string; toJSON(): string; @@ -274,11 +275,11 @@ export class GraphQLScalarType { export interface GraphQLScalarTypeConfig { name: string; - description?: string | void; - astNode?: ScalarTypeDefinitionNode | void; - serialize(value: any): TExternal | void; - parseValue?(value: any): TInternal | void; - parseLiteral?(valueNode: ValueNode, variables: { [key: string]: any } | void): TInternal | void; + description?: Maybe; + astNode?: Maybe; + serialize(value: any): Maybe; + parseValue?(value: any): Maybe; + parseLiteral?(valueNode: ValueNode, variables: Maybe<{ [key: string]: any }>): Maybe; } /** @@ -320,10 +321,10 @@ export interface GraphQLScalarTypeConfig { */ export class GraphQLObjectType { name: string; - description: string | void; - astNode: ObjectTypeDefinitionNode | void; - extensionASTNodes: ReadonlyArray | void; - isTypeOf: GraphQLIsTypeOfFn | void; + description: Maybe; + astNode: Maybe; + extensionASTNodes: Maybe>; + isTypeOf: Maybe>; constructor(config: GraphQLObjectTypeConfig); getFields(): GraphQLFieldMap; @@ -335,19 +336,19 @@ export class GraphQLObjectType { export interface GraphQLObjectTypeConfig { name: string; - interfaces?: Thunk; + interfaces?: Thunk>; fields: Thunk>; - isTypeOf?: GraphQLIsTypeOfFn | void; - description?: string | void; - astNode?: ObjectTypeDefinitionNode | void; - extensionASTNodes?: ReadonlyArray | void; + isTypeOf?: Maybe>; + description?: Maybe; + astNode?: Maybe; + extensionASTNodes?: Maybe>; } export type GraphQLTypeResolver = ( value: TSource, context: TContext, info: GraphQLResolveInfo -) => MaybePromise; +) => MaybePromise>; export type GraphQLIsTypeOfFn = ( source: TSource, @@ -385,9 +386,9 @@ export interface GraphQLFieldConfig; subscribe?: GraphQLFieldResolver; - deprecationReason?: string | void; - description?: string | void; - astNode?: FieldDefinitionNode | void; + deprecationReason?: Maybe; + description?: Maybe; + astNode?: Maybe; } export type GraphQLFieldConfigArgumentMap = { [key: string]: GraphQLArgumentConfig }; @@ -395,8 +396,8 @@ export type GraphQLFieldConfigArgumentMap = { [key: string]: GraphQLArgumentConf export interface GraphQLArgumentConfig { type: GraphQLInputType; defaultValue?: any; - description?: string | void; - astNode?: InputValueDefinitionNode | void; + description?: Maybe; + astNode?: Maybe; } export type GraphQLFieldConfigMap = { @@ -405,22 +406,22 @@ export type GraphQLFieldConfigMap = { export interface GraphQLField { name: string; - description: string | void; + description: Maybe; type: GraphQLOutputType; args: GraphQLArgument[]; resolve?: GraphQLFieldResolver; subscribe?: GraphQLFieldResolver; isDeprecated?: boolean; - deprecationReason?: string | void; - astNode?: FieldDefinitionNode | void; + deprecationReason?: Maybe; + astNode?: Maybe; } export interface GraphQLArgument { name: string; type: GraphQLInputType; defaultValue?: any; - description?: string | void; - astNode?: InputValueDefinitionNode | void; + description?: Maybe; + astNode?: Maybe; } export type GraphQLFieldMap = { @@ -447,10 +448,10 @@ export type GraphQLFieldMap = { */ export class GraphQLInterfaceType { name: string; - description: string | void; - astNode?: InterfaceTypeDefinitionNode | void; - extensionASTNodes: ReadonlyArray | void; - resolveType: GraphQLTypeResolver | void; + description: Maybe; + astNode?: Maybe; + extensionASTNodes: Maybe>; + resolveType: Maybe>; constructor(config: GraphQLInterfaceTypeConfig); @@ -469,10 +470,10 @@ export interface GraphQLInterfaceTypeConfig { * the default implementation will call `isTypeOf` on each implementing * Object type. */ - resolveType?: GraphQLTypeResolver | void; - description?: string | void; - astNode?: InterfaceTypeDefinitionNode | void; - extensionASTNodes?: ReadonlyArray | void; + resolveType?: Maybe>; + description?: Maybe; + astNode?: Maybe; + extensionASTNodes?: Maybe>; } /** @@ -500,9 +501,9 @@ export interface GraphQLInterfaceTypeConfig { */ export class GraphQLUnionType { name: string; - description: string | void; - astNode?: UnionTypeDefinitionNode | void; - resolveType: GraphQLTypeResolver | void; + description: Maybe; + astNode?: Maybe; + resolveType: Maybe>; constructor(config: GraphQLUnionTypeConfig); @@ -521,9 +522,9 @@ export interface GraphQLUnionTypeConfig { * the default implementation will call `isTypeOf` on each implementing * Object type. */ - resolveType?: GraphQLTypeResolver | void; - description?: string | void; - astNode?: UnionTypeDefinitionNode | void; + resolveType?: Maybe>; + description?: Maybe; + astNode?: Maybe; } /** @@ -549,15 +550,15 @@ export interface GraphQLUnionTypeConfig { */ export class GraphQLEnumType { name: string; - description: string | void; - astNode: EnumTypeDefinitionNode | void; + description: Maybe; + astNode: Maybe; constructor(config: GraphQLEnumTypeConfig); getValues(): GraphQLEnumValue[]; - getValue(name: string): GraphQLEnumValue | void; - serialize(value: any): string | void; - parseValue(value: any): any; - parseLiteral(valueNode: ValueNode, _variables: { [key: string]: any } | void): any; + getValue(name: string): Maybe; + serialize(value: any): Maybe; + parseValue(value: any): Maybe; + parseLiteral(valueNode: ValueNode, _variables: Maybe<{ [key: string]: any }>): Maybe; toString(): string; toJSON(): string; inspect(): string; @@ -566,25 +567,25 @@ export class GraphQLEnumType { export interface GraphQLEnumTypeConfig { name: string; values: GraphQLEnumValueConfigMap; - description?: string | void; - astNode?: EnumTypeDefinitionNode | void; + description?: Maybe; + astNode?: Maybe; } export type GraphQLEnumValueConfigMap = { [key: string]: GraphQLEnumValueConfig }; export interface GraphQLEnumValueConfig { value?: any; - deprecationReason?: string | void; - description?: string | void; - astNode?: EnumValueDefinitionNode | void; + deprecationReason?: Maybe; + description?: Maybe; + astNode?: Maybe; } export interface GraphQLEnumValue { name: string; - description: string | void; + description: Maybe; isDeprecated?: boolean; - deprecationReason: string | void; - astNode?: EnumValueDefinitionNode | void; + deprecationReason: Maybe; + astNode?: Maybe; value: any; } @@ -610,8 +611,8 @@ export interface GraphQLEnumValue { */ export class GraphQLInputObjectType { name: string; - description: string | void; - astNode: InputObjectTypeDefinitionNode | void; + description: Maybe; + astNode: Maybe; constructor(config: GraphQLInputObjectTypeConfig); getFields(): GraphQLInputFieldMap; toString(): string; @@ -622,15 +623,15 @@ export class GraphQLInputObjectType { export interface GraphQLInputObjectTypeConfig { name: string; fields: Thunk; - description?: string | void; - astNode?: InputObjectTypeDefinitionNode | void; + description?: Maybe; + astNode?: Maybe; } export interface GraphQLInputFieldConfig { type: GraphQLInputType; defaultValue?: any; - description?: string | void; - astNode?: InputValueDefinitionNode | void; + description?: Maybe; + astNode?: Maybe; } export type GraphQLInputFieldConfigMap = { @@ -641,8 +642,8 @@ export interface GraphQLInputField { name: string; type: GraphQLInputType; defaultValue?: any; - description?: string | void; - astNode?: InputValueDefinitionNode | void; + description?: Maybe; + astNode?: Maybe; } export type GraphQLInputFieldMap = { [key: string]: GraphQLInputField }; diff --git a/types/graphql/type/directives.d.ts b/types/graphql/type/directives.d.ts index f6e19f674d..ca9e947640 100644 --- a/types/graphql/type/directives.d.ts +++ b/types/graphql/type/directives.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLFieldConfigArgumentMap, GraphQLArgument } from "./definition"; import { DirectiveDefinitionNode } from "../language/ast"; import { DirectiveLocationEnum } from "../language/directiveLocation"; @@ -13,20 +14,20 @@ export function isDirective(directive: any): directive is GraphQLDirective; */ export class GraphQLDirective { name: string; - description: string | void; + description: Maybe; locations: DirectiveLocationEnum[]; args: GraphQLArgument[]; - astNode: DirectiveDefinitionNode | void; + astNode: Maybe; constructor(config: GraphQLDirectiveConfig); } export interface GraphQLDirectiveConfig { name: string; - description?: string | void; + description?: Maybe; locations: DirectiveLocationEnum[]; - args?: GraphQLFieldConfigArgumentMap | void; - astNode?: DirectiveDefinitionNode | void; + args?: Maybe; + astNode?: Maybe; } /** diff --git a/types/graphql/type/schema.d.ts b/types/graphql/type/schema.d.ts index a7bb94f5c5..b5ddc9d8d4 100644 --- a/types/graphql/type/schema.d.ts +++ b/types/graphql/type/schema.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLObjectType } from "./definition"; import { GraphQLType, GraphQLNamedType, GraphQLAbstractType } from "./definition"; import { SchemaDefinitionNode } from "../language/ast"; @@ -35,21 +36,21 @@ export function isSchema(schema: any): schema is GraphQLSchema; * */ export class GraphQLSchema { - astNode: SchemaDefinitionNode | void; + astNode: Maybe; constructor(config: GraphQLSchemaConfig); - getQueryType(): GraphQLObjectType | void; - getMutationType(): GraphQLObjectType | void; - getSubscriptionType(): GraphQLObjectType | void; + getQueryType(): Maybe; + getMutationType(): Maybe; + getSubscriptionType(): Maybe; getTypeMap(): TypeMap; - getType(name: string): GraphQLNamedType | void; + getType(name: string): Maybe; getPossibleTypes(abstractType: GraphQLAbstractType): ReadonlyArray; isPossibleType(abstractType: GraphQLAbstractType, possibleType: GraphQLObjectType): boolean; getDirectives(): ReadonlyArray; - getDirective(name: string): GraphQLDirective | void; + getDirective(name: string): Maybe; } type TypeMap = { [key: string]: GraphQLNamedType }; @@ -72,14 +73,14 @@ export interface GraphQLSchemaValidationOptions { * This option is provided to ease adoption and may be removed in a future * major release. */ - allowedLegacyNames?: ReadonlyArray | void; + allowedLegacyNames?: Maybe>; } export interface GraphQLSchemaConfig extends GraphQLSchemaValidationOptions { - query: GraphQLObjectType | void; - mutation?: GraphQLObjectType | void; - subscription?: GraphQLObjectType | void; - types?: GraphQLNamedType[] | void; - directives?: GraphQLDirective[] | void; - astNode?: SchemaDefinitionNode | void; + query: Maybe; + mutation?: Maybe; + subscription?: Maybe; + types?: Maybe; + directives?: Maybe; + astNode?: Maybe; } diff --git a/types/graphql/utilities/TypeInfo.d.ts b/types/graphql/utilities/TypeInfo.d.ts index 1c2f139642..826704a52b 100644 --- a/types/graphql/utilities/TypeInfo.d.ts +++ b/types/graphql/utilities/TypeInfo.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLSchema } from "../type/schema"; import { GraphQLOutputType, @@ -28,14 +29,15 @@ export class TypeInfo { initialType?: GraphQLType ); - getType(): GraphQLOutputType | void; - getParentType(): GraphQLCompositeType | void; - getInputType(): GraphQLInputType | void; - getParentInputType(): GraphQLInputType | void; - getFieldDef(): GraphQLField | void; - getDirective(): GraphQLDirective | void; - getArgument(): GraphQLArgument | void; - getEnumValue(): GraphQLEnumValue | void; + getType(): Maybe; + getParentType(): Maybe; + getInputType(): Maybe; + getParentInputType(): Maybe; + getFieldDef(): GraphQLField>; + getDefaultValue(): Maybe; + getDirective(): Maybe; + getArgument(): Maybe; + getEnumValue(): Maybe; enter(node: ASTNode): any; leave(node: ASTNode): any; } @@ -44,4 +46,4 @@ type getFieldDef = ( schema: GraphQLSchema, parentType: GraphQLType, fieldNode: FieldNode -) => GraphQLField | void; +) => Maybe>; diff --git a/types/graphql/utilities/astFromValue.d.ts b/types/graphql/utilities/astFromValue.d.ts index 9c2198e6d6..e6c9f1ba6c 100644 --- a/types/graphql/utilities/astFromValue.d.ts +++ b/types/graphql/utilities/astFromValue.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { ValueNode } from "../language/ast"; import { GraphQLInputType } from "../type/definition"; @@ -18,4 +19,4 @@ import { GraphQLInputType } from "../type/definition"; * | null | NullValue | * */ -export function astFromValue(value: any, type: GraphQLInputType): ValueNode | void; +export function astFromValue(value: any, type: GraphQLInputType): Maybe; diff --git a/types/graphql/utilities/buildASTSchema.d.ts b/types/graphql/utilities/buildASTSchema.d.ts index ebff50b4f7..e2406c7ee1 100644 --- a/types/graphql/utilities/buildASTSchema.d.ts +++ b/types/graphql/utilities/buildASTSchema.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { DocumentNode, Location, @@ -47,7 +48,7 @@ type TypeDefinitionsMap = { [key: string]: TypeDefinitionNode }; type TypeResolver = (typeRef: NamedTypeNode) => GraphQLNamedType; export class ASTDefinitionBuilder { - constructor(typeDefinitionsMap: TypeDefinitionsMap, options: BuildSchemaOptions | void, resolveType: TypeResolver); + constructor(typeDefinitionsMap: TypeDefinitionsMap, options: Maybe, resolveType: TypeResolver); buildTypes(nodes: ReadonlyArray): Array; @@ -69,7 +70,7 @@ export class ASTDefinitionBuilder { */ export function getDescription( node: { readonly description?: StringValueNode; readonly loc?: Location }, - options: BuildSchemaOptions | void + options: Maybe ): string | undefined; /** diff --git a/types/graphql/utilities/getOperationAST.d.ts b/types/graphql/utilities/getOperationAST.d.ts index 81e9bd4cbe..a36cfa139c 100644 --- a/types/graphql/utilities/getOperationAST.d.ts +++ b/types/graphql/utilities/getOperationAST.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { DocumentNode, OperationDefinitionNode } from "../language/ast"; /** @@ -7,5 +8,5 @@ import { DocumentNode, OperationDefinitionNode } from "../language/ast"; */ export function getOperationAST( documentAST: DocumentNode, - operationName: string | void -): OperationDefinitionNode | void; + operationName: Maybe +): Maybe; diff --git a/types/graphql/utilities/introspectionQuery.d.ts b/types/graphql/utilities/introspectionQuery.d.ts index 750fe0d99c..f2172595f8 100644 --- a/types/graphql/utilities/introspectionQuery.d.ts +++ b/types/graphql/utilities/introspectionQuery.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { DirectiveLocationEnum } from "../language/directiveLocation"; export interface IntrospectionOptions { @@ -16,8 +17,8 @@ export interface IntrospectionQuery { export interface IntrospectionSchema { readonly queryType: IntrospectionNamedTypeRef; - readonly mutationType: IntrospectionNamedTypeRef | void; - readonly subscriptionType: IntrospectionNamedTypeRef | void; + readonly mutationType: Maybe>; + readonly subscriptionType: Maybe>; readonly types: ReadonlyArray; readonly directives: ReadonlyArray; } @@ -42,13 +43,13 @@ export type IntrospectionInputType = IntrospectionScalarType | IntrospectionEnum export interface IntrospectionScalarType { readonly kind: "SCALAR"; readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; } export interface IntrospectionObjectType { readonly kind: "OBJECT"; readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly fields: ReadonlyArray; readonly interfaces: ReadonlyArray>; } @@ -56,7 +57,7 @@ export interface IntrospectionObjectType { export interface IntrospectionInterfaceType { readonly kind: "INTERFACE"; readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly fields: ReadonlyArray; readonly possibleTypes: ReadonlyArray>; } @@ -64,21 +65,21 @@ export interface IntrospectionInterfaceType { export interface IntrospectionUnionType { readonly kind: "UNION"; readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly possibleTypes: ReadonlyArray>; } export interface IntrospectionEnumType { readonly kind: "ENUM"; readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly enumValues: ReadonlyArray; } export interface IntrospectionInputObjectType { readonly kind: "INPUT_OBJECT"; readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly inputFields: ReadonlyArray; } @@ -114,30 +115,30 @@ export interface IntrospectionNamedTypeRef; readonly args: ReadonlyArray; readonly type: IntrospectionOutputTypeRef; readonly isDeprecated: boolean; - readonly deprecationReason?: string | void; + readonly deprecationReason?: Maybe; } export interface IntrospectionInputValue { readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly type: IntrospectionInputTypeRef; - readonly defaultValue?: string | void; + readonly defaultValue?: Maybe; } export interface IntrospectionEnumValue { readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly isDeprecated: boolean; - readonly deprecationReason?: string | void; + readonly deprecationReason?: Maybe; } export interface IntrospectionDirective { readonly name: string; - readonly description?: string | void; + readonly description?: Maybe; readonly locations: ReadonlyArray; readonly args: ReadonlyArray; } diff --git a/types/graphql/utilities/valueFromAST.d.ts b/types/graphql/utilities/valueFromAST.d.ts index cd67108aad..c95eca9002 100644 --- a/types/graphql/utilities/valueFromAST.d.ts +++ b/types/graphql/utilities/valueFromAST.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLInputType } from "../type/definition"; import { ValueNode, VariableNode, ListValueNode, ObjectValueNode } from "../language/ast"; @@ -22,7 +23,7 @@ import { ValueNode, VariableNode, ListValueNode, ObjectValueNode } from "../lang * */ export function valueFromAST( - valueNode: ValueNode | void, + valueNode: Maybe, type: GraphQLInputType, - variables?: { [key: string]: any } | void + variables?: Maybe<{ [key: string]: any }> ): any; diff --git a/types/graphql/utilities/valueFromASTUntyped.d.ts b/types/graphql/utilities/valueFromASTUntyped.d.ts index 98d3137694..4ca58ca867 100644 --- a/types/graphql/utilities/valueFromASTUntyped.d.ts +++ b/types/graphql/utilities/valueFromASTUntyped.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { ValueNode } from "../language/ast"; /** @@ -16,4 +17,4 @@ import { ValueNode } from "../language/ast"; * | Null | null | * */ -export function valueFromASTUntyped(valueNode: ValueNode, variables?: { [key: string]: any } | void): any; +export function valueFromASTUntyped(valueNode: ValueNode, variables?: Maybe<{ [key: string]: any }>): any; diff --git a/types/graphql/validation/ValidationContext.d.ts b/types/graphql/validation/ValidationContext.d.ts index 0f8a4ea8f7..24049decdf 100644 --- a/types/graphql/validation/ValidationContext.d.ts +++ b/types/graphql/validation/ValidationContext.d.ts @@ -1,3 +1,4 @@ +import Maybe from "../tsutils/Maybe"; import { GraphQLError } from "../error"; import { DocumentNode, @@ -19,7 +20,11 @@ import { GraphQLDirective } from "../type/directives"; import { TypeInfo } from "../utilities/TypeInfo"; type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; -type VariableUsage = { node: VariableNode; type: GraphQLInputType | void }; +type VariableUsage = { + readonly node: VariableNode; + readonly type: Maybe; + readonly defaultValue: Maybe; +}; /** * An instance of this class is passed as the "this" context to all validators, @@ -37,7 +42,7 @@ export default class ValidationContext { getDocument(): DocumentNode; - getFragment(name: string): FragmentDefinitionNode | void; + getFragment(name: string): Maybe; getFragmentSpreads(node: SelectionSetNode): ReadonlyArray; @@ -47,17 +52,17 @@ export default class ValidationContext { getRecursiveVariableUsages(operation: OperationDefinitionNode): ReadonlyArray; - getType(): GraphQLOutputType | void; + getType(): Maybe; - getParentType(): GraphQLCompositeType | void; + getParentType(): Maybe; - getInputType(): GraphQLInputType | void; + getInputType(): Maybe; - getParentInputType(): GraphQLInputType | void; + getParentInputType(): Maybe; - getFieldDef(): GraphQLField | void; + getFieldDef(): Maybe>; - getDirective(): GraphQLDirective | void; + getDirective(): Maybe; - getArgument(): GraphQLArgument | void; + getArgument(): Maybe; } diff --git a/types/graphql/validation/rules/NoUndefinedVariables.d.ts b/types/graphql/validation/rules/NoUndefinedVariables.d.ts index 611ad01a9b..f340b41ad8 100644 --- a/types/graphql/validation/rules/NoUndefinedVariables.d.ts +++ b/types/graphql/validation/rules/NoUndefinedVariables.d.ts @@ -1,7 +1,8 @@ +import Maybe from "../../tsutils/Maybe"; import ValidationContext from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; -export function undefinedVarMessage(varName: string, opName: string | void): string; +export function undefinedVarMessage(varName: string, opName: Maybe): string; /** * No undefined variables diff --git a/types/graphql/validation/rules/NoUnusedVariables.d.ts b/types/graphql/validation/rules/NoUnusedVariables.d.ts index 10282cdacd..1846995a1f 100644 --- a/types/graphql/validation/rules/NoUnusedVariables.d.ts +++ b/types/graphql/validation/rules/NoUnusedVariables.d.ts @@ -1,7 +1,8 @@ +import Maybe from "../../tsutils/Maybe"; import ValidationContext from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; -export function unusedVariableMessage(varName: string, opName: string | void): string; +export function unusedVariableMessage(varName: string, opName: Maybe): string; /** * No unused variables diff --git a/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts b/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts index fef0869710..54b1fec36a 100644 --- a/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts +++ b/types/graphql/validation/rules/SingleFieldSubscriptions.d.ts @@ -1,7 +1,8 @@ +import Maybe from "../../tsutils/Maybe"; import ValidationContext from "../ValidationContext"; import { ASTVisitor } from "../../language/visitor"; -export function singleFieldOnlyMessage(name: string | void): string; +export function singleFieldOnlyMessage(name: Maybe): string; /** * Subscriptions must only include one field. diff --git a/types/gulp-svgmin/gulp-svgmin-tests.ts b/types/gulp-svgmin/gulp-svgmin-tests.ts new file mode 100644 index 0000000000..2d3d6e7e44 --- /dev/null +++ b/types/gulp-svgmin/gulp-svgmin-tests.ts @@ -0,0 +1,51 @@ +import svgmin = require("gulp-svgmin"); +import { basename, extname } from "path"; + +// From tests + +svgmin({ plugins: [] }); +svgmin({ plugins: [{ removeDoctype: false }] }); +svgmin({ plugins: [{ removeDoctype: false }, { removeComments: false }] }); + +// From examples given in README + +// $ExpectType Transform +svgmin(); + +// $ExpectType Transform +svgmin({ + plugins: [{ + removeDoctype: false + }, { + removeComments: false + }, { + cleanupNumericValues: { + floatPrecision: 2 + } + }, { + convertColors: { + names2hex: false, + rgb2hex: false + } + }] +}); + +// $ExpectType Transform +svgmin({ + js2svg: { + pretty: true + } +}); + +// $ExpectType Transform +svgmin(function getOptions(file) { + const prefix = basename(file.relative, extname(file.relative)); + return { + plugins: [{ + cleanupIDs: { + prefix: prefix + '-', + minify: true + } + }] + }; +}); diff --git a/types/gulp-svgmin/index.d.ts b/types/gulp-svgmin/index.d.ts new file mode 100644 index 0000000000..08c84bc930 --- /dev/null +++ b/types/gulp-svgmin/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for gulp-svgmin 1.2 +// Project: https://github.com/ben-eb/gulp-svgmin +// Definitions by: Aankhen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +// (required because svgo specifies 2.2) + +/// + +import SVGO = require("svgo"); +import { Transform } from "stream"; +import * as File from "vinyl"; + +export = GulpSvgmin; + +declare function GulpSvgmin(cb: (file: File) => SVGO.Options): Transform; +declare function GulpSvgmin(options?: SVGO.Options): Transform; diff --git a/types/gulp-svgmin/tsconfig.json b/types/gulp-svgmin/tsconfig.json new file mode 100644 index 0000000000..1d94db7181 --- /dev/null +++ b/types/gulp-svgmin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-svgmin-tests.ts" + ] +} diff --git a/types/gulp-svgmin/tslint.json b/types/gulp-svgmin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-svgmin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index f0730e6f67..d8edc40685 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -544,7 +544,7 @@ export interface Request extends Podium { * @return void * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) */ - setUrl(url: string | url.URL, stripTrailingSlash?: boolean): void; + setUrl(url: string | url.Url, stripTrailingSlash?: boolean): void; } /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/types/he/he-tests.ts b/types/he/he-tests.ts index 6045574fa5..3fce7214c9 100644 --- a/types/he/he-tests.ts +++ b/types/he/he-tests.ts @@ -2,18 +2,18 @@ import he = require('he'); function main() { var result: string; - + result = he.encode('foo \xa9 bar \u2260 baz qux'); // 'foo © bar ≠ baz qux' - + he.encode('foo \0 bar'); // 'foo \0 bar' - + // Passing an `options` object to `encode`, to explicitly disallow named references: he.encode('foo \xa9 bar \u2260 baz qux', { 'useNamedReferences': false }); - + he.encode('foo \xa9 bar \u2260 baz qux', { 'encodeEverything': true }); @@ -22,21 +22,43 @@ function main() { 'encodeEverything': true, 'useNamedReferences': true }); - + he.encode('\x01', { 'strict': false }); - // '' - + // '' + he.encode('foo © and & ampersand', { 'allowUnsafeSymbols': true }); - + + // Using the global default setting (defaults to `false`): + he.encode('foo © bar ≠ baz 𝌆 qux'); + // → 'foo © bar ≠ baz 𝌆 qux' + + // Passing an `options` object to `encode`, to explicitly disable decimal escapes: + he.encode('foo © bar ≠ baz 𝌆 qux', { + 'decimal': false + }); + // → 'foo © bar ≠ baz 𝌆 qux' + + // Passing an `options` object to `encode`, to explicitly enable decimal escapes: + he.encode('foo © bar ≠ baz 𝌆 qux', { + 'decimal': true + }); + // → 'foo © bar ≠ baz 𝌆 qux' + + // Passing an `options` object to `encode`, to explicitly allow named references and decimal escapes: + he.encode('foo © bar ≠ baz 𝌆 qux', { + 'useNamedReferences': true, + 'decimal': true + }); + // Override the global default setting: he.encode.options.useNamedReferences = true; - + he.decode('foo © bar ≠ baz 𝌆 qux'); - + he.decode('foo&bar', { 'isAttributeValue': false }); diff --git a/types/he/index.d.ts b/types/he/index.d.ts index a890ad823c..e729b6bbdc 100644 --- a/types/he/index.d.ts +++ b/types/he/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for he v0.5.0 +// Type definitions for he v1.1.1 // Project: https://github.com/mathiasbynens/he // Definitions by: Simon Edwards +// Robin Tregaskis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // he - "HTML Entities" - A high quality pair of HTML encode and decode functions. @@ -18,6 +19,18 @@ export interface EncodeOptions { */ useNamedReferences?: boolean; + /** + * The default value for the decimal option is false. If the option is + * enabled, encode will generally use decimal escapes (e.g. ©) + * rather than hexadecimal escapes (e.g. ©). Beside of this + * replacement, the basic behavior remains the same when combined with + * other options. For example: if both options useNamedReferences and + * decimal are enabled, named references (e.g. ©) are used over + * decimal escapes. HTML entities without a named reference are encoded + * using decimal escapes. + */ + decimal?: boolean; + /** * The default value for the encodeEverything option is false. This means * that encode() will not use any character references for printable ASCII diff --git a/types/hexo-log/hexo-log-tests.ts b/types/hexo-log/hexo-log-tests.ts index 9d0c263c03..a6fbcced57 100644 --- a/types/hexo-log/hexo-log-tests.ts +++ b/types/hexo-log/hexo-log-tests.ts @@ -1,90 +1,52 @@ -import mocha = require('mocha'); -import chai = require('chai'); -const should = chai.should(); -import rewire = require('rewire'); -import sinon = require('sinon'); import logger = require('hexo-log'); -const _c = logger(); -type HexoLogger = typeof _c; +declare function it(s: string, cb: () => void): void; -describe('hexo-log', () => { - const loggerModule = rewire<(options?: { name?: string; silent?: boolean; debug?: boolean; }) => HexoLogger>('./'); +it('add alias for levels', () => { + const log = logger(); - it('add alias for levels', () => { - const log = logger(); - - log.d.should.eql(log.debug); - log.i.should.eql(log.info); - log.w.should.eql(log.warn); - log.e.should.eql(log.error); - log.log.should.eql(log.info); - }); - - it('default name is hexo', () => { - const log = logger(); - - log.fields.name.should.eql('hexo'); - }); - - it('options.name', () => { - const log = logger({ name: 'foo' }); - - log.fields.name.should.eql('foo'); - }); - - it('level should be trace if options.debug is true', () => { - const log: any = logger({ debug: true }); - - log.streams[0].level.should.eql(10); - }); - - it('should add file stream if options.debug is true', () => { - const log: any = logger({ debug: true }); - - log.streams[1].path.should.eql('debug.log'); - }); - - it('should remove console stream if options.silent is true', () => { - const log: any = logger({ silent: true }); - - log.streams.length.should.eql(0); - }); - - it('should display time if options.debug is true', () => { - const spy = sinon.spy(); - const now = new Date(); - - loggerModule.__with__({ - process: { - stdout: { - write: spy - } - } - })(() => { - sinon.useFakeTimers(now.valueOf()); - const log = loggerModule({ debug: true }); - log.info('test'); - sinon.restore(undefined); - }); - - spy.args[0][0].should.contain(now.toISOString().substring(11, 23)); - }); - - it('should print error to process.stderr stream', () => { - const spy = sinon.spy(); - - loggerModule.__with__({ - process: { - stderr: { - write: spy - } - } - })(() => { - const log = loggerModule(); - log.error('test'); - }); - - spy.calledOnce.should.be.true; - }); + log.d === log.debug; + log.i === log.info; + log.w === log.warn; + log.e === log.error; + log.log === log.info; +}); + +it('default name is hexo', () => { + const log = logger(); + + log.fields.name === 'hexo'; +}); + +it('options.name', () => { + const log = logger({ name: 'foo' }); + log.fields === 'foo'; +}); + +it('level should be trace if options.debug is true', () => { + const log = logger({ debug: true }); + // TODO + // log.streams[0].level.should.eql(10); +}); + +it('should add file stream if options.debug is true', () => { + const log = logger({ debug: true }); + // TODO + // log.streams[1].path === 'debug.log'; +}); + +it('should remove console stream if options.silent is true', () => { + const log = logger({ silent: true }); + // TODO + // log.streams.length === 0; +}); + +it('should display time if options.debug is true', () => { + const log = logger({ debug: true }); + log.info('test'); +}); + +it('should print error to process.stderr stream', () => { + const log = logger(); + log.error('test'); }); diff --git a/types/http-proxy/http-proxy-tests.ts b/types/http-proxy/http-proxy-tests.ts index 70ea803da6..1610befc7d 100644 --- a/types/http-proxy/http-proxy-tests.ts +++ b/types/http-proxy/http-proxy-tests.ts @@ -24,3 +24,11 @@ proxy.on("start", (req, res, target) => { http.createServer((req, res) => { proxy.web(req, res); }); + +const newProxy = HttpProxy.createProxyServer({ + target: { + host: 'localhost', + port: '9015' + }, + ws: true +}); diff --git a/types/http-proxy/index.d.ts b/types/http-proxy/index.d.ts index e9ef9a572d..fb7eb26abc 100644 --- a/types/http-proxy/index.d.ts +++ b/types/http-proxy/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for node-http-proxy 1.16 // Project: https://github.com/nodejitsu/node-http-proxy -// Definitions by: Maxime LUCE , Florian Oellerich +// Definitions by: Maxime LUCE +// Florian Oellerich +// Daniel Schmidt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -166,9 +168,9 @@ declare namespace Server { /** Buffer */ buffer?: stream.Stream; /** URL string to be parsed with the url module. */ - target?: string; + target?: ProxyTargetUrl; /** URL string to be parsed with the url module. */ - forward?: string; + forward?: ProxyTargetUrl; /** Object to be passed to http(s).request. */ agent?: any; /** Object to be passed to https.createServer(). */ diff --git a/types/ibm_db/index.d.ts b/types/ibm_db/index.d.ts index 662a16ffb3..de54b9ca26 100644 --- a/types/ibm_db/index.d.ts +++ b/types/ibm_db/index.d.ts @@ -187,6 +187,9 @@ export class ODBCStatement { export class ODBCResult { fetchMode: number; + fetchAllSync(): any[]; + moreResultsSync(): any[]; + closeSync(): void; } // Class ODBCResult export function getElapsedTime(): string; diff --git a/types/ids/ids-tests.ts b/types/ids/ids-tests.ts deleted file mode 100644 index 16ba06e34f..0000000000 --- a/types/ids/ids-tests.ts +++ /dev/null @@ -1,9 +0,0 @@ -import Ids = require('ids'); - -const ids = new Ids(); - -const next = ids.next(); // returns id - -ids.claim('f71a81'); // claim id as already existing - -ids.assigned('f71a81'); // true if id was already generated / claimed diff --git a/types/ids/index.d.ts b/types/ids/index.d.ts deleted file mode 100644 index f744f77a5c..0000000000 --- a/types/ids/index.d.ts +++ /dev/null @@ -1,53 +0,0 @@ -// Type definitions for ids 0.2.0 -// Project: https://github.com/bpmn-io/ids -// Definitions by: Jan Steinbruecker -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = Ids; - -declare class Ids { - - /** - * Create a new id generator / cache instance. - * @param {number[]} [seed] a seed that is used internally. - */ - constructor(seed?: number[]); - - /** - * Returns true if the given id has already been assigned. - * @param {string} id - * @return {boolean} - */ - assigned(id: string): boolean; - - /** - * Manually claim an existing id. - * @param {string} id - * @param {*} [element] element the id is claimed by - */ - claim(id: string, element?: any): void; - - /** Clear all claimed ids. */ - clear(): void; - - /** - * Generate a next id. - * @param {*} [element] element to bind the id to - * @return {string} id - */ - next(element?: any): string; - - /** - * Generate a next id with a given prefix. - * @param {*} [element] element to bind the id to - * @return {string} id - */ - nextPrefixed(prefix: string, element?: any): string; - - /** - * Unclaim an id. - * @param {string} id - the id to unclaim - */ - unclaim(id: string): void; - -} diff --git a/types/idyll-ast/idyll-ast-tests.ts b/types/idyll-ast/idyll-ast-tests.ts new file mode 100644 index 0000000000..6b3eb7d651 --- /dev/null +++ b/types/idyll-ast/idyll-ast-tests.ts @@ -0,0 +1,99 @@ +import { AST, Property, TreeNode, Node } from "idyll-compiler"; + +import { + appendNode, + getNodesByName, + appendNodes, + prependNode, + prependNodes, + createNode, + getChildren, + walkNodes, + findNodes, + modifyChildren, + filterChildren, + filterNodes, + modifyNodesByName, + getProperty, + getProperties, + getPropertiesByType, + removeNodesByName, + setProperty, + setProperties, + removeProperty +} from "idyll-ast"; + +const ast: AST = [ + ["h2", [], []], + "world", + ["h1", [], ["child1", ["child2", [], []]]] +]; +const prop: Property = ["className", ["value", "hello"]]; + +// $ExpectType Node[] +appendNode(ast, "hello"); + +// $ExpectType Node[] +appendNode(getNodesByName(ast, "div"), "test"); + +// $ExpectType Node[] +appendNodes(ast, [["strong", [], ["div", ["pre", [], []]]], "test"]); + +// $ExpectType Node[] +prependNode(getNodesByName(ast, "div"), "test"); + +// $ExpectType Node[] +prependNodes(ast, [["strong", [], ["div", ["pre", [], []]]], "test"]); + +// $ExpectType TreeNode +createNode("div", { prop1: "prop1", prop2: ["expression", "x=2"] }, []); + +// $ExpectType Node[] +getChildren(ast[0]); + +// $ExpectType void +walkNodes(ast, (n: Node) => { + (n as TreeNode)[0] = "funky-name"; +}); + +// $ExpectType Node[] +findNodes(ast, n => n instanceof Array); + +// $ExpectType Node +modifyChildren(ast[0], (n: Node) => { + if (typeof n === "object") { + n[0] = "somename"; + } +}); +// $ExpectType Node[] +getNodesByName(ast, "h1"); + +// $ExpectType Node +filterChildren(ast[1], n => n === "world"); + +// $ExpectType Node[] +filterNodes(ast, n => (n instanceof Object ? n[0] === "h1" : false)); + +// $ExpectType Node[] +modifyNodesByName(ast, "h2", n => { + typeof n === "object" ? (n[1] = []) : undefined; +}); + +// $ExpectType [PropType, PropData] | null +getProperty(ast[1], "someProp"); +// $ExpectType [string, [PropType, PropData]] +getProperties(ast[1])[0]; +// $ExpectType [string, [PropType, PropData]][] +getPropertiesByType(["h1", [], []], "variable"); + +// $ExpectType Node[] +removeNodesByName(ast, "h1"); + +// $ExpectType Node +setProperty(ast[0], "prop", 9); + +// $ExpectType Node +setProperties(ast[1], { prop1: ["expression", "x"], prop2: 3 }); + +// $ExpectType Node +removeProperty(ast[0], "prop1"); diff --git a/types/idyll-ast/index.d.ts b/types/idyll-ast/index.d.ts new file mode 100644 index 0000000000..4a46320b82 --- /dev/null +++ b/types/idyll-ast/index.d.ts @@ -0,0 +1,137 @@ +// Type definitions for idyll-ast 1.3 +// Project: https://github.com/idyll-lang/idyll/tree/master/packages/idyll-ast +// Definitions by: Thanh Ngo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { + AST, + Node, + TreeNode, + PropValue, + Property, + PropType +} from "idyll-compiler"; + +/** + * appends a single node to the AST + */ +export function appendNode(ast: AST, node: Node): AST; +/** + * appends multiple nodes to the AST + */ +export function appendNodes(ast: AST, nodes: AST): AST; +/** + * creates a node + */ +export function createNode( + name: string, + props: Record, + children: Node[] +): TreeNode; +/** + * gets all children of the node if there is any + * returns an empty array if there is no child + */ +export function getChildren(node: Node): Node[]; +/** + * executes func against every node + */ +export function walkNodes(ast: AST | null, func: (n: Node) => void): void; +/** + * deeply walks the AST tree and returns all the nodes that satisfies the + * given filter + */ +export function findNodes(ast: AST, filter: (n: Node) => boolean): Node[]; +/** + * visits each child of the node and modifies them using the modifier + */ +export function modifyChildren(node: Node, modifier: (n: Node) => void): Node; +/** + * get all nodes by name + */ +export function getNodesByName(ast: AST, name: string): Node[]; +/** + * filters and returns the same node where all children + * satisfy the given filter + */ +export function filterChildren( + node: Node, + filter: (child: Node) => boolean +): Node; + +/** + * filters every node in the AST and returns a new AST whose nodes + * satisfy the given filter + */ +export function filterNodes(ast: AST, filter: (node: Node) => boolean): AST; + +/** + * applies the modifier against node whose name is the given name + * Returns a new ast with the modified nodes + * + * Names are case-insensitive + */ +export function modifyNodesByName( + ast: AST, + name: string, + modifier: (node: Node) => void +): AST; + +/** + * gets the node's property value + * + * returns null if node is a string node + */ +export function getProperty(node: Node, key: string): PropValue | null; + +/** + * returns all node's properties + * + * returns empty array if node is a string node + */ +export function getProperties(node: Node): Property[]; + +/** + * returns all properties having the given property's type + */ +export function getPropertiesByType(node: Node, type: PropType): Property[]; + +export function prependNode(ast: AST, node: Node): AST; +export function prependNodes(ast: AST, nodes: Node[]): AST; + +/** + * returns a new AST with nodes having the given name + * + * Names are case-insensitive + */ +export function removeNodesByName(ast: AST, name: string): AST; + +/** + * sets the property of the node + * + * if value is an array, the property's type is assumed to be included in it + * otherwise, "value" will be the property's type, and parameter value + * is the property's value + * + */ +export function setProperty( + node: Node, + key: string, + value: PropValue | PropValue[1] +): Node; + +/** + * sets the properties of the node + * + * also see setProperty() + */ +export function setProperties( + node: Node, + properties: Record +): Node; + +/** + * removes the node's property which has the given key + */ +export function removeProperty(node: Node, key: string): Node; diff --git a/types/idyll-ast/tsconfig.json b/types/idyll-ast/tsconfig.json new file mode 100644 index 0000000000..1e026c3377 --- /dev/null +++ b/types/idyll-ast/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "idyll-ast-tests.ts"] +} diff --git a/types/idyll-ast/tslint.json b/types/idyll-ast/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/idyll-ast/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/idyll-document/idyll-document-tests.ts b/types/idyll-document/idyll-document-tests.ts new file mode 100644 index 0000000000..880e017013 --- /dev/null +++ b/types/idyll-document/idyll-document-tests.ts @@ -0,0 +1,5 @@ +import IdyllDocument, { IdyllDocumentProps } from "idyll-document"; +import { createElement } from "react"; + +// $ExpectType ReactElement +createElement(IdyllDocument); diff --git a/types/idyll-document/index.d.ts b/types/idyll-document/index.d.ts new file mode 100644 index 0000000000..47ba1f7845 --- /dev/null +++ b/types/idyll-document/index.d.ts @@ -0,0 +1,62 @@ +// Type definitions for idyll-document 2.9 +// Project: https://github.com/idyll-lang/idyll/tree/master/packages/idyll-document +// Definitions by: Thanh Ngo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { PureComponent, ReactType } from "react"; +import { Options as CompilerOptions, AST } from "idyll-compiler"; + +export interface IdyllDocumentProps { + /** + * Components to be rendered with + */ + components: any; + /** + * the AST to be rendered on the page + * If provided, this will be used insteaed of + * the markup + */ + ast?: AST; + /** + * The Idyll markup to be compiled into AST + */ + markup?: string; + /** + * Initial data set + */ + datasets?: object; + + /** + * The theme for idyll document + * Will correspond to one theme in idyll-theme package + */ + theme?: string; + /** + * The layout for idyll document + * Will correspond to one one layout in idyll-layouts package + */ + layout?: string; + /** + * Callback function if error happens during compilation + */ + onError?: (err: Error) => void; + /** + * The React component rendered when an error occurs + */ + errorComponent?: ReactType<{ + className?: string; + children: Error["message"] | null; + }>; + /** + * Compiler option for Idyll compiler when compiling markup + */ + compilerOptions?: CompilerOptions; + + context?: (context: any) => void; + initialState?: any; +} + +declare class IdyllDocument extends PureComponent {} + +export default IdyllDocument; diff --git a/types/idyll-document/tsconfig.json b/types/idyll-document/tsconfig.json new file mode 100644 index 0000000000..6e3da4c990 --- /dev/null +++ b/types/idyll-document/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "idyll-document-tests.ts"] +} diff --git a/types/idyll-document/tslint.json b/types/idyll-document/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/idyll-document/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/idyll/idyll-tests.ts b/types/idyll/idyll-tests.ts new file mode 100644 index 0000000000..3f4b90c18c --- /dev/null +++ b/types/idyll/idyll-tests.ts @@ -0,0 +1,7 @@ +import idyll = require("idyll"); + +// $ExpectType IdyllInstance +idyll({ + watch: true, + datasets: "." +}); diff --git a/types/idyll/index.d.ts b/types/idyll/index.d.ts new file mode 100644 index 0000000000..a2f1846a7a --- /dev/null +++ b/types/idyll/index.d.ts @@ -0,0 +1,130 @@ +// Type definitions for idyll 2.10 +// Project: https://github.com/idyll-lang/idyll/tree/master/packages/idyll-cli +// Definitions by: Thanh Ngo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { EventEmitter } from "events"; +import { Options as CompilerOptions } from "idyll-compiler"; + +interface Options { + /** + * Monitor input files and rebuild on changes + */ + watch?: boolean; + /** + * The datasets directory + */ + datasets?: string; + /** + * Whether to minify output build + */ + minify?: boolean; + /** + * + * Pre-render HTML as part of the build + */ + ssr?: boolean; + /** + * The components directory + */ + components?: boolean; + /** + * The default component directory + * This corresponds to where the idyll-components package stays + */ + defaultComponents?: boolean; + /** + * The layout defined in idyll-layouts package + */ + layout?: string; + /** + * The theme defined in idyll-theme package + */ + theme?: string; + /** + * The output directory for compiled documents + */ + output?: string; + /** + * Custom port to bind the local server to. + */ + port?: number; + /** + * Temporary directory used by idyll + */ + temp?: string; + /** + * path to HTML template + * + */ + template?: string; + + /** + * Custom CSS file to include in output + */ + css?: string; + /** + * Custom browserify transforms to apply. + */ + transform?: string[]; + /** + * Compiler options + */ + compiler?: CompilerOptions; + /** + * the idyll file to be compiled into + */ + inputFile?: string; + + /** + * used internally by IdyllInstance + */ + inputConfig?: { + components: any; + transform: any[]; + compiler: CompilerOptions; + }; +} + +type PredefinedFile = + | "APP_PATH" + | "CSS_INPUT_FILE" + | "DATA_DIR" + | "HTML_TEMPLATE_FILE" + | "IDYLL_INPUT_FILE" + | "INPUT_DIR" + | "PACKAGE_FILE" + | "OUTPUT_DIR" + | "TMP_DIR" + | "CSS_OUTPUT_FILE" + | "HTML_OUTPUT_FILE" + | "JS_OUTPUT_FILE"; + +type ComponentFiles = "COMPONENT_DIRS" | "DEFAULT_COMPONENT_DIRS"; + +type Paths = Record & Record; + +declare class IdyllInstance extends EventEmitter { + /** + * Returns internal paths used by idyll-cli + */ + getPaths(): Paths; + /** + * Returns idyll compiling's options + */ + getOptions(): Options; + /** + * + * if indexIdyllMarkup is provided, compiles it + * + * Otherwise, compiles and optionally watches + * the idyll file at IOptions.inputFile + * + */ + build(indexIdyllMarkup?: string | null): this; +} + +declare function idyll(options: Options, callback?: () => void): IdyllInstance; + +export = idyll; diff --git a/types/idyll/tsconfig.json b/types/idyll/tsconfig.json new file mode 100644 index 0000000000..6e24200367 --- /dev/null +++ b/types/idyll/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "idyll-tests.ts"] +} diff --git a/types/idyll/tslint.json b/types/idyll/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/idyll/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/in-app-purchase/in-app-purchase-tests.ts b/types/in-app-purchase/in-app-purchase-tests.ts new file mode 100644 index 0000000000..4e142e53e2 --- /dev/null +++ b/types/in-app-purchase/in-app-purchase-tests.ts @@ -0,0 +1,38 @@ +import * as iap from 'in-app-purchase'; + +iap.config({ + /* Configurations for Amazon Store */ + amazonAPIVersion: 2, // tells the module to use API version 2 + secret: 'abcdefghijklmnoporstuvwxyz', // this comes from Amazon + + /* Configurations for Apple */ + applePassword: 'abcdefg...', // this comes from iTunes Connect (You need this to valiate subscriptions) + + /* Configurations for Google Play */ + googlePublicKeyPath: 'path/to/public/key/directory/', // this is the path to the directory containing iap-sanbox/iap-live files + googleAccToken: 'abcdef...', // optional, for Google Play subscriptions + googleRefToken: 'dddd...', // optional, for Google Play subscritions + clientId: 'aaaa', // optional, for Google Play subscriptions + clientSecret: 'bbbb', // optional, for Google Play subscriptions + refreshToken: 'cccc', // optional, for Google Play subscriptions + + /* Configurations for Roku */ + rokuApiKey: 'aaaa...', // this comes from Roku Developer Dashboard + + /* Configurations all platforms */ + test: true, // For Apple and Googl Play to force Sandbox validation only + verbose: true // Output debug logs to stdout stream +}); +iap.setup() + .then(() => iap.validate('abcdef')) + .then((validatedData) => { + const options = { + ignoreCanceled: true, // Apple ONLY (for now...): purchaseData will NOT contain cancceled items + ignoreExpired: true // purchaseData will NOT contain exipired subscription items + }; + + const purchaseData = iap.getPurchaseData(validatedData, options); + }) + .catch((error) => { + // error... + }); diff --git a/types/in-app-purchase/index.d.ts b/types/in-app-purchase/index.d.ts new file mode 100644 index 0000000000..b27daf2c20 --- /dev/null +++ b/types/in-app-purchase/index.d.ts @@ -0,0 +1,107 @@ +// Type definitions for in-app-purchase 1.9 +// Project: https://github.com/voltrue2/in-app-purchase#readme +// Definitions by: Jonas Lochmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export const UNITY = 'unity'; +export const APPLE = 'apple'; +export const GOOGLE = 'google'; +export const WINDOWS = 'windows'; +export const AMAZON = 'amazon'; +export const ROKU = 'roku'; + +export function config(params: Config): void; +export function setup(): Promise; +export function setup(callback: (err: any) => void): void; +export function getService(receipt: Receipt): Service; + +export function validate(receipt: Receipt): Promise; +export function validate(receipt: Receipt, callback: (err: any, res: ValidationResponse) => void): void; +export function validate(service: Service, receipt: Receipt, callback: (err: any, res: ValidationResponse) => void): void; + +export function validateOnce(receipt: Receipt, secretOrPubKey: any): Promise; +export function validateOnce(receipt: Receipt, secretOrPubKey: any, callback: (err: any, res: ValidationResponse) => void): void; +export function validateOnce(service: Service, secretOrPubKey: any, receipt: Receipt, callback: (err: any, res: ValidationResponse) => void): void; + +export function isValidated(response: ValidationResponse): boolean; +export function isExpired(item: PurchasedItem): boolean; +export function getPurchaseData(purchaseData?: ValidationResponse, options?: { + ignoreCanceled: boolean; + ignoreExpired: boolean; +}): PurchasedItem[] | null; + +export function refreshGoogleToken(): Promise; +export function refreshGoogleToken(callback: (err: any) => void): void; + +// for test use only, resets the google setup +export function reset(): void; + +export interface Config { + /* Configurations for Amazon Store */ + amazonAPIVersion?: number; + secret?: string; + + /* Configurations for Apple */ + + // this comes from iTunes Connect (You need this to valiate subscriptions) + applePassword?: string; + + /* Configurations for Google Play */ + // this is the path to the directory containing iap-sanbox/iap-live files + googlePublicKeyPath?: string; + // optional, for Google Play subscriptions + googleAccToken?: string; + // optional, for Google Play subscritions + googleRefToken?: string; + // optional, for Google Play subscriptions + clientId?: string; + // optional, for Google Play subscriptions + clientSecret?: string; + // optional, for Google Play subscriptions + refreshToken?: string; + + /* Configurations for Roku */ + // this comes from Roku Developer Dashboard + rokuApiKey?: string; + + /* Configurations all platforms */ + // For Apple and Googl Play to force Sandbox validation only + test?: boolean; + // Output debug logs to stdout stream + verbose?: boolean; +} + +export type Service = typeof UNITY | typeof APPLE | typeof GOOGLE | typeof WINDOWS | typeof AMAZON | typeof ROKU; + +export type UnityReceipt = object | string; +export type AppleReceipt = string; +export type GoogleReceipt = { + date: string; + signature: string; +} | string; +export type WindowsReceipt = string; +export type AmazonReceipt = object | string; +export type RokuReceipt = string; + +export type Receipt = UnityReceipt | AppleReceipt | GoogleReceipt | WindowsReceipt | AmazonReceipt | RokuReceipt; + +export interface ValidationResponse { + service: Service; + status: number; + // there are more fields depending on the used service +} + +export interface PurchasedItem { + bundleId?: string; // only Apple + orderId?: string; // only Google + transactionId: string; + productId: string; + purchaseDate: number; + // iTunes, windows and amazon subscription only + // Google subscriptions only with google play store api info + expirationDate?: number; + quantity: number; + // this was created based on the source code of in-app-purchase + // eventually there are more fields +} diff --git a/types/in-app-purchase/tsconfig.json b/types/in-app-purchase/tsconfig.json new file mode 100644 index 0000000000..7752182f8a --- /dev/null +++ b/types/in-app-purchase/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "in-app-purchase-tests.ts" + ] +} diff --git a/types/in-app-purchase/tslint.json b/types/in-app-purchase/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/in-app-purchase/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/intercom-client/index.d.ts b/types/intercom-client/index.d.ts new file mode 100644 index 0000000000..b68dc87e71 --- /dev/null +++ b/types/intercom-client/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for intercom-client 2.9 +// Project: https://github.com/intercom/intercom-node +// Definitions by: Jinesh Shah +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface IdentityVerificationOptions { + secretKey: string; + identifier: string; +} + +export const IdentityVerification: { + userHash(opts: IdentityVerificationOptions): string; +}; diff --git a/types/intercom-client/intercom-client-tests.ts b/types/intercom-client/intercom-client-tests.ts new file mode 100644 index 0000000000..e74dab4f53 --- /dev/null +++ b/types/intercom-client/intercom-client-tests.ts @@ -0,0 +1,3 @@ +import * as intercom from "intercom-client"; + +intercom.IdentityVerification.userHash({ secretKey: "", identifier: "" }); // $ExpectType string diff --git a/types/intercom-client/tsconfig.json b/types/intercom-client/tsconfig.json new file mode 100644 index 0000000000..a74d113775 --- /dev/null +++ b/types/intercom-client/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "intercom-client-tests.ts"] +} diff --git a/types/intercom-client/tslint.json b/types/intercom-client/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/intercom-client/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/intercom-web/index.d.ts b/types/intercom-web/index.d.ts index a0b4e71015..563d241c31 100755 --- a/types/intercom-web/index.d.ts +++ b/types/intercom-web/index.d.ts @@ -4,6 +4,7 @@ // customize-the-intercom-messenger/the-intercom-javascript-api // Definitions by: Andrew Fong // Samer Albahra +// Onat Yigit Mercan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Intercom_ { @@ -27,6 +28,8 @@ declare namespace Intercom_ { monthly_spend?: number, [index: string]: any; }; + vertical_padding?: number; + horizontal_padding?: number; } type IntercomCommand = 'boot' diff --git a/types/intercom-web/intercom-web-tests.ts b/types/intercom-web/intercom-web-tests.ts index 22eeddc8fa..b07013322d 100755 --- a/types/intercom-web/intercom-web-tests.ts +++ b/types/intercom-web/intercom-web-tests.ts @@ -60,3 +60,15 @@ intercomSettings = { user_id: "12345", user_hash: "775c502lcc1087d12398571837c" }; + +/* + From https://docs.intercom.com/configure-intercom-for-your-product-or-site/ + customize-the-intercom-messenger/ + customize-the-intercom-messenger-technical +*/ +intercomSettings = { + app_id: "pi3243fa", + alignment: "left", + horizontal_padding: 20, + vertical_padding: 20 +}; diff --git a/types/ip/index.d.ts b/types/ip/index.d.ts index 602a71eed9..c51a8d37f5 100644 --- a/types/ip/index.d.ts +++ b/types/ip/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Peter Harris // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface NodeBuffer { } +/// interface SubnetInfo { networkAddress: string; @@ -26,16 +26,16 @@ declare module "ip" { /** * Convert an IP string into a buffer. **/ - export function toBuffer(ip: string, buffer?: number, offset?: number): NodeBuffer; + export function toBuffer(ip: string, buffer?: number, offset?: number): Buffer; /** * Convert an IP buffer into a string. **/ - export function toString(ip: NodeBuffer, offset?: number, length?: number): string; + export function toString(ip: Buffer, offset?: number, length?: number): string; /** * Get the subnet mask from a CIDR prefix length. - * + * * @param family The IP family is infered from the prefixLength, but can be explicity specified as either "ipv4" or "ipv6". **/ export function fromPrefixLen(prefixLength: number, family?:string): string; @@ -79,15 +79,15 @@ declare module "ip" { * Check whether an IP is a IPv4 address. **/ export function isV4Format(ip: string): boolean; - + /** * Check whether an IP is a IPv6 address. **/ export function isV6Format(ip: string): boolean; - + /** * Get the loopback address for an IP family. - * + * * @param family The family can be either "ipv4" or "ipv6". Default: "ipv4". **/ export function loopback(family?: string): string; @@ -95,7 +95,7 @@ declare module "ip" { /** * Get the address for the network interface on the current system with the specified 'name'. * If no interface name is specified, the first IPv4 address or loopback address is returned. - * + * * @param name The name can be any named interface, or 'public' or 'private'. * @param family The family can be either "ipv4" or "ipv6". Default: "ipv4". **/ diff --git a/types/is/index.d.ts b/types/is/index.d.ts index 3b70472d65..37b485e0a0 100644 --- a/types/is/index.d.ts +++ b/types/is/index.d.ts @@ -87,6 +87,11 @@ interface IsStatic { */ undefined(value: any): boolean; + /** + * Checks if the given value type is defined. + */ + defined(value: any): boolean; + /** * Checks if the given value types are same type. */ @@ -748,6 +753,16 @@ interface IsStaticApi { */ undefined(value: any[]): boolean; + /** + * Checks if the given value type is defined. + */ + defined(...value: any[]): boolean; + + /** + * Checks if the given value type is defined. + */ + defined(value: any[]): boolean; + //#endregion //#region Presence checks diff --git a/types/is/is-tests.ts b/types/is/is-tests.ts index 0084de8990..77a88a81b3 100644 --- a/types/is/is-tests.ts +++ b/types/is/is-tests.ts @@ -104,6 +104,12 @@ is.all.undefined(undefined, 1); is.any.undefined(undefined, 2); is.all.undefined([{}, undefined]); +is.defined(undefined); +is.not.defined(null); +is.all.defined(undefined, 1); +is.any.defined(undefined, 2); +is.all.defined([{}, undefined]); + is.sameType(42, 7); is.sameType(42, '7'); is.not.sameType(42, 7); diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index f3e0407bab..cd1d5de31e 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -130,6 +130,7 @@ declare function waits(timeout?: number): void; declare namespace jasmine { type Expected = T | ObjectContaining | Any | Spy; + type SpyObjMethodNames = string[] | {[methodName: string]: any}; var clock: () => Clock; @@ -144,12 +145,11 @@ declare namespace jasmine { function objectContaining(sample: Partial): ObjectContaining; function createSpy(name?: string, originalFn?: Function): Spy; - function createSpyObj(baseName: string, methodNames: any[] | {[methodName: string]: any}): any; - function createSpyObj(baseName: string, methodNames: any[] | {[methodName: string]: any}): SpyObj; + function createSpyObj(baseName: string, methodNames: SpyObjMethodNames): any; + function createSpyObj(baseName: string, methodNames: SpyObjMethodNames): SpyObj; - function createSpyObj(baseName: string, methodNames: any): any; - function createSpyObj(methodNames: any[]): any; - function createSpyObj(methodNames: any): any; + function createSpyObj(methodNames: SpyObjMethodNames): any; + function createSpyObj(methodNames: SpyObjMethodNames): SpyObj; function pp(value: any): string; diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index b54269aa61..54e97ed73e 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -1109,7 +1109,17 @@ describe("createSpyObj", function () { expect(spyObj.method2.and.identity()).toEqual('BaseName.method2'); }); - it("should allow you to omit the baseName", function () { + it("should allow you to omit the baseName and takes only an object", function () { + var spyObj = jasmine.createSpyObj({ 'method1': 42, 'method2': 'special sauce' }); + + expect(spyObj.method1()).toEqual(42); + expect(spyObj.method1.and.identity()).toEqual('unknown.method1'); + + expect(spyObj.method2()).toEqual('special sauce'); + expect(spyObj.method2.and.identity()).toEqual('unknown.method2'); + }); + + it("should allow you to omit the baseName and takes only a list of methods", function () { var spyObj = jasmine.createSpyObj(['method1', 'method2']); expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function) }); @@ -1117,12 +1127,6 @@ describe("createSpyObj", function () { expect(spyObj.method2.and.identity()).toEqual('unknown.method2'); }); - it("should throw if you do not pass an array or object argument", function () { - expect(function () { - jasmine.createSpyObj('BaseName'); - }).toThrow("createSpyObj requires a non-empty array or object of method names to create spies for"); - }); - it("should throw if you pass an empty array argument", function () { expect(function () { jasmine.createSpyObj('BaseName', []); diff --git a/types/jest-axe/index.d.ts b/types/jest-axe/index.d.ts new file mode 100644 index 0000000000..f16f4e7651 --- /dev/null +++ b/types/jest-axe/index.d.ts @@ -0,0 +1,85 @@ +// Type definitions for jest-axe 2.2 +// Project: https://github.com/nickcolley/jest-axe +// Definitions by: Josh Goldberg +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +import { AxeResults, Result, RunOnly } from "axe-core"; + +/** + * Version of the aXe verifier with defaults set. + * + * @remarks You can still pass additional options to this new instance; + * they will be merged with the defaults. + */ +export const axe: JestAxe; + +/** + * Core options to run aXe. + */ +export interface AxeOptions { + elementRef?: boolean; + iframes?: boolean; + rules?: object; + runOnly?: RunOnly; + selectors?: boolean; +} + +/** + * Runs aXe on HTML. + * + * @param html Raw HTML string to verify with aXe. + * @param options Options to run aXe. + * @returns Promise for the results of running aXe. + */ +export type JestAxe = (html: string, options?: AxeOptions) => Promise; + +/** + * Creates a new aXe verifier function. + * + * @param options Options to run aXe. + * @returns New aXe verifier function. + */ +export function configureAxe(options?: AxeOptions): JestAxe; + +/** + * Results from asserting whether aXe verification passed. + */ +export interface AssertionsResult { + /** + * Actual checked aXe verification results. + */ + actual: Result[]; + + /** + * @returns Message from the Jest assertion. + */ + message(): string; + + /** + * Whether the assertion passed. + */ + pass: boolean; +} + +/** + * Asserts an aXe-verified result has no violations. + * + * @param results aXe verification result, if not running via expect(). + * @returns Jest expectations for the aXe result. + */ +export type IToHaveNoViolations = (results?: Partial) => AssertionsResult; + +export const toHaveNoViolations: { + toHaveNoViolations: IToHaveNoViolations; +}; + +declare global { + namespace jest { + interface Matchers { + toHaveNoViolations: IToHaveNoViolations; + } + } +} diff --git a/types/jest-axe/jest-axe-tests.ts b/types/jest-axe/jest-axe-tests.ts new file mode 100644 index 0000000000..38caeb88eb --- /dev/null +++ b/types/jest-axe/jest-axe-tests.ts @@ -0,0 +1,19 @@ +import { configureAxe, axe, toHaveNoViolations, JestAxe } from "jest-axe"; + +expect.extend(toHaveNoViolations); + +const newJestWithDefaults: JestAxe = configureAxe(); + +const newJestWithOptions: JestAxe = configureAxe({ + elementRef: false, + iframes: false, + rules: {}, + runOnly: { + type: "rules", + }, + selectors: false, +}); + +const sameJest: JestAxe = axe; + +expect("").toHaveNoViolations(); diff --git a/types/jest-axe/package.json b/types/jest-axe/package.json new file mode 100644 index 0000000000..d9427293a7 --- /dev/null +++ b/types/jest-axe/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "axe-core": "^2.6.1" + } +} diff --git a/types/jest-axe/tsconfig.json b/types/jest-axe/tsconfig.json new file mode 100644 index 0000000000..887813c869 --- /dev/null +++ b/types/jest-axe/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jest-axe-tests.ts" + ] +} diff --git a/types/jest-axe/tslint.json b/types/jest-axe/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jest-axe/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jquery-next-id/index.d.ts b/types/jquery-next-id/index.d.ts new file mode 100644 index 0000000000..bdb573dfa1 --- /dev/null +++ b/types/jquery-next-id/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for jquery-next-id 1.0 +// Project: https://github.com/makeup-jquery/jquery-next-id +// Definitions by: Anderson Friaça +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +export interface JQueryNextId { + (prefix?: string): JQuery; + + defaults: { + prefix: string; + separator: string; + }; +} + +declare global { + interface JQuery { + nextId: JQueryNextId; + } +} diff --git a/types/jquery-next-id/jquery-next-id-tests.ts b/types/jquery-next-id/jquery-next-id-tests.ts new file mode 100644 index 0000000000..663dfbabe3 --- /dev/null +++ b/types/jquery-next-id/jquery-next-id-tests.ts @@ -0,0 +1,6 @@ +$('div').nextId('my-prefix'); + +$.fn.nextId.defaults = { + prefix: 'id', + separator: '-' +}; diff --git a/types/jquery-next-id/tsconfig.json b/types/jquery-next-id/tsconfig.json new file mode 100644 index 0000000000..a8bd98da54 --- /dev/null +++ b/types/jquery-next-id/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "jquery-next-id-tests.ts" + ] +} \ No newline at end of file diff --git a/types/jquery-next-id/tslint.json b/types/jquery-next-id/tslint.json new file mode 100644 index 0000000000..d04fe2e1fa --- /dev/null +++ b/types/jquery-next-id/tslint.json @@ -0,0 +1 @@ +{"extends": "dtslint/dt.json"} \ No newline at end of file diff --git a/types/json3/index.d.ts b/types/json3/index.d.ts new file mode 100644 index 0000000000..768a76cf14 --- /dev/null +++ b/types/json3/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for json3 3.3 +// Project: https://bestiejs.github.io/json3/ +// Definitions by: NN +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var json3: JSON; +export = json3; diff --git a/types/json3/json3-tests.ts b/types/json3/json3-tests.ts new file mode 100644 index 0000000000..464f266509 --- /dev/null +++ b/types/json3/json3-tests.ts @@ -0,0 +1,5 @@ +import * as JSON3 from "json3"; + +const obj = JSON3.parse('{ "a" : { "b" : [1, 2] } }'); +const str = JSON3.stringify(obj, null, "\t"); +console.log(str); diff --git a/types/json3/tsconfig.json b/types/json3/tsconfig.json new file mode 100644 index 0000000000..4aa2789a30 --- /dev/null +++ b/types/json3/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "json3-tests.ts" + ] +} diff --git a/types/json3/tslint.json b/types/json3/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/json3/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/jsonic/index.d.ts b/types/jsonic/index.d.ts new file mode 100644 index 0000000000..610101b136 --- /dev/null +++ b/types/jsonic/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for jsonic 0.3 +// Project: https://github.com/rjrodger/jsonic +// Definitions by: Rong SHen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function jsonic(text: string): any; +declare namespace jsonic { + interface Options { + depth?: number; + maxitems?: number; + maxchars?: number; + omit?: string[]; + exclude?: string[]; + } + + function stringify(val: any, opts?: Options): string; +} + +export = jsonic; diff --git a/types/jsonic/jsonic-tests.ts b/types/jsonic/jsonic-tests.ts new file mode 100644 index 0000000000..fb0df5dd95 --- /dev/null +++ b/types/jsonic/jsonic-tests.ts @@ -0,0 +1,7 @@ +import * as jsonic from "jsonic"; + +jsonic("a:x, b:y z"); +jsonic.stringify( + { a: "a", b: "b", c: { c1: "c1" } }, + { depth: 1, omit: ["a"], exclude: ["b"] } +); diff --git a/types/jsonic/tsconfig.json b/types/jsonic/tsconfig.json new file mode 100644 index 0000000000..88bfd64ef6 --- /dev/null +++ b/types/jsonic/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "jsonic-tests.ts"] +} diff --git a/types/jsonic/tslint.json b/types/jsonic/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jsonic/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jwplayer/index.d.ts b/types/jwplayer/index.d.ts index 58c656956c..aee22c16f1 100644 --- a/types/jwplayer/index.d.ts +++ b/types/jwplayer/index.d.ts @@ -261,49 +261,181 @@ interface JWPlayer { load(playlist: any[]): void; load(playlist: string): void; on(event: 'adClick', callback: EventCallback): void; + once(event: 'adClick', callback: EventCallback): void; + off(event: 'adClick'): void; + trigger(event: 'adClick', args: AdProgressParam): void; on(event: 'adCompanions', callback: EventCallback): void; + once(event: 'adCompanions', callback: EventCallback): void; + off(event: 'adCompanions'): void; + trigger(event: 'adCompanions', args: AdCompanionsParam): void; on(event: 'adComplete', callback: EventCallback): void; + once(event: 'adComplete', callback: EventCallback): void; + off(event: 'adComplete'): void; + trigger(event: 'adComplete', args: AdProgressParam): void; on(event: 'adSkipped', callback: EventCallback): void; + once(event: 'adSkipped', callback: EventCallback): void; + off(event: 'adSkipped'): void; + trigger(event: 'adSkipped', args: AdProgressParam): void; on(event: 'adError', callback: EventCallback): void; + once(event: 'adError', callback: EventCallback): void; + off(event: 'adError'): void; + trigger(event: 'adError', args: AdErrorParam): void; on(event: 'adBlock', callback: () => void): void; + once(event: 'adBlock', callback: () => void): void; + off(event: 'adBlock'): void; + trigger(event: 'adBlock'): void; on(event: 'adRequest', callback: EventCallback): void; + once(event: 'adRequest', callback: EventCallback): void; + off(event: 'adRequest'): void; + trigger(event: 'adRequest', args: AdRequestParam): void; on(event: 'adStarted', callback: EventCallback): void; + once(event: 'adStarted', callback: EventCallback): void; + off(event: 'adStarted'): void; + trigger(event: 'adStarted', args: AdStartedParam): void; on(event: 'adImpression', callback: EventCallback): void; + once(event: 'adImpression', callback: EventCallback): void; + off(event: 'adImpression'): void; + trigger(event: 'adImpression', args: AdImpressionParam): void; on(event: 'adPlay', callback: EventCallback): void; + once(event: 'adPlay', callback: EventCallback): void; + off(event: 'adPlay'): void; + trigger(event: 'adPlay', args: AdPlayParam): void; on(event: 'adPause', callback: EventCallback): void; + once(event: 'adPause', callback: EventCallback): void; + off(event: 'adPause'): void; + trigger(event: 'adPause', args: AdPlayParam): void; on(event: 'adTime', callback: EventCallback): void; + once(event: 'adTime', callback: EventCallback): void; + off(event: 'adTime'): void; + trigger(event: 'adTime', args: AdTimeParam): void; on(event: 'meta', callback: EventCallback): void; + once(event: 'meta', callback: EventCallback): void; + off(event: 'meta'): void; + trigger(event: 'meta', args: MetadataParam): void; on(event: 'audioTracks', callback: EventCallback): void; + once(event: 'audioTracks', callback: EventCallback): void; + off(event: 'audioTracks'): void; + trigger(event: 'audioTracks', args: AudioTracksParam): void; on(event: 'audioTrackChanged', callback: EventCallback): void; + once(event: 'audioTrackChanged', callback: EventCallback): void; + off(event: 'audioTrackChanged'): void; + trigger(event: 'audioTrackChanged', args: AudioTrackChangedParam): void; on(event: 'beforeComplete', callback: () => void): void; + once(event: 'beforeComplete', callback: () => void): void; + off(event: 'beforeComplete'): void; + trigger(event: 'beforeComplete'): void; on(event: 'complete', callback: () => void): void; + once(event: 'complete', callback: () => void): void; + off(event: 'complete'): void; + trigger(event: 'complete'): void; on(event: 'firstFrame', callback: EventCallback): void; + once(event: 'firstFrame', callback: EventCallback): void; + off(event: 'firstFrame'): void; + trigger(event: 'firstFrame', args: FirstFrameParam): void; on(event: 'beforePlay', callback: () => void): void; + once(event: 'beforePlay', callback: () => void): void; + off(event: 'beforePlay'): void; + trigger(event: 'beforePlay'): void; on(event: 'buffer', callback: EventCallback): void; + once(event: 'buffer', callback: EventCallback): void; + off(event: 'buffer'): void; + trigger(event: 'buffer', args: BufferParam): void; on(event: 'bufferChange', callback: EventCallback): void; + once(event: 'bufferChange', callback: EventCallback): void; + off(event: 'bufferChange'): void; + trigger(event: 'bufferChange', args: BufferChangeParam): void; on(event: 'captionsChanged', callback: EventCallback): void; + once(event: 'captionsChanged', callback: EventCallback): void; + off(event: 'captionsChanged'): void; + trigger(event: 'captionsChanged', args: CaptionsChangedParam): void; on(event: 'captionsList', callback: EventCallback): void; + once(event: 'captionsList', callback: EventCallback): void; + off(event: 'captionsList'): void; + trigger(event: 'captionsList', args: CaptionsListParam): void; on(event: 'controls', callback: EventCallback): void; + once(event: 'controls', callback: EventCallback): void; + off(event: 'controls'): void; + trigger(event: 'controls', args: ControlsParam): void; on(event: 'displayClick', callback: () => void): void; + once(event: 'displayClick', callback: () => void): void; + off(event: 'displayClick'): void; + trigger(event: 'displayClick'): void; on(event: 'error', callback: EventCallback): void; + once(event: 'error', callback: EventCallback): void; + off(event: 'error'): void; + trigger(event: 'error', args: ErrorParam): void; on(event: 'fullscreen', callback: EventCallback): void; + once(event: 'fullscreen', callback: EventCallback): void; + off(event: 'fullscreen'): void; + trigger(event: 'fullscreen', args: FullscreenParam): void; on(event: 'idle', callback: EventCallback): void; + once(event: 'idle', callback: EventCallback): void; + off(event: 'idle'): void; + trigger(event: 'idle', args: IdleParam): void; on(event: 'levelsChanged', callback: EventCallback): void; + once(event: 'levelsChanged', callback: EventCallback): void; + off(event: 'levelsChanged'): void; + trigger(event: 'levelsChanged', args: LevelsChangedParam): void; on(event: 'mute', callback: EventCallback): void; + once(event: 'mute', callback: EventCallback): void; + off(event: 'mute'): void; + trigger(event: 'mute', args: MuteParam): void; on(event: 'volume', callback: EventCallback): void; + once(event: 'volume', callback: EventCallback): void; + off(event: 'volume'): void; + trigger(event: 'volume', args: VolumeParam): void; on(event: 'pause', callback: EventCallback): void; + once(event: 'pause', callback: EventCallback): void; + off(event: 'pause'): void; + trigger(event: 'pause', args: PlayParam): void; on(event: 'play', callback: EventCallback): void; + once(event: 'play', callback: EventCallback): void; + off(event: 'play'): void; + trigger(event: 'play', args: PlayParam): void; on(event: 'playlist', callback: EventCallback): void; + once(event: 'playlist', callback: EventCallback): void; + off(event: 'playlist'): void; + trigger(event: 'playlist', args: PlaylistParam): void; on(event: 'playlistItem', callback: EventCallback): void; + once(event: 'playlistItem', callback: EventCallback): void; + off(event: 'playlistItem'): void; + trigger(event: 'playlistItem', args: PlaylistItemParam): void; on(event: 'playlistComplete', callback: () => void): void; + once(event: 'playlistComplete', callback: () => void): void; + off(event: 'playlistComplete'): void; + trigger(event: 'playlistComplete'): void; on(event: 'ready', callback: EventCallback): void; + once(event: 'ready', callback: EventCallback): void; + off(event: 'ready'): void; + trigger(event: 'ready'): void; on(event: 'resize', callback: EventCallback): void; + once(event: 'resize', callback: EventCallback): void; + off(event: 'resize'): void; + trigger(event: 'resize', args: ResizeParam): void; on(event: 'visualQuality', callback: EventCallback): void; + once(event: 'visualQuality', callback: EventCallback): void; + off(event: 'visualQuality'): void; + trigger(event: 'visualQuality', args: VisualQualityParam): void; on(event: 'levels', callback: EventCallback): void; + once(event: 'levels', callback: EventCallback): void; + off(event: 'levels'): void; + trigger(event: 'levels', args: LevelsParam): void; on(event: 'seek', callback: EventCallback): void; + once(event: 'seek', callback: EventCallback): void; + off(event: 'seek'): void; + trigger(event: 'seek', args: SeekParam): void; on(event: 'setupError', callback: EventCallback): void; + once(event: 'setupError', callback: EventCallback): void; + off(event: 'setupError'): void; + trigger(event: 'setupError', args: ErrorParam): void; on(event: 'remove', callback: () => void): void; + once(event: 'remove', callback: () => void): void; + off(event: 'remove'): void; + trigger(event: 'remove'): void; on(event: 'time', callback: EventCallback): void; + once(event: 'time', callback: EventCallback): void; + off(event: 'time'): void; + trigger(event: 'time', args: TimeParam): void; pause(state?: boolean): void; play(state?: boolean): void; playAd(tag: string): void; diff --git a/types/keyv/index.d.ts b/types/keyv/index.d.ts index 9d0e2c6404..69e644c2d9 100644 --- a/types/keyv/index.d.ts +++ b/types/keyv/index.d.ts @@ -3,9 +3,7 @@ // Definitions by: AryloYeung // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 - /// - interface KeyvOptions { /** Namespace for the current instance. */ namespace?: string; @@ -35,6 +33,9 @@ declare class Keyv extends NodeJS.EventEmitter { * @param opts The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options. */ constructor(uri?: string, opts?: KeyvOptions); + /** Returns the namespace of a key */ + _getKeyPrefix(key: string): string; + /** Returns the value. */ get(key: string): Promise; /** @@ -42,7 +43,7 @@ declare class Keyv extends NodeJS.EventEmitter { * * By default keys are persistent. You can set an expiry TTL in milliseconds. */ - set(key: string, value: any, ttl?: number): Promise; + set(key: string, value: any, ttl?: number): (Promise | undefined); /** * Deletes an entry. * diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 90a700b7dc..624fde2d01 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -23,7 +23,7 @@ type ColumnName = string | Knex.Raw | Knex.QueryBuilder | {[key: string]: string type TableName = string | Knex.Raw | Knex.QueryBuilder; interface Knex extends Knex.QueryInterface { - (tableName?: string): Knex.QueryBuilder; + (tableName?: TableName): Knex.QueryBuilder; VERSION: string; __knex__: string; @@ -179,7 +179,7 @@ declare namespace Knex { } interface Table { - (tableName: string): QueryBuilder; + (tableName: TableName): QueryBuilder; (callback: Function): QueryBuilder; (raw: Raw): QueryBuilder; } @@ -269,8 +269,8 @@ declare namespace Knex { (callback: QueryCallback): QueryBuilder; (object: Object): QueryBuilder; (columnName: string, value: Value | null): QueryBuilder; - (columnName: string, operator: string, value: Value | null): QueryBuilder; - (columnName: string, operator: string, query: QueryBuilder): QueryBuilder; + (columnName: string, operator: string, value: Value | QueryBuilder | null): QueryBuilder; + (left: Raw, operator: string, right: Value | QueryBuilder | null): QueryBuilder; } interface WhereRaw extends RawQueryBuilder { diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index eaf186a186..9167ad3f77 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -206,6 +206,11 @@ knex('users').where('votes', '>', 100); knex('users').where('votes', null); knex('users').where('votes', 'is not', null); +// Using Raw in where +knex('users').where(knex.raw('votes + 1'), '>', 101); +knex('users').where(knex.raw('votes + 1'), '>', knex.raw('100 + 1')); +knex('users').where('votes', '>', knex.raw('100 + 1')); + var subquery = knex('users').where('votes', '>', 100).andWhere('status', 'active').orWhere('name', 'John').select('id'); knex('accounts').where('id', 'in', subquery); diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index d4031b2337..5076a05231 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -1,10 +1,10 @@ // Type definitions for Knockout v3.4.0 // Project: http://knockoutjs.com -// Definitions by: Boris Yankov , -// Igor Oleinikov , -// Clément Bourgeois , -// Matt Brooks , -// Benjamin Eckardt , +// Definitions by: Boris Yankov , +// Igor Oleinikov , +// Clément Bourgeois , +// Matt Brooks , +// Benjamin Eckardt , // Mathias Lorenzen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -150,10 +150,10 @@ interface KnockoutAllBindingsAccessor { has(name: string): boolean; } -interface KnockoutBindingHandler { +interface KnockoutBindingHandler { after?: Array; - init?: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => void | { controlsDescendantBindings: boolean; }; - update?: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => void; + init?: (element: E, valueAccessor: () => V, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: VM, bindingContext: KnockoutBindingContext) => void | { controlsDescendantBindings: boolean; }; + update?: (element: E, valueAccessor: () => V, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: VM, bindingContext: KnockoutBindingContext) => void; options?: any; preprocess?: (value: string, name: string, addBindingCallback?: (name: string, value: string) => void) => string; [s: string]: any; @@ -440,7 +440,7 @@ interface KnockoutStatic { contextFor(node: any): any; isSubscribable(instance: any): instance is KnockoutSubscribable; toJSON(viewModel: any, replacer?: Function, space?: any): string; - + toJS(viewModel: any): any; isObservable(instance: any): instance is KnockoutObservable; @@ -451,7 +451,7 @@ interface KnockoutStatic { isComputed(instance: any): instance is KnockoutComputed; isComputed(instance: KnockoutObservable | T): instance is KnockoutComputed; - + dataFor(node: any): any; removeNode(node: Node): void; cleanNode(node: Node): Node; diff --git a/types/knockout/test/index.ts b/types/knockout/test/index.ts index a106d7af9b..38f439efb7 100644 --- a/types/knockout/test/index.ts +++ b/types/knockout/test/index.ts @@ -192,7 +192,7 @@ function test_bindings() { var value = ko.utils.unwrapObservable(valueAccessor()); $(element).toggle(value); } - }; + } as KnockoutBindingHandler | boolean>; ko.bindingHandlers.hasFocus = { init: function (element, valueAccessor) { $(element).focus(function () { @@ -211,7 +211,7 @@ function test_bindings() { else element.blur(); } - }; + } as KnockoutBindingHandler>; ko.bindingHandlers.allowBindings = { init: function (elem, valueAccessor) { var shouldAllowBindings = ko.utils.unwrapObservable(valueAccessor()); @@ -749,4 +749,4 @@ interface MyObservableArray extends KnockoutObservableArray { interface MyComputed extends KnockoutComputed { isBeautiful?: boolean; -} \ No newline at end of file +} diff --git a/types/koa-response-time/index.d.ts b/types/koa-response-time/index.d.ts new file mode 100644 index 0000000000..17c3525682 --- /dev/null +++ b/types/koa-response-time/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for koa-response-time 2.0 +// Project: https://github.com/koajs/response-time#readme +// Definitions by: Thor Sedeke +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +declare function koa_response_time(): any; +export = koa_response_time; diff --git a/types/koa-response-time/koa-response-time-tests.ts b/types/koa-response-time/koa-response-time-tests.ts new file mode 100644 index 0000000000..6b35c60f9a --- /dev/null +++ b/types/koa-response-time/koa-response-time-tests.ts @@ -0,0 +1,4 @@ +import koaResponseTime = require('koa-response-time'); +import Koa = require('koa'); + +new Koa().use(koaResponseTime()); diff --git a/types/koa-response-time/tsconfig.json b/types/koa-response-time/tsconfig.json new file mode 100644 index 0000000000..cd6c50be36 --- /dev/null +++ b/types/koa-response-time/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-response-time-tests.ts" + ] +} diff --git a/types/koa-response-time/tslint.json b/types/koa-response-time/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-response-time/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/leaflet-draw/index.d.ts b/types/leaflet-draw/index.d.ts index 62025a7c46..b431cf04ba 100644 --- a/types/leaflet-draw/index.d.ts +++ b/types/leaflet-draw/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Matt Guest // Ryan Blace // Yun Shi +// Kevin Richter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -13,6 +14,63 @@ declare module 'leaflet' { drawControl?: boolean; } + interface ToolbarAction { + title: string; + text: string; + callback: () => void; + context: object; + } + + interface ToolbarModeHandler { + enabled: boolean; + handler: Handler; + title: string; + } + + interface ToolbarOptions { + polyline?: DrawOptions.PolylineOptions; + polygon?: DrawOptions.PolygonOptions; + rectangle?: DrawOptions.RectangleOptions; + circle?: DrawOptions.CircleOptions; + marker?: DrawOptions.MarkerOptions; + circlemarker?: DrawOptions.CircleOptions; + } + + interface PrecisionOptions { + km?: number; + ha?: number; + m?: number; + mi?: number; + ac?: number; + yd?: number; + ft?: number; + nm?: number; + } + + class Toolbar extends Class { + constructor(options?: ToolbarOptions); + + addToolbar(map: Map): HTMLElement | void; + + removeToolbar(): void; + } + + class DrawToolbar extends Toolbar { + getModeHandlers(map: Map): ToolbarModeHandler[]; + + getActions(handler: Draw.Feature): ToolbarAction[]; + + setOptions(options: Control.DrawConstructorOptions): void; + } + + class EditToolbar extends Toolbar { + getModeHandlers(map: Map): ToolbarModeHandler[]; + + getActions(handler: Draw.Feature): ToolbarAction[]; + + setOptions(options: Control.DrawConstructorOptions): void; + } + namespace Control { interface DrawConstructorOptions { /** @@ -30,9 +88,9 @@ declare module 'leaflet' { draw?: DrawOptions; /** - * The options used to configure the edit toolbar. + * The options used to configure the edit toolbar. * - * Default value: false + * Default value: false */ edit?: EditOptions; } @@ -41,42 +99,42 @@ declare module 'leaflet' { /** * Polyline draw handler options. Set to false to disable handler. * - * Default value: {} + * Default value: {} */ polyline?: DrawOptions.PolylineOptions | false; /** * Polygon draw handler options. Set to false to disable handler. * - * Default value: {} + * Default value: {} */ polygon?: DrawOptions.PolygonOptions | false; /** * Rectangle draw handler options. Set to false to disable handler. * - * Default value: {} + * Default value: {} */ rectangle?: DrawOptions.RectangleOptions | false; /** * Circle draw handler options. Set to false to disable handler. * - * Default value: {} + * Default value: {} */ circle?: DrawOptions.CircleOptions | false; /** * Circle marker draw handler options. Set to false to disable handler. * - * Default value: {} + * Default value: {} */ circlemarker?: DrawOptions.CircleMarkerOptions | false; /** * Marker draw handler options. Set to false to disable handler. * - * Default value: {} + * Default value: {} */ marker?: DrawOptions.MarkerOptions | false; } @@ -115,6 +173,15 @@ declare module 'leaflet' { } namespace DrawOptions { + interface SimpleShapeOptions { + /** + * Determines if the draw tool remains enabled after drawing a shape. + * + * Default value: false + */ + repeatMode?: boolean; + } + interface PolylineOptions { /** * Determines if line segments can cross. @@ -123,12 +190,23 @@ declare module 'leaflet' { */ allowIntersection?: boolean; + /** + * Determines if the draw tool remains enabled after drawing a shape. + * + * Default value: false + */ + repeatMode?: boolean; + /** * Configuration options for the error that displays if an intersection is detected. * * Default value: See code */ - drawError?: any; + drawError?: DrawErrorOptions; + + icon?: Icon | DivIcon; + + touchIcon?: Icon | DivIcon; /** * Distance in pixels between each guide dash. @@ -137,12 +215,19 @@ declare module 'leaflet' { */ guidelineDistance?: number; + /** + * The maximum length of the guide line + * + * Default value: 4000 + */ + maxGuideLineLength?: number; + /** * The options used when drawing the polyline/polygon on the map. * * Default value: See code */ - shapeOptions?: L.PolylineOptions; + shapeOptions?: PathOptions; /** * Determines which measurement system (metric or imperial) is used. @@ -152,18 +237,46 @@ declare module 'leaflet' { metric?: boolean; /** - * This should be a high number to ensure that you can draw over all other layers on the map. + * When not metric, to use feet instead of yards for display. + * + * Default value: true + */ + feet?: boolean; + + /** + * When not metric, not feet use nautic mile for display + * + * Default value: false + */ + nautic?: boolean; + + /** + * Whether to display distance in the tooltip + * + * Default value: true + */ + showLength?: boolean; + + /** + * This should be a high number to ensure that you can draw over all other layers on the map. * * Default value: 2000 */ zIndexOffset?: number; /** - * Determines if the draw tool remains enabled after drawing a shape. + * To change distance calculation * - * Default value: false + * Default value: 1 */ - repeatMode?: boolean; + factor?: number; + + /** + * Once this number of points are placed, finish shape + * + * Default value: 0 + */ + maxPoints?: number; } interface PolygonOptions extends PolylineOptions { @@ -174,9 +287,16 @@ declare module 'leaflet' { * Default value: false */ showArea?: boolean; + + /** + * Defines the precision for each type of unit (e.g. {km: 2, ft: 0} + * + * Default value: {} + */ + precision?: PrecisionOptions; } - interface RectangleOptions { + interface RectangleOptions extends SimpleShapeOptions { /** * The options used when drawing the rectangle on the map. * @@ -185,14 +305,14 @@ declare module 'leaflet' { shapeOptions?: PathOptions; /** - * Determines if the draw tool remains enabled after drawing a shape. + * Whether to use the metric measurement system or imperial * - * Default value: false + * Default value: true */ - repeatMode?: boolean; + metric?: boolean; } - interface CircleOptions { + interface CircleOptions extends SimpleShapeOptions { /** * The options used when drawing the circle on the map. * @@ -201,11 +321,32 @@ declare module 'leaflet' { shapeOptions?: PathOptions; /** - * Determines if the draw tool remains enabled after drawing a shape. + * Whether to show the radius in the tooltip + * + * Default value: true + */ + showRadius?: boolean; + + /** + * Whether to use the metric measurement system or imperial + * + * Default value: true + */ + metric?: boolean; + + /** + * When not metric, use feet instead of yards for display + * + * Default value: true + */ + feet?: boolean; + + /** + * When not metric, not feet use nautic mile for display * * Default value: false */ - repeatMode?: boolean; + nautic?: boolean; } interface CircleMarkerOptions { @@ -308,6 +449,11 @@ declare module 'leaflet' { interface DeleteHandlerOptions { } + + interface DrawErrorOptions { + color?: string; + timeout?: number; + } } namespace Draw { @@ -325,6 +471,9 @@ declare module 'leaflet' { const EDITSTOP: string; const DELETESTART: string; const DELETESTOP: string; + const TOOLBAROPENED: string; + const TOOLBARCLOSED: string; + const TOOLBARCONTEXT: string; } class Feature extends Handler { @@ -338,7 +487,9 @@ declare module 'leaflet' { ): void; } - class SimpleShape extends Feature { } + class SimpleShape extends Feature { + } + class Marker extends Feature { constructor( map: Map, @@ -346,14 +497,14 @@ declare module 'leaflet' { ) } - class CircleMarker extends Feature { + class CircleMarker extends Marker { constructor( map: Map, options?: DrawOptions.MarkerOptions ) } - class Circle extends Feature { + class Circle extends SimpleShape { constructor( map: Map, options?: DrawOptions.CircleOptions @@ -365,21 +516,41 @@ declare module 'leaflet' { map: Map, options?: DrawOptions.PolylineOptions ) + + deleteLastVertex(): void; + + addVertex(latlng: LatLng): void; + + completeShape(): void; } - class Rectangle extends Feature { + class Rectangle extends SimpleShape { constructor( map: Map, options?: DrawOptions.RectangleOptions ) } - class Polygon extends Feature { + class Polygon extends Polyline { constructor( map: Map, options?: DrawOptions.PolygonOptions ) } + + class Tooltip extends Class { + constructor(map: Map); + + dispose(): void; + + updateContent(labelText?: { text: string, subtext?: string }): Tooltip; + + updatePosition(latlng: LatLng): Tooltip; + + showAsError(): Tooltip; + + removeError(): Tooltip; + } } namespace DrawEvents { @@ -426,6 +597,13 @@ declare module 'leaflet' { layerType: string; } + interface DrawVertex extends Event { + /** + * List of all layers just being added from the map. + */ + layers: LayerGroup; + } + interface EditStart extends Event { /** * The type of edit this is. One of: edit @@ -433,6 +611,29 @@ declare module 'leaflet' { handler: string; } + interface EditMove extends Event { + /** + * Layer that was just moved. + */ + layer: Layer; + } + + interface EditResize extends Event { + /** + * Layer that was just resized. + */ + layer: Layer; + } + + interface EditVertex extends Event { + /** + * List of all layers just being edited from the map. + */ + layers: LayerGroup; + + poly: Polyline | Polygon; + } + interface EditStop extends Event { /** * The type of edit this is. One of: edit @@ -453,6 +654,15 @@ declare module 'leaflet' { */ handler: string; } + + interface ToolbarOpened extends Event { + } + + interface ToolbarClosed extends Event { + } + + interface MarkerContext extends Event { + } } namespace GeometryUtil { @@ -461,9 +671,105 @@ declare module 'leaflet' { */ function geodesicArea(coordinates: LatLngLiteral[]): number; + /** + * Returns n in specified number format (if defined) and precision + */ + function formattedNumber(n: string, precision: number): string; + /** * Returns a readable area string in yards or metric */ - function readableArea(area: number, isMetric: boolean): string; + function readableArea(area: number, isMetric?: boolean, precision?: PrecisionOptions): string; + + /** + * Converts metric distance to distance string. + * The value will be rounded as defined by the precision option object. + */ + function readableDistance(distance: number, isMetric?: boolean, isFeet?: boolean, isNauticalMile?: boolean, precision?: PrecisionOptions): string; + + /** + * Returns true if the Leaflet version is 0.7.x, false otherwise. + */ + function isVersion07x(): boolean; + } + + namespace LatLngUtil { + /** + * Clone the latLng point or points or nested points and return an array with those points + */ + function cloneLatLngs(latlngs: LatLng[]): LatLng[][]; + + /** + * Clone the latLng and return a new LatLng object. + */ + function cloneLatLng(latlng: LatLng): LatLng; + } + + namespace EditToolbar { + class Edit extends Toolbar { + constructor(map: Map, options?: ToolbarOptions); + + revertLayers(): void; + + save(): void; + } + + class Delete extends Toolbar { + constructor(map: Map, options?: ToolbarOptions); + + revertLayers(): void; + + save(): void; + + removeAllLayers(): void; + } + } + + namespace EditOptions { + interface EditPolyVerticesEditOptions { + icon?: Icon | DivIcon; + touchIcon?: Icon | DivIcon; + drawError?: DrawOptions.DrawErrorOptions; + } + + interface EditSimpleShapeOptions { + moveIcon?: Icon | DivIcon; + resizeIcon?: Icon | DivIcon; + touchMoveIcon?: Icon | DivIcon; + touchResizeIcon?: Icon | DivIcon; + } + } + + namespace Edit { + class Circle extends CircleMarker { + } + + class CircleMarker extends SimpleShape { + } + + class Marker extends Handler { + constructor(marker: Marker, options?: object); + } + + class Poly extends Handler { + constructor(poly: Draw.Polyline); + + updateMarkers(): void; + } + + class PolyVerticesEdit extends Handler { + constructor(poly: Poly, latlngs: LatLngExpression[], options?: EditOptions.EditPolyVerticesEditOptions); + + updateMarkers(): void; + } + + class Rectangle extends SimpleShape { + } + + class SimpleShape extends Handler { + constructor(shape: SimpleShape, options?: EditOptions.EditSimpleShapeOptions); + + updateMarkers(): void; + } } } diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index f878e2b2bd..ece34d0938 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -26,21 +26,13 @@ declare namespace mapboxgl { constructor(options?: MapboxOptions); addControl(control: Control, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; - + addControl(control: IControl, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; removeControl(control: Control): this; - + removeControl(control: IControl): this; - addClass(klass: string, options?: mapboxgl.StyleOptions): this; - - removeClass(klass: string, options?: mapboxgl.StyleOptions): this; - - setClasses(klasses: string[], options?: mapboxgl.StyleOptions): this; - - hasClass(klass: string): boolean; - getClasses(): string[]; resize(): this; @@ -413,6 +405,7 @@ declare namespace mapboxgl { */ export class GeolocateControl extends Control { constructor(options?: { positionOptions?: PositionOptions, fitBoundsOptions?: FitBoundsOptions, trackUserLocation?: boolean, showUserLocation?: boolean }); + trigger(): boolean; } /** @@ -1103,6 +1096,7 @@ declare namespace mapboxgl { 'circle-color'?: string | StyleFunction | Expression; 'circle-blur'?: number | StyleFunction | Expression; 'circle-opacity'?: number | StyleFunction | Expression; + 'circle-opacity-transition'?: Transition; 'circle-translate'?: number[] | Expression; 'circle-translate-anchor'?: 'map' | 'viewport'; 'circle-pitch-scale'?: 'map' | 'viewport'; diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 307ce84115..2d8631eb22 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for material-ui 0.21 +// Type definitions for material-ui 0.20 // Project: https://github.com/callemall/material-ui // Definitions by: Nathan Brown // Igor Beagorudsky diff --git a/types/materialize-css/autocomplete.d.ts b/types/materialize-css/autocomplete.d.ts new file mode 100644 index 0000000000..83eae14bfb --- /dev/null +++ b/types/materialize-css/autocomplete.d.ts @@ -0,0 +1,88 @@ +/// + +declare namespace M { + class Autocomplete extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Autocomplete; + + /** + * Init autocomplete + */ + static init(els: Element, options?: Partial): Autocomplete; + + /** + * Init autocompletes + */ + static init(els: MElements, options?: Partial): Autocomplete[]; + + /** + * Select a specific autocomplete options. + * @param el Element of the autocomplete option. + */ + selectOption(el: Element): void; + + /** + * Update autocomplete options data. + * @param data Autocomplete options data object. + */ + updateData(data: AutocompleteData): void; + + /** + * If the autocomplete is open. + */ + isOpen: boolean; + + /** + * Number of matching autocomplete options. + */ + count: number; + + /** + * Index of the current selected option. + */ + activeIndex: number; + } + + interface AutocompleteData { + [key: string]: string | null; + } + + interface AutocompleteOptions { + /** + * Data object defining autocomplete options with optional icon strings. + */ + data: AutocompleteData; + + /** + * Limit of results the autocomplete shows. + * @default infinity + */ + limit: number; + + /** + * Callback for when autocompleted. + */ + onAutocomplete: (this: Autocomplete, text: string) => void; + + /** + * Minimum number of characters before autocomplete starts. + * @default 1 + */ + minLength: number; + + /** + * Sort function that defines the order of the list of autocomplete options. + */ + sortFunction: (a: string, b: string, inputText: string) => number; + } +} + +interface JQuery { + // Pick to check methods exist. + autocomplete(method: keyof Pick): JQuery; + autocomplete(method: keyof Pick, el: Element): JQuery; + autocomplete(method: keyof Pick, data: M.AutocompleteData): JQuery; + autocomplete(options?: Partial): JQuery; +} diff --git a/types/materialize-css/carousel.d.ts b/types/materialize-css/carousel.d.ts new file mode 100644 index 0000000000..fd660694d1 --- /dev/null +++ b/types/materialize-css/carousel.d.ts @@ -0,0 +1,117 @@ +/// + +declare namespace M { + class Carousel extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Carousel; + + /** + * Init carousel + */ + static init(els: Element, options?: Partial): Carousel; + + /** + * Init carousels + */ + static init(els: MElements, options?: Partial): Carousel[]; + + /** + * If the carousel is being clicked or tapped + */ + pressed: boolean; + + /** + * If the carousel is currently being dragged + */ + dragged: number; + + /** + * The index of the center carousel item + */ + center: number; + + /** + * Move carousel to next slide or go forward a given amount of slides + * @param n How many times the carousel slides + */ + next(n?: number): void; + + /** + * Move carousel to previous slide or go back a given amount of slides + * @param n How many times the carousel slides + */ + prev(n?: number): void; + + /** + * Move carousel to nth slide + * @param n Index of slide + */ + set(n?: number): void; + } + + interface CarouselOptions { + /** + * Transition duration in milliseconds + * @default 200 + */ + duration: number; + + /** + * Perspective zoom. If 0, all items are the same size + * @default -100 + */ + dist: number; + + /** + * Set the spacing of the center item + * @default 0 + */ + shift: number; + + /** + * Set the padding between non center items + * @default 0 + */ + padding: number; + + /** + * Set the number of visible items + * @default 5 + */ + numVisible: number; + + /** + * Make the carousel a full width slider like the second example + * @default false + */ + fullWidth: boolean; + + /** + * Set to true to show indicators + * @default false + */ + indicators: boolean; + + /** + * Don't wrap around and cycle through items + * @default false + */ + noWrap: boolean; + + /** + * Callback for when a new slide is cycled to + * @default null + */ + onCycleTo: (this: Carousel, current: Element, dragged: boolean) => void; + } +} + +interface JQuery { + carousel(method: keyof Pick): JQuery; + carousel(method: keyof Pick, n?: number): JQuery; + carousel(method: keyof Pick, n?: number): JQuery; + carousel(method: keyof Pick, n?: number): JQuery; + carousel(options?: Partial): JQuery; +} diff --git a/types/materialize-css/character-counter.d.ts b/types/materialize-css/character-counter.d.ts new file mode 100644 index 0000000000..4d34ac170e --- /dev/null +++ b/types/materialize-css/character-counter.d.ts @@ -0,0 +1,25 @@ +/// + +declare namespace M { + class CharacterCounter extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): CharacterCounter; + + /** + * Init CharacterCounter + */ + static init(els: Element, options?: Partial): CharacterCounter; + + /** + * Init CharacterCounters + */ + static init(els: MElements, options?: Partial): CharacterCounter[]; + } +} + +interface JQuery { + characterCounter(method: keyof Pick): JQuery; + characterCounter(): JQuery; +} diff --git a/types/materialize-css/chips.d.ts b/types/materialize-css/chips.d.ts new file mode 100644 index 0000000000..d912d4ff7e --- /dev/null +++ b/types/materialize-css/chips.d.ts @@ -0,0 +1,124 @@ +/// +/// + +declare namespace M { + class Chips extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Chips; + + /** + * Init Chips + */ + static init(els: Element, options?: Partial): Chips; + + /** + * Init Chipses + */ + static init(els: MElements, options?: Partial): Chips[]; + + /** + * Array of the current chips data + */ + chipsData: ChipData[]; + + /** + * If the chips has autocomplete enabled + */ + hasAutocomplete: boolean; + + /** + * Autocomplete instance, if any + */ + autocomplete: Autocomplete; + + /** + * Add chip to input + * @param data Chip data object + */ + addChip(chip: ChipData): void; + + /** + * Delete nth chip + * @param n Index of chip + */ + deleteChip(n?: number): void; + + /** + * Select nth chip + * @param n Index of chip + */ + selectChip(n: number): void; + } + + interface ChipData { + /** + * Chip tag + */ + tag: string; + + /** + * Chip image + */ + img?: string; + } + + interface ChipsOptions { + /** + * Set the chip data + * @default [] + */ + data: ChipData[]; + + /** + * Set first placeholder when there are no tags + * @default '' + */ + placeholder: string; + + /** + * Set second placeholder when adding additional tags + * @default '' + */ + secondaryPlaceholder: string; + + /** + * Set autocomplete options + * @default {} + */ + autocompleteOptions: Partial; + + /** + * Set chips limit + * @default Infinity + */ + limit: number; + + /** + * Callback for chip add + * @default null + */ + onChipAdd: (this: Chips, element: Element, chip: Element) => void; + + /** + * Callback for chip select + * @default null + */ + onChipSelect: (this: Chips, element: Element, chip: Element) => void; + + /** + * Callback for chip delete + * @default null + */ + onChipDelete: (this: Chips, element: Element, chip: Element) => void; + } +} + +interface JQuery { + chips(method: keyof Pick): JQuery; + chips(method: keyof Pick, chip: M.ChipData): JQuery; + chips(method: keyof Pick, n?: number): JQuery; + chips(method: keyof Pick, n: number): JQuery; + chips(options?: Partial): JQuery; +} diff --git a/types/materialize-css/collapsible.d.ts b/types/materialize-css/collapsible.d.ts new file mode 100644 index 0000000000..649a59e9bb --- /dev/null +++ b/types/materialize-css/collapsible.d.ts @@ -0,0 +1,83 @@ +/// + +declare namespace M { + class Collapsible extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Collapsible; + + /** + * Init Collapsible + */ + static init(els: Element, options?: Partial): Collapsible; + + /** + * Init Collapsibles + */ + static init(els: MElements, options?: Partial): Collapsible[]; + + /** + * Open collapsible section + * @param n Nth section to open + */ + open(n: number): void; + + /** + * Close collapsible section + * @param n Nth section to close + */ + close(n: number): void; + } + + interface CollapsibleOptions { + /** + * If accordion versus collapsible + * @default true + */ + accordion: boolean; + + /** + * Transition in duration in milliseconds. + * @default 300 + */ + inDuration: number; + + /** + * Transition out duration in milliseconds. + * @default 300 + */ + outDuration: number; + + /** + * Callback function called before modal is opened + * @default null + */ + onOpenStart: (this: Collapsible, el: Element) => void; + + /** + * Callback function called after modal is opened + * @default null + */ + onOpenEnd: (this: Collapsible, el: Element) => void; + + /** + * Callback function called before modal is closed + * @default null + */ + onCloseStart: (this: Collapsible, el: Element) => void; + + /** + * Callback function called after modal is closed + * @default null + */ + onCloseEnd: (this: Collapsible, el: Element) => void; + } +} + +interface JQuery { + collapsible(method: keyof Pick): JQuery; + collapsible(method: keyof Pick, n: number): JQuery; + collapsible(method: keyof Pick, n: number): JQuery; + collapsible(options?: Partial): JQuery; +} diff --git a/types/materialize-css/common.d.ts b/types/materialize-css/common.d.ts new file mode 100644 index 0000000000..605e9389be --- /dev/null +++ b/types/materialize-css/common.d.ts @@ -0,0 +1,51 @@ +/// +/// + +type MElements = NodeListOf | JQuery | Cash; + +declare namespace M { + abstract class Component extends ComponentBase { + /** + * Construct component instance and set everything up + */ + constructor(elem: Element, options?: Partial); + + /** + * Destroy plugin instance and teardown + */ + destroy(): void; + } + + abstract class ComponentBase { + constructor(options?: Partial); + + /** + * The DOM element the plugin was initialized with + */ + el: Element; + + /** + * The options the instance was initialized with + */ + options: TOptions; + } + + interface Openable { + isOpen: boolean; + open(): void; + close(): void; + } + + interface InternationalizationOptions { + cancel: string; + clear: string; + done: string; + previousMonth: string; + nextMonth: string; + months: string[]; + monthsShort: string; + weekdays: string[]; + weekdaysShort: string[]; + weekdaysAbbrev: string[]; + } +} diff --git a/types/materialize-css/datepicker.d.ts b/types/materialize-css/datepicker.d.ts new file mode 100644 index 0000000000..3940027173 --- /dev/null +++ b/types/materialize-css/datepicker.d.ts @@ -0,0 +1,201 @@ +/// + +declare namespace M { + class Datepicker extends Component implements Openable { + /** + * Get Instance + */ + static getInstance(elem: Element): Datepicker; + + /** + * Init Datepicker + */ + static init(els: Element, options?: Partial): Datepicker; + + /** + * Init Datepickers + */ + static init(els: MElements, options?: Partial): Datepicker[]; + + /** + * If the picker is open. + */ + isOpen: boolean; + + /** + * The selected Date. + */ + date: Date; + + /** + * DONE button instance (undocumented!). + */ + doneBtn: HTMLButtonElement; + + /** + * CLEAR button instance (undocumented!). + */ + clearBtn: HTMLButtonElement; + + /** + * Open datepicker + */ + open(): void; + + /** + * Close datepicker + */ + close(): void; + + /** + * Gets a string representation of the selected date + */ + toString(): string; + + /** + * Set a date on the datepicker + * @param date Date to set on the datepicker. + * @param preventOnSelect Undocumented as of 5 March 2018 + */ + setDate(date?: Date | string, preventOnSelect?: boolean): void; + + /** + * Change date view to a specific date on the datepicker + * @param date Date to show on the datepicker. + */ + gotoDate(date: Date): void; + + setInputValue(): void; + } + + interface DatepickerOptions { + /** + * Automatically close picker when date is selected + * @default false + */ + autoClose: boolean; + + /** + * The date output format for the input field value. + * @default 'mmm dd, yyyy' + */ + format: string; + + /** + * Used to create date object from current input string. + */ + parse: (value: string, format: string) => Date; + + /** + * The initial date to view when first opened. + */ + defaultDate: Date; + + /** + * Make the `defaultDate` the initial selected value + * @default false + */ + setDefaultDate: boolean; + + /** + * Prevent selection of any date on the weekend. + * @default false + */ + disableWeekends: boolean; + + /** + * Custom function to disable certain days. + */ + disableDayFn: (day: Date) => boolean; + + /** + * First day of week (0: Sunday, 1: Monday etc). + * @default 0 + */ + firstDay: number; + + /** + * The earliest date that can be selected. + */ + minDate: Date; + + /** + * The latest date that can be selected. + */ + maxDate: Date; + + /** + * Number of years either side, or array of upper/lower range. + * @default 10 + */ + yearRange: number | number[]; + + /** + * Changes Datepicker to RTL. + * @default false + */ + isRTL: boolean; + + /** + * Show month after year in Datepicker title. + * @default false + */ + showMonthAfterYear: boolean; + + /** + * Render days of the calendar grid that fall in the next or previous month. + * @default false + */ + showDaysInNextAndPreviousMonths: boolean; + + /** + * Specify a DOM element to render the calendar in, by default it will be placed before the input + * @default null + */ + container: Element; + + /** + * Show the clear button in the datepicker + * @default false + */ + showClearBtn: boolean; + + /** + * Internationalization options + */ + i18n: Partial; + + /** + * An array of string returned by `Date.toDateString()`, indicating there are events in the specified days. + * @default [] + */ + events: string[]; + + /** + * Callback function when date is selected, first parameter is the newly selected date. + */ + onSelect: (this: Datepicker, selectedDate: Date) => void; + + /** + * Callback function when Datepicker is opened + */ + onOpen: (this: Datepicker) => void; + + /** + * Callback function when Datepicker is closed + */ + onClose: (this: Datepicker) => void; + + /** + * Callback function when Datepicker HTML is refreshed + */ + onDraw: (this: Datepicker) => void; + } +} + +interface JQuery { + datepicker(method: keyof Pick): JQuery; + datepicker(method: keyof Pick, date?: Date): JQuery; + datepicker(method: keyof Pick, date: Date): JQuery; + datepicker(options?: Partial): JQuery; +} diff --git a/types/materialize-css/dropdown.d.ts b/types/materialize-css/dropdown.d.ts new file mode 100644 index 0000000000..fb9b7d90c1 --- /dev/null +++ b/types/materialize-css/dropdown.d.ts @@ -0,0 +1,145 @@ +/// + +declare namespace M { + class Dropdown extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Dropdown; + + /** + * Init Dropdown + */ + static init(els: Element, options?: Partial): Dropdown; + + /** + * Init Dropdowns + */ + static init(els: MElements, options?: Partial): Dropdown[]; + + /** + * ID of the dropdown element + */ + id: string; + + /** + * The DOM element of the dropdown + */ + dropdownEl: Element; + + /** + * If the dropdown is open + */ + isOpen: boolean; + + /** + * If the dropdown content is scrollable + */ + isScrollable: boolean; + + /** + * The index of the item focused + */ + focusedIndex: number; + + /** + * Open dropdown + */ + open(): void; + + /** + * Close dropdown + */ + close(): void; + + /** + * While dropdown is open, you can recalculate its dimensions if its contents have changed + */ + recalculateDimensions(): void; + } + + interface DropdownOptions { + /** + * Defines the edge the menu is aligned to + * @default 'left' + */ + alignment: 'left' | 'right'; + + /** + * If true, automatically focus dropdown el for keyboard + * @default true + */ + autoTrigger: boolean; + + /** + * If true, constrainWidth to the size of the dropdown activator + * @default true + */ + constrainWidth: boolean; + + /** + * Provide an element that will be the bounding container of the dropdown + * @default null + */ + container: Element; + + /** + * If false, the dropdown will show below the trigger + * @default true + */ + coverTrigger: boolean; + + /** + * If true, close dropdown on item click + * @default true + */ + closeOnClick: boolean; + + /** + * If true, the dropdown will open on hover + * @default false + */ + hover: boolean; + + /** + * The duration of the transition enter in milliseconds + * @default 150 + */ + inDuration: number; + + /** + * The duration of the transition out in milliseconds + * @default 250 + */ + outDuration: number; + + /** + * Function called when dropdown starts entering + * @default null + */ + onOpenStart: (this: Dropdown, el: Element) => void; + + /** + * Function called when dropdown finishes entering + * @default null + */ + onOpenEnd: (this: Dropdown, el: Element) => void; + + /** + * Function called when dropdown starts exiting + * @default null + */ + onCloseStart: (this: Dropdown, el: Element) => void; + + /** + * Function called when dropdown finishes exiting + * @default null + */ + onCloseEnd: (this: Dropdown, el: Element) => void; + } +} + +interface JQuery { + dropdown(method: keyof Pick): JQuery; + dropdown(options?: Partial): JQuery; +} diff --git a/types/materialize-css/fab.d.ts b/types/materialize-css/fab.d.ts new file mode 100644 index 0000000000..74a7c89bfb --- /dev/null +++ b/types/materialize-css/fab.d.ts @@ -0,0 +1,60 @@ +/// + +declare namespace M { + class FloatingActionButton extends Component implements Openable { + /** + * Get Instance + */ + static getInstance(elem: Element): FloatingActionButton; + + /** + * Init FloatingActionButton + */ + static init(els: Element, options?: Partial): FloatingActionButton; + + /** + * Init FloatingActionButtons + */ + static init(els: MElements, options?: Partial): FloatingActionButton[]; + + /** + * Open FAB + */ + open(): void; + + /** + * Close FAB + */ + close(): void; + + /** + * Describes open/close state of FAB. + */ + isOpen: boolean; + } + + interface FloatingActionButtonOptions { + /** + * Direction FAB menu opens + * @default "top" + */ + direction: "top" | "right" | "buttom" | "left"; + + /** + * true: FAB menu appears on hover, false: FAB menu appears on click + * @default true + */ + hoverEnabled: boolean; + + /** + * Enable transit the FAB into a toolbar on click + * @default false + */ + toolbarEnabled: boolean; + } +} + +interface JQuery { + floatingActionButton(method: keyof Pick): JQuery; + floatingActionButton(options?: Partial): JQuery; +} diff --git a/types/materialize-css/formselect.d.ts b/types/materialize-css/formselect.d.ts new file mode 100644 index 0000000000..de901d7fbf --- /dev/null +++ b/types/materialize-css/formselect.d.ts @@ -0,0 +1,70 @@ +/// +/// + +declare namespace M { + class FormSelect extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): FormSelect; + + /** + * Init FormSelect + */ + static init(els: Element, options?: Partial): FormSelect; + + /** + * Init FormSelects + */ + static init(els: MElements, options?: Partial): FormSelect[]; + + /** + * If this is a multiple select + */ + isMultiple: boolean; + + /** + * The select wrapper element + */ + wrapper: Element; + + /** + * Dropdown UL element + */ + dropdownOptions: HTMLUListElement; + + /** + * Text input that shows current selected option + */ + input: HTMLInputElement; + + /** + * Instance of the dropdown plugin for this select + */ + dropdown: Dropdown; + + /** + * Get selected values in an array + */ + getSelectedValues(): string[]; + } + + interface FormSelectOptions { + /** + * Classes to be added to the select wrapper element + * @default '' + */ + classes: string; + + /** + * Pass options object to select dropdown initialization + * @default {} + */ + dropdownOptions: Partial; + } +} + +interface JQuery { + formSelect(method: keyof Pick): JQuery; + formSelect(options?: Partial): JQuery; +} diff --git a/types/materialize-css/index.d.ts b/types/materialize-css/index.d.ts index 0a383f1c65..f8502cafb4 100644 --- a/types/materialize-css/index.d.ts +++ b/types/materialize-css/index.d.ts @@ -1,975 +1,37 @@ // Type definitions for materialize-css 1.0 // Project: http://materializecss.com/ -// Definitions by: 胡玮文 , Maxim Balaganskiy +// Definitions by: 胡玮文 +// Maxim Balaganskiy +// David Moniz +// Daniel Hoenes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 /// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// export = M; - -declare global { - namespace M { - class Autocomplete extends Component { - /** - * Get Instance - */ - static getInstance(elem: Element): Autocomplete; - - /** - * Select a specific autocomplete options. - * @param el Element of the autocomplete option. - */ - selectOption(el: Element): void; - - /** - * Update autocomplete options data. - * @param data Autocomplete options data object. - */ - updateData(data: AutocompleteData): void; - - /** - * If the autocomplete is open. - */ - isOpen: boolean; - - /** - * Number of matching autocomplete options. - */ - count: number; - - /** - * Index of the current selected option. - */ - activeIndex: number; - } - - interface AutocompleteData { - [key: string]: string | null; - } - - interface AutocompleteOptions { - /** - * Data object defining autocomplete options with optional icon strings. - */ - data: AutocompleteData; - - /** - * Limit of results the autocomplete shows. - * @default infinity - */ - limit: number; - - /** - * Callback for when autocompleted. - */ - onAutocomplete: (this: Autocomplete, text: string) => void; - - /** - * Minimum number of characters before autocomplete starts. - * @default 1 - */ - minLength: number; - - /** - * Sort function that defines the order of the list of autocomplete options. - */ - sortFunction: (a: string, b: string, inputText: string) => number; - } - - class DatePicker extends Component implements Openable { - /** - * Get Instance - */ - static getInstance(elem: Element): DatePicker; - - /** - * If the picker is open. - */ - isOpen: boolean; - - /** - * The selected Date. - */ - date: Date; - - /** - * Open datepicker - */ - open(): void; - - /** - * Close datepicker - */ - close(): void; - - /** - * Gets a string representation of the selected date - */ - toString(): string; - - /** - * Set a date on the datepicker - * @param date Date to set on the datepicker. - */ - setDate(date?: Date): void; - - /** - * Change date view to a specific date on the datepicker - * @param date Date to show on the datepicker. - */ - gotoDate(date: Date): void; - } - - interface DatePickerOptions { - /** - * The date output format for the input field value. - * @default 'mmm dd, yyyy' - */ - format: string; - - /** - * Used to create date object from current input string. - */ - parse: (value: string, format: string) => Date; - - /** - * The initial date to view when first opened. - */ - defaultDate: Date; - - /** - * Make the `defaultDate` the initial selected value - * @default false - */ - setDefaultDate: boolean; - - /** - * Prevent selection of any date on the weekend. - * @default false - */ - disableWeekends: boolean; - - /** - * Custom function to disable certain days. - */ - disableDayFn: (day: Date) => boolean; - - /** - * First day of week (0: Sunday, 1: Monday etc). - * @default 0 - */ - firstDay: number; - - /** - * The earliest date that can be selected. - */ - minDate: Date; - - /** - * The latest date that can be selected. - */ - maxDate: Date; - - /** - * Number of years either side, or array of upper/lower range. - * @default 10 - */ - yearRange: number | number[]; - - /** - * Changes Datepicker to RTL. - * @default false - */ - isRTL: boolean; - - /** - * Show month after year in Datepicker title. - * @default false - */ - showMonthAfterYear: boolean; - - /** - * Render days of the calendar grid that fall in the next or previous month. - * @default false - */ - showDaysInNextAndPreviousMonths: boolean; - - /** - * Specify a selector for a DOM element to render the calendar in, by default it will be placed before the input. - */ - container: string; - - /** - * An array of string returned by `Date.toDateString()`, indicating there are events in the specified days. - * @default [] - */ - events: string[]; - - /** - * Callback function when date is selected, first parameter is the newly selected date. - */ - onSelect: (this: DatePicker, selectedDate: Date) => void; - - /** - * Callback function when Datepicker is opened - */ - onOpen: (this: DatePicker) => void; - - /** - * Callback function when Datepicker is closed - */ - onClose: (this: DatePicker) => void; - - /** - * Callback function when Datepicker HTML is refreshed - */ - onDraw: (this: DatePicker) => void; - } - - interface DropdownOptions { - /** - * Defines the edge the menu is aligned to - * @default 'left' - */ - alignment: string; - - /** - * If true, automatically focus dropdown el for keyboard - * @default true - */ - autoTrigger: boolean; - - /** - * If true, constrainWidth to the size of the dropdown activator - * @default true - */ - constrainWidth: boolean; - - /** - * Provide an element that will be the bounding container of the dropdown - * @default null - */ - container: Element; - - /** - * If false, the dropdown will show below the trigger - * @default true - */ - coverTrigger: boolean; // If false, the dropdown will show below the trigger. - - /** - * If true, close dropdown on item click - * @default true - */ - closeOnClick: boolean; - - /** - * If true, the dropdown will open on hover - * @default false - */ - hover: boolean; - - /** - * The duration of the transition enter in milliseconds - * @default 150 - */ - inDuration: number; - - /** - * The duration of the transition out in milliseconds - * @default 250 - */ - outDuration: number; - - /** - * Function called when dropdown starts entering - * @default null - */ - onOpenStart: (this: Dropdown, el: Element) => void; - - /** - * Function called when dropdown finishes entering - * @default null - */ - onOpenEnd: (this: Dropdown, el: Element) => void; - - /** - * Function called when dropdown starts exiting - * @default null - */ - onCloseStart: (this: Dropdown, el: Element) => void; - - /** - * Function called when dropdown finishes exiting - * @default null - */ - onCloseEnd: (this: Dropdown, el: Element) => void; - } - - class Dropdown extends Component { - /** - * ID of the dropdown element - */ - id: string; - - /** - * The DOM element of the dropdown - */ - dropdownEl: Element; - - /** - * If the dropdown is open - */ - isOpen: boolean; - - /** - * If the dropdown content is scrollable - */ - isScrollable: boolean; - - /** - * The index of the item focused - */ - focusedIndex: number; - - /** - * Open dropdown - */ - open(): void; - - /** - * Close dropdown - */ - close(): void; - - /** - * While dropdown is open, you can recalculate its dimensions if its contents have changed - */ - recalculateDimensions(): void; - } - - class FloatingActionButton extends Component implements Openable { - /** - * Get Instance - */ - static getInstance(elem: Element): FloatingActionButton; - - /** - * Open FAB - */ - open(): void; - - /** - * Close FAB - */ - close(): void; - - /** - * Describes open/close state of FAB. - */ - isOpen: boolean; - } - - interface FloatingActionButtonOptions { - /** - * Direction FAB menu opens - * @default "top" - */ - direction: "top" | "right" | "buttom" | "left"; - - /** - * true: FAB menu appears on hover, false: FAB menu appears on click - * @default true - */ - hoverEnabled: boolean; - - /** - * Enable transit the FAB into a toolbar on click - * @default false - */ - toolbarEnabled: boolean; - } - - interface FormSelectOptions { - /** - * Classes to be added to the select wrapper element - * @default '' - */ - classes: string; - - /** - * Pass options object to select dropdown initialization - * @default {} - */ - dropdownOptions: Partial; - } - - class FormSelect extends Component { - /** - * If this is a multiple select - */ - isMultiple: boolean; - - /** - * The select wrapper element - */ - wrapper: Element; - - /** - * Dropdown UL element - */ - dropdownOptions: HTMLUListElement; - - /** - * Text input that shows current selected option - */ - input: HTMLInputElement; - - /** - * Instance of the dropdown plugin for this select - */ - dropdown: Dropdown; - - /** - * Get selected values in an array - */ - getSelectedValues(): string[]; - } - - class Sidenav extends Component implements Openable { - /** - * Get Instance - */ - static getInstance(elem: Element): Sidenav; - - /** - * Opens Sidenav - */ - open(): void; - - /** - * Closes Sidenav - */ - close(): void; - - /** - * Describes open/close state of Sidenav - */ - isOpen: boolean; - - /** - * Describes if sidenav is fixed - */ - isFixed: boolean; - - /** - * Describes if Sidenav is being dragged - */ - isDragged: boolean; - } - - /** - * Options for the Sidenav - */ - interface SidenavOptions { - /** - * Side of screen on which Sidenav appears - * @default 'left' - */ - edge: 'left' | 'right'; - - /** - * Allow swipe gestures to open/close Sidenav - * @default true - */ - draggable: boolean; - - /** - * Length in ms of enter transition - * @default 250 - */ - inDuration: number; - - /** - * Length in ms of exit transition - * @default 200 - */ - outDuration: number; - - /** - * Function called when sidenav starts entering - */ - onOpenStart: (this: Sidenav, elem: Element) => void; - - /** - * Function called when sidenav finishes entering - */ - onOpenEnd: (this: Sidenav, elem: Element) => void; - - /** - * Function called when sidenav starts exiting - */ - onCloseStart: (this: Sidenav, elem: Element) => void; - - /** - * Function called when sidenav finishes exiting - */ - onCloseEnd: (this: Sidenav, elem: Element) => void; - } - - class Tabs extends Component { - /** - * Get Instance - */ - static getInstance(elem: Element): Tabs; - - /** - * Show tab content that corresponds to the tab with the id - * @param tabId The id of the tab that you want to switch to - */ - select(tabId: string): void; - - /** - * The index of tab that is currently shown - */ - index: number; - } - - /** - * Options for the Tabs - */ - interface TabsOptions { - /** - * Transition duration in milliseconds. - * @default 300 - */ - duration: number; - - /** - * Callback for when a new tab content is shown - */ - onShow: (this: Tabs, newContent: Element) => void; - - /** - * Set to true to enable swipeable tabs. This also uses the responsiveThreshold option - * @default false - */ - swipeable: boolean; - - /** - * The maximum width of the screen, in pixels, where the swipeable functionality initializes. - * @default infinity - */ - responsiveThreshold: number; - } - - class TimePicker extends Component { - /** - * Get Instance - */ - static getInstance(elem: Element): TimePicker; - - /** - * If the picker is open. - */ - isOpen: boolean; - - /** - * The selected time. - */ - time: string; - - /** - * Open timepicker - */ - open(): void; - - /** - * Close timepicker - */ - close(): void; - - /** - * Show hours or minutes view on timepicker - * @param view The name of the view you want to switch to, 'hours' or 'minutes'. - */ - showView(view: "hours" | "minutes"): void; - } - - interface TimePickerOptions { - /** - * Duration of the transition from/to the hours/minutes view. - * @default 350 - */ - duration: number; - - /** - * Specify a selector for a DOM element to render the calendar in, by default it will be placed before the input. - */ - container: string; - - /** - * Default time to set on the timepicker 'now' or '13:14' - * @default 'now'; - */ - defaultTime: string; - - /** - * Millisecond offset from the defaultTime. - * @default 0 - */ - fromnow: number; - - /** - * Done button text. - * @default 'Ok' - */ - doneText: string; - - /** - * Clear button text. - * @default 'Clear' - */ - clearText: string; - - /** - * Cancel button text. - * @default 'Cancel' - */ - cancelText: string; - - /** - * Automatically close picker when minute is selected. - * @default false; - */ - autoClose: boolean; - - /** - * Use 12 hour AM/PM clock instead of 24 hour clock. - * @default true - */ - twelveHour: boolean; - - /** - * Vibrate device when dragging clock hand. - * @default true - */ - vibrate: boolean; - } - - class Modal extends Component implements Openable { - /** - * Get Instance - */ - static getInstance(elem: Element): Modal; - - /** - * Open modal - */ - open(): void; - - /** - * Close modal - */ - close(): void; - - /** - * If the modal is open. - */ - isOpen: boolean; - - /** - * ID of the modal element - */ - id: string; - } - - /** - * Options for the Modal - */ - interface ModalOptions { - /** - * Opacity of the modal overlay. - * @default 0.5 - */ - opacity: number; - - /** - * Transition in duration in milliseconds. - * @default 250 - */ - inDuration: number; - - /** - * Transition out duration in milliseconds. - * @default 250 - */ - outDuration: number; - - /** - * Callback function called when modal is finished entering. - */ - ready: (this: Modal, elem: Element, openingTrigger: Element) => void; - - /** - * Callback function called when modal is finished exiting. - */ - complete: (this: Modal, elem: Element) => void; - - /** - * Allow modal to be dismissed by keyboard or overlay click. - * @default true - */ - dismissible: boolean; - - /** - * Starting top offset - * @default '4%' - */ - startingTop: string; - - /** - * Ending top offset - * @default '10%' - */ - endingTop: string; - } - - class Toast extends ComponentBase { - /** - * Get Instance - */ - static getInstance(elem: Element): Toast; - - /** - * Describes the current pan state of the Toast. - */ - panning: boolean; - - /** - * The remaining amount of time in ms that the toast will stay before dismissal. - */ - timeRemaining: number; - - /** - * remove a specific toast - */ - dismiss(): void; - - /** - * dismiss all toasts - */ - static dismissAll(): void; - } - - interface ToastOptions { - /** - * The HTML content of the Toast. - */ - html: string; - - /** - * Length in ms the Toast stays before dismissal. - * @default 4000 - */ - displayLength: number; - - /** - * Transition in duration in milliseconds. - * @default 300 - */ - inDuration: number; - - /** - * Transition out duration in milliseconds. - * @default 375 - */ - outDuration: number; - - /** - * Classes to be added to the toast element. - */ - classes: string; - - /** - * Callback function called when toast is dismissed. - */ - completeCallback: () => void; - - /** - * The percentage of the toast's width it takes for a drag to dismiss a Toast. - * @default 0.8 - */ - activationPercent: number; - } - - /** - * Create a toast - */ - function toast(options: Partial): Toast; - - class Tooltip extends Component implements Openable { - /** - * Get Instance - */ - static getInstance(elem: Element): Tooltip; - - /** - * Show tooltip. - */ - open(): void; - - /** - * Hide tooltip. - */ - close(): void; - - /** - * If tooltip is open. - */ - isOpen: boolean; - - /** - * If tooltip is hovered. - */ - isHovered: boolean; - } - - interface TooltipOptions { - /** - * Delay time before tooltip disappears. - * @default 0 - */ - exitDelay: number; - - /** - * Delay time before tooltip appears. - * @default 200 - */ - enterDelay: number; - - /** - * Can take regular text or HTML strings. - * @default null - */ - html: string | null; - - /** - * Set distance tooltip appears away from its activator excluding transitionMovement. - * @default 5 - */ - margin: number; - - /** - * Enter transition duration. - * @default 300 - */ - inDuration: number; - - /** - * Exit transition duration. - * @default 250 - */ - outDuration: number; - - /** - * Set the direction of the tooltip. - * @default 'bottom' - */ - position: 'top' | 'right' | 'bottom' | 'left'; - - /** - * Amount in px that the tooltip moves during its transition. - * @default 10 - */ - transitionMovement: number; - } - - function updateTextFields(): void; - - class CharacterCounter extends Component { - /** - * Get Instance - */ - static getInstance(elem: Element): CharacterCounter; - } - - abstract class Component extends ComponentBase { - /** - * Construct component instance and set everything up - */ - constructor(elem: Element, options?: Partial); - - /** - * Destroy plugin instance and teardown - */ - destroy(): void; - } - - abstract class ComponentBase { - constructor(options?: Partial); - - /** - * The DOM element the plugin was initialized with - */ - el: Element; - - /** - * The options the instance was initialized with - */ - options: TOptions; - } - - interface Openable { - isOpen: boolean; - open(): void; - close(): void; - } - } - - interface JQuery { - // Pick to check methods exist. - autocomplete(method: keyof Pick): JQuery; - autocomplete(method: keyof Pick, el: Element): JQuery; - autocomplete(method: keyof Pick, data: M.AutocompleteData): JQuery; - autocomplete(options?: Partial): JQuery; - - datepicker(method: keyof Pick): JQuery; - datepicker(method: keyof Pick, date?: Date): JQuery; - datepicker(method: keyof Pick, date: Date): JQuery; - datepicker(options?: Partial): JQuery; - - dropdown(method: keyof Pick): JQuery; - dropdown(options?: Partial): JQuery; - - floatingActionButton(method: keyof Pick): JQuery; - floatingActionButton(options?: Partial): JQuery; - - formSelect(method: keyof Pick): JQuery; - formSelect(options?: Partial): JQuery; - - sidenav(method: keyof Pick): JQuery; - sidenav(options?: Partial): JQuery; - - tabs(method: keyof Pick): JQuery; - tabs(method: keyof Pick, tabId: string): JQuery; - tabs(options?: Partial): JQuery; - - timepicker(method: keyof Pick): JQuery; - timepicker(method: keyof Pick, view: "hours" | "minutes"): JQuery; - timepicker(options?: Partial): JQuery; - - // Toast can not be invoked using jQuery. - - tooltip(method: keyof Pick): JQuery; - tooltip(options?: Partial): JQuery; - - modal(method: keyof Pick): JQuery; - modal(options?: Partial): JQuery; - - // tslint:disable-next-line unified-signatures - characterCounter(method: keyof Pick): JQuery; - characterCounter(): JQuery; - } -} diff --git a/types/materialize-css/inputfields.d.ts b/types/materialize-css/inputfields.d.ts new file mode 100644 index 0000000000..23c5ca9489 --- /dev/null +++ b/types/materialize-css/inputfields.d.ts @@ -0,0 +1,7 @@ +/// + +declare namespace M { + function updateTextFields(): void; + + function textareaAutoResize(textarea: Element | JQuery | Cash): void; +} diff --git a/types/materialize-css/materialbox.d.ts b/types/materialize-css/materialbox.d.ts new file mode 100644 index 0000000000..225afd67e6 --- /dev/null +++ b/types/materialize-css/materialbox.d.ts @@ -0,0 +1,98 @@ +/// + +declare namespace M { + class Materialbox extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Materialbox; + + /** + * Init Materialbox + */ + static init(els: Element, options?: Partial): Materialbox; + + /** + * Init Materialboxes + */ + static init(els: MElements, options?: Partial): Materialbox[]; + + /** + * If the materialbox overlay is showing + */ + overlayActive: boolean; + + /** + * If the materialbox is no longer being animated + */ + doneAnimating: boolean; + + /** + * Caption if specified + */ + caption: string; + + /** + * Original width of image + */ + originalWidth: number; + + /** + * Original height of image + */ + originalHeight: number; + + /** + * Open materialbox + */ + open(): void; + + /** + * Close materialbox + */ + close(): void; + } + + interface MaterialboxOptions { + /** + * Transition in duration in milliseconds + * @default 275 + */ + inDuration: number; + + /** + * Transition out duration in milliseconds + * @default 200 + */ + outDuration: number; + + /** + * Callback function called before materialbox is opened + * @default null + */ + onOpenStart: (this: Materialbox, el: Element) => void; + + /** + * Callback function called after materialbox is opened + * @default null + */ + onOpenEnd: (this: Materialbox, el: Element) => void; + + /** + * Callback function called before materialbox is closed + * @default null + */ + onCloseStart: (this: Materialbox, el: Element) => void; + + /** + * Callback function called after materialbox is closed + * @default null + */ + onCloseEnd: (this: Materialbox, el: Element) => void; + } +} + +interface JQuery { + materialbox(method: keyof Pick): JQuery; + materialbox(options?: Partial): JQuery; +} diff --git a/types/materialize-css/modal.d.ts b/types/materialize-css/modal.d.ts new file mode 100644 index 0000000000..d23a4f9c33 --- /dev/null +++ b/types/materialize-css/modal.d.ts @@ -0,0 +1,116 @@ +/// + +declare namespace M { + class Modal extends Component implements Openable { + /** + * Get Instance + */ + static getInstance(elem: Element): Modal; + + /** + * Init Modal + */ + static init(els: Element, options?: Partial): Modal; + + /** + * Init Modals + */ + static init(els: MElements, options?: Partial): Modal[]; + + /** + * Open modal + */ + open(): void; + + /** + * Close modal + */ + close(): void; + + /** + * If the modal is open. + */ + isOpen: boolean; + + /** + * ID of the modal element + */ + id: string; + } + + /** + * Options for the Modal + */ + interface ModalOptions { + /** + * Opacity of the modal overlay. + * @default 0.5 + */ + opacity: number; + + /** + * Transition in duration in milliseconds. + * @default 250 + */ + inDuration: number; + + /** + * Transition out duration in milliseconds. + * @default 250 + */ + outDuration: number; + + /** + * Prevent page from scrolling while modal is open + * @default true + */ + preventScrolling: boolean; + + /** + * Callback function called before modal is opened + * @default null + */ + onOpenStart: (this: Modal, el: Element) => void; + + /** + * Callback function called after modal is opened + * @default null + */ + onOpenEnd: (this: Modal, el: Element) => void; + + /** + * Callback function called before modal is closed + * @default null + */ + onCloseStart: (this: Modal, el: Element) => void; + + /** + * Callback function called after modal is closed + * @default null + */ + onCloseEnd: (this: Modal, el: Element) => void; + + /** + * Allow modal to be dismissed by keyboard or overlay click. + * @default true + */ + dismissible: boolean; + + /** + * Starting top offset + * @default '4%' + */ + startingTop: string; + + /** + * Ending top offset + * @default '10%' + */ + endingTop: string; + } +} + +interface JQuery { + modal(method: keyof Pick): JQuery; + modal(options?: Partial): JQuery; +} diff --git a/types/materialize-css/parallax.d.ts b/types/materialize-css/parallax.d.ts new file mode 100644 index 0000000000..17d2de56b9 --- /dev/null +++ b/types/materialize-css/parallax.d.ts @@ -0,0 +1,33 @@ +/// + +declare namespace M { + class Parallax extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Parallax; + + /** + * Init Parallax + */ + static init(els: Element, options?: Partial): Parallax; + + /** + * Init Parallaxs + */ + static init(els: MElements, options?: Partial): Parallax[]; + } + + interface ParallaxOptions { + /** + * The minimum width of the screen, in pixels, where the parallax functionality starts working + * @default 0 + */ + responsiveThreshold: number; + } +} + +interface JQuery { + parallax(options?: Partial): JQuery; + parallax(method: keyof Pick): JQuery; +} diff --git a/types/materialize-css/pushpin.d.ts b/types/materialize-css/pushpin.d.ts new file mode 100644 index 0000000000..cab559e713 --- /dev/null +++ b/types/materialize-css/pushpin.d.ts @@ -0,0 +1,56 @@ +/// + +declare namespace M { + class Pushpin extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Pushpin; + + /** + * Init Pushpin + */ + static init(els: Element, options?: Partial): Pushpin; + + /** + * Init Pushpins + */ + static init(els: MElements, options?: Partial): Pushpin[]; + + /** + * Original offsetTop of element + */ + originalOffset: number; + } + + interface PushpinOptions { + /** + * The distance in pixels from the top of the page where the element becomes fixed + * @default 0 + */ + top: number; + + /** + * The distance in pixels from the top of the page where the elements stops being fixed + * @default Infinity + */ + bottom: number; + + /** + * The offset from the top the element will be fixed at + * @default 0 + */ + offset: number; + + /** + * Callback function called when pushpin position changes. You are provided with a position string + * @default null + */ + onPositionChange: (this: Pushpin, position: "pinned" | "pin-top" | "pin-bottom") => void; + } +} + +interface JQuery { + pushpin(options?: Partial): JQuery; + pushpin(method: keyof Pick): JQuery; +} diff --git a/types/materialize-css/range.d.ts b/types/materialize-css/range.d.ts new file mode 100644 index 0000000000..dac7a7edf2 --- /dev/null +++ b/types/materialize-css/range.d.ts @@ -0,0 +1,25 @@ +/// + +declare namespace M { + class Range extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Range; + + /** + * Init Range + */ + static init(els: Element, options?: Partial): Range; + + /** + * Init Ranges + */ + static init(els: MElements, options?: Partial): Range[]; + } +} + +interface JQuery { + range(): JQuery; + range(method: keyof Pick): JQuery; +} diff --git a/types/materialize-css/scrollspy.d.ts b/types/materialize-css/scrollspy.d.ts new file mode 100644 index 0000000000..3f5f2bd21b --- /dev/null +++ b/types/materialize-css/scrollspy.d.ts @@ -0,0 +1,51 @@ +/// + +declare namespace M { + class ScrollSpy extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): ScrollSpy; + + /** + * Init ScrollSpy + */ + static init(els: Element, options?: Partial): ScrollSpy; + + /** + * Init ScrollSpies + */ + static init(els: MElements, options?: Partial): ScrollSpy[]; + } + + interface ScrollSpyOptions { + /** + * Throttle of scroll handler + * @default 100 + */ + throttle: number; + + /** + * Offset for centering element when scrolled to + * @default 200 + */ + scrollOffset: number; + + /** + * Class applied to active elements + * @default 'active' + */ + activeClass: string; + + /** + * Used to find active element + * @default id => 'a[href="#' + id + '"]' + */ + getActiveElement: (id: string) => string; + } +} + +interface JQuery { + scrollSpy(options?: Partial): JQuery; + scrollSpy(method: keyof Pick): JQuery; +} diff --git a/types/materialize-css/sidenav.d.ts b/types/materialize-css/sidenav.d.ts new file mode 100644 index 0000000000..3843393d88 --- /dev/null +++ b/types/materialize-css/sidenav.d.ts @@ -0,0 +1,99 @@ +/// + +declare namespace M { + class Sidenav extends Component implements Openable { + /** + * Get Instance + */ + static getInstance(elem: Element): Sidenav; + + /** + * Init Sidenav + */ + static init(els: Element, options?: Partial): Sidenav; + + /** + * Init Sidenavs + */ + static init(els: MElements, options?: Partial): Sidenav[]; + + /** + * Opens Sidenav + */ + open(): void; + + /** + * Closes Sidenav + */ + close(): void; + + /** + * Describes open/close state of Sidenav + */ + isOpen: boolean; + + /** + * Describes if sidenav is fixed + */ + isFixed: boolean; + + /** + * Describes if Sidenav is being dragged + */ + isDragged: boolean; + } + + /** + * Options for the Sidenav + */ + interface SidenavOptions { + /** + * Side of screen on which Sidenav appears + * @default 'left' + */ + edge: 'left' | 'right'; + + /** + * Allow swipe gestures to open/close Sidenav + * @default true + */ + draggable: boolean; + + /** + * Length in ms of enter transition + * @default 250 + */ + inDuration: number; + + /** + * Length in ms of exit transition + * @default 200 + */ + outDuration: number; + + /** + * Function called when sidenav starts entering + */ + onOpenStart: (this: Sidenav, elem: Element) => void; + + /** + * Function called when sidenav finishes entering + */ + onOpenEnd: (this: Sidenav, elem: Element) => void; + + /** + * Function called when sidenav starts exiting + */ + onCloseStart: (this: Sidenav, elem: Element) => void; + + /** + * Function called when sidenav finishes exiting + */ + onCloseEnd: (this: Sidenav, elem: Element) => void; + } +} + +interface JQuery { + sidenav(method: keyof Pick): JQuery; + sidenav(options?: Partial): JQuery; +} diff --git a/types/materialize-css/slider.d.ts b/types/materialize-css/slider.d.ts new file mode 100644 index 0000000000..4ab110ba58 --- /dev/null +++ b/types/materialize-css/slider.d.ts @@ -0,0 +1,86 @@ +/// + +declare namespace M { + class Slider extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Slider; + + /** + * Init Slider + */ + static init(els: Element, options?: Partial): Slider; + + /** + * Init Sliders + */ + static init(els: MElements, options?: Partial): Slider[]; + + /** + * ID of the dropdown element + */ + el: Element; + + /** + * ID of the dropdown element + */ + options: SliderOptions; + + /** + * Index of current slide + */ + activeIndex: number; + + /** + * Pause slider autoslide + */ + pause(): void; + + /** + * Start slider autoslide + */ + start(): void; + + /** + * Move to next slider + */ + next(): void; + + /** + * Move to prev slider + */ + prev(): void; + } + + interface SliderOptions { + /** + * Set to false to hide slide indicators + * @default true + */ + indicators: boolean; + + /** + * Set height of slider + * @default 400 + */ + height: number; + + /** + * Set the duration of the transition animation in ms + * @default 500 + */ + duration: number; + + /** + * Set the duration between transitions in ms + * @default 6000 + */ + interval: number; + } +} + +interface JQuery { + slider(method: keyof Pick): JQuery; + slider(options?: Partial): JQuery; +} diff --git a/types/materialize-css/tabs.d.ts b/types/materialize-css/tabs.d.ts new file mode 100644 index 0000000000..b8cb2d5fec --- /dev/null +++ b/types/materialize-css/tabs.d.ts @@ -0,0 +1,70 @@ +/// + +declare namespace M { + class Tabs extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Tabs; + + /** + * Init Tabs + */ + static init(els: Element, options?: Partial): Tabs; + + /** + * Init Tabses + */ + static init(els: MElements, options?: Partial): Tabs[]; + + /** + * Show tab content that corresponds to the tab with the id + * @param tabId The id of the tab that you want to switch to + */ + select(tabId: string): void; + + /** + * The index of tab that is currently shown + */ + index: number; + + /** + * Recalculate tab indicator position. This is useful when the indicator position is not correct + */ + updateTabIndicator(): void; + } + + /** + * Options for the Tabs + */ + interface TabsOptions { + /** + * Transition duration in milliseconds. + * @default 300 + */ + duration: number; + + /** + * Callback for when a new tab content is shown + */ + onShow: (this: Tabs, newContent: Element) => void; + + /** + * Set to true to enable swipeable tabs. This also uses the responsiveThreshold option + * @default false + */ + swipeable: boolean; + + /** + * The maximum width of the screen, in pixels, where the swipeable functionality initializes. + * @default infinity + */ + responsiveThreshold: number; + } +} + +interface JQuery { + tabs(method: keyof Pick): JQuery; + tabs(method: keyof Pick, tabId: string): JQuery; + tabs(options?: Partial): JQuery; +} diff --git a/types/materialize-css/taptarget.d.ts b/types/materialize-css/taptarget.d.ts new file mode 100644 index 0000000000..eeea843592 --- /dev/null +++ b/types/materialize-css/taptarget.d.ts @@ -0,0 +1,54 @@ +/// + +declare namespace M { + class TapTarget extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): TapTarget; + + /** + * Init TapTarget + */ + static init(els: Element, options?: Partial): TapTarget; + + /** + * Init TapTargets + */ + static init(els: MElements, options?: Partial): TapTarget[]; + + /** + * If the tap target is open + */ + isOpen: boolean; + + /** + * Open Tap Target + */ + open(): void; + + /** + * Close Tap Target + */ + close(): void; + } + + interface TapTargetOptions { + /** + * Callback function called when Tap Target is opened + * @default null + */ + onOpen: (this: TapTarget, origin: Element) => void; + + /** + * Callback function called when Tap Target is closed + * @default null + */ + onClose: (this: TapTarget, origin: Element) => void; + } +} + +interface JQuery { + tapTarget(method: keyof Pick): JQuery; + tapTarget(options?: Partial): JQuery; +} diff --git a/types/materialize-css/test/autocomplete.test.ts b/types/materialize-css/test/autocomplete.test.ts new file mode 100644 index 0000000000..dece4118bd --- /dev/null +++ b/types/materialize-css/test/autocomplete.test.ts @@ -0,0 +1,55 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Autocomplete +const _autocomplete = new M.Autocomplete(elem); +// $ExpectType Autocomplete +const el = M.Autocomplete.init(elem); +// $ExpectType Autocomplete[] +const els = M.Autocomplete.init(document.querySelectorAll('.whatever')); + +// $ExpectType Autocomplete +new materialize.Autocomplete(elem); +// $ExpectType Autocomplete +const autocomplete = new materialize.Autocomplete(elem, { + data: { + Apple: null, + Google: "https://placehold.it/250x250" + }, + minLength: 3, + limit: 3, + onAutocomplete(text) { + // $ExpectType Autocomplete + this; + // $ExpectType string + text; + }, + sortFunction(a, b, input) { + // $ExpectType string + a; + // $ExpectType string + b; + // $ExpectType string + input; + return 0; + } +}); +// $ExpectType void +autocomplete.updateData({ Microsoft: null }); +// $ExpectType void +autocomplete.destroy(); +// $ExpectType AutocompleteOptions +autocomplete.options; +// $ExpectType Element +autocomplete.el; +// $ExpectType boolean +autocomplete.isOpen; + +$(".whatever").autocomplete({ + data: { + Apple: null, + Google: "https://placehold.it/250x250" + } +}); +$(".whatever").autocomplete("updateData", { Microsoft: null }); diff --git a/types/materialize-css/test/carousel.test.ts b/types/materialize-css/test/carousel.test.ts new file mode 100644 index 0000000000..e6658e8862 --- /dev/null +++ b/types/materialize-css/test/carousel.test.ts @@ -0,0 +1,53 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Carousel +const _carousel = new M.Carousel(elem); +// $ExpectType Carousel +const el = M.Carousel.init(elem); +// $ExpectType Carousel[] +const els = M.Carousel.init(document.querySelectorAll('.whatever')); + +// $ExpectType Carousel +const carousel = new materialize.Carousel(elem, { + dist: 1, + duration: 1, + fullWidth: true, + indicators: true, + noWrap: true, + numVisible: 10, + onCycleTo(current, dragged) { + // $ExpectType Element + current; + // $ExpectType boolean + dragged; + }, + padding: 1, + shift: 1 +}); + +// $ExpectType number +carousel.center; +// $ExpectType number +carousel.dragged; +// $ExpectType Element +carousel.el; +// $ExpectType CarouselOptions +carousel.options; +// $ExpectType boolean +carousel.pressed; +// $ExpectType void +carousel.destroy(); +// $ExpectType void +carousel.next(1); +// $ExpectType void +carousel.prev(1); +// $ExpectType void +carousel.set(2); + +$(".whatever").carousel(); +$(".whatever").carousel("destroy"); +$(".whatever").carousel("next", 1); +$(".whatever").carousel("prev", 1); +$(".whatever").carousel("set", 1); diff --git a/types/materialize-css/test/character-counter.test.ts b/types/materialize-css/test/character-counter.test.ts new file mode 100644 index 0000000000..e928510662 --- /dev/null +++ b/types/materialize-css/test/character-counter.test.ts @@ -0,0 +1,20 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType CharacterCounter +const _characterCounter = new M.CharacterCounter(elem); +// $ExpectType CharacterCounter +const el = M.CharacterCounter.init(elem); +// $ExpectType CharacterCounter[] +const els = M.CharacterCounter.init(document.querySelectorAll('.whatever')); + +// $ExpectType CharacterCounter +const characterCounter = new materialize.CharacterCounter(elem); +// $ExpectType void +characterCounter.destroy(); +// $ExpectType Element +characterCounter.el; + +$(".whatever").characterCounter(); +$(".whatever").characterCounter("destroy"); diff --git a/types/materialize-css/test/chips.test.ts b/types/materialize-css/test/chips.test.ts new file mode 100644 index 0000000000..de68820070 --- /dev/null +++ b/types/materialize-css/test/chips.test.ts @@ -0,0 +1,40 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Chips +const _chips = new M.Chips(elem); +// $ExpectType Chips +const el = M.Chips.init(elem); +// $ExpectType Chips[] +const els = M.Chips.init(document.querySelectorAll('.whatever')); + +// $ExpectType Chips +const chips = new materialize.Chips(elem, { + data: [{ tag: "tag" }], + onChipAdd() { }, + onChipDelete() { }, + onChipSelect() { } +}); + +// $ExpectType void +chips.addChip({ tag: "tag" }); +// $ExpectType void +chips.deleteChip(1); +// $ExpectType void +chips.destroy(); +// $ExpectType void +chips.selectChip(1); +// $ExpectType Autocomplete +chips.autocomplete; +// $ExpectType ChipData[] +chips.chipsData; +// $ExpectType Element +chips.el; +// $ExpectType boolean +chips.hasAutocomplete; +// $ExpectType ChipsOptions +chips.options; + +$(".whatever").chips({ data: [{ tag: "tag" }] }); +$(".whatever").chips("destroy"); diff --git a/types/materialize-css/test/collapsible.test.ts b/types/materialize-css/test/collapsible.test.ts new file mode 100644 index 0000000000..927cd16cb7 --- /dev/null +++ b/types/materialize-css/test/collapsible.test.ts @@ -0,0 +1,49 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Collapsible +const _collapsible = new M.Collapsible(elem); +// $ExpectType Collapsible +const el = M.Collapsible.init(elem); +// $ExpectType Collapsible[] +const els = M.Collapsible.init(document.querySelectorAll('.whatever')); + +// $ExpectType Collapsible +const collapsible = new materialize.Collapsible(elem, { + accordion: true, + inDuration: 1, + outDuration: 1, + onCloseEnd(el) { + // $ExpectType Element + el; + }, + onCloseStart(el) { + // $ExpectType Element + el; + }, + onOpenEnd(el) { + // $ExpectType Element + el; + }, + onOpenStart(el) { + // $ExpectType Element + el; + } +}); + +// $ExpectType void +collapsible.close(1); +// $ExpectType void +collapsible.destroy(); +// $ExpectType void +collapsible.open(1); +// $ExpectType Element +collapsible.el; +// $ExpectType CollapsibleOptions +collapsible.options; + +$(".whatever").collapsible(); +$(".whatever").collapsible("destroy"); +$(".whatever").collapsible("open", 1); +$(".whatever").collapsible("close", 1); diff --git a/types/materialize-css/test/common.test.ts b/types/materialize-css/test/common.test.ts new file mode 100644 index 0000000000..a46cd7fe28 --- /dev/null +++ b/types/materialize-css/test/common.test.ts @@ -0,0 +1,13 @@ +import * as M from "materialize-css"; +import * as jQuery from "jquery"; + +// Test Component Initialization + +// $ExpectType Autocomplete +M.Autocomplete.init(document.querySelector('.whatever')!); +// $ExpectType Autocomplete[] +M.Autocomplete.init(document.querySelectorAll('.whatever')); +// $ExpectType Autocomplete[] +M.Autocomplete.init(jQuery('.whatever')); +// $ExpectType Autocomplete[] +M.Autocomplete.init(cash('.whatever')); diff --git a/types/materialize-css/test/datepicker.test.ts b/types/materialize-css/test/datepicker.test.ts new file mode 100644 index 0000000000..bd5279243e --- /dev/null +++ b/types/materialize-css/test/datepicker.test.ts @@ -0,0 +1,42 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Datepicker +const _datePicker = new M.Datepicker(elem); +// $ExpectType Datepicker +const el = M.Datepicker.init(elem); +// $ExpectType Datepicker[] +const els = M.Datepicker.init(document.querySelectorAll('.whatever')); + +// $ExpectType Datepicker +new materialize.Datepicker(elem); +// $ExpectType Datepicker +const datePicker = new materialize.Datepicker(elem, { + defaultDate: new Date(), + onSelect(date) { + // $ExpectType Datepicker + this; + // $ExpectType Date + date; + } +}); +// $ExpectType void +datePicker.open(); +// $ExpectType void +datePicker.setDate(new Date()); +// $ExpectType void +datePicker.destroy(); +// $ExpectType DatepickerOptions +datePicker.options; +// $ExpectType Element +datePicker.el; +// $ExpectType boolean +datePicker.isOpen; + +$(".whatever").datepicker(); +$(".whatever").datepicker({ defaultDate: new Date() }); +$(".whatever").datepicker("open"); +$(".whatever").datepicker("destroy"); +$(".whatever").datepicker("setDate", new Date()); +$(".whatever").datepicker("gotoDate", new Date()); diff --git a/types/materialize-css/test/dropdown.test.ts b/types/materialize-css/test/dropdown.test.ts new file mode 100644 index 0000000000..a10eef6fc1 --- /dev/null +++ b/types/materialize-css/test/dropdown.test.ts @@ -0,0 +1,46 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Dropdown +const _dropdown = new M.Dropdown(elem); +// $ExpectType Dropdown +const el = M.Dropdown.init(elem); +// $ExpectType Dropdown[] +const els = M.Dropdown.init(document.querySelectorAll('.whatever')); + +// $ExpectType Dropdown +new materialize.Dropdown(elem); +// $ExpectType Dropdown +const dropdown = new materialize.Dropdown(elem, { + alignment: "left" +}); +// $ExpectType void +dropdown.open(); +// $ExpectType void +dropdown.close(); +// $ExpectType void +dropdown.destroy(); +// $ExpectType void +dropdown.recalculateDimensions(); +// $ExpectType Element +dropdown.dropdownEl; +// $ExpectType Element +dropdown.el; +// $ExpectType number +dropdown.focusedIndex; +// $ExpectType string +dropdown.id; +// $ExpectType boolean +dropdown.isOpen; +// $ExpectType boolean +dropdown.isScrollable; +// $ExpectType DropdownOptions +dropdown.options; + +$(".whatever").dropdown(); +$(".whatever").dropdown({ alignment: "left" }); +$(".whatever").dropdown("open"); +$(".whatever").dropdown("close"); +$(".whatever").dropdown("destroy"); +$(".whatever").dropdown("recalculateDimensions"); diff --git a/types/materialize-css/test/fab.test.ts b/types/materialize-css/test/fab.test.ts new file mode 100644 index 0000000000..988adbf4bb --- /dev/null +++ b/types/materialize-css/test/fab.test.ts @@ -0,0 +1,32 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType FloatingActionButton +const _fab = new M.FloatingActionButton(elem); +// $ExpectType FloatingActionButton +const el = M.FloatingActionButton.init(elem); +// $ExpectType FloatingActionButton[] +const els = M.FloatingActionButton.init(document.querySelectorAll('.whatever')); + +// $ExpectType FloatingActionButton +new materialize.FloatingActionButton(elem); +// $ExpectType FloatingActionButton +const fab = new materialize.FloatingActionButton(elem, { + direction: 'left' +}); +// $ExpectType void +fab.open(); +// $ExpectType void +fab.destroy(); +// $ExpectType FloatingActionButtonOptions +fab.options; +// $ExpectType Element +fab.el; +// $ExpectType boolean +fab.isOpen; + +$(".whatever").floatingActionButton(); +$(".whatever").floatingActionButton({ direction: "left" }); +$(".whatever").floatingActionButton("open"); +$(".whatever").floatingActionButton("destroy"); diff --git a/types/materialize-css/test/formselect.test.ts b/types/materialize-css/test/formselect.test.ts new file mode 100644 index 0000000000..1a5192de41 --- /dev/null +++ b/types/materialize-css/test/formselect.test.ts @@ -0,0 +1,42 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType FormSelect +const _formselect = new M.FormSelect(elem); +// $ExpectType FormSelect +const el = M.FormSelect.init(elem); +// $ExpectType FormSelect[] +const els = M.FormSelect.init(document.querySelectorAll('.whatever')); + +// $ExpectType FormSelect +new materialize.FormSelect(elem); +// $ExpectType FormSelect +const formSelect = new materialize.FormSelect(elem, { + classes: "whatever", + dropdownOptions: { + alignment: "left" + } +}); +// $ExpectType string[] +formSelect.getSelectedValues(); +// $ExpectType void +formSelect.destroy(); +// $ExpectType FormSelectOptions +formSelect.options; +// $ExpectType Element +formSelect.el; +// $ExpectType Dropdown +formSelect.dropdown; +// $ExpectType HTMLUListElement +formSelect.dropdownOptions; +// $ExpectType HTMLInputElement +formSelect.input; +// $ExpectType boolean +formSelect.isMultiple; +// $ExpectType Element +formSelect.wrapper; + +$(".whatever").formSelect(); +$(".whatever").formSelect({ classes: "whatever" }); +$(".whatever").formSelect("destroy"); diff --git a/types/materialize-css/test/inputfields.test.ts b/types/materialize-css/test/inputfields.test.ts new file mode 100644 index 0000000000..ecde571537 --- /dev/null +++ b/types/materialize-css/test/inputfields.test.ts @@ -0,0 +1,7 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +M.textareaAutoResize(elem); +M.textareaAutoResize($(elem)); +M.textareaAutoResize(cash(elem)); diff --git a/types/materialize-css/test/materialbox.test.ts b/types/materialize-css/test/materialbox.test.ts new file mode 100644 index 0000000000..277edb7305 --- /dev/null +++ b/types/materialize-css/test/materialbox.test.ts @@ -0,0 +1,49 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Materialbox +const _materialbox = new M.Materialbox(elem); +// $ExpectType Materialbox +const el = M.Materialbox.init(elem); +// $ExpectType Materialbox[] +const els = M.Materialbox.init(document.querySelectorAll('.whatever')); + +// $ExpectType Materialbox +const materialbox = new materialize.Materialbox(elem, { + inDuration: 1, + outDuration: 1, + onCloseEnd(el) { + // $ExpectType Element + el; + }, + onCloseStart(el) { + // $ExpectType Element + el; + }, + onOpenEnd(el) { + // $ExpectType Element + el; + }, + onOpenStart(el) { + // $ExpectType Element + el; + } +}); + +// $ExpectType void +materialbox.close(); +// $ExpectType void +materialbox.destroy(); +// $ExpectType void +materialbox.open(); +// $ExpectType Element +materialbox.el; +// $ExpectType MaterialboxOptions +materialbox.options; + +$(".whatever").materialbox(); +$(".whatever").materialbox({ inDuration: 2 }); +$(".whatever").materialbox("open"); +$(".whatever").materialbox("destroy"); +$(".whatever").materialbox("close"); diff --git a/types/materialize-css/test/materialize-css-global.test.ts b/types/materialize-css/test/materialize-css-global.test.ts deleted file mode 100644 index 79ed142be4..0000000000 --- a/types/materialize-css/test/materialize-css-global.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -const elem = document.querySelector('.whatever')!; -// $ExpectType Sidenav -const sidenav = new M.Sidenav(elem); - -// $ExpectType Tabs -const tabs = new M.Tabs(elem); - -// $ExpectType Modal -const modal = new M.Modal(elem); - -// $ExpectType Autocomplete -const autocomplete = new M.Autocomplete(elem); - -// $ExpectType CharacterCounter -const characterCounter = new M.CharacterCounter(elem); - -// $ExpectType Tooltip -const tooltips = new M.Tooltip(elem); - -// $ExpectType FloatingActionButton -const fab = new M.FloatingActionButton(elem); - -// $ExpectType Toast -const toast = M.toast({ html: 'I am a toast!' }); - -// $ExpectType DatePicker -const datePicker = new M.DatePicker(elem); - -// $ExpectType TimePicker -const timePicker = new M.TimePicker(elem); - -// $ExpectType Dropdown -const dropdown = new M.Dropdown(elem); - -// $ExpectType FormSelect -const formSelect = new M.FormSelect(elem); diff --git a/types/materialize-css/test/materialize-css-jquery.test.ts b/types/materialize-css/test/materialize-css-jquery.test.ts deleted file mode 100644 index 7bf9faa957..0000000000 --- a/types/materialize-css/test/materialize-css-jquery.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -$(".whatever").sidenav(); -$(".whatever").sidenav({ inDuration: 200 }); -$(".whatever").sidenav("open"); -$(".whatever").sidenav("destroy"); - -$(".whatever").tabs(); -$(".whatever").tabs({ duration: 200 }); -$(".whatever").tabs("destroy"); -$(".whatever").tabs("select", "id"); - -$(".whatever").modal(); -$(".whatever").modal({ inDuration: 200 }); -$(".whatever").modal("open"); -$(".whatever").modal("destroy"); - -$(".whatever").characterCounter(); -$(".whatever").characterCounter("destroy"); - -$(".whatever").autocomplete({ - data: { - Apple: null, - Google: "https://placehold.it/250x250" - } -}); -$(".whatever").autocomplete("updateData", { Microsoft: null }); - -$(".whatever").tooltip(); -$(".whatever").tooltip({ html: "" }); -$(".whatever").tooltip("open"); -$(".whatever").tooltip("destroy"); - -$(".whatever").floatingActionButton(); -$(".whatever").floatingActionButton({ direction: "left" }); -$(".whatever").floatingActionButton("open"); -$(".whatever").floatingActionButton("destroy"); - -// Toast can not be invoked using jQuery. - -$(".whatever").datepicker(); -$(".whatever").datepicker({ defaultDate: new Date() }); -$(".whatever").datepicker("open"); -$(".whatever").datepicker("destroy"); -$(".whatever").datepicker("setDate", new Date()); -$(".whatever").datepicker("gotoDate", new Date()); - -$(".whatever").timepicker(); -$(".whatever").timepicker({ defaultTime: "13:14" }); -$(".whatever").timepicker("open"); -$(".whatever").timepicker("destroy"); -$(".whatever").timepicker("showView", "hours"); - -$(".whatever").formSelect(); -$(".whatever").formSelect({ classes: "whatever" }); -$(".whatever").formSelect("destroy"); - -$(".whatever").dropdown(); -$(".whatever").dropdown({ alignment: "left" }); -$(".whatever").dropdown("open"); -$(".whatever").dropdown("close"); -$(".whatever").dropdown("destroy"); -$(".whatever").dropdown("recalculateDimensions"); diff --git a/types/materialize-css/test/materialize-css-module.test.ts b/types/materialize-css/test/materialize-css-module.test.ts deleted file mode 100644 index 874e596aaa..0000000000 --- a/types/materialize-css/test/materialize-css-module.test.ts +++ /dev/null @@ -1,277 +0,0 @@ -import * as materialize from "materialize-css"; - -const elem = document.querySelector('.whatever')!; - -// Sidenav -// $ExpectType Sidenav -new materialize.Sidenav(elem); -// $ExpectType Sidenav -const sidenav = new materialize.Sidenav(elem, { - edge: "left", - inDuration: 300, - onCloseStart(el) { - // $ExpectType Sidenav - this; - // $ExpectType Element - el; - } -}); -// $ExpectType void -sidenav.open(); -// $ExpectType void -sidenav.destroy(); -// $ExpectType SidenavOptions -sidenav.options; -// $ExpectType Element -sidenav.el; -// $ExpectType boolean -sidenav.isOpen; - -// Tabs -// $ExpectType Tabs -new materialize.Tabs(elem); -// $ExpectType Tabs -const tabs = new materialize.Tabs(elem, { - duration: 200, - onShow(content) { - // $ExpectType Tabs - this; - // $ExpectType Element - content; - } -}); -// $ExpectType void -tabs.destroy(); -// $ExpectType void -tabs.select("id"); -// $ExpectType TabsOptions -tabs.options; -// $ExpectType Element -tabs.el; -// $ExpectType number -tabs.index; - -// Modal -// $ExpectType Modal -new materialize.Modal(elem); -// $ExpectType Modal -const modal = new materialize.Modal(elem, { - inDuration: 300, - ready(el, trigger) { - // $ExpectType Modal - this; - // $ExpectType Element - el; - // $ExpectType Element - trigger; - } -}); -// $ExpectType void -modal.open(); -// $ExpectType void -modal.destroy(); -// $ExpectType ModalOptions -modal.options; -// $ExpectType Element -modal.el; -// $ExpectType boolean -modal.isOpen; - -// CharacterCounter -// $ExpectType CharacterCounter -const characterCounter = new materialize.CharacterCounter(elem); -// $ExpectType void -characterCounter.destroy(); -// $ExpectType Element -characterCounter.el; - -// Autocomplete -// $ExpectType Autocomplete -new materialize.Autocomplete(elem); -// $ExpectType Autocomplete -const autocomplete = new materialize.Autocomplete(elem, { - data: { - Apple: null, - Google: "https://placehold.it/250x250" - }, - minLength: 3, - onAutocomplete(text) { - // $ExpectType Autocomplete - this; - // $ExpectType string - text; - }, - sortFunction(a, b, input) { - // $ExpectType string - a; - // $ExpectType string - b; - // $ExpectType string - input; - return 0; - } -}); -// $ExpectType void -autocomplete.updateData({ Microsoft: null }); -// $ExpectType void -autocomplete.destroy(); -// $ExpectType AutocompleteOptions -autocomplete.options; -// $ExpectType Element -autocomplete.el; -// $ExpectType boolean -autocomplete.isOpen; - -// Tooltip -// $ExpectType Tooltip -new materialize.Tooltip(elem); -// $ExpectType Tooltip -const tooltip = new materialize.Tooltip(elem, { - inDuration: 300, - position: "right" -}); -// $ExpectType void -tooltip.open(); -// $ExpectType void -tooltip.destroy(); -// $ExpectType TooltipOptions -tooltip.options; -// $ExpectType Element -tooltip.el; -// $ExpectType boolean -tooltip.isOpen; - -// FloatingActionButton -// $ExpectType FloatingActionButton -new materialize.FloatingActionButton(elem); -// $ExpectType FloatingActionButton -const fab = new materialize.FloatingActionButton(elem, { - direction: 'left' -}); -// $ExpectType void -fab.open(); -// $ExpectType void -fab.destroy(); -// $ExpectType FloatingActionButtonOptions -fab.options; -// $ExpectType Element -fab.el; -// $ExpectType boolean -fab.isOpen; - -// Toasts -// $ExpectType Toast -const toast = materialize.toast({ html: 'I am a toast!' }); -// $ExpectType ToastOptions -toast.options; -// $ExpectType Element -fab.el; -// $ExpectType void -toast.dismiss(); -// $ExpectType void -materialize.Toast.dismissAll(); - -// DatePicker -// $ExpectType DatePicker -new materialize.DatePicker(elem); -// $ExpectType DatePicker -const datePicker = new materialize.DatePicker(elem, { - defaultDate: new Date(), - onSelect(date) { - // $ExpectType DatePicker - this; - // $ExpectType Date - date; - } -}); -// $ExpectType void -datePicker.open(); -// $ExpectType void -datePicker.setDate(new Date()); -// $ExpectType void -datePicker.destroy(); -// $ExpectType DatePickerOptions -datePicker.options; -// $ExpectType Element -datePicker.el; -// $ExpectType boolean -datePicker.isOpen; - -// TimePicker -// $ExpectType TimePicker -new materialize.TimePicker(elem); -// $ExpectType TimePicker -const timePicker = new materialize.TimePicker(elem, { - defaultTime: "13:14" -}); -// $ExpectType void -timePicker.open(); -// $ExpectType void -timePicker.showView("hours"); -// $ExpectType void -timePicker.destroy(); -// $ExpectType TimePickerOptions -timePicker.options; -// $ExpectType Element -timePicker.el; -// $ExpectType boolean -timePicker.isOpen; - -// Dropdown -// $ExpectType Dropdown -new materialize.Dropdown(elem); -// $ExpectType Dropdown -const dropdown = new materialize.Dropdown(elem, { - alignment: "left" -}); -// $ExpectType void -dropdown.open(); -// $ExpectType void -dropdown.close(); -// $ExpectType void -dropdown.destroy(); -// $ExpectType void -dropdown.recalculateDimensions(); -// $ExpectType Element -dropdown.dropdownEl; -// $ExpectType Element -dropdown.el; -// $ExpectType number -dropdown.focusedIndex; -// $ExpectType string -dropdown.id; -// $ExpectType boolean -dropdown.isOpen; -// $ExpectType boolean -dropdown.isScrollable; -// $ExpectType DropdownOptions -dropdown.options; - -// FormSelect -// $ExpectType FormSelect -new materialize.FormSelect(elem); -// $ExpectType FormSelect -const formSelect = new materialize.FormSelect(elem, { - classes: "whatever", - dropdownOptions: { - alignment: "left" - } -}); -// $ExpectType string[] -formSelect.getSelectedValues(); -// $ExpectType void -formSelect.destroy(); -// $ExpectType FormSelectOptions -formSelect.options; -// $ExpectType Element -formSelect.el; -// $ExpectType Dropdown -formSelect.dropdown; -// $ExpectType HTMLUListElement -formSelect.dropdownOptions; -// $ExpectType HTMLInputElement -formSelect.input; -// $ExpectType boolean -formSelect.isMultiple; -// $ExpectType Element -formSelect.wrapper; diff --git a/types/materialize-css/test/modal.test.ts b/types/materialize-css/test/modal.test.ts new file mode 100644 index 0000000000..3d3923e28b --- /dev/null +++ b/types/materialize-css/test/modal.test.ts @@ -0,0 +1,38 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Modal +const _modal = new M.Modal(elem); +// $ExpectType Modal +const el = M.Modal.init(elem); +// $ExpectType Modal[] +const els = M.Modal.init(document.querySelectorAll('.whatever')); + +// $ExpectType Modal +new materialize.Modal(elem); +// $ExpectType Modal +const modal = new materialize.Modal(elem, { + inDuration: 300, + onOpenStart(el) { + // $ExpectType Modal + this; + // $ExpectType Element + el; + } +}); +// $ExpectType void +modal.open(); +// $ExpectType void +modal.destroy(); +// $ExpectType ModalOptions +modal.options; +// $ExpectType Element +modal.el; +// $ExpectType boolean +modal.isOpen; + +$(".whatever").modal(); +$(".whatever").modal({ inDuration: 200 }); +$(".whatever").modal("open"); +$(".whatever").modal("destroy"); diff --git a/types/materialize-css/test/parallax.test.ts b/types/materialize-css/test/parallax.test.ts new file mode 100644 index 0000000000..62beb046e7 --- /dev/null +++ b/types/materialize-css/test/parallax.test.ts @@ -0,0 +1,24 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Parallax +const _parallax = new M.Parallax(elem); +// $ExpectType Parallax +const el = M.Parallax.init(elem); +// $ExpectType Parallax[] +const els = M.Parallax.init(document.querySelectorAll('.whatever')); + +// $ExpectType Parallax +const parallax = new materialize.Parallax(elem, { responsiveThreshold: 1 }); + +// $ExpectType void +parallax.destroy(); +// $ExpectType Element +parallax.el; +// $ExpectType ParallaxOptions +parallax.options; + +$(".whatever").parallax(); +$(".whatever").parallax({ responsiveThreshold: 2 }); +$(".whatever").parallax("destroy"); diff --git a/types/materialize-css/test/pushpin.test.ts b/types/materialize-css/test/pushpin.test.ts new file mode 100644 index 0000000000..bb521b2cf6 --- /dev/null +++ b/types/materialize-css/test/pushpin.test.ts @@ -0,0 +1,34 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Pushpin +const _pushpin = new M.Pushpin(elem); +// $ExpectType Pushpin +const el = M.Pushpin.init(elem); +// $ExpectType Pushpin[] +const els = M.Pushpin.init(document.querySelectorAll('.whatever')); + +// $ExpectType Pushpin +const pushpin = new materialize.Pushpin(elem, { + bottom: 1, + offset: 1, + onPositionChange(position) { + // $ExpectType "pinned" | "pin-top" | "pin-bottom" + position; + }, + top: 1 +}); + +// $ExpectType void +pushpin.destroy(); +// $ExpectType Element +pushpin.el; +// $ExpectType PushpinOptions +pushpin.options; +// $ExpectType number +pushpin.originalOffset; + +$(".whatever").pushpin(); +$(".whatever").pushpin({ top: 2 }); +$(".whatever").pushpin("destroy"); diff --git a/types/materialize-css/test/range.test.ts b/types/materialize-css/test/range.test.ts new file mode 100644 index 0000000000..cf343b0341 --- /dev/null +++ b/types/materialize-css/test/range.test.ts @@ -0,0 +1,22 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Range +const _range = new M.Range(elem); +// $ExpectType Range +const el = M.Range.init(elem); +// $ExpectType Range[] +const els = M.Range.init(document.querySelectorAll('.whatever')); + +// $ExpectType Range +const range = new materialize.Range(elem); +// $ExpectType void +range.destroy(); +// $ExpectType Element +range.el; +// $ExpectType undefined +range.options; + +$(".whatever").range(); +$(".whatever").range("destroy"); diff --git a/types/materialize-css/test/scrollspy.test.ts b/types/materialize-css/test/scrollspy.test.ts new file mode 100644 index 0000000000..a797123626 --- /dev/null +++ b/types/materialize-css/test/scrollspy.test.ts @@ -0,0 +1,32 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType ScrollSpy +const _scrollspy = new M.ScrollSpy(elem); +// $ExpectType ScrollSpy +const el = M.ScrollSpy.init(elem); +// $ExpectType ScrollSpy[] +const els = M.ScrollSpy.init(document.querySelectorAll('.whatever')); + +// $ExpectType ScrollSpy +const scrollspy = new materialize.ScrollSpy(elem, { + activeClass: "class", + getActiveElement(id) { + // $ExpectType string + id; + return "string"; + }, + scrollOffset: 1, + throttle: 1 +}); + +// $ExpectType void +scrollspy.destroy(); +// $ExpectType Element +scrollspy.el; +// $ExpectType ScrollSpyOptions +scrollspy.options; + +$(".whatever").scrollSpy(); +$(".whatever").scrollSpy("destroy"); diff --git a/types/materialize-css/test/sidenav.test.ts b/types/materialize-css/test/sidenav.test.ts new file mode 100644 index 0000000000..485c3be144 --- /dev/null +++ b/types/materialize-css/test/sidenav.test.ts @@ -0,0 +1,39 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Sidenav +const _sidenav = new M.Sidenav(elem); +// $ExpectType Sidenav +const el = M.Sidenav.init(elem); +// $ExpectType Sidenav[] +const els = M.Sidenav.init(document.querySelectorAll('.whatever')); + +// $ExpectType Sidenav +new materialize.Sidenav(elem); +// $ExpectType Sidenav +const sidenav = new materialize.Sidenav(elem, { + edge: "left", + inDuration: 300, + onCloseStart(el) { + // $ExpectType Sidenav + this; + // $ExpectType Element + el; + } +}); +// $ExpectType void +sidenav.open(); +// $ExpectType void +sidenav.destroy(); +// $ExpectType SidenavOptions +sidenav.options; +// $ExpectType Element +sidenav.el; +// $ExpectType boolean +sidenav.isOpen; + +$(".whatever").sidenav(); +$(".whatever").sidenav({ inDuration: 200 }); +$(".whatever").sidenav("open"); +$(".whatever").sidenav("destroy"); diff --git a/types/materialize-css/test/slider.test.ts b/types/materialize-css/test/slider.test.ts new file mode 100644 index 0000000000..c1950ed165 --- /dev/null +++ b/types/materialize-css/test/slider.test.ts @@ -0,0 +1,43 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Slider +const _slider = new M.Slider(elem); +// $ExpectType Slider +const el = M.Slider.init(elem); +// $ExpectType Slider[] +const els = M.Slider.init(document.querySelectorAll('.whatever')); + +// $ExpectType Slider +const slider = new materialize.Slider(elem, { + duration: 1, + height: 1, + indicators: true, + interval: 1 +}); + +// $ExpectType void +slider.destroy(); +// $ExpectType Element +slider.el; +// $ExpectType SliderOptions +slider.options; +// $ExpectType number +slider.activeIndex; +// $ExpectType void +slider.next(); +// $ExpectType void +slider.pause(); +// $ExpectType void +slider.prev(); +// $ExpectType void +slider.start(); + +$(".whatever").slider(); +$(".whatever").slider({ duration: 1 }); +$(".whatever").slider("destroy"); +$(".whatever").slider("next"); +$(".whatever").slider("pause"); +$(".whatever").slider("prev"); +$(".whatever").slider("start"); diff --git a/types/materialize-css/test/tabs.test.ts b/types/materialize-css/test/tabs.test.ts new file mode 100644 index 0000000000..9c0c0acdad --- /dev/null +++ b/types/materialize-css/test/tabs.test.ts @@ -0,0 +1,38 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Tabs +const _tabs = new M.Tabs(elem); +// $ExpectType Tabs +const el = M.Tabs.init(elem); +// $ExpectType Tabs[] +const els = M.Tabs.init(document.querySelectorAll('.whatever')); + +// $ExpectType Tabs +new materialize.Tabs(elem); +// $ExpectType Tabs +const tabs = new materialize.Tabs(elem, { + duration: 200, + onShow(content) { + // $ExpectType Tabs + this; + // $ExpectType Element + content; + } +}); +// $ExpectType void +tabs.destroy(); +// $ExpectType void +tabs.select("id"); +// $ExpectType TabsOptions +tabs.options; +// $ExpectType Element +tabs.el; +// $ExpectType number +tabs.index; + +$(".whatever").tabs(); +$(".whatever").tabs({ duration: 200 }); +$(".whatever").tabs("destroy"); +$(".whatever").tabs("select", "id"); diff --git a/types/materialize-css/test/taptarget.test.ts b/types/materialize-css/test/taptarget.test.ts new file mode 100644 index 0000000000..91b00168cd --- /dev/null +++ b/types/materialize-css/test/taptarget.test.ts @@ -0,0 +1,38 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType TapTarget +const _taptarget = new M.TapTarget(elem); +// $ExpectType TapTarget +const el = M.TapTarget.init(elem); +// $ExpectType TapTarget[] +const els = M.TapTarget.init(document.querySelectorAll('.whatever')); + +// $ExpectType TapTarget +const taptarget = new materialize.TapTarget(elem, { + onClose(origin) { + // $ExpectType Element + origin; + }, + onOpen(origin) { + // $ExpectType Element + origin; + } +}); + +// $ExpectType void +taptarget.destroy(); +// $ExpectType void +taptarget.close(); +// $ExpectType void +taptarget.open(); +// $ExpectType Element +taptarget.el; +// $ExpectType TapTargetOptions +taptarget.options; + +$(".whatever").tapTarget(); +$(".whatever").tapTarget("destroy"); +$(".whatever").tapTarget("close"); +$(".whatever").tapTarget("open"); diff --git a/types/materialize-css/test/timepicker.test.ts b/types/materialize-css/test/timepicker.test.ts new file mode 100644 index 0000000000..6c187b2cfe --- /dev/null +++ b/types/materialize-css/test/timepicker.test.ts @@ -0,0 +1,65 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Timepicker +const _timePicker = new M.Timepicker(elem); +// $ExpectType Timepicker +const el = M.Timepicker.init(elem); +// $ExpectType Timepicker[] +const els = M.Timepicker.init(document.querySelectorAll('.whatever')); + +// $ExpectType Timepicker +new materialize.Timepicker(elem); +// $ExpectType Timepicker +const timePicker = new materialize.Timepicker(elem, { + duration: 1, + container: "selector", + showClearBtn: true, + defaultTime: "13:14", + fromNow: 1, + i18n: { done: "Ok, Mate" }, + autoClose: true, + twelveHour: true, + vibrate: true, + onOpenStart(el) { + // $ExpectType Element + el; + }, + onOpenEnd(el) { + // $ExpectType Element + el; + }, + onCloseStart(el) { + // $ExpectType Element + el; + }, + onCloseEnd(el) { + // $ExpectType Element + el; + }, + onSelect(hour, minute) { + // $ExpectType number + hour; + // $ExpectType number + minute; + } +}); +// $ExpectType void +timePicker.open(); +// $ExpectType void +timePicker.showView("hours"); +// $ExpectType void +timePicker.destroy(); +// $ExpectType TimepickerOptions +timePicker.options; +// $ExpectType Element +timePicker.el; +// $ExpectType boolean +timePicker.isOpen; + +$(".whatever").timepicker(); +$(".whatever").timepicker({ defaultTime: "13:14" }); +$(".whatever").timepicker("open"); +$(".whatever").timepicker("destroy"); +$(".whatever").timepicker("showView", "hours"); diff --git a/types/materialize-css/test/toast.test.ts b/types/materialize-css/test/toast.test.ts new file mode 100644 index 0000000000..ede26bcc20 --- /dev/null +++ b/types/materialize-css/test/toast.test.ts @@ -0,0 +1,17 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Toast +const _toast = M.toast({ html: 'I am a toast!' }); + +// $ExpectType Toast +const toast = materialize.toast({ html: 'I am a toast!' }); +// $ExpectType ToastOptions +toast.options; +// $ExpectType Element +toast.el; +// $ExpectType void +toast.dismiss(); +// $ExpectType void +materialize.Toast.dismissAll(); diff --git a/types/materialize-css/test/tooltip.test.ts b/types/materialize-css/test/tooltip.test.ts new file mode 100644 index 0000000000..db9453e95f --- /dev/null +++ b/types/materialize-css/test/tooltip.test.ts @@ -0,0 +1,33 @@ +import * as materialize from "materialize-css"; + +const elem = document.querySelector('.whatever')!; + +// $ExpectType Tooltip +const _tooltip = new M.Tooltip(elem); +// $ExpectType Tooltip +const el = M.Tooltip.init(elem); +// $ExpectType Tooltip[] +const els = M.Tooltip.init(document.querySelectorAll('.whatever')); + +// $ExpectType Tooltip +new materialize.Tooltip(elem); +// $ExpectType Tooltip +const tooltip = new materialize.Tooltip(elem, { + inDuration: 300, + position: "right" +}); +// $ExpectType void +tooltip.open(); +// $ExpectType void +tooltip.destroy(); +// $ExpectType TooltipOptions +tooltip.options; +// $ExpectType Element +tooltip.el; +// $ExpectType boolean +tooltip.isOpen; + +$(".whatever").tooltip(); +$(".whatever").tooltip({ html: "" }); +$(".whatever").tooltip("open"); +$(".whatever").tooltip("destroy"); diff --git a/types/materialize-css/test/waves.test.ts b/types/materialize-css/test/waves.test.ts new file mode 100644 index 0000000000..c73ae78904 --- /dev/null +++ b/types/materialize-css/test/waves.test.ts @@ -0,0 +1,4 @@ +const elem = document.querySelector('.whatever')!; + +// $ExpectType void +Waves.attach(elem); diff --git a/types/materialize-css/timepicker.d.ts b/types/materialize-css/timepicker.d.ts new file mode 100644 index 0000000000..5f9b3ec5bf --- /dev/null +++ b/types/materialize-css/timepicker.d.ts @@ -0,0 +1,136 @@ +/// + +declare namespace M { + class Timepicker extends Component { + /** + * Get Instance + */ + static getInstance(elem: Element): Timepicker; + + /** + * Init Timepicker + */ + static init(els: Element, options?: Partial): Timepicker; + + /** + * Init Timepickers + */ + static init(els: MElements, options?: Partial): Timepicker[]; + + /** + * If the picker is open. + */ + isOpen: boolean; + + /** + * The selected time. + */ + time: string; + + /** + * Open timepicker + */ + open(): void; + + /** + * Close timepicker + */ + close(): void; + + /** + * Show hours or minutes view on timepicker + * @param view The name of the view you want to switch to, 'hours' or 'minutes'. + */ + showView(view: "hours" | "minutes"): void; + } + + interface TimepickerOptions { + /** + * Duration of the transition from/to the hours/minutes view. + * @default 350 + */ + duration: number; + + /** + * Specify a selector for a DOM element to render the calendar in, by default it will be placed before the input. + */ + container: string; + + /** + * Show the clear button in the Timepicker + * @default false + */ + showClearBtn: boolean; + + /** + * Default time to set on the timepicker 'now' or '13:14' + * @default 'now'; + */ + defaultTime: string; + + /** + * Millisecond offset from the defaultTime. + * @default 0 + */ + fromNow: number; + + /** + * Internationalization options + */ + i18n: Partial; + + /** + * Automatically close picker when minute is selected. + * @default false; + */ + autoClose: boolean; + + /** + * Use 12 hour AM/PM clock instead of 24 hour clock. + * @default true + */ + twelveHour: boolean; + + /** + * Vibrate device when dragging clock hand. + * @default true + */ + vibrate: boolean; + + /** + * Callback function called before modal is opened + * @default null + */ + onOpenStart: (this: Modal, el: Element) => void; + + /** + * Callback function called after modal is opened + * @default null + */ + onOpenEnd: (this: Modal, el: Element) => void; + + /** + * Callback function called before modal is closed + * @default null + */ + onCloseStart: (this: Modal, el: Element) => void; + + /** + * Callback function called after modal is closed + * @default null + */ + onCloseEnd: (this: Modal, el: Element) => void; + + /** + * Callback function when a time is selected + * @default null + */ + onSelect: (this: Modal, hour: number, minute: number) => void; + } +} + +interface JQuery { + timepicker(method: keyof Pick): JQuery; + timepicker(method: keyof Pick, view: "hours" | "minutes"): JQuery; + timepicker(options?: Partial): JQuery; +} diff --git a/types/materialize-css/toast.d.ts b/types/materialize-css/toast.d.ts new file mode 100644 index 0000000000..4953c7135b --- /dev/null +++ b/types/materialize-css/toast.d.ts @@ -0,0 +1,76 @@ +/// + +declare namespace M { + class Toast extends ComponentBase { + /** + * Get Instance + */ + static getInstance(elem: Element): Toast; + + /** + * Describes the current pan state of the Toast. + */ + panning: boolean; + + /** + * The remaining amount of time in ms that the toast will stay before dismissal. + */ + timeRemaining: number; + + /** + * remove a specific toast + */ + dismiss(): void; + + /** + * dismiss all toasts + */ + static dismissAll(): void; + } + + interface ToastOptions { + /** + * The HTML content of the Toast. + */ + html: string; + + /** + * Length in ms the Toast stays before dismissal. + * @default 4000 + */ + displayLength: number; + + /** + * Transition in duration in milliseconds. + * @default 300 + */ + inDuration: number; + + /** + * Transition out duration in milliseconds. + * @default 375 + */ + outDuration: number; + + /** + * Classes to be added to the toast element. + */ + classes: string; + + /** + * Callback function called when toast is dismissed. + */ + completeCallback: () => void; + + /** + * The percentage of the toast's width it takes for a drag to dismiss a Toast. + * @default 0.8 + */ + activationPercent: number; + } + + /** + * Create a toast + */ + function toast(options: Partial): Toast; +} diff --git a/types/materialize-css/tooltip.d.ts b/types/materialize-css/tooltip.d.ts new file mode 100644 index 0000000000..6b7320a20a --- /dev/null +++ b/types/materialize-css/tooltip.d.ts @@ -0,0 +1,95 @@ +/// + +declare namespace M { + class Tooltip extends Component implements Openable { + /** + * Get Instance + */ + static getInstance(elem: Element): Tooltip; + + /** + * Init Tooltip + */ + static init(els: Element, options?: Partial): Tooltip; + + /** + * Init Tooltips + */ + static init(els: MElements, options?: Partial): Tooltip[]; + + /** + * Show tooltip. + */ + open(): void; + + /** + * Hide tooltip. + */ + close(): void; + + /** + * If tooltip is open. + */ + isOpen: boolean; + + /** + * If tooltip is hovered. + */ + isHovered: boolean; + } + + interface TooltipOptions { + /** + * Delay time before tooltip disappears. + * @default 0 + */ + exitDelay: number; + + /** + * Delay time before tooltip appears. + * @default 200 + */ + enterDelay: number; + + /** + * Can take regular text or HTML strings. + * @default null + */ + html: string; + + /** + * Set distance tooltip appears away from its activator excluding transitionMovement. + * @default 5 + */ + margin: number; + + /** + * Enter transition duration. + * @default 300 + */ + inDuration: number; + + /** + * Exit transition duration. + * @default 250 + */ + outDuration: number; + + /** + * Set the direction of the tooltip. + * @default 'bottom' + */ + position: 'top' | 'right' | 'bottom' | 'left'; + + /** + * Amount in px that the tooltip moves during its transition. + * @default 10 + */ + transitionMovement: number; + } +} + +interface JQuery { + tooltip(method: keyof Pick): JQuery; + tooltip(options?: Partial): JQuery; +} diff --git a/types/materialize-css/tsconfig.json b/types/materialize-css/tsconfig.json index 617d1b925a..cf2b279cb7 100644 --- a/types/materialize-css/tsconfig.json +++ b/types/materialize-css/tsconfig.json @@ -19,8 +19,30 @@ }, "files": [ "index.d.ts", - "test/materialize-css-global.test.ts", - "test/materialize-css-module.test.ts", - "test/materialize-css-jquery.test.ts" + "test/autocomplete.test.ts", + "test/carousel.test.ts", + "test/character-counter.test.ts", + "test/chips.test.ts", + "test/collapsible.test.ts", + "test/common.test.ts", + "test/datepicker.test.ts", + "test/dropdown.test.ts", + "test/fab.test.ts", + "test/formselect.test.ts", + "test/inputfields.test.ts", + "test/materialbox.test.ts", + "test/modal.test.ts", + "test/parallax.test.ts", + "test/pushpin.test.ts", + "test/range.test.ts", + "test/scrollspy.test.ts", + "test/sidenav.test.ts", + "test/slider.test.ts", + "test/tabs.test.ts", + "test/taptarget.test.ts", + "test/timepicker.test.ts", + "test/toast.test.ts", + "test/tooltip.test.ts", + "test/waves.test.ts" ] -} \ No newline at end of file +} diff --git a/types/materialize-css/waves.d.ts b/types/materialize-css/waves.d.ts new file mode 100644 index 0000000000..cc86b017e4 --- /dev/null +++ b/types/materialize-css/waves.d.ts @@ -0,0 +1,9 @@ +declare namespace Waves { + /** + * Attach Waves to an input element (or any element which doesn't + * bubble mouseup/mousedown events). + * Intended to be used with dynamically loaded forms/inputs, or + * where the user doesn't want a delegated click handler. + */ + function attach(element: Element): void; +} diff --git a/types/meteor-univserse-i18n/index.d.ts b/types/meteor-univserse-i18n/index.d.ts new file mode 100644 index 0000000000..66ba85ff90 --- /dev/null +++ b/types/meteor-univserse-i18n/index.d.ts @@ -0,0 +1,117 @@ +// Type definitions for https://github.com/vazco/meteor-universe-i18n 1.14 +// Project: meteor-universe-i18n +// Definitions by: Mathias Scherer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// +/// + +// tslint:disable-next-line no-single-declare-module +declare module "meteor/universe:i18n" { + import { OutgoingHttpHeaders } from "http"; + + namespace i18n { + // component functions + function createComponent(translator?: Translator, locale?: string, reactjs?: React.ReactInstance, type?: any): new () => React.Component; + + // translator functions + function createTranslator(namespace: string, options?: TranslaterOptions): Translator; + function createReactiveTranslator(namespace: string, locale: string): new () => React.Component; + + // translation setter / getter functions + function addTranslation(locale: string, namespace: string, translation: string): void; + // tslint:disable-next-line unified-signatures + function addTranslation(locale: string, namespace: string, key: string, translation: string): void; + function addTranslations(locale: string, translationsMap: {}): void; + function addTranslations(locale: string, namespace: string, translationsMap: {}): void; + function getTranslation(key: string, params?: GetTranslationParams): string; + function getTranslation(namespace: string, key: string, params: GetTranslationParams): string; + function getTranslation(...key: string[]): string; + function __(key: string, params?: GetTranslationParams): string; + function __(namespace: string, key: string, params: GetTranslationParams): string; + function __(...key: string[]): string; + function getTranslations(namespace: string, locale?: string): string[]; + + // options setter + function setOptions(options: i18nOptions): void; + + // number operations + function parseNumber(number: string, locale?: string): string; + + // locale setter / getter + function setLocale(locale: string, params?: LocateParams): Promise; + function setLocaleOnConnection(locale: string, connectionId?: number): void; + function getLocale(): string; + function loadLocale(locale: string, params?: LoadLocaleParams): void; + + // executes function in the locale context, + // it means that every default locale used inside a called function will be set to a passed locale + // keep in mind that locale must be loaded first (if it is not bundled) + function runWithLocale(locale: string, func: (...keys: any[]) => void): void; + + // language getters + function getLanguages(type?: 'code' | 'name' | 'nativeNames'): string[]; + function getLanguageName(locale?: string): string; + function getLanguageNativeName(locale?: string): string; + + // currency symbols + function getCurrencySymbol(locale?: string): string | undefined; + function getCurrencyCodes(locale?: string): string[]; + + // others + function isRTL(locale?: string): boolean; + function getAllKeysForLocale(locale?: string, excactlyThis?: boolean): string[]; + + // events + function onChangeLocale(callback: (locale: string) => void): void; + } + + interface ReactComponentProps { + _locale?: string; + _tagType?: string; + _namespace?: string; + _props?: React.HTMLAttributes; + _translateProps?: string[]; + _containerType?: string; + } + + interface i18nOptions { + defaultLocale?: string; + open?: string; + close?: string; + purify?: () => void; + hideMissing?: boolean; + hostUrl?: string; + translationsHeaders?: OutgoingHttpHeaders; + sameLocaleOnServerConnection?: boolean; + } + + interface GetTranslationParams { + _locale?: string; + _namespace?: string; + [key: string]: any; + } + + interface TranslaterOptions { + _locale?: string; + _purify?: boolean; + } + + interface LoadLocaleParams { + fresh?: boolean; + async?: boolean; + silent?: boolean; + host?: string; + pathOnHost?: string; + } + + interface LocateParams { + noDownload?: boolean; + silent?: boolean; + async?: boolean; + fresh?: boolean; + } + + type Translator = (...args: any[]) => string; +} diff --git a/types/meteor-univserse-i18n/meteor-univserse-i18n-tests.ts b/types/meteor-univserse-i18n/meteor-univserse-i18n-tests.ts new file mode 100644 index 0000000000..fbfb921a18 --- /dev/null +++ b/types/meteor-univserse-i18n/meteor-univserse-i18n-tests.ts @@ -0,0 +1,107 @@ +import { i18n, Translator } from 'meteor/universe:i18n'; + +/** + * All code below was copied from the examples at https://github.com/vazco/meteor-universe-i18n + * When necessary, code was added to make the examples work (e.g. declaring a variable + * that was assumed to have been declared earlier); + */ + +let translator: Translator; +translator = i18n.createTranslator('test', { + _locale: 'de-CH', + _purify: true, +}); +translator = i18n.createTranslator('test'); + +i18n.createComponent(); +i18n.createComponent(translator); +i18n.createComponent(translator, 'de-CH'); + +i18n.addTranslation('de-CH', 'test.foo', 'bar'); +i18n.addTranslation('de-CH', 'test', 'foo', 'bar'); +i18n.addTranslation('en-US', 'Common', 'no', 'No'); +i18n.addTranslation('en-US', 'Common.ok', 'Ok'); + +i18n.addTranslations('en-US', { + Common: { + hello: 'Hello {$name} {$0}!' + } +}); + +i18n.addTranslations('en-US', 'Common', { + hello: 'Hello {$name} {$0}!' +}); +i18n.__('foo'); +i18n.__('foo', { _locale: 'de-CH', _namespace: 'test' }); +i18n.__('test', 'foo', { _locale: 'de-CH' }); +i18n.__('hello', { name: 'Ania' }); // output: Hello Ania! +i18n.__('lengthOfArr', { length: ['a', 'b', 'c'].length }); // output: length 3 +i18n.__('items', ['a', 'b', 'c']); // output: The first item is a and the last one is c! +i18n.getTranslations('test', 'de-CH'); + +i18n.setOptions({ + // default locale + defaultLocale: 'en-US', + + // opens string + open: '{$', + + // closes string + close: '}', + + // cleanups untrust/unknown tags, to secure your application against XSS attacks. + // at browser side, default policy is to sanitize strings as a PCDATA + purify: () => { }, // On server side as a default option is that nothing is purifying (but you can provide function for that); + + // decides whether to show when there's no translation in the current and default language + hideMissing: false, + + // url to the host with translations (default: Meteor.absoluteUrl()); + // useful when you want to load translations from a different host + hostUrl: 'http://current.host.url/', + + // (on the server side only) gives you the possibility to add/change response headers + translationsHeaders: { 'Cache-Control': 'max-age=2628000' }, + + // synchronizes server connection with locale on client. (method invoked by client will be with client side locale); + sameLocaleOnServerConnection: true +}); + +i18n.parseNumber('7013217.715'); // 7,013,217.715 +i18n.parseNumber('16217 and 17217,715'); // 16,217 and 17,217.715 +i18n.parseNumber('7013217.715', 'ru-RU'); // 7 013 217,715 + +i18n.setLocale('de-CH').then(() => { + console.log('already is!'); +}); + +i18n.setLocaleOnConnection('de-CH'); +i18n.setLocaleOnConnection('de-CH', 1); + +i18n.getLocale(); + +i18n.getLanguages(); // ['en', 'de'] +i18n.getLanguages('name'); // ['English', 'German'] + +i18n.getLanguageName(); +i18n.getLanguageName('de-CH'); + +i18n.getLanguageNativeName(); +i18n.getLanguageNativeName('de-CH'); + +i18n.getCurrencySymbol(); +i18n.getCurrencySymbol('en-US'); // = $ +i18n.getCurrencySymbol('USD'); // = $ +i18n.getCurrencyCodes(); +i18n.getCurrencyCodes('en-US'); // = ["USD", "USN", "USS"] + +i18n.isRTL(); +i18n.isRTL('en-US'); // = $ + +i18n.getAllKeysForLocale(); +i18n.getAllKeysForLocale('de-CH'); +i18n.getAllKeysForLocale('de-CH', true); + +i18n.onChangeLocale((newLocale: string) => { + console.log(newLocale); +}); diff --git a/types/meteor-univserse-i18n/tsconfig.json b/types/meteor-univserse-i18n/tsconfig.json new file mode 100644 index 0000000000..7beab3bd30 --- /dev/null +++ b/types/meteor-univserse-i18n/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "meteor-univserse-i18n-tests.ts" + ] +} diff --git a/types/meteor-univserse-i18n/tslint.json b/types/meteor-univserse-i18n/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/meteor-univserse-i18n/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mirrorx/index.d.ts b/types/mirrorx/index.d.ts index 3e7090eab2..07b26d494c 100644 --- a/types/mirrorx/index.d.ts +++ b/types/mirrorx/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mirrorjs/mirror // Definitions by: Aaronphy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as H from 'history'; diff --git a/types/mobx-devtools-mst/index.d.ts b/types/mobx-devtools-mst/index.d.ts new file mode 100644 index 0000000000..54a3f09bf6 --- /dev/null +++ b/types/mobx-devtools-mst/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for mobx-devtools-mst 0.9 +// Project: https://mobxjs.github.io/mobx +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare function makeInspectable(state: object): void; +export = makeInspectable; diff --git a/types/mobx-devtools-mst/mobx-devtools-mst-tests.ts b/types/mobx-devtools-mst/mobx-devtools-mst-tests.ts new file mode 100644 index 0000000000..a00d1c36af --- /dev/null +++ b/types/mobx-devtools-mst/mobx-devtools-mst-tests.ts @@ -0,0 +1,7 @@ +import makeInspectable = require("mobx-devtools-mst"); + +const myModel = { + /* some mst instance */ +}; + +makeInspectable(myModel); diff --git a/types/mobx-devtools-mst/tsconfig.json b/types/mobx-devtools-mst/tsconfig.json new file mode 100644 index 0000000000..06ccbf6965 --- /dev/null +++ b/types/mobx-devtools-mst/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "mobx-devtools-mst-tests.ts"] +} diff --git a/types/mobx-devtools-mst/tslint.json b/types/mobx-devtools-mst/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mobx-devtools-mst/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 6963da082d..d1c47eff64 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -238,6 +238,8 @@ export interface ReplSetOptions extends SSLOptions, HighAvailabilityOptions { socketOptions?: SocketOptions; } +export type ProfilingLevel = 'off' | 'slow_only' | 'all'; + // Class documentation : http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html export class Db extends EventEmitter { constructor(databaseName: string, serverConfig: Server | ReplSet | Mongos, options?: DbCreateOptions); @@ -292,13 +294,14 @@ export class Db extends EventEmitter { /** http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html#listCollections */ listCollections(filter?: Object, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html#profilingInfo */ + /** @deprecated Query the system.profile collection directly. */ profilingInfo(callback: MongoCallback): void; profilingInfo(options?: { session?: ClientSession }): Promise; profilingInfo(options: { session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html#profilingLevel */ - profilingLevel(callback: MongoCallback): void; - profilingLevel(options?: { session?: ClientSession }): Promise; - profilingLevel(options: { session?: ClientSession }, callback: MongoCallback): void; + profilingLevel(callback: MongoCallback): void; + profilingLevel(options?: { session?: ClientSession }): Promise; + profilingLevel(options: { session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html#removeUser */ removeUser(username: string, callback: MongoCallback): void; removeUser(username: string, options?: CommonOptions): Promise; @@ -308,9 +311,9 @@ export class Db extends EventEmitter { renameCollection(fromCollection: string, toCollection: string, options?: { dropTarget?: boolean }): Promise>; renameCollection(fromCollection: string, toCollection: string, options: { dropTarget?: boolean }, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html#setProfilingLevel */ - profilingLevel(level: string, callback: MongoCallback): void; - profilingLevel(level: string, options?: { session?: ClientSession }): Promise; - profilingLevel(level: string, options: { session?: ClientSession }, callback: MongoCallback): void; + setProfilingLevel(level: ProfilingLevel, callback: MongoCallback): void; + setProfilingLevel(level: ProfilingLevel, options?: { session?: ClientSession }): Promise; + setProfilingLevel(level: ProfilingLevel, options: { session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Db.html#stats */ stats(callback: MongoCallback): void; stats(options?: { scale?: number }): Promise; @@ -1527,7 +1530,7 @@ export interface LoggerState { } /** http://mongodb.github.io/node-mongodb-native/3.0/api/Logger.html */ -export class Logger{ +export class Logger { constructor(className: string, options?: LoggerOptions) // Log a message at the debug level debug(message: string, state: LoggerState):void diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 5723a9a881..481b37c0a3 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mongoose 5.0.12 +// Type definitions for Mongoose 5.0.14 // Project: http://mongoosejs.com/ // Definitions by: horiuchi // sindrenm @@ -47,8 +47,12 @@ declare module "mongoose" { import stream = require('stream'); import mongoose = require('mongoose'); - /** Pluralises the given name */ - export function pluralize(str: string): string; + /** + * Gets and optionally overwrites the function used to pluralize collection names + * @param fn function to use for pluralization of collection names + * @returns the current function used to pluralize collection names (defaults to the `mongoose-legacy-pluralize` module's function) + */ + export function pluralize(fn?: (str: string) => string): (str: string) => string; /* * Some mongoose classes have the same name as the native JS classes @@ -2714,6 +2718,16 @@ declare module "mongoose" { insertMany(doc: any, callback?: (error: any, doc: T) => void): Promise; insertMany(doc: any, options?: { ordered?: boolean, rawResult?: boolean }, callback?: (error: any, doc: T) => void): Promise; + /** + * Performs any async initialization of this model against MongoDB. + * This function is called automatically, so you don't need to call it. + * This function is also idempotent, so you may call it to get back a promise + * that will resolve when your indexes are finished building as an alternative + * to `MyModel.on('index')` + * @param callback optional + */ + init(callback?: (err: any) => void): Promise; + /** * Executes a mapReduce command. * @param o an object specifying map-reduce options diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index a6fe9f406a..aaedb577d3 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -170,7 +170,8 @@ mongooseError.stack; mongoose.Error.messages.hasOwnProperty(''); mongoose.Error.Messages.hasOwnProperty(''); -const plural: string = mongoose.pluralize('foo'); +const pluralize = mongoose.pluralize(); +const plural: string = pluralize('foo'); /* * section querycursor.js @@ -1420,6 +1421,7 @@ var MongoModel = mongoose.model('MongoModel', new mongoose.Schema({ required: true } }), 'myCollection', true); +MongoModel.init().then(cb); MongoModel.find({}).$where('indexOf("val") !== -1').exec(function (err, docs) { docs[0].save(); docs[0].__v; diff --git a/types/natural-sort/index.d.ts b/types/natural-sort/index.d.ts index 4e929d4edc..3a88919a25 100644 --- a/types/natural-sort/index.d.ts +++ b/types/natural-sort/index.d.ts @@ -1,9 +1,18 @@ // Type definitions for NaturalSort // Project: https://github.com/studio-b12/natural-sort // Definitions by: Antonio Morales +// Brian Crowell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace naturalSort; -declare function naturalSort(a: T, b: T): number; +interface Options { + /** Set to true to make the sort case-sensitive. */ + caseSensitive?: boolean; + + /** Set to 'desc' to sort in reverse. */ + direction?: 'desc' +} + +declare function naturalSort(options?: Options): (a: string | number, b: string | number) => number; export = naturalSort; diff --git a/types/natural-sort/natural-sort-tests.ts b/types/natural-sort/natural-sort-tests.ts index b336542520..6218f4e796 100644 --- a/types/natural-sort/natural-sort-tests.ts +++ b/types/natural-sort/natural-sort-tests.ts @@ -1,5 +1,8 @@ import naturalSort = require("natural-sort"); -[5, 3, 2, 4, 1].sort(naturalSort); -["a", "c", "b", "z", "w", "l"].sort(naturalSort); +['10. tenth', 'odd', 1, '', '2. second'].sort(naturalSort()); +[3, 4, 1, 5, 2].sort(naturalSort({direction: 'desc'})); + +['a', 'B'].sort(naturalSort()); +['a', 'B'].sort(naturalSort({caseSensitive: true})); diff --git a/types/net-keepalive/net-keepalive-tests.ts b/types/net-keepalive/net-keepalive-tests.ts index 68b71daff4..71b5104e27 100644 --- a/types/net-keepalive/net-keepalive-tests.ts +++ b/types/net-keepalive/net-keepalive-tests.ts @@ -9,7 +9,7 @@ const server = Net.createServer((socket) => { }) server.listen(1337, '127.0.0.1', () => { - const {port, address} = server.address() + const {port, address} = server.address() as Net.AddressInfo const clientSocket = Net.createConnection({ port, host: address }, () => { @@ -18,4 +18,4 @@ server.listen(1337, '127.0.0.1', () => { NetKeepAlive.setKeepAliveProbes(clientSocket, 1) clientSocket.end() }) -}) \ No newline at end of file +}) diff --git a/types/next-redux-wrapper/index.d.ts b/types/next-redux-wrapper/index.d.ts index 16dc88b1a4..cdbcb7b9e5 100644 --- a/types/next-redux-wrapper/index.d.ts +++ b/types/next-redux-wrapper/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/kirill-konshin/next-redux-wrapper // Definitions by: Steve // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// /*~ Note that ES6 modules cannot directly export callable functions. diff --git a/types/next/document.d.ts b/types/next/document.d.ts index 4696819626..b8ae0864ba 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -1,15 +1,46 @@ import * as React from "react"; +import * as http from "http"; + +export interface Context { + err?: Error; + req: http.IncomingMessage; + res: http.ServerResponse; + pathname: string; + query?: { + [key: string]: + | boolean + | boolean[] + | number + | number[] + | string + | string[]; + }; + asPath: string; + + renderPage( + enhancer?: (page: React.Component) => React.ComponentType + ): { + html?: string; + head: Array>; + errorHtml: string; + }; +} export interface DocumentProps { __NEXT_DATA__?: any; dev?: boolean; chunks?: string[]; + html?: string; head?: Array>; + errorHtml?: string; styles?: Array>; + [key: string]: any; } export class Head extends React.Component {} export class Main extends React.Component {} export class NextScript extends React.Component {} -export default class extends React.Component {} +export default class extends React.Component { + static getInitialProps(ctx: Context): DocumentProps; +} diff --git a/types/ngtoaster/index.d.ts b/types/ngtoaster/index.d.ts index caf9bd0539..092e1a7b0e 100644 --- a/types/ngtoaster/index.d.ts +++ b/types/ngtoaster/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for angularjs-toaster v0.4.13 +// Type definitions for angularjs-toaster 2.2 // Project: https://github.com/jirikavi/AngularJS-Toaster // Definitions by: Ben Tesser // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,100 +10,126 @@ export = ngtoaster; export as namespace toaster; declare namespace ngtoaster { - interface IToasterService { - pop(params:IPopParams): void - /** - * @param {string} type Type of toaster -- 'error', 'info', 'wait', 'success', and 'warning' - */ - pop(type?:string, title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number, showCloseButton?:boolean): void - error(params: IPopParams): void - error(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - info(params: IPopParams): void - info(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - wait(params: IPopParams): void - wait(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - success(params: IPopParams): void - success(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - warning(params: IPopParams): void - warning(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - clear(): void - toast:IToast; - } + interface IToasterService { + pop(params: IPopParams): void; + /** + * @param type Type of toaster -- 'error', 'info', 'wait', 'success', and 'warning' + */ + pop(type?: string, title?: string, body?: string, timeout?: number, bodyOutputType?: string, clickHandler?: EventListener, + toasterId?: number, showCloseButton?: boolean, toastId?: string|number, + onHideCallback?: IToastCallback): IPopReturn; + error(params: IPopParams): void; + error(title?: string, body?: string, timeout?: number, bodyOutputType?: string, clickHandler?: EventListener, + toasterId?: number, showCloseButton?: boolean, toastId?: string|number, + onHideCallback?: IToastCallback): IPopReturn; + info(params: IPopParams): void; + info(title?: string, body?: string, timeout?: number, bodyOutputType?: string, clickHandler?: EventListener, + toasterId?: number, showCloseButton?: boolean, toastId?: string|number, + onHideCallback?: IToastCallback): IPopReturn; + wait(params: IPopParams): void; + wait(title?: string, body?: string, timeout?: number, bodyOutputType?: string, clickHandler?: EventListener, + toasterId?: number, showCloseButton?: boolean, toastId?: string|number, + onHideCallback?: IToastCallback): IPopReturn; + success(params: IPopParams): void; + success(title?: string, body?: string, timeout?: number, bodyOutputType?: string, clickHandler?: EventListener, + toasterId?: number, showCloseButton?: boolean, toastId?: string|number, + onHideCallback?: IToastCallback): IPopReturn; + warning(params: IPopParams): void; + warning(title?: string, body?: string, timeout?: number, bodyOutputType?: string, clickHandler?: EventListener, + toasterId?: number, showCloseButton?: boolean, toastId?: string|number, + onHideCallback?: IToastCallback): IPopReturn; + clear(toasterId?: number, toastId?: string|number): void; + toast: IToast; + } - interface IToasterEventRegistry { - setup(): void - subscribeToNewToastEvent(onNewToast:IToastEventListener): void - subscribeToClearToastsEvent(onClearToasts:IToastEventListener): void - unsubscribeToNewToastEvent(onNewToast:IToastEventListener): void - unsubscribeToClearToastsEvent(onClearToasts:IToastEventListener): void - } + interface IToasterEventRegistry { + setup(): void; + subscribeToNewToastEvent(onNewToast: IToastEventListener): void; + subscribeToClearToastsEvent(onClearToasts: IToastEventListener): void; + unsubscribeToNewToastEvent(onNewToast: IToastEventListener): void; + unsubscribeToClearToastsEvent(onClearToasts: IToastEventListener): void; + } - interface IPopParams extends IToast{ - toasterId?: number; - } + interface IPopParams extends IToast { + toasterId?: number; + } - interface IToastEventListener { - (event:Event, toasterId: number): void; - } + interface IPopReturn { + toasterId: number; + toastId: string|number; + } - interface IToast { - /** - * Acceptable types are: - * 'error', 'info', 'wait', 'success', and 'warning' - */ - type?: string; - title?: string; - body?: string; - timeout?: number; - bodyOutputType?: string; - clickHandler?: EventListener; - showCloseButton?: boolean; - } + type IToastCallback = (toast: IToast) => void; - interface IToasterConfig { - /** - * limits max number of toasts - */ - limit?: number; - 'tap-to-dismiss'?: boolean; - 'close-button'?: boolean; - 'newest-on-top'?: boolean; - 'time-out'?: number; - 'icon-classes'?: IIconClasses; - /** - * Options include: - * '', 'trustedHtml', 'template', 'templateWithData' - */ - 'body-output-type'?: string; - 'body-template'?: string; - 'icon-class'?: string; - /** - * Options include: - * 'toast-top-full-width', 'toast-bottom-full-width', 'toast-center', - * 'toast-top-left', 'toast-top-center', 'toast-top-rigt', - * 'toast-bottom-left', 'toast-bottom-center', 'toast-bottom-rigt', - */ - 'position-class'?: string; - 'title-class'?: string; - 'message-class'?: string; - 'prevent-duplicates'?: boolean; - /** - * stop timeout on mouseover and restart timer on mouseout - */ - 'mouseover-timer-stop'?: boolean; - } + type IToastEventListener = (event: Event, toasterId: number, toastId: string|number) => void; - interface IIconClasses { - error: string; - info: string; - wait: string; - success: string; - warning: string; - } + interface IToast { + /** + * Acceptable types are: + * 'error', 'info', 'wait', 'success', and 'warning' + */ + type?: string; + title?: string; + body?: string; + timeout?: number; + bodyOutputType?: string; + clickHandler?: EventListener; + showCloseButton?: boolean; + closeHtml?: string; + toastId?: string|number; + /** + * Called when the toast has been displayed. + * @param toast the displayed toast + */ + onShowCallback?: IToastCallback; + /** + * Called when the toast has been removed. + * @param toast the displayed toast + */ + onHideCallback?: IToastCallback; + directiveData?: any; + tapToDismiss?: boolean; + } + + interface IToasterConfig { + /** + * limits max number of toasts + */ + limit?: number; + 'tap-to-dismiss'?: boolean; + 'close-button'?: boolean; + 'close-html'?: string; + 'newest-on-top'?: boolean; + 'time-out'?: number; + 'icon-classes'?: IIconClasses; + /** + * Options include: + * '', 'trustedHtml', 'template', 'templateWithData' + */ + 'body-output-type'?: string; + 'body-template'?: string; + 'icon-class'?: string; + /** + * Options include: + * 'toast-top-full-width', 'toast-bottom-full-width', 'toast-center', + * 'toast-top-left', 'toast-top-center', 'toast-top-rigt', + * 'toast-bottom-left', 'toast-bottom-center', 'toast-bottom-rigt', + */ + 'position-class'?: string; + 'title-class'?: string; + 'message-class'?: string; + 'prevent-duplicates'?: boolean; + /** + * stop timeout on mouseover and restart timer on mouseout + */ + 'mouseover-timer-stop'?: boolean; + } + + interface IIconClasses { + error: string; + info: string; + wait: string; + success: string; + warning: string; + } } diff --git a/types/ngtoaster/ngtoaster-tests.ts b/types/ngtoaster/ngtoaster-tests.ts index eb30c181d4..0640ba2191 100644 --- a/types/ngtoaster/ngtoaster-tests.ts +++ b/types/ngtoaster/ngtoaster-tests.ts @@ -1,45 +1,57 @@ -import ngtoaster = require("ngtoaster"); -import * as ng from 'angular'; +import ngtoaster = require('ngtoaster'); import * as angular from 'angular'; class NgToasterTestController { - constructor(public $scope: ng.IScope, public $window: ng.IWindowService, public toaster: ngtoaster.IToasterService) { - this.bar = 'Hi'; - } - bar: string; - - pop(): void { - this.toaster.success({ title: "title", body: "text1" }); - this.toaster.error("title", "text2"); - this.toaster.pop({ type: 'wait', title: "title", body: "text" }); - this.toaster.pop('success', "title", '
  • Render html
', 5000, 'trustedHtml'); - this.toaster.pop('error', "title", '
  • Render html
', null, 'trustedHtml'); - this.toaster.pop('wait', "title", null, null, 'template'); - this.toaster.pop('warning', "title", "myTemplate.html", null, 'template'); - this.toaster.pop('note', "title", "text"); - this.toaster.pop('success', "title", 'Its address is https://google.com.', 5000, 'trustedHtml', (toaster: ngtoaster.IToast): boolean => { - var match = toaster.body.match(/http[s]?:\/\/[^\s]+/); - if (match) { - this.$window.open(match[0]); - } - return true; - }); - this.toaster.pop('warning', "Hi ", "{template: 'myTemplateWithData.html', data: 'MyData'}", 15000, 'templateWithData'); - } - - goToLink(toaster: ngtoaster.IToast): boolean { - var match = toaster.body.match(/http[s]?:\/\/[^\s]+/); - if (match) { - this.$window.open(match[0]); + constructor( + public $scope: angular.IScope, + public $window: angular.IWindowService, + public toaster: ngtoaster.IToasterService + ) { + this.bar = 'Hi'; } - return true; - } + bar: string; - clear(): void { - this.toaster.clear(); - } + pop(): void { + this.toaster.success({ title: 'title', body: 'text1' }); + this.toaster.error('title', 'text2'); + this.toaster.pop({ + type: 'wait', + title: 'title', + body: 'text', + onShowCallback: (toast) => { + this.toaster.clear(null, toast.toastId); + } + }); + this.toaster.pop('success', 'title', '
  • Render html
', 5000, 'trustedHtml'); + this.toaster.pop('error', 'title', '
  • Render html
', null, 'trustedHtml'); + this.toaster.pop('wait', 'title', null, null, 'template'); + this.toaster.pop('warning', 'title', 'myTemplate.html', null, 'template'); + this.toaster.pop('note', 'title', 'text'); + this.toaster.pop('success', 'title', 'Its address is https://google.com.', 5000, 'trustedHtml', (toaster: ngtoaster.IToast): boolean => { + const match = toaster.body.match(/http[s]?:\/\/[^\s]+/); + if (match) { + this.$window.open(match[0]); + } + return true; + }); + this.toaster.pop('warning', 'Hi ', `{template: 'myTemplateWithData.html', data: 'MyData'}`, 15000, 'templateWithData'); + } + + goToLink(toaster: ngtoaster.IToast): boolean { + const match = toaster.body.match(/http[s]?:\/\/[^\s]+/); + if (match) { + this.$window.open(match[0]); + } + return true; + } + + clear(): void { + this.toaster.clear(); + this.toaster.clear(1); + this.toaster.clear(null, 'mytoast'); + } } angular - .module('main', ['ngAnimate', 'toaster']) - .controller('myController', NgToasterTestController); \ No newline at end of file + .module('main', ['ngAnimate', 'toaster']) + .controller('myController', NgToasterTestController); diff --git a/types/ngtoaster/tslint.json b/types/ngtoaster/tslint.json index a41bf5d19a..eaaf55d976 100644 --- a/types/ngtoaster/tslint.json +++ b/types/ngtoaster/tslint.json @@ -1,79 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "interface-name": false } } diff --git a/types/nightmare/index.d.ts b/types/nightmare/index.d.ts index 60c73d850f..b36d014b63 100644 --- a/types/nightmare/index.d.ts +++ b/types/nightmare/index.d.ts @@ -158,6 +158,7 @@ declare namespace Nightmare { typeInterval?: number; x?: number; y?: number; + electronPath?: string; openDevTools?: { /** * Opens the devtools with specified dock state, can be right, bottom, undocked, detach. diff --git a/types/noble/noble-tests.ts b/types/noble/noble-tests.ts index 5e00105433..0c8dcf6c20 100644 --- a/types/noble/noble-tests.ts +++ b/types/noble/noble-tests.ts @@ -59,7 +59,7 @@ peripheral.discoverAllServicesAndCharacteristics(); peripheral.discoverAllServicesAndCharacteristics((error: string, services: noble.Service[], characteristics: noble.Characteristic[]): void => {}); peripheral.discoverSomeServicesAndCharacteristics(["180d"], ["2a38"]); peripheral.discoverSomeServicesAndCharacteristics(["180d"], ["2a38"], (error: string, services: noble.Service[], characteristics: noble.Characteristic[]): void => {}); -peripheral.readHandle(new Buffer(1), (error: string, data: NodeBuffer): void => {}); +peripheral.readHandle(new Buffer(1), (error: string, data: Buffer): void => {}); peripheral.writeHandle(new Buffer(1), new Buffer(1), true, (error: string): void => {}); peripheral.on("connect", (error: string): void => {}); peripheral.on("disconnect", (error: string): void => {}); @@ -84,7 +84,7 @@ characteristic.name = ""; characteristic.type = ""; characteristic.properties = ["read", "notify"]; characteristic.read(); -characteristic.read((error: string, data: NodeBuffer): void => {}); +characteristic.read((error: string, data: Buffer): void => {}); characteristic.write(new Buffer(1), true); characteristic.write(new Buffer(1), true, (error: string): void => {}); characteristic.broadcast(true); @@ -93,7 +93,7 @@ characteristic.notify(true); characteristic.notify(true, (error: string): void => {}); characteristic.discoverDescriptors(); characteristic.discoverDescriptors((error: string, descriptors: noble.Descriptor[]): void => {}); -characteristic.on("read", (data: NodeBuffer, isNotification: boolean): void => {}); +characteristic.on("read", (data: Buffer, isNotification: boolean): void => {}); characteristic.on("write", true, (error: string): void => {}); characteristic.on("broadcast", (state: string): void => {}); characteristic.on("notify", (state: string): void => {}); @@ -108,9 +108,9 @@ descriptor.uuid = ""; descriptor.name = ""; descriptor.type = ""; descriptor.readValue(); -descriptor.readValue((error: string, data: NodeBuffer): void => {}); +descriptor.readValue((error: string, data: Buffer): void => {}); descriptor.writeValue(new Buffer(1)); descriptor.writeValue(new Buffer(1), (error: string): void => {}); -descriptor.on("valueRead", (error: string, data: NodeBuffer): void => {}); +descriptor.on("valueRead", (error: string, data: Buffer): void => {}); descriptor.on("valueWrite", (error: string): void => {}); diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index 016b9b7b1a..65ff4edb47 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -50,6 +50,7 @@ declare module "node-forge" { function publicKeyFromPem(pem: PEM): Key; function privateKeyFromPem(pem: PEM): Key; function certificateToPem(cert: Certificate, maxline?: number): PEM; + function certificateFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate; interface oids { [key: string]: string; diff --git a/types/node-forge/node-forge-tests.ts b/types/node-forge/node-forge-tests.ts index a5487ed027..575661e9aa 100644 --- a/types/node-forge/node-forge-tests.ts +++ b/types/node-forge/node-forge-tests.ts @@ -10,6 +10,7 @@ let publicKeyRsa = forge.pki.publicKeyFromPem(pemKey); let privateKeyRsa = forge.pki.privateKeyFromPem(privateKeyPem); let privateKeyRsa2 = forge.pki.privateKeyInfoToPem(privateKeyPem); let byteBufferString = forge.pki.pemToDer(privateKeyRsa); +let certPem = forge.pki.certificateFromPem(pemKey); let cert = forge.pki.createCertificate(); { diff --git a/types/node/index.d.ts b/types/node/index.d.ts index b545ec718e..d228742629 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -13,7 +13,6 @@ // Deividas Bakanas // Kelvin Jin // Alvis HT Tang -// Oliver Joseph Ash // Sebastian Silbermann // Hannes Magnusson // Alberto Schiabel @@ -32,17 +31,101 @@ // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build interface Console { Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ assert(value: any, message?: string, ...optionalParams: any[]): void; - dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ log(message?: any, ...optionalParams: any[]): void; - time(label: string): void; - timeEnd(label: string): void; - trace(message?: any, ...optionalParams: any[]): void; - warn(message?: any, ...optionalParams: any[]): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ table(tabularData: any, properties?: string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ + warn(message?: any, ...optionalParams: any[]): void; + + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; } interface Error { @@ -175,7 +258,61 @@ declare var SlowBuffer: { // Buffer class type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; -interface Buffer extends NodeBuffer { } +interface Buffer extends Uint8Array { + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} /** * Raw data is stored in instances of the Buffer class. @@ -242,7 +379,7 @@ declare var Buffer: { * Creates a new Buffer using the passed {data} * @param data data to create a new Buffer */ - from(data: any[] | string | Buffer | ArrayBuffer /*| TypedArray*/): Buffer; + from(data: any[] | string | Buffer | ArrayBuffer | Uint8Array /*| TypedArray*/): Buffer; /** * Creates a new Buffer containing the given JavaScript string {str}. * If provided, the {encoding} parameter identifies the character encoding. @@ -483,6 +620,7 @@ declare namespace NodeJS { rss: number; heapTotal: number; heapUsed: number; + external: number; } export interface CpuUsage { @@ -829,65 +967,6 @@ declare namespace NodeJS { interface IterableIterator { } -/** - * @deprecated - */ -interface NodeBuffer extends Uint8Array { - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - keys(): IterableIterator; - values(): IterableIterator; -} - /************************************************ * * * MODULES * @@ -2101,7 +2180,7 @@ declare module "child_process" { windowsHide?: boolean; } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; export interface ExecOptions { cwd?: string; @@ -2586,6 +2665,12 @@ declare module "net" { type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + export interface AddressInfo { + address: string; + family: string; + port: number; + } + export interface SocketConstructorOpts { fd?: number; allowHalfOpen?: boolean; @@ -2633,7 +2718,7 @@ declare module "net" { setTimeout(timeout: number, callback?: Function): this; setNoDelay(noDelay?: boolean): this; setKeepAlive(enable?: boolean, initialDelay?: number): this; - address(): { port: number; family: string; address: string; }; + address(): AddressInfo | string; unref(): void; ref(): void; @@ -2749,7 +2834,7 @@ declare module "net" { listen(handle: any, backlog?: number, listeningListener?: Function): this; listen(handle: any, listeningListener?: Function): this; close(callback?: Function): this; - address(): { port: number; family: string; address: string; }; + address(): AddressInfo | string; getConnections(cb: (error: Error | null, count: number) => void): void; ref(): this; unref(): this; @@ -2825,22 +2910,17 @@ declare module "net" { } declare module "dgram" { - import * as events from "events"; + import { AddressInfo } from "net"; import * as dns from "dns"; + import * as events from "events"; - interface RemoteInfo { + export interface RemoteInfo { address: string; family: string; port: number; } - interface AddressInfo { - address: string; - family: string; - port: number; - } - - interface BindOptions { + export interface BindOptions { port: number; address?: string; exclusive?: boolean; @@ -2848,7 +2928,7 @@ declare module "dgram" { type SocketType = "udp4" | "udp6"; - interface SocketOptions { + export interface SocketOptions { type: SocketType; reuseAddr?: boolean; recvBufferSize?: number; @@ -2860,14 +2940,14 @@ declare module "dgram" { export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; export class Socket extends events.EventEmitter { - send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; bind(port?: number, address?: string, callback?: () => void): void; bind(port?: number, callback?: () => void): void; bind(callback?: () => void): void; bind(options: BindOptions, callback?: Function): void; close(callback?: () => void): void; - address(): AddressInfo; + address(): AddressInfo | string; setBroadcast(flag: boolean): void; setTTL(ttl: number): void; setMulticastTTL(ttl: number): void; @@ -5544,23 +5624,6 @@ declare module "tls" { prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; } - export interface ClearTextStream extends stream.Duplex { - authorized: boolean; - authorizationError: Error; - getPeerCertificate(): any; - getCipher: { - name: string; - version: string; - }; - address: { - port: number; - family: string; - address: string; - }; - remoteAddress: string; - remotePort: number; - } - export interface SecurePair { encrypted: any; cleartext: any; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index efc00ef201..d428cf8753 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -432,10 +432,13 @@ function bufferTests() { // String const buf3: Buffer = Buffer.from('this is a tést'); // ArrayBuffer - const arr: Uint16Array = new Uint16Array(2); - arr[0] = 5000; - arr[1] = 4000; - const buf4: Buffer = Buffer.from(arr.buffer); + const arrUint16: Uint16Array = new Uint16Array(2); + arrUint16[0] = 5000; + arrUint16[1] = 4000; + const buf4: Buffer = Buffer.from(arrUint16.buffer); + const arrUint8: Uint8Array = new Uint8Array(2); + const buf5: Buffer = Buffer.from(arrUint8); + const buf6: Buffer = Buffer.from(buf1); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) @@ -1551,7 +1554,7 @@ namespace dgram_tests { ds.bind(4123, 'localhost', () => { }); ds.bind(4123, () => { }); ds.bind(() => { }); - var ai: dgram.AddressInfo = ds.address(); + const addr: net.AddressInfo | string = ds.address(); ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { }); ds.send(new Buffer("hello"), 5000, "127.0.0.1"); @@ -1564,7 +1567,7 @@ namespace dgram_tests { let _boolean: boolean; let _err: Error; let _str: string; - let _rinfo: dgram.AddressInfo; + let _rinfo: net.AddressInfo; /** * events.EventEmitter * 1. close @@ -1580,7 +1583,7 @@ namespace dgram_tests { _socket = _socket.addListener("listening", () => { }); _socket = _socket.addListener("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _boolean = _socket.emit("close"); @@ -1595,7 +1598,7 @@ namespace dgram_tests { _socket = _socket.on("listening", () => { }); _socket = _socket.on("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _socket = _socket.once("close", () => { }); @@ -1605,7 +1608,7 @@ namespace dgram_tests { _socket = _socket.once("listening", () => { }); _socket = _socket.once("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _socket = _socket.prependListener("close", () => { }); @@ -1615,7 +1618,7 @@ namespace dgram_tests { _socket = _socket.prependListener("listening", () => { }); _socket = _socket.prependListener("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _socket = _socket.prependOnceListener("close", () => { }); @@ -1625,7 +1628,7 @@ namespace dgram_tests { _socket = _socket.prependOnceListener("listening", () => { }); _socket = _socket.prependOnceListener("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); } @@ -2730,10 +2733,7 @@ namespace net_tests { server = server.close((...args: any[]) => { }); // test the types of the address object fields - let address = server.address(); - address.port = 1234; - address.family = "ipv4"; - address.address = "127.0.0.1"; + let address: net.AddressInfo | string = server.address(); } { diff --git a/types/node/v0/index.d.ts b/types/node/v0/index.d.ts index ef1c485d2d..37f92cbc50 100644 --- a/types/node/v0/index.d.ts +++ b/types/node/v0/index.d.ts @@ -881,7 +881,7 @@ declare module "child_process" { unref(): void; } - export function spawn(command: string, args?: string[], options?: { + export function spawn(command: string, args?: ReadonlyArray, options?: { cwd?: string; stdio?: any; custom?: any; diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index 3a7825dff8..db5518575d 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -1240,7 +1240,7 @@ declare module "child_process" { gid?: number; shell?: boolean | string; } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; export interface ExecOptions { cwd?: string; diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index e615662fe6..92e6fe75ad 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -413,6 +413,7 @@ declare namespace NodeJS { rss: number; heapTotal: number; heapUsed: number; + external: number; } export interface CpuUsage { @@ -1787,7 +1788,7 @@ declare module "child_process" { gid?: number; shell?: boolean | string; } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; export interface ExecOptions { cwd?: string; @@ -1957,8 +1958,54 @@ declare module "url" { } export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; + export function format(URL: URL, options?: URLFormatOptions): string; export function format(urlObject: UrlObject | string): string; export function resolve(from: string, to: string): string; + + export function domainToASCII(domain: string): string; + export function domainToUnicode(domain: string): string; + + export interface URLFormatOptions { + auth?: boolean; + fragment?: boolean; + search?: boolean; + unicode?: boolean; + } + + export class URLSearchParams implements Iterable { + constructor(init?: URLSearchParams | string | { [key: string]: string | string[] } | Iterable ); + append(name: string, value: string): void; + delete(name: string): void; + entries(): Iterator; + forEach(callback: (value: string, name: string) => void): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + keys(): Iterator; + set(name: string, value: string): void; + sort(): void; + toString(): string; + values(): Iterator; + [Symbol.iterator](): Iterator; + } + + export class URL { + constructor(input: string, base?: string | URL); + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toString(): string; + toJSON(): string; + } } declare module "dns" { diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index f9d5a9cd62..4457f83492 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -486,12 +486,113 @@ namespace url_tests { pathname: 'search', query: { q: "you're a lizard, gary" } }); + + const myURL = new url.URL('https://a:b@你好你好?abc#foo'); + url.format(myURL, { fragment: false, unicode: true, auth: false }); } { var helloUrl = url.parse('http://example.com/?hello=world', true) assert.equal(helloUrl.query.hello, 'world'); } + + { + const ascii: string = url.domainToASCII('español.com'); + const unicode: string = url.domainToUnicode('xn--espaol-zwa.com'); + } + + { + let myURL = new url.URL('https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert.equal(myURL.hash, '#bar'); + assert.equal(myURL.host, 'example.org:81'); + assert.equal(myURL.hostname, 'example.org'); + assert.equal(myURL.href, 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert.equal(myURL.origin, 'https://example.org:81'); + assert.equal(myURL.password, 'thepwd'); + assert.equal(myURL.username, 'theuser'); + assert.equal(myURL.pathname, '/foo/path'); + assert.equal(myURL.port, "81"); + assert.equal(myURL.protocol, "https:"); + assert.equal(myURL.search, "?query=string"); + assert.equal(myURL.toString(), 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert(myURL.searchParams instanceof url.URLSearchParams); + + myURL.host = 'example.org:82'; + myURL.hostname = 'example.com'; + myURL.href = 'http://other.com'; + myURL.hash = 'baz'; + myURL.password = "otherpwd"; + myURL.username = "otheruser"; + myURL.pathname = "/otherPath"; + myURL.port = "82"; + myURL.protocol = "http"; + myURL.search = "a=b"; + assert.equal(myURL.href, 'http://otheruser:otherpwd@other.com:82/otherPath?a=b#baz'); + + myURL = new url.URL('/foo', 'https://example.org/'); + assert.equal(myURL.href, 'https://example.org/foo'); + assert.equal(myURL.toJSON(), myURL.href); + } + + { + const searchParams = new url.URLSearchParams('abc=123'); + + assert.equal(searchParams.toString(), 'abc=123'); + searchParams.forEach((value: string, name: string): void => { + assert.equal(name, 'abc'); + assert.equal(value, '123'); + }); + + assert.equal(searchParams.get('abc'), '123'); + + searchParams.append('abc', 'xyz'); + + assert.deepEqual(searchParams.getAll('abc'), ['123', 'xyz']); + + const entries = searchParams.entries(); + assert.deepEqual(entries.next(), { value: ["abc", "123"], done: false}); + assert.deepEqual(entries.next(), { value: ["abc", "xyz"], done: false}); + assert.deepEqual(entries.next(), { value: undefined, done: true}); + + const keys = searchParams.keys(); + assert.deepEqual(keys.next(), { value: "abc", done: false}); + assert.deepEqual(keys.next(), { value: "abc", done: false}); + assert.deepEqual(keys.next(), { value: undefined, done: true}); + + const values = searchParams.values(); + assert.deepEqual(values.next(), { value: "123", done: false}); + assert.deepEqual(values.next(), { value: "xyz", done: false}); + assert.deepEqual(values.next(), { value: undefined, done: true}); + + searchParams.set('abc', 'b'); + assert.deepEqual(searchParams.getAll('abc'), ['b']); + + searchParams.delete('a'); + assert(!searchParams.has('a')); + assert.equal(searchParams.get('a'), null); + + searchParams.sort(); + } + + { + const searchParams = new url.URLSearchParams({ + user: 'abc', + query: ['first', 'second'] + }); + + assert.equal(searchParams.toString(), 'user=abc&query=first%2Csecond'); + assert.deepEqual(searchParams.getAll('query'), ['first,second']); + } + + { + // Using an array + let params = new url.URLSearchParams([ + ['user', 'abc'], + ['query', 'first'], + ['query', 'second'] + ]); + assert.equal(params.toString(), 'user=abc&query=first&query=second'); + } } ///////////////////////////////////////////////////// diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index 366eb247fd..58497e23d6 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -424,6 +424,7 @@ declare namespace NodeJS { rss: number; heapTotal: number; heapUsed: number; + external: number; } export interface CpuUsage { @@ -1847,7 +1848,7 @@ declare module "child_process" { gid?: number; shell?: boolean | string; } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; export interface ExecOptions { cwd?: string; diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index 05d617dd58..45f1c85b64 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -472,6 +472,7 @@ declare namespace NodeJS { rss: number; heapTotal: number; heapUsed: number; + external: number; } export interface CpuUsage { @@ -2091,7 +2092,7 @@ declare module "child_process" { windowsHide?: boolean; } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; export interface ExecOptions { cwd?: string; @@ -2850,8 +2851,8 @@ declare module "dgram" { export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; export class Socket extends events.EventEmitter { - send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; bind(port?: number, address?: string, callback?: () => void): void; bind(port?: number, callback?: () => void): void; bind(callback?: () => void): void; diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 5012d70183..5a76e4cc45 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -32,16 +32,101 @@ // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build interface Console { Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ assert(value: any, message?: string, ...optionalParams: any[]): void; - dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ log(message?: any, ...optionalParams: any[]): void; - time(label: string): void; - timeEnd(label: string): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ warn(message?: any, ...optionalParams: any[]): void; + + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ + table(tabularData: any, properties?: string[]): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; } interface Error { @@ -172,7 +257,61 @@ declare var SlowBuffer: { // Buffer class type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; -interface Buffer extends NodeBuffer { } +interface Buffer extends Uint8Array { + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} /** * Raw data is stored in instances of the Buffer class. @@ -473,6 +612,7 @@ declare namespace NodeJS { rss: number; heapTotal: number; heapUsed: number; + external: number; } export interface CpuUsage { @@ -819,65 +959,6 @@ declare namespace NodeJS { interface IterableIterator { } -/** - * @deprecated - */ -interface NodeBuffer extends Uint8Array { - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - keys(): IterableIterator; - values(): IterableIterator; -} - /************************************************ * * * MODULES * @@ -2091,7 +2172,7 @@ declare module "child_process" { windowsHide?: boolean; } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + export function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; export interface ExecOptions { cwd?: string; @@ -2576,6 +2657,12 @@ declare module "net" { type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + export interface AddressInfo { + address: string; + family: string; + port: number; + } + export interface SocketConstructorOpts { fd?: number; allowHalfOpen?: boolean; @@ -2623,7 +2710,7 @@ declare module "net" { setTimeout(timeout: number, callback?: Function): this; setNoDelay(noDelay?: boolean): this; setKeepAlive(enable?: boolean, initialDelay?: number): this; - address(): { port: number; family: string; address: string; }; + address(): AddressInfo | string; unref(): void; ref(): void; @@ -2739,7 +2826,7 @@ declare module "net" { listen(handle: any, backlog?: number, listeningListener?: Function): this; listen(handle: any, listeningListener?: Function): this; close(callback?: Function): this; - address(): { port: number; family: string; address: string; }; + address(): AddressInfo | string; getConnections(cb: (error: Error | null, count: number) => void): void; ref(): this; unref(): this; @@ -2815,22 +2902,17 @@ declare module "net" { } declare module "dgram" { - import * as events from "events"; + import { AddressInfo } from "net"; import * as dns from "dns"; + import * as events from "events"; - interface RemoteInfo { + export interface RemoteInfo { address: string; family: string; port: number; } - interface AddressInfo { - address: string; - family: string; - port: number; - } - - interface BindOptions { + export interface BindOptions { port: number; address?: string; exclusive?: boolean; @@ -2838,7 +2920,7 @@ declare module "dgram" { type SocketType = "udp4" | "udp6"; - interface SocketOptions { + export interface SocketOptions { type: SocketType; reuseAddr?: boolean; recvBufferSize?: number; @@ -2850,14 +2932,14 @@ declare module "dgram" { export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; export class Socket extends events.EventEmitter { - send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; bind(port?: number, address?: string, callback?: () => void): void; bind(port?: number, callback?: () => void): void; bind(callback?: () => void): void; bind(options: BindOptions, callback?: Function): void; close(callback?: () => void): void; - address(): AddressInfo; + address(): AddressInfo | string; setBroadcast(flag: boolean): void; setTTL(ttl: number): void; setMulticastTTL(ttl: number): void; @@ -5058,23 +5140,6 @@ declare module "tls" { prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; } - export interface ClearTextStream extends stream.Duplex { - authorized: boolean; - authorizationError: Error; - getPeerCertificate(): any; - getCipher: { - name: string; - version: string; - }; - address: { - port: number; - family: string; - address: string; - }; - remoteAddress: string; - remotePort: number; - } - export interface SecurePair { encrypted: any; cleartext: any; diff --git a/types/node/v9/node-tests.ts b/types/node/v9/node-tests.ts index efc00ef201..d6751541b9 100644 --- a/types/node/v9/node-tests.ts +++ b/types/node/v9/node-tests.ts @@ -1551,7 +1551,7 @@ namespace dgram_tests { ds.bind(4123, 'localhost', () => { }); ds.bind(4123, () => { }); ds.bind(() => { }); - var ai: dgram.AddressInfo = ds.address(); + const addr: net.AddressInfo | string = ds.address(); ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { }); ds.send(new Buffer("hello"), 5000, "127.0.0.1"); @@ -1564,7 +1564,7 @@ namespace dgram_tests { let _boolean: boolean; let _err: Error; let _str: string; - let _rinfo: dgram.AddressInfo; + let _rinfo: net.AddressInfo; /** * events.EventEmitter * 1. close @@ -1580,7 +1580,7 @@ namespace dgram_tests { _socket = _socket.addListener("listening", () => { }); _socket = _socket.addListener("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _boolean = _socket.emit("close"); @@ -1595,7 +1595,7 @@ namespace dgram_tests { _socket = _socket.on("listening", () => { }); _socket = _socket.on("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _socket = _socket.once("close", () => { }); @@ -1605,7 +1605,7 @@ namespace dgram_tests { _socket = _socket.once("listening", () => { }); _socket = _socket.once("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _socket = _socket.prependListener("close", () => { }); @@ -1615,7 +1615,7 @@ namespace dgram_tests { _socket = _socket.prependListener("listening", () => { }); _socket = _socket.prependListener("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); _socket = _socket.prependOnceListener("close", () => { }); @@ -1625,7 +1625,7 @@ namespace dgram_tests { _socket = _socket.prependOnceListener("listening", () => { }); _socket = _socket.prependOnceListener("message", (msg, rinfo) => { let _msg: Buffer = msg; - let _rinfo: dgram.AddressInfo = rinfo; + let _rinfo: net.AddressInfo = rinfo; }); } @@ -2730,10 +2730,7 @@ namespace net_tests { server = server.close((...args: any[]) => { }); // test the types of the address object fields - let address = server.address(); - address.port = 1234; - address.family = "ipv4"; - address.address = "127.0.0.1"; + let address: net.AddressInfo | string = server.address(); } { diff --git a/types/notifyjs/index.d.ts b/types/notifyjs/index.d.ts index d01ae91a92..0b32e0bdbe 100644 --- a/types/notifyjs/index.d.ts +++ b/types/notifyjs/index.d.ts @@ -1,118 +1,112 @@ -// Type definitions for notifyjs 1.2.8 +// Type definitions for notifyjs 3.0.0 // Project: https://github.com/alexgibson/notify.js // Definitions by: soundTricker +// NateScarlet // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var Notify: { - new (title : string , options? : notifyjs.INotifyOption): notifyjs.INotify; +declare class Notify { + constructor(title: string, options?: INotifyOption); /** * Check is permission is needed for the user to receive notifications. * @return true : needs permission, false : does not need */ - needsPermission : boolean; + static needsPermission: boolean; /** * Asks the user for permission to display notifications * @param onPermissionGrantedCallback A callback for permission is granted. * @param onPermissionDeniedCallback A callback for permission is denied. */ - requestPermission(onPermissionGrantedCallback?: ()=> any, onPermissionDeniedCallback? : ()=> any) : void; + static requestPermission(onPermissionGrantedCallback?: () => any, onPermissionDeniedCallback?: () => any): void; /** * return true if the browser supports HTML5 Notification * @param true : the browser supports HTML5 Notification, false ; the browser does not supports HTML5 Notification. */ - isSupported(): boolean; + static isSupported(): boolean; /** * shows the user's current permission level (granted, denied or default), returns null if notifications are not supported. * @return 'granted' : permission has been given, 'denied' : permission has been denied, 'default' : permission has not yet been set, null : notifications are not supported */ - permissionLevel: string; -} - -declare namespace notifyjs { + static permissionLevel: string; /** - * Interface for Web Notifications API Wrapper. + * Show the notification. */ - interface INotify { - /** - * Show the notification. - */ - show() : void; - - /** - * Remove all event listener. - */ - destroy() : void; - - /** - * Close the notification. - */ - close() : void; - onShowNotification(e : Event) : void; - onCloseNotification() : void; - onClickNotification() : void; - onErrorNotification() : void; - handleEvent(e : Event) : void; - } + show(): void; /** - * Interface for the Notify's optional parameter. + * Remove all event listener. */ - interface INotifyOption { + destroy(): void; - /** - * notification message body - */ - body? : string; - - /** - * path for icon to display in notification - */ - icon? : string; - - /** - * unique identifier to stop duplicate notifications - */ - tag? : string; - - /** - * number of seconds to close the notification automatically - */ - timeout? : number; - - /** - * callback when notification is shown - */ - notifyShow? (e : Event): any; - /** - * callback when notification is closed - */ - notifyClose? : Function; - /** - * callback when notification is clicked - */ - notifyClick? : Function; - /** - * callback when notification throws an error - */ - notifyError? : Function; - /** - * callback when user has granted permission - */ - permissionGranted? : Function; - /** - * callback when user has denied permission - */ - permissionDenied?: Function; - - /** - * whether we expect for user interaction or not - * in case value is true the timeout for closing the notification won't be set - */ - requireInteraction?: boolean; - } + /** + * Close the notification. + */ + close(): void; + onShowNotification(e: Event): void; + onCloseNotification(): void; + onClickNotification(): void; + onErrorNotification(): void; + handleEvent(e: Event): void; } + +/** + * Interface for the Notify's optional parameter. + */ +interface INotifyOption { + + /** + * notification message body + */ + body?: string; + + /** + * path for icon to display in notification + */ + icon?: string; + + /** + * unique identifier to stop duplicate notifications + */ + tag?: string; + + /** + * number of seconds to close the notification automatically + */ + timeout?: number; + + /** + * callback when notification is shown + */ + notifyShow?(e: Event): any; + /** + * callback when notification is closed + */ + notifyClose?: Function; + /** + * callback when notification is clicked + */ + notifyClick?: Function; + /** + * callback when notification throws an error + */ + notifyError?: Function; + /** + * callback when user has granted permission + */ + permissionGranted?: Function; + /** + * callback when user has denied permission + */ + permissionDenied?: Function; + + /** + * whether we expect for user interaction or not + * in case value is true the timeout for closing the notification won't be set + */ + requireInteraction?: boolean; +} +export = Notify \ No newline at end of file diff --git a/types/notifyjs/notifyjs-tests.ts b/types/notifyjs/notifyjs-tests.ts index 4eb6890d77..bdac4d2c05 100644 --- a/types/notifyjs/notifyjs-tests.ts +++ b/types/notifyjs/notifyjs-tests.ts @@ -1,27 +1,27 @@ - +import Notify from 'notifyjs'; function test_Notify_constructor() { //Min var n = new Notify("hoge") n.show(); - + //With option - n = new Notify("hoge", {body : "fuga"}); + n = new Notify("hoge", { body: "fuga" }); n.show(); - + //With Full option n = new Notify("hoge", { - body : "fuga", - icon : "./logo.png", - tag : "user", + body: "fuga", + icon: "./logo.png", + tag: "user", timeout: 2, - notifyShow : (e:Event)=> console.log("notifyShow", e), - notifyClose : ()=> console.log("notifyClose"), - notifyClick : ()=> console.log("notifyClick"), - notifyError : ()=> console.log("notifyError"), - permissionGranted : ()=> console.log("permissionGranted"), - permissionDenied : ()=> console.log("permissionDenied"), - requireInteraction:true + notifyShow: (e: Event) => console.log("notifyShow", e), + notifyClose: () => console.log("notifyClose"), + notifyClick: () => console.log("notifyClick"), + notifyError: () => console.log("notifyError"), + permissionGranted: () => console.log("permissionGranted"), + permissionDenied: () => console.log("permissionDenied"), + requireInteraction: true }); n.show(); @@ -30,8 +30,8 @@ function test_Notify_constructor() { function test_Notify_static_methods() { Notify.needsPermission; Notify.requestPermission(); - Notify.requestPermission(()=> console.log("onPermissionGrantedCallback")); - Notify.requestPermission(()=> console.log("onPermissionGrantedCallback"), ()=> console.log("onPermissionDeniedCallback")); + Notify.requestPermission(() => console.log("onPermissionGrantedCallback")); + Notify.requestPermission(() => console.log("onPermissionGrantedCallback"), () => console.log("onPermissionDeniedCallback")); Notify.isSupported(); Notify.permissionLevel; } diff --git a/types/notifyjs/tsconfig.json b/types/notifyjs/tsconfig.json index 0652ac5cfc..c3df5229ab 100644 --- a/types/notifyjs/tsconfig.json +++ b/types/notifyjs/tsconfig.json @@ -15,7 +15,8 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "allowSyntheticDefaultImports": true }, "files": [ "index.d.ts", diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index e08e0f1ee0..629ccacb21 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -20,6 +20,13 @@ declare namespace Office { * @param reason Indicates how the app was initialized */ export function initialize(reason: InitializationReason): void; + /** + * Ensures that the Office JavaScript APIs are ready to be called by the add-in. If the framework hasn't initialized yet, the callback or promise will wait until the Office host is ready to accept API calls. + * Note that though this API is intended to be used inside an Office add-in, it can also be used outside the add-in. In that case, once Office.js determines that it is running outside of an Office host application, it will call the callback and resolve the promise with "null" for both the host and platform. + * @param callback - An optional callback method, that will receive the host and platform info. Alternatively, rather than use a callback, an add-in may simply wait for the Promise returned by the function to resolve. + * @returns A Promise that contains the host and platform info, once initialization is completed. + */ + export function onReady(callback?: (info: { host: HostType, platform: PlatformType} ) => any): Promise<{ host: HostType, platform: PlatformType }>; /** * Indicates if the large namespace for objects will be used or not. * @param useShortNamespace Indicates if 'true' that the short namespace will be used diff --git a/types/passport-http-bearer/index.d.ts b/types/passport-http-bearer/index.d.ts index 58da308106..14f6f91e26 100644 --- a/types/passport-http-bearer/index.d.ts +++ b/types/passport-http-bearer/index.d.ts @@ -28,7 +28,7 @@ interface VerifyFunctionWithRequest { (req: express.Request, token: string, done: (error: any, user?: any, options?: IVerifyOptions | string) => void): void; } -declare class Strategy extends passport.Strategy { +declare class Strategy implements passport.Strategy { constructor(verify: VerifyFunction); constructor(options: IStrategyOptions, verify: VerifyFunction); constructor(options: IStrategyOptions, verify: VerifyFunctionWithRequest); diff --git a/types/passport-remember-me-extended/index.d.ts b/types/passport-remember-me-extended/index.d.ts new file mode 100644 index 0000000000..044647fe0b --- /dev/null +++ b/types/passport-remember-me-extended/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for passport-remember-me-extended 0.0 +// Project: https://github.com/dereklakin/passport-remember-me +// Definitions by: AylaJK +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import passport = require('passport'); +import express = require('express'); + +export interface StrategyOption { + key?: string; + cookie?: express.CookieOptions; +} + +export interface StrategyOptionWithRequest extends StrategyOption { + passReqToCallback: true; +} + +export type VerifyFunction = + (token: any, done: (err: any, user?: any, info?: any) => void) => void; + +export type VerifyFunctionWithRequest = + (req: express.Request, token: any, done: (err: any, user?: any, info?: any) => void) => void; + +export type IssueFunction = + (user: any, done: (err: any, token?: any) => void) => void; + +export type IssueFunctionWithRequest = + (req: express.Request, user: any, done: (err: any, token?: any) => void) => void; + +export class Strategy extends passport.Strategy { + constructor(verify: VerifyFunction, issue: IssueFunction); + constructor(options: StrategyOptionWithRequest, verify: VerifyFunctionWithRequest, issue: IssueFunctionWithRequest); + constructor(options: StrategyOption, verify: VerifyFunction, issue: IssueFunction); + + authenticate(req: express.Request, options?: passport.AuthenticateOptions): void; +} diff --git a/types/passport-remember-me-extended/passport-remember-me-extended-tests.ts b/types/passport-remember-me-extended/passport-remember-me-extended-tests.ts new file mode 100644 index 0000000000..2b5e1adee5 --- /dev/null +++ b/types/passport-remember-me-extended/passport-remember-me-extended-tests.ts @@ -0,0 +1,85 @@ +/** + * Create by AylaJK on 05/05/2018 + */ +import express = require('express'); +import passport = require('passport'); +import rememberme = require('passport-remember-me-extended'); + +// just some test model +const Token = { + consume(token: any, callback: (err: any, user?: any) => void): void { + callback(null, { id: '1234', username: 'james' }); + }, + save(token: any, user: any, callback: (err: any) => void): void { + callback(null); + } +}; + +passport.use(new rememberme.Strategy( + (token: any, done: (err: any, user?: any) => void) => { + Token.consume(token, (err, user) => { + if (err) done(err); + else if (!user) done(null, false); + else done(null, user); + }); + }, + (user: any, done: (err: any, token?: any) => void) => { + const token = { id: 'token' }; + Token.save(token, { userId: user.id }, (err) => { + if (err) done(err); + else done(null, token); + }); + } +)); + +passport.use(new rememberme.Strategy({ + key: 'remember-me', + cookie: { + path: '/', + httpOnly: true, + maxAge: 604800000, + }, + }, + (token: any, done: (err: any, user?: any) => void) => { + Token.consume(token, (err, user) => { + if (err) done(err); + else if (!user) done(null, false); + else done(null, user); + }); + }, + (user: any, done: (err: any, token?: any) => void) => { + const token = { id: 'token' }; + Token.save(token, { userId: user.id }, (err) => { + if (err) done(err); + else done(null, token); + }); + } +)); + +passport.use(new rememberme.Strategy({ + key: 'remember-me', + cookie: { + path: '/', + httpOnly: true, + maxAge: 604800000, + }, + passReqToCallback: true, + }, + (req: express.Request, token: any, done: (err: any, user?: any) => void) => { + Token.consume(token, (err, user) => { + if (err) done(err); + else if (!user) done(null, false); + else done(null, user); + }); + }, + (req: express.Request, user: any, done: (err: any, token?: any) => void) => { + const token = { id: 'token' }; + Token.save(token, { userId: user.id }, (err) => { + if (err) done(err); + else done(null, token); + }); + } +)); + +const app = express(); +app.use(passport.authenticate('remember-me')); diff --git a/types/passport-remember-me-extended/tsconfig.json b/types/passport-remember-me-extended/tsconfig.json new file mode 100644 index 0000000000..7062f9acbc --- /dev/null +++ b/types/passport-remember-me-extended/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "passport-remember-me-extended-tests.ts" + ] +} diff --git a/types/passport-remember-me-extended/tslint.json b/types/passport-remember-me-extended/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/passport-remember-me-extended/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index 6b405d3e53..ac35dc064b 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -347,6 +347,7 @@ export interface ModeBarButton { // Data export type Datum = string | number | Date; +export type TypedArray = Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array; export type Dash = 'solid' | 'dot' | 'dash' | 'longdash' | 'dashdot' | 'longdashdot'; @@ -356,9 +357,9 @@ export type Color = string | Array | Array +// Microsoft +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace powerbi { + enum VisualDataRoleKind { + /** Indicates that the role should be bound to something that evaluates to a grouping of values. */ + Grouping = 0, + /** Indicates that the role should be bound to something that evaluates to a single value in a scope. */ + Measure = 1, + /** Indicates that the role can be bound to either Grouping or Measure. */ + GroupingOrMeasure = 2, + } + enum VisualDataChangeOperationKind { + Create = 0, + Append = 1, + } + enum VisualUpdateType { + Data = 2, + Resize = 4, + ViewMode = 8, + Style = 16, + ResizeEnd = 32, + All = 62, + } + + const enum CartesianRoleKind { + X = 0, + Y = 1, + } + const enum ViewMode { + View = 0, + Edit = 1, + InFocusEdit = 2, + } + const enum EditMode { + /** Default editing mode for the visual. */ + Default = 0, + /** Indicates the user has asked the visual to display advanced editing controls. */ + Advanced = 1, + } + const enum AdvancedEditModeSupport { + /** The visual doesn't support Advanced Edit mode. Do not display the 'Edit' button on this visual. */ + NotSupported = 0, + /** The visual supports Advanced Edit mode, but doesn't require any further changes aside from setting EditMode=Advanced. */ + SupportedNoAction = 1, + /** The visual supports Advanced Edit mode, and requires that the host pops out the visual when entering Advanced EditMode. */ + SupportedInFocus = 2, + } + const enum ResizeMode { + Resizing = 1, + Resized = 2, + } + const enum JoinPredicateBehavior { + /** Prevent items in this role from acting as join predicates. */ + None = 0, + } + const enum PromiseResultType { + Success = 0, + Failure = 1, + } + /** + * Defines actions to be taken by the visual in response to a selection. + * + * An undefined/null VisualInteractivityAction should be treated as Selection, + * as that is the default action. + */ + const enum VisualInteractivityAction { + /** Normal selection behavior which should call onSelect */ + Selection = 0, + /** No additional action or feedback from the visual is needed */ + None = 1, + } + /** + * Defines various events Visuals can notify the host on. + */ + const enum VisualEventType { + /** Should be used at the beginning of a visual's rendering operation. */ + RenderStarted = 0, + /** Should be used at the end of a visual's rendering operation. */ + RenderCompleted = 1, + /** Should be used by visuals to trace information in PBI telemetry. */ + Trace = 2, + /** Should be used by visuals to trace errors in PBI telemetry. */ + Error = 3, + } + const enum FilterAction { + /** Merging filter into existing filters. */ + merge = 0, + /** removing existing filter. */ + remove = 1, + } +} + +declare namespace powerbi.visuals.plugins { + /** This IVisualPlugin interface is only used by the CLI tools when compiling */ + + interface IVisualPlugin { + /** The name of the plugin. Must match the property name in powerbi.visuals. */ + name: string; + + /** Function to call to create the visual. */ + create: (options?: extensibility.VisualConstructorOptions) => extensibility.IVisual; + + /** The class of the plugin. At the moment it is only used to have a way to indicate the class name that a custom visual has. */ + class: string; + + /** Check if a visual is custom */ + custom: boolean; + + /** The version of the api that this plugin should be run against */ + apiVersion: string; + + /** Human readable plugin name displayed to users */ + displayName: string; + } +} + +declare namespace jsCommon { + interface IStringResourceProvider { + get(id: string): string; + getOptional(id: string): string; + } +} + +declare namespace powerbi { + /** + * An interface to promise/deferred, + * which abstracts away the underlying mechanism (e.g., Angular, jQuery, etc.). + */ + + interface IPromiseFactory { + /** + * Creates a Deferred object which represents a task which will finish in the future. + */ + // tslint:disable-next-line + defer(): IDeferred; + + /** + * Creates a Deferred object which represents a task which will finish in the future. + */ + // tslint:disable-next-line + defer(): IDeferred2; + + /** + * Creates a promise that is resolved as rejected with the specified reason. + * This api should be used to forward rejection in a chain of promises. + * If you are dealing with the last promise in a promise chain, you don't need to worry about it. + * When comparing deferreds/promises to the familiar behavior of try/catch/throw, + * think of reject as the throw keyword in JavaScript. + * This also means that if you "catch" an error via a promise error callback and you want + * to forward the error to the promise derived from the current promise, + * you have to "rethrow" the error by returning a rejection constructed via reject. + * + * @param reason Constant, message, exception or an object representing the rejection reason. + */ + reject(reason?: TError): IPromise2; + + /** + * Creates a promise that is resolved with the specified value. + * This api should be used to forward rejection in a chain of promises. + * If you are dealing with the last promise in a promise chain, you don't need to worry about it. + * + * @param value Object representing the promise result. + */ + resolve(value?: TSuccess): IPromise2; + + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * Rejects immediately if any of the promises fail + */ + all(promises: Array>): IPromise; + + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * Does not resolve until all promises finish (success or failure). + */ + // tslint:disable-next-line + allSettled(promises: Array>): IPromise>>; + + /** + * Wraps an object that might be a value or a then-able promise into a promise. + * This is useful when you are dealing with an object that might or might not be a promise + */ + when(value: T | IPromise): IPromise; + } + + /** + * Represents an operation, to be completed (resolve/rejected) in the future. + */ + interface IPromise extends IPromise2 {// eslint-disable-line interface-name + } + + /** + * Represents an operation, to be completed (resolve/rejected) in the future. + * Success and failure types can be set independently. + */ + interface IPromise2 { + /** + * Regardless of when the promise was or will be resolved or rejected, + * then calls one of the success or error callbacks asynchronously as soon as the result is available. + * The callbacks are called with a single argument: the result or rejection reason. + * Additionally, the notify callback may be called zero or more times to provide a progress indication, + * before the promise is resolved or rejected. + * This method returns a new promise which is resolved or rejected via + * the return value of the successCallback, errorCallback. + */ + then( + successCallback: (promiseValue: TSuccess) => TSuccessResult | IPromise2, + errorCallback?: (reason: TError) => TErrorResult): + IPromise2; + + /** + * Shorthand for promise.then(null, errorCallback). + */ + catch(onRejected: (reason: any) => IPromise2): IPromise2; + + /** + * Shorthand for promise.then(null, errorCallback). + */ + catch(onRejected: (reason: any) => TErrorResult): IPromise2; + + /** + * Allows you to observe either the fulfillment or rejection of a promise, + * but to do so without modifying the final value. + * This is useful to release resources or do some clean-up that needs to be done + * whether the promise was rejected or resolved. + * See the full specification for more information. + * Because finally is a reserved word in JavaScript and reserved keywords + * are not supported as property names by ES3, you'll need to invoke + * the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible. + */ + // tslint:disable-next-line + finally(finallyCallback: () => any): IPromise2; + } + + interface IDeferred extends IDeferred2 { + } + + interface IDeferred2 { + resolve(value: TSuccess): void; + reject(reason?: TError): void; + promise: IPromise2; + } + + interface RejectablePromise2 extends IPromise2 { + reject(reason?: E): void; + resolved(): boolean; + rejected(): boolean; + pending(): boolean; + } + + interface RejectablePromise extends RejectablePromise2 { + } + + interface IResultCallback { + // tslint:disable-next-line + (result: T, done: boolean): void; + } + + interface IPromiseResult { + type: PromiseResultType; + value: T; + } +} + +declare namespace powerbi.visuals { + import Selector = data.Selector; + import SelectorsByColumn = data.SelectorsByColumn; + + interface ISelectionIdBuilder { + withCategory(categoryColumn: DataViewCategoryColumn, index: number): this; + withSeries(seriesColumn: DataViewValueColumns, valueColumn: DataViewValueColumn | DataViewValueColumnGroup): this; + withMeasure(measureId: string): this; + createSelectionId(): ISelectionId; + } + + interface ISelectionId { + equals(other: ISelectionId): boolean; + includes(other: ISelectionId, ignoreHighlight?: boolean): boolean; + getKey(): string; + getSelector(): Selector; + getSelectorsByColumn(): SelectorsByColumn; + hasIdentity(): boolean; + } +} + +declare namespace powerbi { + const enum SortDirection { + Ascending = 1, + Descending = 2, + } +} + +declare namespace powerbi { + /** Represents views of a data set. */ + interface DataView { + metadata: DataViewMetadata; + categorical?: DataViewCategorical; + single?: DataViewSingle; + tree?: DataViewTree; + table?: DataViewTable; + matrix?: DataViewMatrix; + scriptResult?: DataViewScriptResultData; + } + + interface DataViewMetadata { + columns: DataViewMetadataColumn[]; + + /** The metadata repetition objects. */ + objects?: DataViewObjects; + + /** When defined, describes whether the DataView contains just a segment of the complete data set. */ + segment?: {}; + + /** Describes the data reduction applied to this data set when limits are exceeded. */ + dataReduction?: DataViewReductionMetadata; + } + + interface DataViewMetadataColumn { + /** The user-facing display name of the column. */ + displayName: string; + + /** The query name the source column in the query. */ + queryName?: string; + + /** The format string of the column. */ + format?: string; // TODO: Deprecate this, and populate format string through objects instead. + + /** Data type information for the column. */ + type?: ValueTypeDescriptor; + + /** Indicates that this column is a measure (aggregate) value. */ + isMeasure?: boolean; + + /** The position of the column in the select statement. */ + index?: number; + + /** The properties that this column provides to the visualization. */ + roles?: { [name: string]: boolean }; + + /** The metadata repetition objects. */ + objects?: DataViewObjects; + + /** The name of the containing group. */ + groupName?: PrimitiveValue; + + /** The sort direction of this column. */ + sort?: SortDirection; + + /** The order sorts are applied. Lower values are applied first. Undefined indicates no sort was done on this column. */ + sortOrder?: number; + + /** The KPI metadata to use to convert a numeric status value into its visual representation. */ + kpi?: DataViewKpiColumnMetadata; + + /** Indicates that aggregates should not be computed across groups with different values of this column. */ + discourageAggregationAcrossGroups?: boolean; + + /** The aggregates computed for this column, if any. */ + aggregates?: DataViewColumnAggregates; + + /** The SQExpr this column represents. */ + expr?: data.ISQExpr; + + /** + * The set of expressions that define the identity for instances of this grouping field. + * This must be a subset of the items in the DataViewScopeIdentity in the grouped items result. + * This property is undefined for measure fields, as well as for grouping fields in DSR generated prior to the CY16SU08 or SU09 timeframe. + */ + identityExprs?: data.ISQExpr[]; + + parameter?: {}; + } + + interface DataViewReductionMetadata { + categorical?: DataViewCategoricalReductionMetadata; + } + + interface DataViewCategoricalReductionMetadata { + categories?: DataViewReductionAlgorithmMetadata; + values?: DataViewReductionAlgorithmMetadata; + metadata?: DataViewReductionAlgorithmMetadata; + } + + interface DataViewReductionAlgorithmMetadata { + binnedLineSample?: {}; + } + + interface DataViewColumnAggregates { + subtotal?: PrimitiveValue; + max?: PrimitiveValue; + min?: PrimitiveValue; + average?: PrimitiveValue; + median?: PrimitiveValue; + count?: number; + percentiles?: DataViewColumnPercentileAggregate[]; + + /** Represents a single value evaluation, similar to a total. */ + single?: PrimitiveValue; + + /** Client-computed maximum value for a column. */ + maxLocal?: PrimitiveValue; + + /** Client-computed maximum value for a column. */ + minLocal?: PrimitiveValue; + } + + interface DataViewColumnPercentileAggregate { + exclusive?: boolean; + k: number; + value: PrimitiveValue; + } + + interface DataViewCategorical { + categories?: DataViewCategoryColumn[]; + values?: DataViewValueColumns; + } + + interface DataViewCategoricalColumn { + source: DataViewMetadataColumn; + + /** The data repetition objects. */ + objects?: DataViewObjects[]; + } + + interface DataViewValueColumns extends Array { + /** Returns an array that groups the columns in this group together. */ + grouped(): DataViewValueColumnGroup[]; + + /** The set of expressions that define the identity for instances of the value group. This must match items in the DataViewScopeIdentity in the grouped items result. */ + identityFields?: data.ISQExpr[]; + + source?: DataViewMetadataColumn; + } + + interface DataViewValueColumnGroup { + values: DataViewValueColumn[]; + identity?: DataViewScopeIdentity; + + /** The data repetition objects. */ + objects?: DataViewObjects; + + name?: PrimitiveValue; + } + + interface DataViewValueColumn extends DataViewCategoricalColumn { + values: PrimitiveValue[]; + highlights?: PrimitiveValue[]; + identity?: DataViewScopeIdentity; + } + + interface DataViewCategoryColumn extends DataViewCategoricalColumn { + values: PrimitiveValue[]; + identity?: DataViewScopeIdentity[]; + + /** The set of expressions that define the identity for instances of the category. This must match items in the DataViewScopeIdentity in the identity. */ + identityFields?: data.ISQExpr[]; + } + + interface DataViewSingle { + value: PrimitiveValue; + } + + interface DataViewTree { + root: DataViewTreeNode; + } + + interface DataViewTreeNode { + name?: PrimitiveValue; + + /** + * When used under the context of DataView.tree, this value is one of the elements in the values property. + * + * When used under the context of DataView.matrix, this property is the value of the particular + * group instance represented by this node (e.g. In a grouping on Year, a node can have value == 2016). + * + * DEPRECATED for usage under the context of DataView.matrix: This property is deprecated for objects + * that conform to the DataViewMatrixNode interface (which extends DataViewTreeNode). + * New visuals code should consume the new property levelValues on DataViewMatrixNode instead. + * If this node represents a composite group node in matrix, this property will be undefined. + */ + value?: PrimitiveValue; + + /** + * This property contains all the values in this node. + * The key of each of the key-value-pair in this dictionary is the position of the column in the + * select statement to which the value belongs. + */ + values?: { [id: number]: DataViewTreeNodeValue }; + + children?: DataViewTreeNode[]; + identity?: DataViewScopeIdentity; + + /** The data repetition objects. */ + objects?: DataViewObjects; + + /** The set of expressions that define the identity for the child nodes. This must match items in the DataViewScopeIdentity of those nodes. */ + childIdentityFields?: data.ISQExpr[]; + } + + interface DataViewTreeNodeValue { + value?: PrimitiveValue; + } + + interface DataViewTreeNodeMeasureValue extends DataViewTreeNodeValue, DataViewColumnAggregates { + highlight?: PrimitiveValue; + } + + interface DataViewTreeNodeGroupValue extends DataViewTreeNodeValue { + count?: PrimitiveValue; + } + + interface DataViewTable { + columns: DataViewMetadataColumn[]; + + identity?: DataViewScopeIdentity[]; + + /** The set of expressions that define the identity for rows of the table. This must match items in the DataViewScopeIdentity in the identity. */ + identityFields?: data.ISQExpr[]; + + rows?: DataViewTableRow[]; + + totals?: PrimitiveValue[]; + } + + interface DataViewTableRow extends Array { + /** The data repetition objects. */ + objects?: DataViewObjects[]; + } + + interface DataViewMatrix { + rows: DataViewHierarchy; + columns: DataViewHierarchy; + + /** + * The metadata columns of the measure values. + * In visual DataView, this array is sorted in projection order. + */ + valueSources: DataViewMetadataColumn[]; + } + + interface DataViewMatrixNode extends DataViewTreeNode { + /** Indicates the level this node is on. Zero indicates the outermost children (root node level is undefined). */ + level?: number; + + children?: DataViewMatrixNode[]; + + /* If this DataViewMatrixNode represents the inner-most dimension of row groups (i.e. a leaf node), then this property will contain the values at the + * matrix intersection under the group. The valueSourceIndex property will contain the position of the column in the select statement to which the + * value belongs. + * + * When this DataViewMatrixNode is used under the context of DataView.matrix.columns, this property is not used. + */ + values?: { [id: number]: DataViewMatrixNodeValue }; + + /** + * Indicates the source metadata index on the node's level. Its value is 0 if omitted. + * + * DEPRECATED: This property is deprecated and exists for backward-compatibility only. + * New visuals code should consume the new property levelSourceIndex on DataViewMatrixGroupValue instead. + */ + levelSourceIndex?: number; + + /** + * The values of the particular group instance represented by this node. + * This array property would contain more than one element in a composite group + * (e.g. Year == 2016 and Month == 'January'). + */ + levelValues?: DataViewMatrixGroupValue[]; + + /** Indicates whether or not the node is a subtotal node. Its value is false if omitted. */ + isSubtotal?: boolean; + } + + /** + * Represents a value at a particular level of a matrix's rows or columns hierarchy. + * In the hierarchy level node is an instance of a composite group, this object will + * be one of multiple values + */ + interface DataViewMatrixGroupValue extends DataViewTreeNodeValue { + /** + * Indicates the index of the corresponding column for this group level value + * (held by DataViewHierarchyLevel.sources). + * + * @example + * // For example, to get the source column metadata of each level value at a particular row hierarchy node: + * let matrixRowsHierarchy: DataViewHierarchy = dataView.matrix.rows; + * let targetRowsHierarchyNode = matrixRowsHierarchy.root.children[0]; + * // Use the DataViewMatrixNode.level property to get the corresponding DataViewHierarchyLevel... + * let targetRowsHierarchyLevel: DataViewHierarchyLevel = matrixRows.levels[targetRowsHierarchyNode.level]; + * for (let levelValue in rowsRootNode.levelValues) { + * // columnMetadata is the source column for the particular levelValue.value in this loop iteration + * let columnMetadata: DataViewMetadataColumn = + * targetRowsHierarchyLevel.sources[levelValue.levelSourceIndex]; + * } + */ + levelSourceIndex: number; + } + + /** Represents a value at the matrix intersection, used in the values property on DataViewMatrixNode (inherited from DataViewTreeNode). */ + interface DataViewMatrixNodeValue extends DataViewTreeNodeValue { + highlight?: PrimitiveValue; + + /** The data repetition objects. */ + objects?: DataViewObjects; + + /** Indicates the index of the corresponding measure (held by DataViewMatrix.valueSources). Its value is 0 if omitted. */ + valueSourceIndex?: number; + } + + interface DataViewHierarchy { + root: DataViewMatrixNode; + levels: DataViewHierarchyLevel[]; + } + + interface DataViewHierarchyLevel { + /** + * The metadata columns of this hierarchy level. + * In visual DataView, this array is sorted in projection order. + */ + sources: DataViewMetadataColumn[]; + } + + interface DataViewKpiColumnMetadata { + graphic: string; + + // When false, five state KPIs are in: { -2, -1, 0, 1, 2 }. + // When true, five state KPIs are in: { -1, -0.5, 0, 0.5, 1 }. + normalizedFiveStateKpiRange?: boolean; + } + + interface DataViewScriptResultData { + payloadBase64: string; + } + + interface ValueRange { + min?: T; + max?: T; + } + + /** Defines the acceptable values of a number. */ + type NumberRange = ValueRange; + + /** Defines the PrimitiveValue range. */ + type PrimitiveValueRange = ValueRange; +} + +declare namespace powerbi { + /** Represents evaluated, named, custom objects in a DataView. */ + interface DataViewObjects { + [name: string]: DataViewObject; + } + + /** Represents an object (name-value pairs) in a DataView. */ + interface DataViewObject { + /** Map of property name to property value. */ + [propertyName: string]: DataViewPropertyValue | DataViewObjectMap; + + /** Instances of this object. When there are multiple instances with the same object name they will appear here. */ + // $instances?: DataViewObjectMap; - moved to indexed property as optional type + } + + interface DataViewObjectWithId { + id: string; + object: DataViewObject; + } + + interface DataViewObjectPropertyIdentifier { + objectName: string; + propertyName: string; + } + + interface DataViewObjectMap { + [id: string]: DataViewObject; + } + + type DataViewPropertyValue = PrimitiveValue | StructuralObjectValue; +} + +declare namespace powerbi.data { + /** Defines a match against all instances of given roles. */ + interface DataViewRoleWildcard { + kind: DataRepetitionKind.RoleWildcard; + roles: string[]; + key: string; + } +} + +declare namespace powerbi { + /** Encapsulates the identity of a data scope in a DataView. */ + interface DataViewScopeIdentity { + kind: DataRepetitionKind.ScopeIdentity; + + /** Predicate expression that identifies the scope. */ + expr: data.ISQExpr; + + /** Key string that identifies the DataViewScopeIdentity to a string, which can be used for equality comparison. */ + key: string; + } +} + +declare namespace powerbi.data { + /** Defines a match against all instances of a given DataView scope. Does not match Subtotals. */ + interface DataViewScopeWildcard { + kind: DataRepetitionKind.ScopeWildcard; + exprs: ISQExpr[]; + key: string; + } +} + +declare namespace powerbi.data { + import IStringResourceProvider = jsCommon.IStringResourceProvider; + + type DisplayNameGetter = ((resourceProvider: IStringResourceProvider) => string) | string; +} + +declare namespace powerbi.data { + /** Defines a selector for content, including data-, metadata, and user-defined repetition. */ + interface Selector { + /** Data-bound repetition selection. */ + data?: DataRepetitionSelector[]; + + /** Metadata-bound repetition selection. Refers to a DataViewMetadataColumn queryName. */ + metadata?: string; + + /** User-defined repetition selection. */ + id?: string; + } + + type DataRepetitionSelector = + DataViewScopeIdentity | + DataViewScopeWildcard | + DataViewRoleWildcard | + DataViewScopeTotal; + + interface SelectorsByColumn { + key?: string; + } +} + +declare namespace powerbi.data { + // intentionally blank interfaces since this is not part of the public API + + interface ISemanticFilter { + whereItems?: {}; + } + + interface ISQExpr { + left?: ISQExpr; + right?: ISQExpr; + args?: ISQExpr; + } + + interface ISQConstantExpr extends ISQExpr { + kind?: number; + } +} + +declare namespace powerbi { + /** Kind of the Data Repetition Selector */ + const enum DataRepetitionKind { + RoleWildcard = 0, + ScopeIdentity = 1, + ScopeTotal = 2, + ScopeWildcard = 3, + } +} + +declare namespace powerbi.data { + /** Defines a match against any Total within a given DataView scope. */ + interface DataViewScopeTotal { + kind: DataRepetitionKind.ScopeTotal; + + /* The exprs defining the scope that this Total has been evaluated for + * It's an array to support expressing Total across a composite group + * Example: If this represents Total sales of USA across States, the Exprs wil refer to "States" + */ + exprs: ISQExpr[]; + + key: string; + } +} + +declare namespace powerbi { + interface DefaultValueDefinition { + value: data.ISQConstantExpr; + identityFieldsValues?: data.ISQConstantExpr[]; + } + + interface DefaultValueTypeDescriptor { + defaultValue: boolean; + } +} + +declare namespace powerbi { + import DisplayNameGetter = data.DisplayNameGetter; + + type EnumMemberValue = string | number; + + interface IEnumMember { + value: EnumMemberValue; + displayName: DisplayNameGetter; + } + + /** Defines a custom enumeration data type, and its values. */ + interface IEnumType { + /** Gets the members of the enumeration, limited to the validMembers, if appropriate. */ + members(validMembers?: EnumMemberValue[]): IEnumMember[]; + } +} + +declare namespace powerbi { + interface Fill { + solid?: { + color?: string; + }; + gradient?: { + startColor?: string; + endColor?: string; + }; + pattern?: { + patternKind?: string; + color?: string; + }; + } + + interface FillTypeDescriptor { + solid?: { + color?: FillSolidColorTypeDescriptor; + }; + gradient?: { + startColor?: boolean; + endColor?: boolean; + }; + pattern?: { + patternKind?: boolean; + color?: boolean; + }; + } + + type FillSolidColorTypeDescriptor = boolean | FillSolidColorAdvancedTypeDescriptor; + + interface FillSolidColorAdvancedTypeDescriptor { + /** Indicates whether the color value may be nullable, and a 'no fill' option is appropriate. */ + nullable: boolean; + } +} + +declare namespace powerbi { + interface FillRule extends FillRuleGeneric { + } + + interface FillRuleGeneric { + linearGradient2?: LinearGradient2Generic; + linearGradient3?: LinearGradient3Generic; + + // stepped2? + // ... + } + + interface LinearGradient2Generic { + max: RuleColorStopGeneric; + min: RuleColorStopGeneric; + nullColoringStrategy?: NullColoringStrategyGeneric; + } + interface LinearGradient3Generic { + max: RuleColorStopGeneric; + mid: RuleColorStopGeneric; + min: RuleColorStopGeneric; + nullColoringStrategy?: NullColoringStrategyGeneric; + } + + interface RuleColorStopGeneric { + color: TColor; + value?: TValue; + } + + interface NullColoringStrategyGeneric { + strategy: TStrategy; + /** + * Only used if strategy is specificColor + */ + color?: TColor; + } +} + +declare namespace powerbi { + interface FilterTypeDescriptor { + selfFilter?: boolean; + } +} + +declare namespace powerbi { + type GeoJson = GeoJsonDefinitionGeneric; + + interface GeoJsonDefinitionGeneric { + type: T; + name: T; + content: T; + } +} + +declare namespace powerbi { + type ImageValue = ImageDefinitionGeneric; + + interface ImageDefinitionGeneric { + name: T; + url: T; + scaling?: T; + } +} + +declare namespace powerbi { + import ISQExpr = data.ISQExpr; + + type Paragraphs = Paragraph[]; + + interface Paragraph { + horizontalTextAlignment?: string; + textRuns: TextRun[]; + } + + interface TextRunStyle { + fontFamily?: string; + fontSize?: string; + fontStyle?: string; + fontWeight?: string; + color?: string; + textDecoration?: string; + } + + interface TextRun { + textStyle?: TextRunStyle; + url?: string; + value: string; + valueExpr?: ISQExpr; + } +} + +declare namespace powerbi { + import SemanticFilter = data.ISemanticFilter; + + /** Defines instances of structural types. */ + type StructuralObjectValue = + Fill | + FillRule | + SemanticFilter | + DefaultValueDefinition | + ImageValue | + Paragraphs | + GeoJson | + DataBars; + + /** Describes a structural type in the client type system. Leaf properties should use ValueType. */ + interface StructuralTypeDescriptor { + fill?: FillTypeDescriptor; + fillRule?: {}; + filter?: FilterTypeDescriptor; + expression?: DefaultValueTypeDescriptor; + image?: {}; + paragraphs?: {}; + geoJson?: {}; + queryTransform?: {}; + dataBars?: {}; + } +} + +declare namespace powerbi { + /** Describes a data value type in the client type system. Can be used to get a concrete ValueType instance. */ + interface ValueTypeDescriptor { + // Simplified primitive types + readonly text?: boolean; + readonly numeric?: boolean; + readonly integer?: boolean; + readonly bool?: boolean; + readonly dateTime?: boolean; + readonly duration?: boolean; + readonly binary?: boolean; + readonly none?: boolean; // TODO: 5005022 remove none type when we introduce property categories. + + // Extended types + readonly temporal?: TemporalTypeDescriptor; + readonly geography?: GeographyTypeDescriptor; + readonly misc?: MiscellaneousTypeDescriptor; + readonly formatting?: FormattingTypeDescriptor; + /*readonly*/ enumeration?: IEnumType; + readonly scripting?: ScriptTypeDescriptor; + readonly operations?: OperationalTypeDescriptor; + + // variant types + readonly variant?: ValueTypeDescriptor[]; + } + + interface ScriptTypeDescriptor { + readonly source?: boolean; + } + + interface TemporalTypeDescriptor { + readonly year?: boolean; + readonly quarter?: boolean; + readonly month?: boolean; + readonly day?: boolean; + readonly paddedDateTableDate?: boolean; + } + + interface GeographyTypeDescriptor { + readonly address?: boolean; + readonly city?: boolean; + readonly continent?: boolean; + readonly country?: boolean; + readonly county?: boolean; + readonly region?: boolean; + readonly postalCode?: boolean; + readonly stateOrProvince?: boolean; + readonly place?: boolean; + readonly latitude?: boolean; + readonly longitude?: boolean; + } + + interface MiscellaneousTypeDescriptor { + readonly image?: boolean; + readonly imageUrl?: boolean; + readonly webUrl?: boolean; + readonly barcode?: boolean; + } + + interface FormattingTypeDescriptor { + readonly color?: boolean; + readonly formatString?: boolean; + readonly alignment?: boolean; + readonly labelDisplayUnits?: boolean; + readonly fontSize?: boolean; + readonly fontFamily?: boolean; + readonly labelDensity?: boolean; + readonly bubbleSize?: boolean; + readonly altText?: boolean; + } + + interface OperationalTypeDescriptor { + readonly searchEnabled?: boolean; + } + + /** Describes instances of value type objects. */ + type PrimitiveValue = string | number | boolean | Date; +} + +declare namespace powerbi { + interface DataBars { + minValue?: number; + maxValue?: number; + positiveColor: Fill; + negativeColor: Fill; + axisColor: Fill; + reverseDirection: boolean; + hideText: boolean; + } +} + +declare namespace powerbi { + interface IViewport { + height: number; + width: number; + } + + interface ScaledViewport extends IViewport { + scale: number; + } +} + +declare namespace powerbi { + import Selector = data.Selector; + + interface VisualObjectInstance { + /** The name of the object (as defined in VisualCapabilities). */ + objectName: string; + + /** A display name for the object instance. */ + displayName?: string; + + /** The set of property values for this object. Some of these properties may be defaults provided by the IVisual. */ + properties: { + [propertyName: string]: DataViewPropertyValue; + }; + + /** The selector that identifies this object. */ + selector: Selector; + + /** (Optional) Defines the constrained set of valid values for a property. */ + validValues?: { + [propertyName: string]: string[] | ValidationOptions; + }; + + /** (Optional) VisualObjectInstanceEnumeration category index. */ + containerIdx?: number; + + /** (Optional) Set the required type for particular properties that support variant types. */ + propertyTypes?: { + [propertyName: string]: ValueTypeDescriptor; + }; + } + + type VisualObjectInstanceEnumeration = VisualObjectInstance[] | VisualObjectInstanceEnumerationObject; + + interface ValidationOptions { + numberRange?: NumberRange; + } + + interface VisualObjectInstanceEnumerationObject { + /** The visual object instances. */ + instances: VisualObjectInstance[]; + + /** Defines a set of containers for related object instances. */ + containers?: VisualObjectInstanceContainer[]; + } + + interface VisualObjectInstanceContainer { + displayName: data.DisplayNameGetter; + } + + interface VisualObjectInstancesToPersist { + /** Instances which should be merged with existing instances. */ + merge?: VisualObjectInstance[]; + + /** Instances which should replace existing instances. */ + replace?: VisualObjectInstance[]; + + /** Instances which should be deleted from the existing instances. */ + remove?: VisualObjectInstance[]; + + /** Instances which should be deleted from the existing objects. */ + removeObject?: VisualObjectInstance[]; + } + + interface EnumerateVisualObjectInstancesOptions { + objectName: string; + } +} + +declare namespace powerbi { + import Selector = data.Selector; + + interface VisualObjectRepetition { + /** The selector that identifies the objects. */ + selector: Selector; + + /** Used to group differernt repetitions into containers. That will be used as the container displayName in the PropertyPane */ + containerName?: string; + + /** The set of repetition descriptors for this object. */ + objects: { + [objectName: string]: DataViewRepetitionObjectDescriptor; + }; + } + + interface DataViewRepetitionObjectDescriptor { + /** Properties used for formatting (e.g., Conditional Formatting). */ + formattingProperties?: string[]; + } +} + +declare namespace powerbi.extensibility { + interface IVisualPluginOptions { + transform?: IVisualDataViewTransform; + } + + interface IVisualConstructor { + __transform__?: IVisualDataViewTransform; + } + + interface IVisualDataViewTransform { + // tslint:disable-next-line + (dataview: DataView[]): T; + } + + // These are the base interfaces. These should remain empty + // All visual versions should extend these for type compatability + + interface IVisual { + /** Notifies the visual that it is being destroyed, and to do any cleanup necessary (such as unsubscribing event handlers). */ + destroy?(): void; + } + + interface IVisualHost { + instanceId: string; + } + + interface VisualUpdateOptions { + type: VisualUpdateType; + } + + interface VisualConstructorOptions { + /** The loaded module, if any, defined by the IVisualPlugin.module. */ + module?: any; + } +} + +declare namespace powerbi { + interface IColorInfo extends IStyleInfo { + value: string; + } + + interface IStyleInfo { + className?: string; + } +} + +declare namespace powerbi.extensibility { + interface ISelectionManager { + select(selectionId: visuals.ISelectionId | visuals.ISelectionId[], multiSelect?: boolean): IPromise; + hasSelection(): boolean; + clear(): IPromise<{}>; + getSelectionIds(): visuals.ISelectionId[]; + applySelectionFilter(): void; + registerOnSelectCallback(callback: (ids: visuals.ISelectionId[]) => void): void; + } +} + +declare namespace powerbi.extensibility { + interface ISelectionIdBuilder { + withCategory(categoryColumn: DataViewCategoryColumn, index: number): this; + withSeries(seriesColumn: DataViewValueColumns, valueColumn: DataViewValueColumn | DataViewValueColumnGroup): this; + withMeasure(measureId: string): this; + createSelectionId(): visuals.ISelectionId; + } +} + +declare namespace powerbi.extensibility { + interface IColorPalette { + getColor(key: string): IColorInfo; + } +} + +declare namespace powerbi.extensibility { + interface VisualTooltipDataItem { + displayName: string; + value: string; + color?: string; + header?: string; + opacity?: string; + } + + interface TooltipMoveOptions { + coordinates: number[]; + isTouchEvent: boolean; + dataItems?: VisualTooltipDataItem[]; + identities: visuals.ISelectionId[]; + } + + interface TooltipShowOptions extends TooltipMoveOptions { + dataItems: VisualTooltipDataItem[]; + } + + interface TooltipHideOptions { + isTouchEvent: boolean; + immediately: boolean; + } + + interface ITooltipService { + enabled(): boolean; + show(options: TooltipShowOptions): void; + move(options: TooltipMoveOptions): void; + hide(options: TooltipHideOptions): void; + } +} + +declare namespace powerbi.extensibility { + interface ITelemetryService { + readonly instanceId: string; + trace(type: VisualEventType, payload?: string): void; + } +} + +declare namespace powerbi.extensibility { + function VisualPlugin(options: IVisualPluginOptions): ClassDecorator; +} + +declare namespace powerbi.extensibility { + interface ILocalizationManager { + getDisplayName(key: string): string; + } +} + +declare namespace powerbi.extensibility { + interface IAuthenticationService { + getAADToken(visualId?: string): IPromise; + } +} + +declare namespace powerbi { + interface IFilter { + conditions?: any; + } +} + +/** + * Change Log Version 1.11.0 + * Added `selectionManager.registerOnSelectCallback()` method for Report Bookmarks support + */ + +declare namespace powerbi.extensibility.visual { + /** + * Represents a visualization displayed within an application (PowerBI dashboards, ad-hoc reporting, etc.). + * This interface does not make assumptions about the underlying JS/HTML constructs the visual uses to render itself. + */ + interface IVisual extends extensibility.IVisual { + /** Notifies the IVisual of an update (data, viewmode, size change). */ + // tslint:disable-next-line + update(options: VisualUpdateOptions, viewModel?: T): void; + + /** Gets the set of objects that the visual is currently displaying. */ + enumerateObjectInstances?(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstanceEnumeration; + } + + interface IVisualHost extends extensibility.IVisualHost { + createSelectionIdBuilder: () => visuals.ISelectionIdBuilder; + createSelectionManager: () => ISelectionManager; + colorPalette: IColorPalette; + persistProperties: (changes: VisualObjectInstancesToPersist) => void; + applyJsonFilter: (filter: IFilter, objectName: string, propertyName: string, action: FilterAction) => void; + tooltipService: ITooltipService; + telemetry: ITelemetryService; + authenticationService: IAuthenticationService; + locale: string; + allowInteractions: boolean; + launchUrl: (url: string) => void; + refreshHostData: () => void; + createLocalizationManager: () => ILocalizationManager; + } + + interface VisualUpdateOptions extends extensibility.VisualUpdateOptions { + viewport: IViewport; + dataViews: DataView[]; + viewMode?: ViewMode; + editMode?: EditMode; + } + + interface VisualConstructorOptions extends extensibility.VisualConstructorOptions { + element: HTMLElement; + host: IVisualHost; + } +} + +export default powerbi; diff --git a/types/powerbi-visuals-tools/powerbi-visuals-tools-tests.ts b/types/powerbi-visuals-tools/powerbi-visuals-tools-tests.ts new file mode 100644 index 0000000000..d6bce0acea --- /dev/null +++ b/types/powerbi-visuals-tools/powerbi-visuals-tools-tests.ts @@ -0,0 +1,110 @@ +import powerbi from './index'; + +import IVisualPlugin = powerbi.visuals.plugins.IVisualPlugin; +import IVisual = powerbi.extensibility.visual.IVisual; + +const visualPlugin: IVisualPlugin = { + name: 'string', + create: (options?: powerbi.extensibility.VisualConstructorOptions) => { + const value: IVisual = { + update: (options: powerbi.extensibility.VisualUpdateOptions) => {} + }; + return value; + }, + class: 'string', + custom: true, + apiVersion: "1.11.0", + displayName: "string" +}; + +import ISelectionIdBuilder = powerbi.visuals.ISelectionIdBuilder; +import ISelectionId = powerbi.visuals.ISelectionId; + +const selectionBuilder: ISelectionIdBuilder = { + withCategory: (categoryColumn: powerbi.DataViewCategoryColumn, index: number): ISelectionIdBuilder => { + return selectionBuilder; + }, + withSeries: (ser: powerbi.DataViewValueColumns, val: powerbi.DataViewValueColumn | powerbi.DataViewValueColumnGroup): ISelectionIdBuilder => { + return selectionBuilder; + }, + withMeasure: (measure: string): ISelectionIdBuilder => { + return selectionBuilder; + }, + createSelectionId: (): ISelectionId => { + const selection: ISelectionId = { + equals: (sel: ISelectionId) => false, + includes: (sel: ISelectionId, ignoreHL: boolean) => false, + getKey: () => "string", + getSelector: () => { + const selector: powerbi.data.Selector = { + }; + return selector; + }, + getSelectorsByColumn: () => { + const selector: powerbi.data.SelectorsByColumn = { + }; + return selector; + }, + hasIdentity: () => false + }; + return selection; + } +}; + +import DataView = powerbi.DataView; +import DataViewMetadata = powerbi.DataViewMetadata; +import DataViewCategorical = powerbi.DataViewCategorical; +import DataViewSingle = powerbi.DataViewSingle; +import DataViewTree = powerbi.DataViewTree; +import DataViewTable = powerbi.DataViewTable; +import DataViewMatrix = powerbi.DataViewMatrix; +import DataViewScriptResultData = powerbi.DataViewScriptResultData; + +const dataView: DataView = { + metadata: { + columns: [ + ], + objects: undefined, + dataReduction: undefined, + segment: { + } + }, + categorical: { + categories: [ + { + identity: [ + { + expr: {}, + key: "string", + kind: powerbi.DataRepetitionKind.ScopeIdentity + } + ], + identityFields: [], + objects: undefined, + source: { + displayName: "string", + format: "string", + groupName: "string", + objects: undefined, + aggregates: { + average: true + }, + isMeasure: false, + queryName: "string", + sort: powerbi.SortDirection.Ascending || powerbi.SortDirection.Descending, + index: 0, + type: { + text: true + }, + sortOrder: 0, + kpi: { + graphic: "string", + normalizedFiveStateKpiRange: false + } + }, + values: [] + } + ], + values: undefined + } +}; diff --git a/types/powerbi-visuals-tools/tsconfig.json b/types/powerbi-visuals-tools/tsconfig.json new file mode 100644 index 0000000000..6b8b1f5507 --- /dev/null +++ b/types/powerbi-visuals-tools/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "powerbi-visuals-tools-tests.ts" + ] +} diff --git a/types/powerbi-visuals-tools/tslint.json b/types/powerbi-visuals-tools/tslint.json new file mode 100644 index 0000000000..aea589947e --- /dev/null +++ b/types/powerbi-visuals-tools/tslint.json @@ -0,0 +1,9 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-relative-import-in-test": false, + "interface-name": false, + "no-mergeable-namespace": false, + "no-const-enum": false + } +} diff --git a/types/prettier/index.d.ts b/types/prettier/index.d.ts index e2fc00be38..0daaa14cca 100644 --- a/types/prettier/index.d.ts +++ b/types/prettier/index.d.ts @@ -109,9 +109,11 @@ export interface ParserOptions extends RequiredOptions { } export interface Plugin { - languages: SupportLanguage; + languages: SupportLanguage[]; parsers: { [parserName: string]: Parser }; printers: { [astFormat: string]: Printer }; + options?: SupportOption[]; + defaultOptions?: Partial; } export interface Parser { @@ -120,6 +122,7 @@ export interface Parser { hasPragma?: (text: string) => boolean; locStart: (node: any) => number; locEnd: (node: any) => number; + preprocess?: (text: string, options: ParserOptions) => string; } export interface Printer { @@ -232,7 +235,7 @@ export function clearConfigCache(): void; export interface SupportLanguage { name: string; - since: string; + since?: string; parsers: string[]; group?: string; tmScope: string; @@ -247,7 +250,7 @@ export interface SupportLanguage { } export interface SupportOption { - since: string; + since?: string; type: 'int' | 'boolean' | 'choice' | 'path'; array?: boolean; deprecated?: string; diff --git a/types/promise-map-limit/index.d.ts b/types/promise-map-limit/index.d.ts new file mode 100644 index 0000000000..17e859aec0 --- /dev/null +++ b/types/promise-map-limit/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for promise-map-limit 1.0 +// Project: https://github.com/dbrockman/promise-map-limit +// Definitions by: Joseph Kohlmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export = promiseMapLimit; + +declare function promiseMapLimit( +iterable: Iterable, +concurrency: number, +iteratee: promiseMapLimit.IIteratee +): Promise; + +declare namespace promiseMapLimit { + type IIteratee = (value: T) => Promise | R; +} diff --git a/types/promise-map-limit/promise-map-limit-tests.ts b/types/promise-map-limit/promise-map-limit-tests.ts new file mode 100644 index 0000000000..8d615e57c7 --- /dev/null +++ b/types/promise-map-limit/promise-map-limit-tests.ts @@ -0,0 +1,26 @@ +import mapPromiseLimit = require('promise-map-limit'); + +const promisedStrings = mapPromiseLimit(['foo', 'bar'], 2, s => s); +promisedStrings; // $ExpectType Promise + +const promisedBooleans = mapPromiseLimit([true, false], 2, b => b); +promisedBooleans; // $ExpectType Promise + +const promiseOfPromisedNumbers = mapPromiseLimit( + [{ foo: 1 }, { foo: 2 }], + 2, + value => Promise.resolve(value.foo), +); +promiseOfPromisedNumbers; // $ExpectType Promise + +const promiseNumber = (value: Record): Promise => + new Promise((resolve, reject) => { resolve(value.foo); }); + +(async () => { + const asyncNumbers = await mapPromiseLimit( + [{ foo: 1 }, { foo: 2 }], + 2, + async value => promiseNumber(value), + ); + asyncNumbers; // $ExpectType number[] +})(); diff --git a/types/promise-map-limit/tsconfig.json b/types/promise-map-limit/tsconfig.json new file mode 100644 index 0000000000..a4b0825f25 --- /dev/null +++ b/types/promise-map-limit/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "promise-map-limit-tests.ts" + ] +} diff --git a/types/promise-map-limit/tslint.json b/types/promise-map-limit/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/promise-map-limit/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/proper-lockfile/index.d.ts b/types/proper-lockfile/index.d.ts new file mode 100644 index 0000000000..885e63808b --- /dev/null +++ b/types/proper-lockfile/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for proper-lockfile 3.0 +// Project: https://github.com/moxystudio/node-proper-lockfile +// Definitions by: Nikita Volodin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface LockOptions { + stale?: number; // default: 10000 + update?: number; // default: stale/2 + retries?: number; // default: 0 + realpath?: boolean; // default: true + fs?: any; // default: graceful-fs + onCompromised?: (err: Error) => any; // default: (err) => throw err +} + +export interface UnlockOptions { + realpath?: boolean; // default: true + fs?: any; // default: graceful-fs +} + +export interface CheckOptions { + stale?: number; // default: 10000 + realpath?: boolean; // default: true + fs?: any; // default: graceful-fs +} + +export function lock(file: string, options?: LockOptions): Promise<() => Promise>; +export function unlock(file: string, options?: UnlockOptions): Promise; +export function check(file: string, options?: CheckOptions): Promise; + +export function lockSync(file: string, options?: LockOptions): () => void; +export function unlockSync(file: string, options?: UnlockOptions): void; +export function checkSync(file: string, options?: CheckOptions): boolean; diff --git a/types/proper-lockfile/proper-lockfile-tests.ts b/types/proper-lockfile/proper-lockfile-tests.ts new file mode 100644 index 0000000000..7555fd5116 --- /dev/null +++ b/types/proper-lockfile/proper-lockfile-tests.ts @@ -0,0 +1,45 @@ +import { + check, + checkSync, + lock, + lockSync, + unlock, + unlockSync +} from 'proper-lockfile'; + +(async () => { + const release = await lock('some/file'); // $ExpectType () => Promise + await release(); // $ExpectType void + + await lock('some/file'); // $ExpectType () => Promise + await unlock('some/file'); // $ExpectType void + + await check('some/file'); // $ExpectType boolean +})(); + +lock('some/file') + .then((release) => { + // Do something while the file is locked + + // Call the provided release function when you're done, + // which will also return a promise + return release(); + }); + +lock('some/file') + .then(() => { + // Do something while the file is locked + + // Later.. + return unlock('some/file'); + }); + +check('some/file') + .then((isLocked) => { + // isLocked will be true if 'some/file' is locked, false otherwise + }); + +const release = lockSync('some/file'); // $ExpectType () => void +release(); // $ExpectType void +unlockSync('some/file'); // $ExpectType void +checkSync('some/file'); // $ExpectType boolean diff --git a/types/proper-lockfile/tsconfig.json b/types/proper-lockfile/tsconfig.json new file mode 100644 index 0000000000..d8e7d42310 --- /dev/null +++ b/types/proper-lockfile/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "proper-lockfile-tests.ts" + ] +} diff --git a/types/proper-lockfile/tslint.json b/types/proper-lockfile/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/proper-lockfile/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/prosemirror-collab/index.d.ts b/types/prosemirror-collab/index.d.ts index cb4949bcba..6412b4b2e2 100644 --- a/types/prosemirror-collab/index.d.ts +++ b/types/prosemirror-collab/index.d.ts @@ -47,7 +47,7 @@ export function sendableSteps( steps: Array>; clientID: number | string; origins: Array>; -} | null | void; +} | null | undefined; /** * Get the version up to which the collab plugin has synced with the * central authority. diff --git a/types/prosemirror-collab/prosemirror-collab-tests.ts b/types/prosemirror-collab/prosemirror-collab-tests.ts index 9d892ca707..60dd42d7d9 100644 --- a/types/prosemirror-collab/prosemirror-collab-tests.ts +++ b/types/prosemirror-collab/prosemirror-collab-tests.ts @@ -10,3 +10,4 @@ plugin = collab.collab({ version: 1 }); plugin = collab.collab({ clientID: 1 }); const sendableSteps = collab.sendableSteps(state); +sendableSteps!.clientID; diff --git a/types/prosemirror-inputrules/index.d.ts b/types/prosemirror-inputrules/index.d.ts index 7c405530e0..7d14305ea6 100644 --- a/types/prosemirror-inputrules/index.d.ts +++ b/types/prosemirror-inputrules/index.d.ts @@ -42,7 +42,7 @@ export class InputRule { match: string[], start: number, end: number - ) => Transaction | null | void) + ) => Transaction | null) ); } /** @@ -81,7 +81,7 @@ export function undoInputRule( export function wrappingInputRule( regexp: RegExp, nodeType: NodeType, - getAttrs?: { [key: string]: any } | ((p: string[]) => { [key: string]: any } | null | void), + getAttrs?: { [key: string]: any } | ((p: string[]) => { [key: string]: any } | null | undefined), joinPredicate?: (p1: string[], p2: ProsemirrorNode) => boolean ): InputRule; /** @@ -95,7 +95,7 @@ export function wrappingInputRule( export function textblockTypeInputRule( regexp: RegExp, nodeType: NodeType, - getAttrs?: { [key: string]: any } | ((p: string[]) => { [key: string]: any } | null | void) + getAttrs?: { [key: string]: any } | ((p: string[]) => { [key: string]: any } | null | undefined) ): InputRule; /** * Converts double dashes to an emdash. diff --git a/types/prosemirror-inputrules/prosemirror-inputrules-tests.ts b/types/prosemirror-inputrules/prosemirror-inputrules-tests.ts index 0d59a02be7..25fa52e6af 100644 --- a/types/prosemirror-inputrules/prosemirror-inputrules-tests.ts +++ b/types/prosemirror-inputrules/prosemirror-inputrules-tests.ts @@ -1,5 +1,8 @@ import * as inputrules from 'prosemirror-inputrules'; import { NodeType } from 'prosemirror-model'; +import { Transaction } from 'prosemirror-state'; const nodeType = new NodeType(); -const rule: inputrules.InputRule = inputrules.wrappingInputRule(/^\$/, nodeType); +const rule1: inputrules.InputRule = inputrules.wrappingInputRule(/^\$/, nodeType); +const rule2 = new inputrules.InputRule(/^$/, 'str'); +const rule3 = new inputrules.InputRule(/^$/, () => null); diff --git a/types/prosemirror-model/index.d.ts b/types/prosemirror-model/index.d.ts index adb8a6141c..095b88f3ba 100644 --- a/types/prosemirror-model/index.d.ts +++ b/types/prosemirror-model/index.d.ts @@ -35,12 +35,12 @@ export class ContentMatch { * Match a node type and marks, returning a match after that node * if successful. */ - matchType(type: NodeType): ContentMatch | null | void; + matchType(type: NodeType): ContentMatch | null | undefined; /** * Try to match a fragment. Returns the resulting match when * successful. */ - matchFragment(frag: Fragment, start?: number, end?: number): ContentMatch | null | void; + matchFragment(frag: Fragment, start?: number, end?: number): ContentMatch | null | undefined; /** * Try to match the given fragment, and if that fails, see if it can * be made to match by inserting nodes in front of it. When @@ -49,14 +49,14 @@ export class ContentMatch { * return a fragment if the resulting match goes to the end of the * content expression. */ - fillBefore(after: Fragment, toEnd?: boolean, startIndex?: number): Fragment | null | void; + fillBefore(after: Fragment, toEnd?: boolean, startIndex?: number): Fragment | null | undefined; /** * Find a set of wrapping node types that would allow a node of the * given type to appear at this position. The result may be empty * (when it fits directly) and will be null when no such wrapping * exists. */ - findWrapping(target: NodeType): Array> | null | void; + findWrapping(target: NodeType): Array> | null | undefined; /** * Get the _n_th outgoing edge from this node in the finite automaton * that describes the content expression. @@ -89,7 +89,7 @@ export class Fragment { start: number, parent: ProsemirrorNode, index: number - ) => boolean | null | void, + ) => boolean | null | undefined | void, startPos?: number ): void; /** @@ -101,7 +101,7 @@ export class Fragment { node: ProsemirrorNode, pos: number, parent: ProsemirrorNode - ) => boolean | null | void + ) => boolean | null | undefined | void ): void; /** * Create a new fragment containing the combined content of this @@ -141,7 +141,7 @@ export class Fragment { /** * Get the child node at the given index, if it exists. */ - maybeChild(index: number): ProsemirrorNode | null | void; + maybeChild(index: number): ProsemirrorNode | null | undefined; /** * Call `f` for every child node, passing the node, its offset * into this parent node, and its index. @@ -151,14 +151,14 @@ export class Fragment { * Find the first position at which this fragment and another * fragment differ, or `null` if they are the same. */ - findDiffStart(other: Fragment): number | null | void; + findDiffStart(other: Fragment): number | null | undefined; /** * Find the first position, searching from the end, at which this * fragment and the given fragment differ, or `null` if they are the * same. Since this position will not be the same in both nodes, an * object with two separate positions is returned. */ - findDiffEnd(other: ProsemirrorNode): { a: number; b: number } | null | void; + findDiffEnd(other: ProsemirrorNode): { a: number; b: number } | null | undefined; /** * Return a debugging string that describes this fragment. */ @@ -166,7 +166,7 @@ export class Fragment { /** * Create a JSON-serializeable representation of this fragment. */ - toJSON(): { [key: string]: any } | null | void; + toJSON(): { [key: string]: any } | null | undefined; /** * Deserialize a fragment from its JSON representation. */ @@ -326,7 +326,7 @@ export interface ParseRule { * Called with a DOM Element for `tag` rules, and with a string (the * style's value) for `style` rules. */ - getAttrs?: ((p: Node | string) => { [key: string]: any } | false | null | void) | null; + getAttrs?: ((p: Node | string) => { [key: string]: any } | false | null | undefined) | null; /** * For `tag` rules that produce non-leaf nodes or marks, by default * the content of the DOM element is parsed as content of the mark @@ -507,7 +507,7 @@ declare class ProsemirrorNode { /** * Get the child node at the given index, if it exists. */ - maybeChild(index: number): ProsemirrorNode | null | void; + maybeChild(index: number): ProsemirrorNode | null | undefined; /** * Call `f` for every child node, passing the node, its offset * into this parent node, and its index. @@ -529,7 +529,7 @@ declare class ProsemirrorNode { pos: number, parent: ProsemirrorNode, index: number - ) => boolean | null | void, + ) => boolean | null | undefined | void, startPos?: number ): void; /** @@ -541,7 +541,7 @@ declare class ProsemirrorNode { node: ProsemirrorNode, pos: number, parent: ProsemirrorNode - ) => boolean | null | void + ) => boolean | null | undefined | void ): void; /** * Concatenates all the text nodes found in this fragment and its @@ -612,7 +612,7 @@ declare class ProsemirrorNode { /** * Find the node starting at the given position. */ - nodeAt(pos: number): ProsemirrorNode | null | void; + nodeAt(pos: number): ProsemirrorNode | null | undefined; /** * Find the (direct) child node after the given offset, if any, * and return it along with its index and offset relative to this @@ -769,7 +769,7 @@ export class Slice { /** * Convert a slice to a JSON-serializable representation. */ - toJSON(): { [key: string]: any } | null | void; + toJSON(): { [key: string]: any } | null | undefined; /** * Deserialize a slice from its JSON representation. */ @@ -892,7 +892,7 @@ export class ResolvedPos { * its parent node or its parent node isn't a textblock (in which * case no marks should be preserved). */ - marksAcross($end: ResolvedPos): Array> | null | void; + marksAcross($end: ResolvedPos): Array> | null | undefined; /** * The depth up to which this position and the given (non-resolved) * position share the same parent nodes. @@ -910,7 +910,7 @@ export class ResolvedPos { blockRange( other?: ResolvedPos, pred?: (p: ProsemirrorNode) => boolean - ): NodeRange | null | void; + ): NodeRange | null | undefined; /** * Query whether the given position shares the same parent node. */ @@ -1061,7 +1061,7 @@ export class NodeType { attrs?: { [key: string]: any }, content?: Fragment | ProsemirrorNode | Array>, marks?: Array> - ): ProsemirrorNode | null | void; + ): ProsemirrorNode | null | undefined; /** * Returns true if the given fragment is valid content for this node * type with the given attributes. @@ -1113,7 +1113,7 @@ export class MarkType { /** * Tests whether there is a mark of this type in the given set. */ - isInSet(set: Array>): Mark | null | void; + isInSet(set: Array>): Mark | null | undefined; /** * Queries whether a given mark type is * [excluded](#model.MarkSpec.excludes) by this one. diff --git a/types/prosemirror-model/prosemirror-model-tests.ts b/types/prosemirror-model/prosemirror-model-tests.ts index 98460d4313..b9041597e7 100644 --- a/types/prosemirror-model/prosemirror-model-tests.ts +++ b/types/prosemirror-model/prosemirror-model-tests.ts @@ -37,6 +37,48 @@ export const nodeSpec: model.NodeSpec = { } }; -const node = new model.Node(); -node.nodesBetween(0, 1, () => {}); -node.descendants(() => {}); +// Verify that non-null assertion operator can be used. + +const res1_1 = new model.Node(); +res1_1.nodesBetween(0, 1, () => {}); +res1_1.nodesBetween(0, 1, () => null); +res1_1.nodesBetween(0, 1, () => undefined); +res1_1.nodesBetween(0, 1, () => true); +res1_1.descendants(() => {}); +res1_1.descendants(() => null); +res1_1.descendants(() => undefined); +res1_1.descendants(() => true); +const res1_2: model.Node = res1_1.maybeChild(0)!; +const res1_3: model.Node = res1_1.nodeAt(0)!; + +const cm1 = new model.ContentMatch(); +const cm2: model.ContentMatch = cm1.matchType({} as any)!; +const cm3: model.ContentMatch = cm1.matchFragment({} as any)!; +const cm4: model.Fragment = cm1.fillBefore({} as any)!; +const cm5: model.NodeType[] = cm1.findWrapping({} as any)!; + +const f1 = new model.Fragment(); +f1.nodesBetween(0, 0, () => {}); +f1.nodesBetween(0, 0, () => null); +f1.nodesBetween(0, 0, () => undefined); +f1.nodesBetween(0, 0, () => true); + +f1.descendants(() => {}); +f1.descendants(() => null); +f1.descendants(() => undefined); +f1.descendants(() => true); + +const res2_1: model.Node = f1.maybeChild(0)!; +const res2_2: number = f1.findDiffStart(f1)!; +const res2_3: { a: number, b: number } = f1.findDiffEnd({} as any)!; +const res2_4: object = f1.toJSON()!; + +const res3_1 = new model.ResolvedPos(); +const res3_2: model.Mark[] = res3_1.marksAcross(res3_1)!; +const res3_3: model.NodeRange = res3_1.blockRange(res3_1)!; + +const res4_1 = new model.NodeType(); +const res4_2: model.Node = res4_1.createAndFill()!; + +const res5_1 = new model.MarkType(); +const res5_2: model.Mark = res5_1.isInSet([])!; diff --git a/types/prosemirror-state/index.d.ts b/types/prosemirror-state/index.d.ts index 6b210a73e1..db5a16e9d3 100644 --- a/types/prosemirror-state/index.d.ts +++ b/types/prosemirror-state/index.d.ts @@ -74,7 +74,7 @@ export interface PluginSpec { transactions: Transaction[], oldState: EditorState, newState: EditorState - ) => Transaction | null | void) + ) => Transaction | null | undefined | void) | null; } /** @@ -147,11 +147,11 @@ export class PluginKey { * Get the active plugin with this key, if any, from an editor * state. */ - get(state: EditorState): Plugin | null | void; + get(state: EditorState): Plugin | null | undefined; /** * Get the plugin's state from an editor state. */ - getState(state: EditorState): any | null | void; + getState(state: EditorState): any | null | undefined; } /** * Superclass for editor selections. Every selection type should @@ -263,7 +263,7 @@ export class Selection { $pos: ResolvedPos, dir: number, textOnly?: boolean - ): Selection | null | void; + ): Selection | null | undefined; /** * Find a valid cursor or leaf node selection near the given * position. Searches forward first by default, but if `bias` is diff --git a/types/prosemirror-state/prosemirror-state-tests.ts b/types/prosemirror-state/prosemirror-state-tests.ts index 0c1cddc24e..1668b844af 100644 --- a/types/prosemirror-state/prosemirror-state-tests.ts +++ b/types/prosemirror-state/prosemirror-state-tests.ts @@ -40,3 +40,15 @@ transaction = transaction.setNodeMarkup(0); transaction = transaction.split(0); transaction = transaction.join(0); transaction = transaction.step(step); + +const res1_1: state.PluginSpec["appendTransaction"] = null; +const res1_2: state.PluginSpec["appendTransaction"] = () => {}; +const res1_3: state.PluginSpec["appendTransaction"] = () => null; +const res1_4: state.PluginSpec["appendTransaction"] = () => undefined; +const res1_5: state.PluginSpec["appendTransaction"] = () => ({} as state.Transaction); + +const res2_1 = new state.PluginKey(); +const res2_2: state.Plugin = res2_1.get({} as state.EditorState)!; + +const res3_1 = new state.Selection({} as any, {} as any); +const res3_2: state.Selection = state.Selection.findFrom({} as model.ResolvedPos, 0)!; diff --git a/types/prosemirror-transform/index.d.ts b/types/prosemirror-transform/index.d.ts index c0b63136f4..88f97ff9e4 100644 --- a/types/prosemirror-transform/index.d.ts +++ b/types/prosemirror-transform/index.d.ts @@ -403,7 +403,7 @@ export function replaceStep( from: number, to?: number, slice?: Slice -): Step | null | void; +): Step | null | undefined; /** * A step object represents an atomic change. It generally applies * only to the document it was created for, since the positions @@ -439,13 +439,13 @@ export class Step { * version of that step with its positions adjusted, or `null` if * the step was entirely deleted by the mapping. */ - map(mapping: Mappable): Step | null | void; + map(mapping: Mappable): Step | null | undefined; /** * Try to merge this step with another one, to be applied directly * after it. Returns the merged step when possible, null if the * steps can't be merged. */ - merge(other: Step): Step | null | void; + merge(other: Step): Step | null | undefined; /** * Create a JSON-serializeable representation of this step. When * defining this for a custom subclass, make sure the result object @@ -504,18 +504,21 @@ export class StepResult { * can be lifted. Will not go across * [isolating](#model.NodeSpec.isolating) parent nodes. */ -export function liftTarget(range: NodeRange): number | null | void; +export function liftTarget(range: NodeRange): number | null | undefined; /** * Try to find a valid way to wrap the content in the given range in a * node of the given type. May introduce extra nodes around and inside * the wrapper node, if necessary. Returns null if no valid wrapping - * could be found. + * could be found. When `innerRange` is given, that range's content is + * used as the content to fit into the wrapping, instead of the + * content of range. */ export function findWrapping( range: NodeRange, nodeType: NodeType, - attrs?: { [key: string]: any } -): Array<{ type: NodeType; attrs?: { [key: string]: any } | null }> | null | void; + attrs?: { [key: string]: any }, + innerRange?: NodeRange +): Array<{ type: NodeType; attrs?: { [key: string]: any } | null }> | null | undefined; /** * Check whether splitting at the given position is allowed. */ @@ -535,7 +538,7 @@ export function canJoin(doc: ProsemirrorNode, pos: number): boolean; * block before (or after if `dir` is positive). Returns the joinable * point, if any. */ -export function joinPoint(doc: ProsemirrorNode, pos: number, dir?: number): number | null | void; +export function joinPoint(doc: ProsemirrorNode, pos: number, dir?: number): number | null | undefined; /** * Try to find a point where a node of the given type can be inserted * near `pos`, by searching up the node hierarchy when `pos` itself @@ -546,4 +549,4 @@ export function insertPoint( doc: ProsemirrorNode, pos: number, nodeType: NodeType -): number | null | void; +): number | null | undefined; diff --git a/types/prosemirror-transform/prosemirror-transform-tests.ts b/types/prosemirror-transform/prosemirror-transform-tests.ts index c3a18ef916..a61108a2a9 100644 --- a/types/prosemirror-transform/prosemirror-transform-tests.ts +++ b/types/prosemirror-transform/prosemirror-transform-tests.ts @@ -1,3 +1,17 @@ import * as transform from 'prosemirror-transform'; const stepmap = new transform.StepMap([]); + +// Verify non-null assertion operator can be used. + +const res1_1: transform.Step = transform.replaceStep({} as any, 0)!; +const res1_2: transform.Step = res1_1.map({} as any)!; +const res1_3: transform.Step = res1_1.merge({} as any)!; + +const res2_1: number = transform.liftTarget({} as any)!; + +const res3_1: any[] = transform.findWrapping({} as any, {} as any)!; + +const res4_1: number = transform.joinPoint({} as any, 0)!; + +const res5_1: number = transform.insertPoint({} as any, 0, {} as any)!; diff --git a/types/prosemirror-view/index.d.ts b/types/prosemirror-view/index.d.ts index f24a5270d1..dba4fb8aec 100644 --- a/types/prosemirror-view/index.d.ts +++ b/types/prosemirror-view/index.d.ts @@ -237,7 +237,7 @@ export class EditorView { posAtCoords(coords: { left: number; top: number; - }): { pos: number; inside: number } | null | void; + }): { pos: number; inside: number } | null | undefined; /** * Returns the viewport rectangle at a given document position. `left` * and `right` will be the same number, as this returns a flat @@ -404,7 +404,7 @@ export interface EditorProps { view: EditorView, anchor: ResolvedPos, head: ResolvedPos - ) => Selection | null | void) + ) => Selection | null | undefined) | null; /** * The [parser](#model.DOMParser) to use when reading editor changes @@ -482,7 +482,7 @@ export interface EditorProps { * A set of [document decorations](#view.Decoration) to show in the * view. */ - decorations?: ((state: EditorState) => DecorationSet | null | void) | null; + decorations?: ((state: EditorState) => DecorationSet | null | undefined) | null; /** * When this returns false, the content of the view is not directly * editable. @@ -500,7 +500,7 @@ export interface EditorProps { */ attributes?: | { [name: string]: string } - | ((p: EditorState) => { [name: string]: string } | null | void) + | ((p: EditorState) => { [name: string]: string } | null | undefined | void) | null; /** * Determines the distance (in pixels) between the cursor and the diff --git a/types/prosemirror-view/prosemirror-view-tests.ts b/types/prosemirror-view/prosemirror-view-tests.ts index fd6c0538eb..a3e76946b8 100644 --- a/types/prosemirror-view/prosemirror-view-tests.ts +++ b/types/prosemirror-view/prosemirror-view-tests.ts @@ -1,3 +1,15 @@ import * as view from 'prosemirror-view'; +import * as state from 'prosemirror-state'; const decoration = new view.Decoration(); + +const res1_1 = new view.EditorView({} as any, {} as any); +const res1_2: { pos: number, inside: number } = res1_1.posAtCoords({ left: 0, top: 0})!; + +const res2_1: view.EditorProps = {} as any; +const res2_2: state.Selection = res2_1.createSelectionBetween!({} as any, {} as any, {} as any)!; +const res2_3: view.DecorationSet = res2_1.decorations!({} as any)!; + +const res3_1: view.EditorProps["attributes"] = () => {}; +const res3_2: view.EditorProps["attributes"] = () => null; +const res3_3: view.EditorProps["attributes"] = () => undefined; diff --git a/types/pumpify/index.d.ts b/types/pumpify/index.d.ts index 474484b95b..067847b1df 100644 --- a/types/pumpify/index.d.ts +++ b/types/pumpify/index.d.ts @@ -1,17 +1,35 @@ // Type definitions for pumpify 1.4 // Project: https://github.com/mafintosh/pumpify // Definitions by: Justin Beckwith +// Ankur Oberoi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -import { Stream, Duplex } from 'stream'; +import { Stream, Writable, Readable, Duplex } from 'stream'; +import * as duplexify from 'duplexify'; -export = pumpify; +declare class Pumpify extends Duplex implements duplexify.Duplexify { + constructor(...streams: Stream[]); + constructor(streams: Stream[]); + setPipeline(...streams: Stream[]): void; + setPipeline(streams: Stream[]): void; -declare class pumpify extends Duplex { - constructor(); - setPipeline(...args: Stream[]): void; + // Duplexify members + setWritable(writable: Writable): void; + setReadable(readable: Readable): void; } -declare namespace pumpify {} +interface PumpifyFactoryOptions { + autoDestroy: boolean; + destroy: boolean; + objectMode: boolean; + highWaterMark: number; +} + +declare namespace Pumpify { + let obj: typeof Pumpify; + function ctor(opts: PumpifyFactoryOptions): typeof Pumpify; +} + +export = Pumpify; diff --git a/types/pumpify/pumpify-tests.ts b/types/pumpify/pumpify-tests.ts index d4dff3bd70..1060c66df0 100644 --- a/types/pumpify/pumpify-tests.ts +++ b/types/pumpify/pumpify-tests.ts @@ -1,7 +1,11 @@ -import pumpify from 'pumpify'; -import { Duplex, Transform, PassThrough } from 'stream'; +import * as Pumpify from 'pumpify'; +import { Duplex, Transform, PassThrough, Writable } from 'stream'; -class Pumpy extends pumpify { +new Pumpify(); +new Pumpify(new Writable(), new Writable()); +const pumpify = new Pumpify([new Writable(), new Writable()]); + +class Pumpy extends Pumpify { constructor() { super(); const dup1 = new Duplex(); @@ -12,3 +16,5 @@ class Pumpy extends pumpify { const pumpy = new Pumpy(); pumpy.pipe(new PassThrough()); + +pumpify.setPipeline(pumpy); diff --git a/types/pumpify/tsconfig.json b/types/pumpify/tsconfig.json index 1404589863..c616e0e309 100644 --- a/types/pumpify/tsconfig.json +++ b/types/pumpify/tsconfig.json @@ -8,7 +8,6 @@ "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, - "allowSyntheticDefaultImports": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 94b57c87b9..510ae37107 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -804,6 +804,15 @@ export interface FrameBase { /** Adds a `` tag into the page with the desired url or a `