diff --git a/.gitignore b/.gitignore index 858238c5bf..ce5d4a9d8c 100644 --- a/.gitignore +++ b/.gitignore @@ -37,5 +37,6 @@ node_modules .sublimets .settings/launch.json + .vscode -yarn.lock \ No newline at end of file +yarn.lock diff --git a/3d-bin-packing/3d-bin-packing.d.ts b/3d-bin-packing/index.d.ts similarity index 100% rename from 3d-bin-packing/3d-bin-packing.d.ts rename to 3d-bin-packing/index.d.ts diff --git a/3d-bin-packing/tsconfig.json b/3d-bin-packing/tsconfig.json index ddad71a1fe..3d26767e8a 100644 --- a/3d-bin-packing/tsconfig.json +++ b/3d-bin-packing/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "3d-bin-packing.d.ts", + "index.d.ts", "3d-bin-packing-tests.ts" ] } \ No newline at end of file diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 8b263f19ae..1036be548d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -1665,7 +1665,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](supertest/supertest.d.ts) [SuperTest](https://github.com/visionmedia/supertest) by [Alex Varju](https://github.com/varju) * [:link:](supertest-as-promised/supertest-as-promised.d.ts) [SuperTest as Promised](https://github.com/WhoopInc/supertest-as-promised) by [Tanguy Krotoff](https://github.com/tkrotoff) * [:link:](svg-injector/svg-injector.d.ts) [SVG Injector](https://github.com/iconic/SVGInjector) by [Patrick Westerhoff](https://github.com/poke) -* [:link:](svg-pan-zoom/svg-pan-zoom.d.ts) [svg-pan-zoom](https://github.com/ariutta/svg-pan-zoom) by [Chintan Shah](https://github.com/Promact) +* [:link:](svg-pan-zoom/svg-pan-zoom-2.3.9.d.ts) [svg-pan-zoom](https://github.com/ariutta/svg-pan-zoom) by [Chintan Shah](https://github.com/Promact) +* [:link:](svg-pan-zoom/svg-pan-zoom.d.ts) [svg-pan-zoom](https://github.com/ariutta/svg-pan-zoom) by [César Vidril](https://github.com/Yimiprod) * [:link:](svg-sprite/svg-sprite.d.ts) [svg-sprite](https://github.com/jkphl/svg-sprite) by [Qubo](https://github.com/tkqubo) * [:link:](svgjs/svgjs.d.ts) [svg.js](http://www.svgjs.com) by [Sean Hess](https://seanhess.github.io) * [:link:](svg2png/svg2png.d.ts) [svg2png node package](https://github.com/domenic/svg2png) by [hans windhoff](https://github.com/hansrwindhoff) diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index a864dbcb13..95d0041063 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -13,5 +13,5 @@ If adding a new definition: - [ ] Include the required [files](https://github.com/DefinitelyTyped/DefinitelyTyped#create-a-new-package) and header. Base these on the README, *not* on an existing project. If changing an existing definition: -- [ ] Provide a URL to documentation or source code which provides context for the suggested changes: <> +- [ ] Provide a URL to documentation or source code which provides context for the suggested changes: <> - [ ] Increase the version number in the header if appropriate. diff --git a/README.md b/README.md index d3e6c0e27c..7187e9e8f6 100644 --- a/README.md +++ b/README.md @@ -52,21 +52,26 @@ DefinitelyTyped only works because of contributions by users like you! Before you share your improvement with the world, use it yourself. -#### Test editing an exiting package +#### Test editing an existing package To add new features you can use [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html). -You can also directly edit the types in `node_modules/@types/foo/index.d.ts`, -or copy them from there and paste inside of `declarations.d.ts` and follow the steps below. +You can also directly edit the types in `node_modules/@types/foo/index.d.ts`, or copy them from there and follow the steps below. #### Test a new package -* Add a new file `declarations.d.ts` to your project. -* Add it to the compilation, through `"includes"` or `"files"` in your [tsconfig](http://www.typescriptlang.org/docs/handbook/tsconfig-json.html), -or through a `/// ` declaration in your code. -* Inside `declarations.d.ts`, write `declare module "foo" { }`, then write the module declaration inside. -* Test that your code works. -* *Then*, once you've tested your definitions, make a PR contributing the definition. +Add to your `tsconfig.json`: + +```json +"baseUrl": "types", +"typeRoots": ["types"], +``` + +(You can also use `src/types`.) +Create `types/foo/index.d.ts` containing declarations for the module "foo". +You should now be able import from `"foo"` in your code and it will route to the new type definition. +Then build *and* run the code to make sure your type definition actually corresponds to what happens at runtime. +Once you've tested your definitions with real code, make a PR contributing the definition by copying `types/foo` to `DefinitelyTyped/foo` and adding a `tsconfig.json` and `foo-tests.ts`. ### Make a pull request @@ -95,7 +100,7 @@ If it doesn't, you can do so yourself in the comment associated with the PR. #### Create a new package -If you are the library author, or can make a pull request to the library, [bundle](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) types instead of publishing to DefinitelyTyped. +If you are the library author, or can make a pull request to the library, [bundle types](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) instead of publishing to DefinitelyTyped. If you are adding typings for an NPM package, create a directory with the same name. If the package you are adding typings for is not on NPM, make sure the name you choose for it does not conflict with the name of a package on NPM. @@ -108,6 +113,7 @@ Your package should have this structure: | index.d.ts | This contains the typings for the package. | | foo-tests.ts | This contains sample code which tests the typings. This code does *not* run, but it is type-checked. | | tsconfig.json | This allows you to run `tsc` within the package. | +| tslint.json | Enables linting. | Generate these by running `npm run new-package -- new-package-name`. @@ -125,7 +131,7 @@ For a good example package, see [base64-js](https://github.com/DefinitelyTyped/D * `interface X {}`: An empty interface is essentially the `{}` type: it places no constraints on an object. * `interface IFoo {}`: Don't add `I` to the front of an interface name. * `interface Foo { new(): Foo; }`: - This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); } + This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); }`. * `const Class: { new(): IClass; }`: Prefer to use a class declaration `class Class { constructor(); }` instead of a new-able constant. * `namespace foo {}`: @@ -187,7 +193,7 @@ Changes to the `master` branch are also manually merged into the `types-2.0` bra #### I'm writing a definition that depends on another definition. Should I use `` or an import? If the module you're referencing is an external module (uses `export`), use an import. -If the module you're referenceing is an ambient module (uses `declare module`, or just declares globals), use ``. +If the module you're referencing is an ambient module (uses `declare module`, or just declares globals), use ``. #### What do I do about older versions of typings? diff --git a/accounting/index.d.ts b/accounting/index.d.ts index b8187e41c4..b437a63c36 100644 --- a/accounting/index.d.ts +++ b/accounting/index.d.ts @@ -3,77 +3,72 @@ // Definitions by: Sergey Gerasimov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface IAccountingCurrencyFormat { - pos: string; // for positive values, eg. "$ 1.00" - neg?: string; // for negative values, eg. "$ (1.00)" - zero?: string; // for zero values, eg. "$ --" +declare namespace accounting { + interface IAccountingCurrencyFormat { + pos: string; // for positive values, eg. "$ 1.00" + neg?: string; // for negative values, eg. "$ (1.00)" + zero?: string; // for zero values, eg. "$ --" + } + + interface IAccountingCurrencySettings { + symbol?: string; // default currency symbol is '$' + format?: TFormat; // controls output: %s = symbol, %v = value/number + decimal?: string; // decimal point separator + thousand?: string; // thousands separator + precision?: number; // decimal places + } + + interface IAccountingNumberSettings { + precision?: number; // default precision on numbers is 0 + thousand?: string; + decimal?: string; + } + + interface IAccountingSettings { + currency: IAccountingCurrencySettings; // IAccountingCurrencySettings or IAccountingCurrencySettings + number: IAccountingNumberSettings; + } + + interface IAccountingStatic { + // format any number into currency + formatMoney(number: number, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string; + formatMoney(number: number, options: IAccountingCurrencySettings | IAccountingCurrencySettings): string; + + formatMoney(numbers: number[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[]; + formatMoney(numbers: number[], options: IAccountingCurrencySettings | IAccountingCurrencySettings): string[]; + + // generic case (any array of numbers) + formatMoney(numbers: any[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): any[]; + formatMoney(numbers: any[], options: IAccountingCurrencySettings | IAccountingCurrencySettings): any[]; + + // format a list of values for column-display + formatColumn(numbers: number[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[]; + formatColumn(numbers: number[], options: IAccountingCurrencySettings | IAccountingCurrencySettings): string[]; + + formatColumn(numbers: number[][], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[][]; + formatColumn(numbers: number[][], options: IAccountingCurrencySettings | IAccountingCurrencySettings): string[][]; + + // format a number with custom precision and localisation + formatNumber(number: number, precision?: number, thousand?: string, decimal?: string): string; + formatNumber(number: number, options: IAccountingNumberSettings): string; + + formatNumber(number: number[], precision?: number, thousand?: string, decimal?: string): string[]; + formatNumber(number: number[], options: IAccountingNumberSettings): string[]; + + formatNumber(number: any[], precision?: number, thousand?: string, decimal?: string): any[]; + formatNumber(number: any[], options: IAccountingNumberSettings): any[]; + + // better rounding for floating point numbers + toFixed(number: number, precision?: number): string; + + // get a value from any formatted number/currency string + unformat(string: string, decimal?: string): number; + + // settings object that controls default parameters for library methods + settings: IAccountingSettings; + } } -interface IAccountingCurrencySettings { - symbol?: string; // default currency symbol is '$' - format?: TFormat; // controls output: %s = symbol, %v = value/number - decimal?: string; // decimal point separator - thousand?: string; // thousands separator - precision?: number // decimal places -} - -interface IAccountingNumberSettings { - precision?: number; // default precision on numbers is 0 - thousand?: string; - decimal?: string; -} - -interface IAccountingSettings { - currency: IAccountingCurrencySettings; // IAccountingCurrencySettings or IAccountingCurrencySettings - number: IAccountingNumberSettings; -} - -interface IAccountingStatic { - // format any number into currency - formatMoney(number: number, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string; - formatMoney(number: number, options: IAccountingCurrencySettings): string; - formatMoney(number: number, options: IAccountingCurrencySettings): string; - - formatMoney(numbers: number[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[]; - formatMoney(numbers: number[], options: IAccountingCurrencySettings): string[]; - formatMoney(numbers: number[], options: IAccountingCurrencySettings): string[]; - - // generic case (any array of numbers) - formatMoney(numbers: any[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): any[]; - formatMoney(numbers: any[], options: IAccountingCurrencySettings): any[]; - formatMoney(numbers: any[], options: IAccountingCurrencySettings): any[]; - - // format a list of values for column-display - formatColumn(numbers: number[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[]; - formatColumn(numbers: number[], options: IAccountingCurrencySettings): string[]; - formatColumn(numbers: number[], options: IAccountingCurrencySettings): string[]; - - formatColumn(numbers: number[][], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[][]; - formatColumn(numbers: number[][], options: IAccountingCurrencySettings): string[][]; - formatColumn(numbers: number[][], options: IAccountingCurrencySettings): string[][]; - - // format a number with custom precision and localisation - formatNumber(number: number, precision?: number, thousand?: string, decimal?: string): string; - formatNumber(number: number, options: IAccountingNumberSettings): string; - - formatNumber(number: number[], precision?: number, thousand?: string, decimal?: string): string[]; - formatNumber(number: number[], options: IAccountingNumberSettings): string[]; - - formatNumber(number: any[], precision?: number, thousand?: string, decimal?: string): any[]; - formatNumber(number: any[], options: IAccountingNumberSettings): any[]; - - // better rounding for floating point numbers - toFixed(number: number, precision?: number): string; - - // get a value from any formatted number/currency string - unformat(string: string, decimal?: string): number; - - // settings object that controls default parameters for library methods - settings: IAccountingSettings; -} - -declare var accounting: IAccountingStatic; - -declare module "accounting" { - export = accounting; -} +declare var accounting: accounting.IAccountingStatic; +export = accounting; +export as namespace accounting; diff --git a/accounting/tslint.json b/accounting/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/accounting/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/rails-actioncable/rails-actioncable-tests.ts b/actioncable/actioncable-tests.ts similarity index 100% rename from rails-actioncable/rails-actioncable-tests.ts rename to actioncable/actioncable-tests.ts diff --git a/rails-actioncable/index.d.ts b/actioncable/index.d.ts similarity index 100% rename from rails-actioncable/index.d.ts rename to actioncable/index.d.ts diff --git a/actioncable/tsconfig.json b/actioncable/tsconfig.json new file mode 100644 index 0000000000..6767b44330 --- /dev/null +++ b/actioncable/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "actioncable-tests.ts" + ] +} \ No newline at end of file diff --git a/algoliasearch-client-js/index.d.ts b/algoliasearch-client-js/index.d.ts deleted file mode 100644 index b0eeb9968b..0000000000 --- a/algoliasearch-client-js/index.d.ts +++ /dev/null @@ -1,1571 +0,0 @@ -// Type definitions for algoliasearch-client-js 3.18.1 -// Project: https://github.com/algolia/algoliasearch-client-js -// Definitions by: Baptiste Coquelle -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -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; -} -/* - Interface for the algolia client object - */ -interface AlgoliaClient { - /** - * 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; - /** - * 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, options: AlgoliaQueryParameters }, cb: (err: Error, res: any) => 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, options: AlgoliaQueryParameters }): Promise; - /** - * clear browser cache - * https://github.com/algolia/algoliasearch-client-js#cache - */ - clearCache(): void; - /** - * kill alive connections - * https://github.com/algolia/algoliasearch-client-js#keep-alive - */ - destroy(): 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; - /** - * Delete a specific index - * @param name - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#delete-index---deleteindex - */ - 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): 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; - /** - * 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): 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; - /** - * 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): void; - /** - * 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; - /** - * 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; - /** - * Lists global API Keys - * @param cb(err, res) - * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse - */ - listUserKeys(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 - */ - listUserKeys(): Promise; - /** - * Add global API Keys - * @param scopes - * @param cb(err, res) - * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey - */ - addUserKey(scopes: string[], cb: (err: Error, res: any) => void): void; - /** - * Add global API Keys - * @param scopes - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey - */ - addUserKey(scopes: string[]): Promise; - /** - * Add global API Key - * @param scopes - * @param options - * @param cb(err, res) - * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey - */ - addUserKey(scopes: string[], options: AlgoliaUserKeyOptions, cb: (err: Error, res: any) => void): void; - /** - * Add global API Key - * @param scopes - * @param options - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey - */ - addUserKey(scopes: string[], options: AlgoliaUserKeyOptions): Promise; - /** - * Update global API key - * @param key - * @param scopes - * @param cb(err, res) - * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey - */ - updateUserKey(key: string, scopes: string[], cb: (err: Error, res: any) => void): void; - /** - * Update global API key - * @param key - * @param scopes - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey - */ - updateUserKey(key: string, scopes: string[]): Promise; - /** - * Update global API key - * @param key - * @param scopes - * @param options - * @param cb(err, res) - * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey - */ - updateUserKey(key: string, scopes: string[], options: AlgoliaUserKeyOptions, cb: (err: Error, res: any) => void): void; - /** - * Update global API key - * @param key - * @param scopes - * @param options - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey - */ - updateUserKey(key: string, scopes: string[], options: AlgoliaUserKeyOptions): Promise; - /** - * Gets the rights of a global key - * @param key - * @param cb(err, res) - * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey - */ - getUserKeyACL(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---updateuserkey - */ - getUserKeyACL(key: string): Promise; - /** - * Deletes a global key - * @param key - * @param cb(err,res) - * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteuserkey - */ - deleteUserKey(key: string, cb: (err: Error, res: any) => void): void; - /** - * Deletes a global key - * @param key - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteuserkey - */ - deleteUserKey(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; - /** - * Get 1000 last events - * @param options - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs - */ - getLogs(options: LogsOptions): Promise; -} -/** - * Interface for the index algolia object - */ -interface AlgoliaIndex { - /** - * 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; - /** - * 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): 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; - /** - * 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; - /** - * 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): 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; - /** - * 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; - /** - * Add or replace several objects - * @param objects - * @param cb(err, res) - * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects - */ - saveObjects(objects: [{}], cb: (err: Error, res: any) => 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; - /** - * 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; - /** - * 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; - /** - * 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): 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(query: string, params: {}, cb: (err: Error, res: any) => 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; - /** - * 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): void; - /** - * Clear cache of an index - * https://github.com/algolia/algoliasearch-client-js#cache - */ - 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; - /** - * 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, option: SynonymOption, cb: (err: Error, res: any) => void): void; - /** - * Save a synonym object - * @param synonyms - * @param options - * @param cb(err, res) - */ - batchSynonyms(synonyms: AlgoliaSynonym[], options: SynonymOption, cb: (err: Error, res: any) => 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): 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): 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; - /** - * Search a synonyms - * @param options - * @param cb(err, res) - * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms - */ - searchSynonyms(options: SearchSynonymOptions, cb: (err: Error, res: any) => void): void; - /** - * List index user keys - * @param cb(err, res) - * https://github.com/algolia/algoliasearch-client-js#list-api-keys---listapikeys - */ - listUserKeys(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---adduserkey - */ - addUserKey(scopes: string[], cb: (err: Error, res: any) => 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---adduserkey - */ - addUserKey(scopes: string[], options: AlgoliaUserKeyOptions, cb: (err: Error, res: any) => 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---updateuserkey - */ - updateUserKey(key: string, scopes: string[], cb: (err: Error, res: any) => 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---updateuserkey - */ - updateUserKey(key: string, scopes: string[], options: AlgoliaUserKeyOptions, cb: (err: Error, res: any) => 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---getuserkeyacl - */ - getUserKeyACL(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---deleteuserkey - */ - deleteUserKey(key: string, cb: (err: Error, res: any) => void): void; - /** - * Gets a specific object - * @param objectID - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects - */ - getObject(objectID: string): Promise ; - /** - * 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 ; - /** - * Gets a list of objects - * @param objectIDs - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects - */ - getObjects(objectIDs: string[]): Promise ; - /** - * Add a specific object - * @param object without objectID - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects - */ - addObject(object: {}): Promise ; - /** - * 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 ; - /** - * Add list of objects - * @param objects - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects - */ - 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 ; - /** - * Add or replace several objects - * @param objects - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects - */ - saveObjects(objects: [{}]): Promise ; - /** - * Update parameters of a specific object - * @param object - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects - */ - partialUpdateObject(object: {}): 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 ; - /** - * Delete a specific object - * @param objectID - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects - */ - 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 ; - /** - * Delete objects that matches the query - * @param query - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#delete-by-query---deletebyquery - */ - deleteByQuery(query: 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 ; - /** - * 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 ; - /** - * Set an index settings - * @param settings - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#set-settings---setsettings - */ - setSettings(settings: AlgoliaIndexSettings): 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 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: any) => 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 an index - * @param query - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse - */ - 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; - /** - * 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; - /** - * Browse an entire index - * return Promise - * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse - */ - browseAll(): Promise; - /** - * Clear an index content - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#clear-index---clearindex - */ - 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, option: SynonymOption): Promise ; - /** - * Save a synonym object - * @param synonyms - * @param options - * return {Promise} - */ - batchSynonyms(synonyms: AlgoliaSynonym[], 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 ; - /** - * 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 ; - /** - * Get a specific synonym - * @param identifier - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#get-synonym---getsynonym - */ - getSynonym(identifier: string): Promise ; - /** - * Search a synonyms - * @param options - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms - */ - searchSynonyms(options: SearchSynonymOptions): Promise ; - /** - * List index user keys - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#list-api-keys---listapikeys - */ - listUserKeys(): Promise ; - /** - * Add key for this index - * @param scopes - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey - */ - addUserKey(scopes: string[]): Promise ; - /** - * Add key for this index - * @param scopes - * @param options - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey - */ - addUserKey(scopes: string[], options: AlgoliaUserKeyOptions): Promise ; - /** - * Update a key for this index - * @param key - * @param scopes - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey - */ - updateUserKey(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---updateuserkey - */ - updateUserKey(key: string, scopes: string[], options: AlgoliaUserKeyOptions): Promise ; - /** - * Gets the rights of an index specific key - * @param key - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#get-key-permissions---getuserkeyacl - */ - getUserKeyACL(key: string): Promise ; - /** - * Deletes an index specific key - * @param key - * return {Promise} - * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteuserkey - */ - deleteUserKey(key: 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 Algolia 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 - * https://github.com/algolia/algoliasearch-client-js#client-options - */ - hosts?: { read?: string[], write?: string[] }; -} -/* - 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). - * default: 0 - * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs - */ - offset?: number; - /** - * Specify the maximum number of entries to retrieve starting at the offset. - * default: 10 - * maximum: 1000 - * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs - */ - length?: number; - /** - * @deprecated - * Retrieve only logs with an HTTP code different than 200 or 201 - * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs - */ - onlyErrors?: boolean; - /** - * Specify the type of logs to retrieve - * 'query' Retrieve only the queries - * 'build' Retrieve only the build operations - * 'error' Retrieve only the errors (same as onlyErrors parameters) - * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs - */ - type?: string; -} -/** - * Describe the action object used for batch operation - */ -interface AlgoliaAction { - /** - * Type of the batch action - * values: addObject, updateObject, partialUpdateObject, partialUpdateObjectNoCreate, deleteObject - * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch - */ - action: string; - /** - * Name of the index where the bact will be performed - * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch - */ - indexName: string; - /** - * Object - * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch - */ - body: {}; -} -/** - * Describes the option used when creating user key - */ -interface AlgoliaUserKeyOptions { - /** - * 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---adduserkey - */ - validity?: number; - /** - * Specify the maximum number of API calls allowed from an IP address per hour - * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey - */ - maxQueriesPerIPPerHour?: number; - /** - * Specify the maximum number of hits this API key can retrieve in one call - * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey - */ - maxHitsPerQuery?: boolean; - /** - * Specify the list of targeted indices - * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey - */ - indexes?: string[]; - /** - * Specify the list of referers - * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey - */ - referers?: string[]; - /** - * Specify the list of query parameters - * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey - */ - queryParameters?: AlgoliaQueryParameters; - /** - * Specify a description to describe where the key is used. - * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey - */ - description?: string; -} -/** - * Describes option used when making operation on synonyms - */ -interface SynonymOption { - /** - * You can forward all settings updates to the slaves of an index - * https://github.com/algolia/algoliasearch-client-js#slave-settings - */ - forwardToSlaves?: boolean; - /** - * Replace all existing synonyms on the index with the content of the batch - * https://github.com/algolia/algoliasearch-client-js#batch-synonyms---batchsynonyms - */ - replaceExistingSynonyms?: boolean; -} -/** - * Describes options used when searching for synonyms - */ -interface SearchSynonymOptions { - /** - * The actual search query to find synonyms - * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms - */ - query?: string; - /** - * The page to fetch when browsing through several pages of results - * default: 100 - * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms - */ - page?: number; - /** - * Restrict the search to a specific type of synonym - * Use an empty string to search all types (default behavior) - * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms - */ - type?: string; - /** - * Number of hits per page - * default: 100 - * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms - */ - hitsPerPage?: number -} -interface AlgoliaBrowseResponse { - cursor?: string, - hits: any[], - params: string, - query: string, - processingTimeMS: number -} -/** - * Describes a synonym object - */ -interface AlgoliaSynonym { - /** - * ObjectID of the synonym - * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym - */ - objectID: string; - /** - * Type of synonym - * values: synonym,oneWaySynonym - * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym - */ - type: string; - /** - * Values used for the synonym - * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym - */ - synonyms: string[]; -} -/** - * Describes the options used when generating new api keys - */ -interface AlgoliaSecuredApiOptions { - /** - * Filter the query with numeric, facet or/and tag filters - * default: "" - * https://github.com/algolia/algoliasearch-client-js#filters-1 - */ - filters?: string; - /** - * Defines the expiration date of the API key - * https://github.com/algolia/algoliasearch-client-js#valid-until - */ - validUntil?: number; - /** - * Restricts the key to a list of index names allowed for the secured API key - * https://github.com/algolia/algoliasearch-client-js#index-restriction - */ - restrictIndices?: string; - /** - * Allows you to restrict a single user to performing a maximum of N API calls per hour - * https://github.com/algolia/algoliasearch-client-js#user-rate-limiting - */ - 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[]; - /** - * 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#slaves - */ - slaves?: 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 { - /** - * 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?: 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; - /** - * 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?: any; - /** - * 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?: 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; - /** - * Search entries inside a given area defined by a set of points - * defauly: '' - * https://github.com/algolia/algoliasearch-client-js#insidepolygon - */ - insidePolygon?: string; - /** - * 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; -} - -declare module "algoliasearch" { - function algoliasearch(applicationId: string, apiKey: string, options?: ClientOptions) : AlgoliaClient; - export = algoliasearch; -} diff --git a/algoliasearch-client-js/algoliasearch-client-js-tests.ts b/algoliasearch/algoliasearch-tests.ts similarity index 94% rename from algoliasearch-client-js/algoliasearch-client-js-tests.ts rename to algoliasearch/algoliasearch-tests.ts index 82d57c55e0..a3a04aadc2 100644 --- a/algoliasearch-client-js/algoliasearch-client-js-tests.ts +++ b/algoliasearch/algoliasearch-tests.ts @@ -1,5 +1,6 @@ - import algoliasearch = require('algoliasearch'); +import { ClientOptions, SynonymOption, AlgoliaUserKeyOptions, SearchSynonymOptions, + AlgoliaSecuredApiOptions, AlgoliaIndexSettings, AlgoliaQueryParameters, AlgoliaIndex } from "algoliasearch"; var _clientOptions: ClientOptions = { timeout : 12, diff --git a/algoliasearch/index.d.ts b/algoliasearch/index.d.ts new file mode 100644 index 0000000000..582e91999b --- /dev/null +++ b/algoliasearch/index.d.ts @@ -0,0 +1,1528 @@ +// Type definitions for algoliasearch-client-js 3.18.1 +// Project: https://github.com/algolia/algoliasearch-client-js +// Definitions by: Baptiste Coquelle +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +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 + */ + 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; + } + /* + Interface for the algolia client object + */ + interface AlgoliaClient { + /** + * 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; + /** + * 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, options: AlgoliaQueryParameters }, cb: (err: Error, res: any) => 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, options: AlgoliaQueryParameters }): Promise; + /** + * clear browser cache + * https://github.com/algolia/algoliasearch-client-js#cache + */ + clearCache(): void; + /** + * kill alive connections + * https://github.com/algolia/algoliasearch-client-js#keep-alive + */ + destroy(): 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; + /** + * Delete a specific index + * @param name + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#delete-index---deleteindex + */ + 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): 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; + /** + * 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): 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; + /** + * 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): void; + /** + * 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; + /** + * 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; + /** + * Lists global API Keys + * @param cb(err, res) + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + listUserKeys(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 + */ + listUserKeys(): Promise; + /** + * Add global API Keys + * @param scopes + * @param cb(err, res) + * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey + */ + addUserKey(scopes: string[], cb: (err: Error, res: any) => void): void; + /** + * Add global API Key + * @param scopes + * @param options + * @param cb(err, res) + * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey + */ + addUserKey(scopes: string[], options: AlgoliaUserKeyOptions, cb: (err: Error, res: any) => void): void; + /** + * Add global API Keys + * @param scopes + * @param options + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey + */ + addUserKey(scopes: string[], options?: AlgoliaUserKeyOptions): Promise; + /** + * Update global API key + * @param key + * @param scopes + * @param cb(err, res) + * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey + */ + updateUserKey(key: string, scopes: string[], cb: (err: Error, res: any) => 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---updateuserkey + */ + updateUserKey(key: string, scopes: string[], options: AlgoliaUserKeyOptions, cb: (err: Error, res: any) => void): void; + /** + * Update global API key + * @param key + * @param scopes + * @param options + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey + */ + updateUserKey(key: string, scopes: string[], options?: AlgoliaUserKeyOptions): Promise; + /** + * Gets the rights of a global key + * @param key + * @param cb(err, res) + * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey + */ + getUserKeyACL(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---updateuserkey + */ + getUserKeyACL(key: string): Promise; + /** + * Deletes a global key + * @param key + * @param cb(err,res) + * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteuserkey + */ + deleteUserKey(key: string, cb: (err: Error, res: any) => void): void; + /** + * Deletes a global key + * @param key + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteuserkey + */ + deleteUserKey(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; + /** + * Get 1000 last events + * @param options + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs + */ + getLogs(options: LogsOptions): Promise; + } + /** + * Interface for the index algolia object + */ + interface AlgoliaIndex { + /** + * 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; + /** + * 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): 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; + /** + * 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; + /** + * 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): 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; + /** + * 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; + /** + * Add or replace several objects + * @param objects + * @param cb(err, res) + * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects + */ + saveObjects(objects: [{}], cb: (err: Error, res: any) => 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; + /** + * 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; + /** + * 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; + /** + * 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): 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(query: string, params: {}, cb: (err: Error, res: any) => 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; + /** + * 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): void; + /** + * Clear cache of an index + * https://github.com/algolia/algoliasearch-client-js#cache + */ + 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; + /** + * 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, option: SynonymOption, cb: (err: Error, res: any) => void): void; + /** + * Save a synonym object + * @param synonyms + * @param options + * @param cb(err, res) + */ + batchSynonyms(synonyms: AlgoliaSynonym[], options: SynonymOption, cb: (err: Error, res: any) => 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): 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): 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; + /** + * Search a synonyms + * @param options + * @param cb(err, res) + * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms + */ + searchSynonyms(options: SearchSynonymOptions, cb: (err: Error, res: any) => void): void; + /** + * List index user keys + * @param cb(err, res) + * https://github.com/algolia/algoliasearch-client-js#list-api-keys---listapikeys + */ + listUserKeys(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---adduserkey + */ + addUserKey(scopes: string[], cb: (err: Error, res: any) => 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---adduserkey + */ + addUserKey(scopes: string[], options: AlgoliaUserKeyOptions, cb: (err: Error, res: any) => 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---updateuserkey + */ + updateUserKey(key: string, scopes: string[], cb: (err: Error, res: any) => 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---updateuserkey + */ + updateUserKey(key: string, scopes: string[], options: AlgoliaUserKeyOptions, cb: (err: Error, res: any) => 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---getuserkeyacl + */ + getUserKeyACL(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---deleteuserkey + */ + deleteUserKey(key: string, cb: (err: Error, res: any) => 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 ; + /** + * Gets a list of objects + * @param objectIDs + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects + */ + getObjects(objectIDs: string[]): Promise ; + /** + * 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 ; + /** + * Add list of objects + * @param objects + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects + */ + 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 ; + /** + * Add or replace several objects + * @param objects + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects + */ + saveObjects(objects: [{}]): Promise ; + /** + * Update parameters of a specific object + * @param object + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects + */ + partialUpdateObject(object: {}): 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 ; + /** + * Delete a specific object + * @param objectID + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects + */ + 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 ; + /** + * 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 ; + /** + * 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 ; + /** + * Set an index settings + * @param settings + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#set-settings---setsettings + */ + setSettings(settings: AlgoliaIndexSettings): 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 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: any) => 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 an index + * @param query + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + 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; + /** + * 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; + /** + * Browse an entire index + * return Promise + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + browseAll(): Promise; + /** + * Clear an index content + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#clear-index---clearindex + */ + 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, option: SynonymOption): Promise ; + /** + * Save a synonym object + * @param synonyms + * @param options + * return {Promise} + */ + batchSynonyms(synonyms: AlgoliaSynonym[], 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 ; + /** + * 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 ; + /** + * Get a specific synonym + * @param identifier + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#get-synonym---getsynonym + */ + getSynonym(identifier: string): Promise ; + /** + * Search a synonyms + * @param options + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms + */ + searchSynonyms(options: SearchSynonymOptions): Promise ; + /** + * List index user keys + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#list-api-keys---listapikeys + */ + listUserKeys(): Promise ; + /** + * Add key for this index + * @param scopes + * @param options + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey + */ + addUserKey(scopes: string[], options?: AlgoliaUserKeyOptions): Promise ; + /** + * Update a key for this index + * @param key + * @param scopes + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey + */ + updateUserKey(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---updateuserkey + */ + updateUserKey(key: string, scopes: string[], options: AlgoliaUserKeyOptions): Promise ; + /** + * Gets the rights of an index specific key + * @param key + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#get-key-permissions---getuserkeyacl + */ + getUserKeyACL(key: string): Promise ; + /** + * Deletes an index specific key + * @param key + * return {Promise} + * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteuserkey + */ + deleteUserKey(key: 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 Algolia 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 + * https://github.com/algolia/algoliasearch-client-js#client-options + */ + hosts?: { read?: string[], write?: string[] }; + } + /* + 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). + * default: 0 + * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs + */ + offset?: number; + /** + * Specify the maximum number of entries to retrieve starting at the offset. + * default: 10 + * maximum: 1000 + * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs + */ + length?: number; + /** + * @deprecated + * Retrieve only logs with an HTTP code different than 200 or 201 + * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs + */ + onlyErrors?: boolean; + /** + * Specify the type of logs to retrieve + * 'query' Retrieve only the queries + * 'build' Retrieve only the build operations + * 'error' Retrieve only the errors (same as onlyErrors parameters) + * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs + */ + type?: string; + } + /** + * Describe the action object used for batch operation + */ + interface AlgoliaAction { + /** + * Type of the batch action + * values: addObject, updateObject, partialUpdateObject, partialUpdateObjectNoCreate, deleteObject + * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch + */ + action: string; + /** + * Name of the index where the bact will be performed + * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch + */ + indexName: string; + /** + * Object + * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch + */ + body: {}; + } + /** + * Describes the option used when creating user key + */ + interface AlgoliaUserKeyOptions { + /** + * 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---adduserkey + */ + validity?: number; + /** + * Specify the maximum number of API calls allowed from an IP address per hour + * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey + */ + maxQueriesPerIPPerHour?: number; + /** + * Specify the maximum number of hits this API key can retrieve in one call + * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey + */ + maxHitsPerQuery?: boolean; + /** + * Specify the list of targeted indices + * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey + */ + indexes?: string[]; + /** + * Specify the list of referers + * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey + */ + referers?: string[]; + /** + * Specify the list of query parameters + * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey + */ + queryParameters?: AlgoliaQueryParameters; + /** + * Specify a description to describe where the key is used. + * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey + */ + description?: string; + } + /** + * Describes option used when making operation on synonyms + */ + interface SynonymOption { + /** + * You can forward all settings updates to the slaves of an index + * https://github.com/algolia/algoliasearch-client-js#slave-settings + */ + forwardToSlaves?: boolean; + /** + * Replace all existing synonyms on the index with the content of the batch + * https://github.com/algolia/algoliasearch-client-js#batch-synonyms---batchsynonyms + */ + replaceExistingSynonyms?: boolean; + } + /** + * Describes options used when searching for synonyms + */ + interface SearchSynonymOptions { + /** + * The actual search query to find synonyms + * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms + */ + query?: string; + /** + * The page to fetch when browsing through several pages of results + * default: 100 + * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms + */ + page?: number; + /** + * Restrict the search to a specific type of synonym + * Use an empty string to search all types (default behavior) + * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms + */ + type?: string; + /** + * Number of hits per page + * default: 100 + * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms + */ + hitsPerPage?: number; + } + interface AlgoliaBrowseResponse { + cursor?: string; + hits: any[]; + params: string; + query: string; + processingTimeMS: number; + } + /** + * Describes a synonym object + */ + interface AlgoliaSynonym { + /** + * ObjectID of the synonym + * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym + */ + objectID: string; + /** + * Type of synonym + * values: synonym,oneWaySynonym + * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym + */ + type: string; + /** + * Values used for the synonym + * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym + */ + synonyms: string[]; + } + /** + * Describes the options used when generating new api keys + */ + interface AlgoliaSecuredApiOptions { + /** + * Filter the query with numeric, facet or/and tag filters + * default: "" + * https://github.com/algolia/algoliasearch-client-js#filters-1 + */ + filters?: string; + /** + * Defines the expiration date of the API key + * https://github.com/algolia/algoliasearch-client-js#valid-until + */ + validUntil?: number; + /** + * Restricts the key to a list of index names allowed for the secured API key + * https://github.com/algolia/algoliasearch-client-js#index-restriction + */ + restrictIndices?: string; + /** + * Allows you to restrict a single user to performing a maximum of N API calls per hour + * https://github.com/algolia/algoliasearch-client-js#user-rate-limiting + */ + 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[]; + /** + * 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#slaves + */ + slaves?: 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 { + /** + * 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?: 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; + /** + * 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?: any; + /** + * 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?: 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; + /** + * Search entries inside a given area defined by a set of points + * defauly: '' + * https://github.com/algolia/algoliasearch-client-js#insidepolygon + */ + insidePolygon?: string; + /** + * 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; + } +} + +declare function algoliasearch(applicationId: string, apiKey: string, options?: algoliasearch.ClientOptions): algoliasearch.AlgoliaClient; +export = algoliasearch; diff --git a/algoliasearch/tsconfig.json b/algoliasearch/tsconfig.json new file mode 100644 index 0000000000..323a28e879 --- /dev/null +++ b/algoliasearch/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "algoliasearch-tests.ts" + ] +} \ No newline at end of file diff --git a/amcharts/index.d.ts b/amcharts/index.d.ts index fbc2ee4ac9..45c848e5af 100644 --- a/amcharts/index.d.ts +++ b/amcharts/index.d.ts @@ -24,6 +24,9 @@ declare namespace AmCharts { /** Set it to true if you want UTC time to be used instead of local time. */ var useUTC: boolean; + /** Object with themes */ + var themes: any; + /** Clears all the charts on page, removes listeners and intervals. */ function clear(): void; diff --git a/amplify-deferred/amplify-deferred-tests.ts b/amplify-deferred/amplify-deferred-tests.ts index 9482a8ef02..a4c7c656c4 100644 --- a/amplify-deferred/amplify-deferred-tests.ts +++ b/amplify-deferred/amplify-deferred-tests.ts @@ -1,265 +1,5 @@ - -/// - -// Copied examples directly from AmplifyJs site - -// Subscribe and publish with no data - -amplify.subscribe("nodataexample", function () { - alert("nodataexample topic published!"); -}); - -// Subscribe and publish with data - -amplify.publish("nodataexample"); - -amplify.subscribe("dataexample", function (data) { - alert(data.foo); // bar -}); - - -amplify.publish("dataexample", { foo: "bar" }); - -amplify.subscribe("dataexample2", function (param1, param2) { - alert(param1 + param2); // barbaz -}); - -//... - -amplify.publish("dataexample2", "bar", "baz"); - -// Subscribe and publish with context and data - -amplify.subscribe("datacontextexample", $("p:first"), function (data) { - this.text(data.exampleText); // first p element would have "foo bar baz" as text -}); - -amplify.publish("datacontextexample", { exampleText: "foo bar baz" }); - -// Subscribe to a topic with high priority - -amplify.subscribe("priorityexample", function (data) { - alert(data.foo); -}); - -amplify.subscribe("priorityexample", function (data) { - if (data.foo === "oops") { - return false; - } -}, 1); - - -// Store data with amplify storage picking the default storage technology: - -amplify.publish("priorityexample", { foo: "bar" }); -amplify.publish("priorityexample", { foo: "oops" }); - -amplify.store("storeExample1", { foo: "bar" }); -amplify.store("storeExample2", "baz"); -// retrieve the data later via the key -var myStoredValue = amplify.store("storeExample1"), - myStoredValue2 = amplify.store("storeExample2"), - myStoredValues = amplify.store(); -myStoredValue.foo; // bar -myStoredValue2; // baz -myStoredValues.storeExample1.foo; // bar -myStoredValues.storeExample2; // baz - -// Store data explicitly with session storage - -amplify.store.sessionStorage("explicitExample", { foo2: "baz" }); -// retrieve the data later via the key -var myStoredValue2 = amplify.store.sessionStorage("explicitExample"); -myStoredValue2.foo2; // baz - - -// REQUEST - -// Set up and use a request utilizing Ajax - - -amplify.request.define("ajaxExample1", "ajax", { - url: "/myApiUrl", - dataType: "json", - type: "GET" -}); - -// later in code -amplify.request("ajaxExample1", function (data) { - data.foo; // bar -}); - -// Set up and use a request utilizing Ajax and Caching - -amplify.request.define("ajaxExample2", "ajax", { - url: "/myApiUrl", - dataType: "json", - type: "GET", - cache: "persist" -}); - -// later in code -amplify.request("ajaxExample2", function (data) { - data.foo; // bar -}); - -// a second call will result in pulling from the cache -amplify.request("ajaxExample2", function (data) { - data.baz; // qux -}) - -// Set up and use a RESTful request utilizing Ajax - -amplify.request.define("ajaxRESTFulExample", "ajax", { - url: "/myRestFulApi/{type}/{id}", - type: "GET" -}) - -// later in code -amplify.request("ajaxRESTFulExample", - { - type: "foo", - id: "bar" - }, - function (data) { - // /myRESTFulApi/foo/bar was the URL used - data.foo; // bar - } - ); - -// POST data with Ajax - -amplify.request.define("ajaxPostExample", "ajax", { - url: "/myRestFulApi", - type: "POST" -}) - -// later in code -amplify.request("ajaxPostExample", - { - type: "foo", - id: "bar" - }, - function (data) { - data.foo; // bar - } - ); -// Using data maps - -// When searching Twitter, the key for the search phrase is q.If we want a more descriptive name, such as term, we can use a data map: - -amplify.request.define("twitter-search", "ajax", { - url: "http://search.twitter.com/search.json", - dataType: "jsonp", - dataMap: { - term: "q" - } -}); - -amplify.request("twitter-search", { term: "amplifyjs" }); - -// Similarly, we can create a request that searches for mentions, by accepting a username: - -amplify.request.define("twitter-mentions", "ajax", { - url: "http://search.twitter.com/search.json", - dataType: "jsonp", - dataMap: function (data) { - return { - q: "@" + data.user - }; - } -}); - -amplify.request("twitter-mentions", { user: "amplifyjs" }); - -// Setting up and using decoders - -//Example: - -var appEnvelopeDecoder: amplifyDecoder = function (data, status, xhr, success, error) { - if (data.status === "success") { - success(data.data); - } else if (data.status === "fail" || data.status === "error") { - error(data.message, data.status); - } else { - error(data.message, "fatal"); - } -}; - -//a new decoder can be added to the amplifyDecoders interface -interface amplifyDecoders { - appEnvelope: amplifyDecoder; -} - -amplify.request.decoders.appEnvelope = appEnvelopeDecoder; - -//but you can also just add it via an index -amplify.request.decoders['appEnvelopeStr'] = appEnvelopeDecoder; - - -amplify.request.define("decoderExample", "ajax", { - url: "/myAjaxUrl", - type: "POST", - decoder: "appEnvelope" -}); - -amplify.request({ - resourceId: "decoderExample", - success: function (data) { - data.foo; // bar - }, - error: function (message, level) { - alert("always handle errors with alerts."); - } -}); - -// POST with caching and single - use decoder - -// Example: - -amplify.request.define("decoderSingleExample", "ajax", { - url: "/myAjaxUrl", - type: "POST", - decoder: function (data, status, xhr, success, error) { - if (data.status === "success") { - success(data.data); - } else if (data.status === "fail" || data.status === "error") { - error(data.message, data.status); - } else { - error(data.message, "fatal"); - } - } -}); - -amplify.request({ - resourceId: "decoderSingleExample", - success: function (data) { - data.foo; // bar - }, - error: function (message, level) { - alert("always handle errors with alerts."); - } -}); -// Handling Status -// Status in Success and Error Callbacks - -// amplify.request comes with built in support for status.The status parameter appears in the default success or error callbacks when using an ajax definition. - -amplify.request.define("statusExample1", "ajax", { - //... -}); - -amplify.request({ - resourceId: "statusExample1", - success: function (data, status) { - }, - error: function (data, status) { - } -}); - amplify.request({ resourceId: "statusExample1" }).done(function (data, status) { }).fail(function (data, status) { }).always(function (data, status) { }); - diff --git a/amplify-deferred/index.d.ts b/amplify-deferred/index.d.ts index 3736a6644b..24f88455e9 100644 --- a/amplify-deferred/index.d.ts +++ b/amplify-deferred/index.d.ts @@ -5,178 +5,26 @@ /// -interface amplifyRequestSettings { - resourceId: string; - data?: any; - success?: (...args: any[]) => void; - error?: (...args: any[]) => void; +import * as amplify from "amplify"; + +declare module "amplify" { + interface Request { + /*** + * Request a resource. + * resourceId: Identifier string for the resource. + * data: A set of key/value pairs of data to be sent to the resource. + * callback: A function to invoke if the resource is retrieved successfully. + */ + (resourceId: string, hash?: any, callback?: Function): JQueryPromise; + + /*** + * Request a resource. + * settings: A set of key/value pairs of settings for the request. + * resourceId: Identifier string for the resource. + * data (optional): Data associated with the request. + * success (optional): Function to invoke on success. + * error (optional): Function to invoke on error. + */ + (settings: RequestSettings): JQueryPromise; + } } - -interface amplifyDecoder { - ( - data?: any, - status?: string, - xhr?: JQueryXHR, - success?: (...args: any[]) => void, - error?: (...args: any[]) => void - ): void -} - -interface amplifyDecoders { - [decoderName: string]: amplifyDecoder; - jsSend: amplifyDecoder; -} - -interface amplifyAjaxSettings extends JQueryAjaxSettings { - cache?: any; - dataMap?: {} | ((data: any) => {}); - decoder?: any /* string or amplifyDecoder */; -} - -interface amplifyRequest { - - /*** - * Request a resource. - * resourceId: Identifier string for the resource. - * data: A set of key/value pairs of data to be sent to the resource. - * callback: A function to invoke if the resource is retrieved successfully. - */ - (resourceId: string, hash?: any, callback?: Function): JQueryPromise; - - /*** - * Request a resource. - * settings: A set of key/value pairs of settings for the request. - * resourceId: Identifier string for the resource. - * data (optional): Data associated with the request. - * success (optional): Function to invoke on success. - * error (optional): Function to invoke on error. - */ - (settings: amplifyRequestSettings): JQueryPromise; - - /*** - * Define a resource. - * resourceId: Identifier string for the resource. - * requestType: The type of data retrieval method from the server. See the request types sections for more information. - * settings: A set of key/value pairs that relate to the server communication technology. The following settings are available: - * Any settings found in jQuery.ajax(). - * cache: See the cache section for more details. - * decoder: See the decoder section for more details. - */ - define(resourceId: string, requestType: string, settings?: amplifyAjaxSettings): void; - - /*** - * Define a custom request. - * resourceId: Identifier string for the resource. - * resource: Function to handle requests. Receives a hash with the following properties: - * resourceId: Identifier string for the resource. - * data: Data provided by the user. - * success: Callback to invoke on success. - * error: Callback to invoke on error. - */ - define(resourceId: string, resource: (settings: amplifyRequestSettings) => void): void; - - decoders: amplifyDecoders; - cache: any; -} - -interface amplifySubscribe { - /*** - * Subscribe to a message. - * topic: Name of the message to subscribe to. - * callback: Function to invoke when the message is published. - */ - (topic: string, callback: Function): void; - /*** - * Subscribe to a message. - * topic: Name of the message to subscribe to. - * context: What this will be when the callback is invoked. - * callback: Function to invoke when the message is published. - * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. - */ - (topic: string, context: any, callback: Function, priority?: number): void; - /*** - * Subscribe to a message. - * topic: Name of the message to subscribe to. - * callback: Function to invoke when the message is published. - * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. - */ - (topic: string, callback: Function, priority?: number): void; -} -interface amplifyStorageTypeStore { - /*** - * Stores a value for a given key using the default storage type. - * - * key: Identifier for the value being stored. - * value: The value to store. The value can be anything that can be serialized as JSON. - * [options]: A set of key/value pairs that relate to settings for storing the value. - */ - (key: string, value: any, options?: any): void; - - /*** - * Gets a stored value based on the key. - */ - (key: string): any; - - /*** - * Gets a hash of all stored values. - */ - (): any; -} - -interface amplifyStore extends amplifyStorageTypeStore { - - /*** - * IE 8+, Firefox 3.5+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ - */ - localStorage: amplifyStorageTypeStore; - - /*** - * IE 8+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ - */ - sessionStorage: amplifyStorageTypeStore; - - /*** - * Firefox 2+ - */ - globalStorage: amplifyStorageTypeStore; - - /*** - * IE 5 - 7 - */ - userData: amplifyStorageTypeStore; - - /*** - * An in-memory store is provided as a fallback if none of the other storage types are available. - */ - memory: amplifyStorageTypeStore; - - -} - -interface amplifyStatic { - - subscribe: amplifySubscribe; - - /*** - * Remove a subscription. - * topic: The topic being unsubscribed from. - * callback: The callback that was originally subscribed. - */ - unsubscribe(topic: string, callback: Function): void; - - /*** - * Publish a message. - * topic: The name of the message to publish. - * Any additional parameters will be passed to the subscriptions. - * amplify.publish returns a boolean indicating whether any subscriptions returned false. The return value is true if none of the subscriptions returned false, and false otherwise. Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked. - */ - publish(topic: string, ...args: any[]): boolean; - - store: amplifyStore; - - request: amplifyRequest; - -} - -declare var amplify: amplifyStatic; - diff --git a/amplify-deferred/tslint.json b/amplify-deferred/tslint.json new file mode 100644 index 0000000000..0f47deabb4 --- /dev/null +++ b/amplify-deferred/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false + } +} \ No newline at end of file diff --git a/amplify/amplifyjs-tests.ts b/amplify/amplifyjs-tests.ts index ec3807435d..f844642b8e 100644 --- a/amplify/amplifyjs-tests.ts +++ b/amplify/amplifyjs-tests.ts @@ -1,6 +1,8 @@ /// +import amplify = require("amplify"); + // Copied examples directly from AmplifyJs site // Subscribe and publish with no data @@ -176,7 +178,7 @@ amplify.request("twitter-mentions", { user: "amplifyjs" }); //Example: -var appEnvelopeDecoder: amplifyDecoder = function (data, status, xhr, success, error) { +var appEnvelopeDecoder: amplify.Decoder = function (data, status, xhr, success, error) { if (data.status === "success") { success(data.data); } else if (data.status === "fail" || data.status === "error") { @@ -187,8 +189,10 @@ var appEnvelopeDecoder: amplifyDecoder = function (data, status, xhr, success, e }; //a new decoder can be added to the amplifyDecoders interface -interface amplifyDecoders { - appEnvelope: amplifyDecoder; +declare module "amplify" { + interface Decoders { + appEnvelope: amplify.Decoder; + } } amplify.request.decoders.appEnvelope = appEnvelopeDecoder; diff --git a/amplify/index.d.ts b/amplify/index.d.ts index 8955fdc7de..ee14a6891e 100644 --- a/amplify/index.d.ts +++ b/amplify/index.d.ts @@ -5,178 +5,173 @@ /// -interface amplifyRequestSettings { - resourceId: string; - data?: any; - success?: (...args: any[]) => void; - error?: (...args: any[]) => void; +declare namespace amplify { + interface RequestSettings { + resourceId: string; + data?: any; + success?: (...args: any[]) => void; + error?: (...args: any[]) => void; + } + + type Decoder = + ( + data?: any, + status?: string, + xhr?: JQueryXHR, + success?: (...args: any[]) => void, + error?: (...args: any[]) => void + ) => void; + + interface Decoders { + [decoderName: string]: Decoder; + jsSend: Decoder; + } + + interface AjaxSettings extends JQueryAjaxSettings { + cache?: any; + dataMap?: {} | ((data: any) => {}); + decoder?: any /* string or amplifyDecoder */; + } + + interface Request { + + /*** + * Request a resource. + * resourceId: Identifier string for the resource. + * data: A set of key/value pairs of data to be sent to the resource. + * callback: A function to invoke if the resource is retrieved successfully. + */ + (resourceId: string, hash?: any, callback?: Function): void; + + /*** + * Request a resource. + * settings: A set of key/value pairs of settings for the request. + * resourceId: Identifier string for the resource. + * data (optional): Data associated with the request. + * success (optional): Function to invoke on success. + * error (optional): Function to invoke on error. + */ + (settings: RequestSettings): any; + + /*** + * Define a resource. + * resourceId: Identifier string for the resource. + * requestType: The type of data retrieval method from the server. See the request types sections for more information. + * settings: A set of key/value pairs that relate to the server communication technology. The following settings are available: + * Any settings found in jQuery.ajax(). + * cache: See the cache section for more details. + * decoder: See the decoder section for more details. + */ + define(resourceId: string, requestType: string, settings?: AjaxSettings): void; + + /*** + * Define a custom request. + * resourceId: Identifier string for the resource. + * resource: Function to handle requests. Receives a hash with the following properties: + * resourceId: Identifier string for the resource. + * data: Data provided by the user. + * success: Callback to invoke on success. + * error: Callback to invoke on error. + */ + define(resourceId: string, resource: (settings: RequestSettings) => void): void; + + decoders: Decoders; + cache: any; + } + + interface Subscribe { + /*** + * Subscribe to a message. + * topic: Name of the message to subscribe to. + * callback: Function to invoke when the message is published. + * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. + */ + (topic: string, callback: Function, priority?: number): void; + /*** + * Subscribe to a message. + * topic: Name of the message to subscribe to. + * context: What this will be when the callback is invoked. + * callback: Function to invoke when the message is published. + * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. + */ + (topic: string, context: any, callback: Function, priority?: number): void; + } + interface StorageTypeStore { + /*** + * Stores a value for a given key using the default storage type. + * + * key: Identifier for the value being stored. + * value: The value to store. The value can be anything that can be serialized as JSON. + * [options]: A set of key/value pairs that relate to settings for storing the value. + */ + (key: string, value: any, options?: any): void; + + /*** + * Gets a stored value based on the key. + */ + (key: string): any; + + /*** + * Gets a hash of all stored values. + */ + (): any; + } + + interface Store extends StorageTypeStore { + + /*** + * IE 8+, Firefox 3.5+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ + */ + localStorage: StorageTypeStore; + + /*** + * IE 8+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ + */ + sessionStorage: StorageTypeStore; + + /*** + * Firefox 2+ + */ + globalStorage: StorageTypeStore; + + /*** + * IE 5 - 7 + */ + userData: StorageTypeStore; + + /*** + * An in-memory store is provided as a fallback if none of the other storage types are available. + */ + memory: StorageTypeStore; + + + } + + interface Static { + + subscribe: Subscribe; + + /*** + * Remove a subscription. + * topic: The topic being unsubscribed from. + * callback: The callback that was originally subscribed. + */ + unsubscribe(topic: string, callback: Function): void; + + /*** + * Publish a message. + * topic: The name of the message to publish. + * Any additional parameters will be passed to the subscriptions. + * amplify.publish returns a boolean indicating whether any subscriptions returned false. The return value is true if none of the subscriptions returned false, and false otherwise. Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked. + */ + publish(topic: string, ...args: any[]): boolean; + + store: Store; + + request: Request; + } } -interface amplifyDecoder { - ( - data?: any, - status?: string, - xhr?: JQueryXHR, - success?: (...args: any[]) => void, - error?: (...args: any[]) => void - ): void -} - -interface amplifyDecoders { - [decoderName: string]: amplifyDecoder; - jsSend: amplifyDecoder; -} - -interface amplifyAjaxSettings extends JQueryAjaxSettings { - cache?: any; - dataMap?: {} | ((data: any) => {}); - decoder?: any /* string or amplifyDecoder */; -} - -interface amplifyRequest { - - /*** - * Request a resource. - * resourceId: Identifier string for the resource. - * data: A set of key/value pairs of data to be sent to the resource. - * callback: A function to invoke if the resource is retrieved successfully. - */ - (resourceId: string, hash?: any, callback?: Function): void; - - /*** - * Request a resource. - * settings: A set of key/value pairs of settings for the request. - * resourceId: Identifier string for the resource. - * data (optional): Data associated with the request. - * success (optional): Function to invoke on success. - * error (optional): Function to invoke on error. - */ - (settings: amplifyRequestSettings): any; - - /*** - * Define a resource. - * resourceId: Identifier string for the resource. - * requestType: The type of data retrieval method from the server. See the request types sections for more information. - * settings: A set of key/value pairs that relate to the server communication technology. The following settings are available: - * Any settings found in jQuery.ajax(). - * cache: See the cache section for more details. - * decoder: See the decoder section for more details. - */ - define(resourceId: string, requestType: string, settings?: amplifyAjaxSettings): void; - - /*** - * Define a custom request. - * resourceId: Identifier string for the resource. - * resource: Function to handle requests. Receives a hash with the following properties: - * resourceId: Identifier string for the resource. - * data: Data provided by the user. - * success: Callback to invoke on success. - * error: Callback to invoke on error. - */ - define(resourceId: string, resource: (settings: amplifyRequestSettings) => void): void; - - decoders: amplifyDecoders; - cache: any; -} - -interface amplifySubscribe { - /*** - * Subscribe to a message. - * topic: Name of the message to subscribe to. - * callback: Function to invoke when the message is published. - */ - (topic: string, callback: Function): void; - /*** - * Subscribe to a message. - * topic: Name of the message to subscribe to. - * context: What this will be when the callback is invoked. - * callback: Function to invoke when the message is published. - * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. - */ - (topic: string, context: any, callback: Function, priority?: number): void; - /*** - * Subscribe to a message. - * topic: Name of the message to subscribe to. - * callback: Function to invoke when the message is published. - * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. - */ - (topic: string, callback: Function, priority?: number): void; -} -interface amplifyStorageTypeStore { - /*** - * Stores a value for a given key using the default storage type. - * - * key: Identifier for the value being stored. - * value: The value to store. The value can be anything that can be serialized as JSON. - * [options]: A set of key/value pairs that relate to settings for storing the value. - */ - (key: string, value: any, options?: any): void; - - /*** - * Gets a stored value based on the key. - */ - (key: string): any; - - /*** - * Gets a hash of all stored values. - */ - (): any; -} - -interface amplifyStore extends amplifyStorageTypeStore{ - - /*** - * IE 8+, Firefox 3.5+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ - */ - localStorage: amplifyStorageTypeStore; - - /*** - * IE 8+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ - */ - sessionStorage: amplifyStorageTypeStore; - - /*** - * Firefox 2+ - */ - globalStorage: amplifyStorageTypeStore; - - /*** - * IE 5 - 7 - */ - userData: amplifyStorageTypeStore; - - /*** - * An in-memory store is provided as a fallback if none of the other storage types are available. - */ - memory: amplifyStorageTypeStore; - - -} - -interface amplifyStatic { - - subscribe: amplifySubscribe; - - /*** - * Remove a subscription. - * topic: The topic being unsubscribed from. - * callback: The callback that was originally subscribed. - */ - unsubscribe(topic: string, callback: Function): void; - - /*** - * Publish a message. - * topic: The name of the message to publish. - * Any additional parameters will be passed to the subscriptions. - * amplify.publish returns a boolean indicating whether any subscriptions returned false. The return value is true if none of the subscriptions returned false, and false otherwise. Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked. - */ - publish(topic: string, ...args: any[]): boolean; - - store: amplifyStore; - - request: amplifyRequest; - -} - -declare var amplify: amplifyStatic; -declare module "amplify" { export =amplify; } +declare var amplify: amplify.Static; +export = amplify; +export as namespace amplify; diff --git a/amplify/tslint.json b/amplify/tslint.json new file mode 100644 index 0000000000..2d6cd90f81 --- /dev/null +++ b/amplify/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + "rules": { + "forbidden-types": false, + "unified-signatures": false + } +} \ No newline at end of file diff --git a/angular-bootstrap-calendar/index.d.ts b/angular-bootstrap-calendar/index.d.ts index 5c6b4f1fec..a451ee9b03 100644 --- a/angular-bootstrap-calendar/index.d.ts +++ b/angular-bootstrap-calendar/index.d.ts @@ -7,7 +7,35 @@ import * as moment from 'moment'; import * as angular from 'angular'; declare module 'angular' { - export namespace bootstrap.calendar { + export namespace bootstrap.calendar { + interface IEventAction { + /** + * The label of the action + */ + label: string; + /** + * CSS class to be added to the action element + */ + cssClass?: string; + /** + * The action that occurs when it's clicked + * @param args - the IEvent whose action was clicked + */ + onClick: (args: any) => void; + } + + interface IEventColor { + /** + * The primary color of the event, should be darker than secondary + */ + primary: string; + + /** + * The secondary color of the event, should be lighter than primary + */ + secondary: string; + } + interface IEvent { /** * The title of the event @@ -16,7 +44,7 @@ declare module 'angular' { /** * The type of the event (determines its color). Can be important, warning, info, inverse, success or special */ - type: string; + type?: string; /** * A javascript date object for when the event starts */ @@ -25,6 +53,14 @@ declare module 'angular' { * Optional - a javascript date object for when the event ends */ endsAt?: Date; + /** + * Color of the Event + */ + color?: IEventColor; + /** + * Actions of the Event + */ + actions?: Array; /** * If edit-event-html is set and this field is explicitly set to false then dont make it editable. */ @@ -53,6 +89,10 @@ declare module 'angular' { * A CSS class (or more, just separate with spaces) that will be added to the event when it is displayed on each view. Useful for marking an event as selected / active etc */ cssClass?: string; + /** + * If set the event will display as all-day event + */ + allDay?: boolean; } interface ICalendarConfig { @@ -134,7 +174,7 @@ declare module 'angular' { } interface IOnViewChangeClick { - (calendarDate: Date, calendarNextView: string): void; + (calendarDate: Date, calendarNextView: string): boolean; } } } diff --git a/angular-breadcrumb/index.d.ts b/angular-breadcrumb/index.d.ts index 81bb8a1d37..81bd4b3d12 100644 --- a/angular-breadcrumb/index.d.ts +++ b/angular-breadcrumb/index.d.ts @@ -76,4 +76,4 @@ declare namespace ncy { **/ getLastStep(): angular.ui.IState; } -} \ No newline at end of file +} diff --git a/angular-material/index.d.ts b/angular-material/index.d.ts index 7895732ada..ffdab5839b 100644 --- a/angular-material/index.d.ts +++ b/angular-material/index.d.ts @@ -76,7 +76,7 @@ declare module 'angular' { } interface IColorService { - applyThemeColors(element: Element|JQuery, colorExpression: IColorExpression): void; + applyThemeColors(element: Element | JQuery, colorExpression: IColorExpression): void; getThemeColor(expression: string): string; hasTheme(): boolean; } @@ -158,7 +158,7 @@ declare module 'angular' { hideDelay(delay: number): T; position(position: string): T; parent(parent?: string | Element | JQuery): T; // default: root node - toastClass(toastClass: string): T; + toastClass(toastClass: string): T; } interface ISimpleToastPreset extends IToastPreset { @@ -225,7 +225,7 @@ declare module 'angular' { hues: IThemeHues; } - interface IBrowserColors{ + interface IBrowserColors { theme: string; palette: string; hue: string; @@ -264,6 +264,7 @@ declare module 'angular' { definePalette(name: string, palette: IPalette): IThemingProvider; enableBrowserColor(browserColors: IBrowserColors): Function; extendPalette(name: string, palette: IPalette): IPalette; + registerStyles(styles: String): void; setDefaultTheme(theme: string): void; setNonce(nonce: string): void; theme(name: string, inheritFrom?: string): ITheme; @@ -414,7 +415,7 @@ declare module 'angular' { ESCAPE: string, }; absPosition: { - TOP: string, + TOP: string, RIGHT: string, BOTTOM: string, LEFT: string, diff --git a/angular-mocks/index.d.ts b/angular-mocks/index.d.ts index 3c24ed1cf6..8aa172e293 100644 --- a/angular-mocks/index.d.ts +++ b/angular-mocks/index.d.ts @@ -301,6 +301,25 @@ declare module 'angular' { whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; } + /////////////////////////////////////////////////////////////////////////// + // AnimateService + // see https://docs.angularjs.org/api/ngMock/service/$animate + /////////////////////////////////////////////////////////////////////////// + module animate { + interface IAnimateService { + + /** + * This method will close all pending animations (both Javascript and CSS) and it will also flush any remaining animation frames and/or callbacks. + */ + closeAndFlush(): void; + + /** + * This method is used to flush the pending callbacks and animation frames to either start an animation or conclude an animation. Note that this will not actually close an actively running animation (see `closeAndFlush()` for that). + */ + flush(): void; + } + } + export module mock { // returned interface by the the mocked HttpBackendService expect/when methods interface IRequestHandler { diff --git a/angular-q-spread/angular-q-spread.d.ts b/angular-q-spread/index.d.ts similarity index 100% rename from angular-q-spread/angular-q-spread.d.ts rename to angular-q-spread/index.d.ts diff --git a/angular-q-spread/tsconfig.json b/angular-q-spread/tsconfig.json index 3461eaa2db..3a3080cf81 100644 --- a/angular-q-spread/tsconfig.json +++ b/angular-q-spread/tsconfig.json @@ -1,6 +1,6 @@ { "files": [ - "angular-q-spread.d.ts", + "index.d.ts", "angular-q-spread-tests.ts" ], "compilerOptions": { diff --git a/angular-resource/index.d.ts b/angular-resource/index.d.ts index e8726cc089..afde3cad14 100644 --- a/angular-resource/index.d.ts +++ b/angular-resource/index.d.ts @@ -162,6 +162,8 @@ declare module 'angular' { * Really just a regular Array object with $promise and $resolve attached to it */ interface IResourceArray extends Array> { + $cancelRequest(): void; + /** the promise of the original server interaction that created this collection. **/ $promise: angular.IPromise>; $resolved: boolean; diff --git a/angular-ui-router/index.d.ts b/angular-ui-router/index.d.ts index 4bbd94d641..035dc93430 100644 --- a/angular-ui-router/index.d.ts +++ b/angular-ui-router/index.d.ts @@ -110,7 +110,7 @@ declare module 'angular' { interface IUrlMatcher { concat(pattern: string): IUrlMatcher; - exec(path: string, searchParams: {}): {}; + exec(path: string, search?: any, hash?: string, options?: any): {}; parameters(): string[]; format(values: {}): string; } diff --git a/angular-websocket/angular-websocket-tests.ts b/angular-websocket/angular-websocket-tests.ts index e7cb30fe49..1df77b7a2a 100644 --- a/angular-websocket/angular-websocket-tests.ts +++ b/angular-websocket/angular-websocket-tests.ts @@ -1,5 +1,3 @@ -/// - let dummySocket: ng.websocket.IWebSocket; let dummyPromise: ng.IPromise; let dummyScope: ng.IScope; diff --git a/angular-websocket/angular-websocket.d.ts b/angular-websocket/index.d.ts similarity index 100% rename from angular-websocket/angular-websocket.d.ts rename to angular-websocket/index.d.ts diff --git a/angular-websocket/tsconfig.json b/angular-websocket/tsconfig.json index a340f7ffbd..e278ba9a25 100644 --- a/angular-websocket/tsconfig.json +++ b/angular-websocket/tsconfig.json @@ -1,6 +1,6 @@ { "files": [ - "angular-websocket.d.ts", + "index.d.ts", "angular-websocket-tests.ts" ], "compilerOptions": { diff --git a/angular-xeditable/angular-xeditable-tests.ts b/angular-xeditable/angular-xeditable-tests.ts index 9264c47f41..57a3e53863 100644 --- a/angular-xeditable/angular-xeditable-tests.ts +++ b/angular-xeditable/angular-xeditable-tests.ts @@ -1,9 +1,7 @@ -/// - -var myApp = angular.module('testModule', ['xeditable']); +var myApp = angular.module('testModule', ['xeditable']); myApp.run(["editableOptions", (editableOptions: angular.xeditable.IEditableOptions) => { - + editableOptions.activate = "select"; editableOptions.activationEvent = "click"; editableOptions.blurElem = "ignore"; diff --git a/angular-xeditable/angular-xeditable.d.ts b/angular-xeditable/index.d.ts similarity index 100% rename from angular-xeditable/angular-xeditable.d.ts rename to angular-xeditable/index.d.ts diff --git a/angular-xeditable/tsconfig.json b/angular-xeditable/tsconfig.json index e81407b730..f85f2b4cef 100644 --- a/angular-xeditable/tsconfig.json +++ b/angular-xeditable/tsconfig.json @@ -1,6 +1,6 @@ { "files": [ - "angular-xeditable.d.ts", + "index.d.ts", "angular-xeditable-tests.ts" ], "compilerOptions": { diff --git a/assert/index.d.ts b/assert/index.d.ts index abd31688f1..23536f9597 100644 --- a/assert/index.d.ts +++ b/assert/index.d.ts @@ -1,10 +1,15 @@ // Type definitions for assert and power-assert -// Project: https://github.com/Jxck/assert -// Project: https://github.com/twada/power-assert +// Project: https://github.com/Jxck/assert, https://github.com/twada/power-assert // Definitions by: vvakame // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// copy from assert external module in node.d.ts +// Definitions for commonjs-assert match that of node.js' assert module, +// but commonjs-assert is intended to be used as an independent module, +// for instance when making a stand-alone site or app that doesn't have +// access to node modules. For that reason, these definitions define a +// "assert" module. This will conflict with node.d.ts and other assert +// modules such as "power-assert", but a project should realistically +// only be using one of these at a time. declare function assert(value:any, message?:string):void; declare namespace assert { @@ -51,3 +56,4 @@ declare namespace assert { export function ifError(value:any):void; } + diff --git a/async/async-tests.ts b/async/async-tests.ts index c4a3506415..2a21a6cabb 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -7,22 +7,23 @@ declare var path: { exists: (path: string, callback?: (err: Error, exists: boolean) => any) => void; }; +function funcStringCbErrBoolean(v:string, cb:(err:Error,res:boolean) => void) {} function callback() { } -async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); -async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); -async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err, results) { }); +async.map(['file1', 'file2', 'file3'], fs.stat, function (err:Error, results:Array) { }); +async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err:Error, results:Array) { }); +async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err:Error, results:Array) { }); -async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.filterSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.filterLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); -async.select(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.selectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.selectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); +async.filter(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.filterSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.filterLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.select(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.selectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.selectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.reject(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.rejectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.rejectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); +async.reject(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.rejectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.rejectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,results:Array) { }); async.parallel([ function () { }, @@ -46,9 +47,9 @@ var openFilesObj = { file2: "fileTwo" } -var saveFile = function () { } -async.each(openFiles, saveFile, function (err) { }); -async.eachSeries(openFiles, saveFile, function (err) { }); +var saveFile = function (file:string,cb:(err:Error)=>void) { } +async.each(openFiles, saveFile, function (err:Error) { }); +async.eachSeries(openFiles, saveFile, function (err:Error) { }); var documents: any, requestApi: any; async.eachLimit(documents, 20, requestApi, function (err) { }); @@ -77,9 +78,9 @@ async.foldl(numArray, 0, reducer, function (err, result) { }); async.reduceRight(numArray, 0, reducer, function (err, result) { }); async.foldr(numArray, 0, reducer, function (err, result) { }); -async.detect(['file1', 'file2', 'file3'], path.exists, function (result) { }); -async.detectSeries(['file1', 'file2', 'file3'], path.exists, function (result) { }); -async.detectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); +async.detect(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err: Error,result:string) { }); +async.detectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err,result) { }); +async.detectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err,result) { }); async.sortBy(['file1', 'file2', 'file3'], function (file, callback) { fs.stat(file, function (err, stats) { @@ -87,13 +88,13 @@ async.sortBy(['file1', 'file2', 'file3'], function (file, callback) { }); }, function (err, results) { }); -async.some(['file1', 'file2', 'file3'], path.exists, function (result) { }); -async.someLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); -async.any(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.some(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); +async.someLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,result:boolean) { }); +async.any(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); -async.every(['file1', 'file2', 'file3'], path.exists, function (result) { }); -async.everyLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); -async.all(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.every(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); +async.everyLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,result:boolean) { }); +async.all(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); @@ -111,7 +112,7 @@ async.series([ ], function (err, results) { }); -async.series([ +async.series([ function (callback) { callback(undefined, 'one'); }, @@ -135,7 +136,7 @@ async.series({ }, function (err, results) { }); -async.series({ +async.series({ one: function (callback) { setTimeout(function () { callback(undefined, 1); @@ -175,7 +176,7 @@ async.parallel([ ], function (err, results) { }); -async.parallel([ +async.parallel([ function (callback) { setTimeout(function () { callback(undefined, 'one'); @@ -204,7 +205,7 @@ async.parallel({ }, function (err, results) { }); -async.parallel({ +async.parallel({ one: function (callback) { setTimeout(function () { callback(undefined, 1); @@ -270,7 +271,7 @@ async.waterfall([ ], function (err, result) { }); -var q = async.queue(function (task: any, callback: any) { +var q = async.queue(function (task: any, callback: () => void) { console.log('hello ' + task.name); callback(); }, 2); @@ -323,7 +324,7 @@ q.resume(); q.kill(); // tests for strongly typed tasks -var q2 = async.queue(function (task: string, callback: any) { +var q2 = async.queue(function (task: string, callback: () => void) { console.log('Task: ' + task); callback(); }, 1); @@ -386,10 +387,10 @@ async.retry({ times: 3, interval: (retryCount) => { return 200 * retryCount; } } async.parallel([ - function (callback) { }, + function (callback: ( err:Error, val:string ) => void ) { }, function (callback) { } ], -function (results) { +function (err:Error,results:Array) { async.series([ function (callback) { }, function email_link(callback) { } @@ -442,10 +443,10 @@ async.dir(function (name: string, callback: any) { // each -async.each({ +async.each({ "a": 1, "b": 2 -}, function(val: number, next: ErrorCallback): void { +}, function(val: number, next: ErrorCallback): void { setTimeout(function(): void { @@ -461,10 +462,10 @@ async.each({ }); -async.eachSeries({ +async.eachSeries({ "a": 1, "b": 2 -}, function(val: number, next: ErrorCallback): void { +}, function(val: number, next: ErrorCallback): void { setTimeout(function(): void { @@ -480,14 +481,14 @@ async.eachSeries({ }); -async.eachLimit({ +async.eachLimit({ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6 -}, 2, function(val: number, next: ErrorCallback): void { +}, 2, function(val: number, next: ErrorCallback): void { setTimeout(function(): void { @@ -505,10 +506,10 @@ async.eachLimit({ // forEachOf/eachOf -async.eachOf({ +async.eachOf({ "a": 1, "b": 2 -}, function(val: number, key: string, next: ErrorCallback): void { +}, function(val: number, key: string, next: ErrorCallback): void { setTimeout(function(): void { @@ -524,10 +525,10 @@ async.eachOf({ }); -async.forEachOfSeries({ +async.forEachOfSeries({ "a": 1, "b": 2 -}, function(val: number, key: string, next: ErrorCallback): void { +}, function(val: number, key: string, next: ErrorCallback): void { setTimeout(function(): void { @@ -543,14 +544,14 @@ async.forEachOfSeries({ }); -async.forEachOfLimit({ +async.forEachOfLimit({ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6 -}, 2, function(val: number, key: string, next: ErrorCallback): void { +}, 2, function(val: number, key: string, next: ErrorCallback): void { setTimeout(function(): void { @@ -568,11 +569,11 @@ async.forEachOfLimit({ // map -async.map({ +async.map({ "a": 1, "b": 2, "c": 3 -}, function(val: number, next: AsyncResultCallback): void { +}, function(val: number, next: AsyncResultCallback): void { setTimeout(function(): void { @@ -588,11 +589,11 @@ async.map({ }); -async.mapSeries({ +async.mapSeries({ "a": 1, "b": 2, "c": 3 -}, function(val: number, next: AsyncResultCallback): void { +}, function(val: number, next: AsyncResultCallback): void { setTimeout(function(): void { @@ -608,14 +609,14 @@ async.mapSeries({ }); -async.mapLimit({ +async.mapLimit({ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6 -}, 2, function(val: number, next: AsyncResultCallback): void { +}, 2, function(val: number, next: AsyncResultCallback): void { setTimeout(function(): void { @@ -633,11 +634,11 @@ async.mapLimit({ // mapValues -async.mapValues({ +async.mapValues({ "a": 1, "b": 2, "c": 3 -}, function(val: number, key: string, next: AsyncResultCallback): void { +}, function(val: number, key: string, next: AsyncResultCallback): void { setTimeout(function(): void { @@ -653,11 +654,11 @@ async.mapValues({ }); -async.mapValuesSeries({ +async.mapValuesSeries({ "a": 1, "b": 2, "c": 3 -}, function(val: number, key: string, next: AsyncResultCallback): void { +}, function(val: number, key: string, next: AsyncResultCallback): void { setTimeout(function(): void { @@ -675,11 +676,11 @@ async.mapValuesSeries({ // filter/select/reject -async.filter({ +async.filter({ "a": 1, "b": 2, "c": 3 -}, function(val: number, next: AsyncBooleanResultCallback): void { +}, function(val: number, next: AsyncBooleanResultCallback): void { setTimeout(function(): void { @@ -695,11 +696,11 @@ async.filter({ }); -async.reject({ +async.reject({ "a": 1, "b": 2, "c": 3 -}, function(val: number, next: AsyncBooleanResultCallback): void { +}, function(val: number, next: AsyncBooleanResultCallback): void { setTimeout(function(): void { @@ -717,11 +718,11 @@ async.reject({ // concat -async.concat({ +async.concat({ "a": "1", "b": "2", "c": "3" -}, function(item: string, next: AsyncResultCallback): void { +}, function(item: string, next: AsyncResultCallback): void { console.log(`async.concat: ${item}`); @@ -735,11 +736,11 @@ async.concat({ // detect/find -async.detect({ +async.detect({ "a": 1, "b": 2, "c": 3 -}, function(item: number, next: AsyncBooleanResultCallback): void { +}, function(item: number, next: AsyncBooleanResultCallback): void { console.log(`async.detect/find: ${item}`); @@ -760,11 +761,11 @@ async.detect({ // every/all -async.every({ +async.every({ "a": 1, "b": 2, "c": 3 -}, function(item: number, next: AsyncBooleanResultCallback): void { +}, function(item: number, next: AsyncBooleanResultCallback): void { console.log(`async.every/all: ${item}`); @@ -778,11 +779,11 @@ async.every({ // some/any -async.some({ +async.some({ "a": 1, "b": 2, "c": 3 -}, function(item: number, next: AsyncBooleanResultCallback): void { +}, function(item: number, next: AsyncBooleanResultCallback): void { console.log(`async.some/any: ${item}`); diff --git a/async/index.d.ts b/async/index.d.ts index 8b564fbd80..45d39ea955 100644 --- a/async/index.d.ts +++ b/async/index.d.ts @@ -5,22 +5,22 @@ interface Dictionary { [key: string]: T; } -interface ErrorCallback { (err?: Error): void; } -interface AsyncWaterfallCallback { (err: Error, ...args: any[]): void; } -interface AsyncBooleanResultCallback { (err: Error, truthValue: boolean): void; } -interface AsyncResultCallback { (err: Error, result: T): void; } -interface AsyncResultArrayCallback { (err: Error, results: T[]): void; } -interface AsyncResultObjectCallback { (err: Error, results: Dictionary): void; } +interface ErrorCallback { (err?: T): void; } +interface AsyncWaterfallCallback { (err: E, ...args: any[]): void; } +interface AsyncBooleanResultCallback { (err: E, truthValue: boolean): void; } +interface AsyncResultCallback { (err: E, result: T): void; } +interface AsyncResultArrayCallback { (err: E, results: T[]): void; } +interface AsyncResultObjectCallback { (err: E, results: Dictionary): void; } -interface AsyncFunction { (callback: (err?: Error, result?: T) => void): void; } -interface AsyncIterator { (item: T, callback: ErrorCallback): void; } -interface AsyncForEachOfIterator { (item: T, key: number|string, callback: ErrorCallback): void; } -interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } -interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } -interface AsyncBooleanIterator { (item: T, callback: AsyncBooleanResultCallback): void; } +interface AsyncFunction { (callback: (err?: E, result?: T) => void): void; } +interface AsyncIterator { (item: T, callback: ErrorCallback): void; } +interface AsyncForEachOfIterator { (item: T, key: number|string, callback: ErrorCallback): void; } +interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } +interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } +interface AsyncBooleanIterator { (item: T, callback: AsyncBooleanResultCallback): void; } -interface AsyncWorker { (task: T, callback: ErrorCallback): void; } -interface AsyncVoidFunction { (callback: ErrorCallback): void; } +interface AsyncWorker { (task: T, callback: ErrorCallback): void; } +interface AsyncVoidFunction { (callback: ErrorCallback): void; } interface AsyncQueue { length(): number; @@ -28,10 +28,10 @@ interface AsyncQueue { running(): number; idle(): boolean; concurrency: number; - push(task: T, callback?: ErrorCallback): void; - push(task: T[], callback?: ErrorCallback): void; - unshift(task: T, callback?: ErrorCallback): void; - unshift(task: T[], callback?: ErrorCallback): void; + push(task: T, callback?: ErrorCallback): void; + push(task: T[], callback?: ErrorCallback): void; + unshift(task: T, callback?: ErrorCallback): void; + unshift(task: T[], callback?: ErrorCallback): void; saturated: () => any; empty: () => any; drain: () => any; @@ -53,8 +53,8 @@ interface AsyncPriorityQueue { concurrency: number; started: boolean; paused: boolean; - push(task: T, priority: number, callback?: AsyncResultArrayCallback): void; - push(task: T[], priority: number, callback?: AsyncResultArrayCallback): void; + push(task: T, priority: number, callback?: AsyncResultArrayCallback): void; + push(task: T[], priority: number, callback?: AsyncResultArrayCallback): void; saturated: () => any; empty: () => any; drain: () => any; @@ -90,122 +90,122 @@ interface AsyncCargo { interface Async { // Collections - each(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; - each(arr: Dictionary, iterator: AsyncIterator, callback?: ErrorCallback): void; + each(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; + each(arr: Dictionary, iterator: AsyncIterator, callback?: ErrorCallback): void; eachSeries: typeof async.each; - eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; - eachLimit(arr: Dictionary, limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; + eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; + eachLimit(arr: Dictionary, limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; forEach: typeof async.each; forEachSeries: typeof async.each; forEachLimit: typeof async.eachLimit; - forEachOf(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; - forEachOf(obj: Dictionary, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOf(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOf(obj: Dictionary, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; forEachOfSeries: typeof async.forEachOf; - forEachOfLimit(obj: T[], limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; - forEachOfLimit(obj: Dictionary, limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOfLimit(obj: T[], limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOfLimit(obj: Dictionary, limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; eachOf: typeof async.forEachOf; eachOfSeries: typeof async.forEachOf; eachOfLimit: typeof async.forEachOfLimit; - map(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; - map(arr: Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + map(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + map(arr: Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; mapSeries: typeof async.map; - mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; - mapLimit(arr: Dictionary, limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; - mapValuesLimit(obj: Dictionary, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; - mapValues(obj: Dictionary, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; + mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + mapLimit(arr: Dictionary, limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + mapValuesLimit(obj: Dictionary, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; + mapValues(obj: Dictionary, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; mapValuesSeries: typeof async.mapValues; - filter(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; - filter(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; + filter(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; + filter(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; filterSeries: typeof async.filter; - filterLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; - filterLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; + filterLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; + filterLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; select: typeof async.filter; selectSeries: typeof async.filter; selectLimit: typeof async.filterLimit; reject: typeof async.filter; rejectSeries: typeof async.filter; rejectLimit: typeof async.filterLimit; - reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): void; + reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): void; inject: typeof async.reduce; foldl: typeof async.reduce; reduceRight: typeof async.reduce; foldr: typeof async.reduce; - detect(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; - detect(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; + detect(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; + detect(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; detectSeries: typeof async.detect; - detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; - detectLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; + detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; + detectLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; find: typeof async.detect; findSeries: typeof async.detect; findLimit: typeof async.detectLimit; - sortBy(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; - some(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; - some(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + sortBy(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + some(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + some(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; someSeries: typeof async.some; - someLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; - someLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + someLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + someLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; any: typeof async.some; anySeries: typeof async.someSeries; anyLimit: typeof async.someLimit; - every(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; - every(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + every(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + every(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; everySeries: typeof async.every; - everyLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; - everyLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + everyLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + everyLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; all: typeof async.every; allSeries: typeof async.every; allLimit: typeof async.everyLimit; - concat(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; - concat(arr: Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + concat(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + concat(arr: Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; concatSeries: typeof async.concat; // Control Flow - series(tasks: AsyncFunction[], callback?: AsyncResultArrayCallback): void; - series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; - parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; - parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; - parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; - parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; - whilst(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; - doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void; - until(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; - doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void; - during(test: (testCallback : AsyncBooleanResultCallback) => void, fn: AsyncVoidFunction, callback: ErrorCallback): void; - doDuring(fn: AsyncVoidFunction, test: (testCallback: AsyncBooleanResultCallback) => void, callback: ErrorCallback): void; - forever(next: (next : ErrorCallback) => void, errBack: ErrorCallback) : void; - waterfall(tasks: Function[], callback?: AsyncResultCallback): void; + series(tasks: AsyncFunction[], callback?: AsyncResultArrayCallback): void; + series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; + parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; + parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; + parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; + parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; + whilst(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; + doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void; + until(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; + doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void; + during(test: (testCallback : AsyncBooleanResultCallback) => void, fn: AsyncVoidFunction, callback: ErrorCallback): void; + doDuring(fn: AsyncVoidFunction, test: (testCallback: AsyncBooleanResultCallback) => void, callback: ErrorCallback): void; + forever(next: (next : ErrorCallback) => void, errBack: ErrorCallback) : void; + waterfall(tasks: Function[], callback?: AsyncResultCallback): void; compose(...fns: Function[]): Function; seq(...fns: Function[]): Function; applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. applyEachSeries(fns: Function[], argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. - queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; - priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; - cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; - auto(tasks: any, concurrency?: number, callback?: AsyncResultCallback): void; - autoInject(tasks: any, callback?: AsyncResultCallback): void; - retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: AsyncResultCallback): void; - retry(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback, results : any) => void, callback: AsyncResultCallback): void; - retryable(opts: number | {times: number, interval: number}, task: AsyncFunction): AsyncFunction; - apply(fn: Function, ...arguments: any[]): AsyncFunction; + queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; + priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; + cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; + auto(tasks: any, concurrency?: number, callback?: AsyncResultCallback): void; + autoInject(tasks: any, callback?: AsyncResultCallback): void; + retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: AsyncResultCallback): void; + retry(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback, results : any) => void, callback: AsyncResultCallback): void; + retryable(opts: number | {times: number, interval: number}, task: AsyncFunction): AsyncFunction; + apply(fn: Function, ...arguments: any[]): AsyncFunction; nextTick(callback: Function, ...args: any[]): void; setImmediate: typeof async.nextTick; - reflect(fn: AsyncFunction) : (callback: (err: void, result: {error?: Error, value?: T}) => void) => void; - reflectAll(tasks: AsyncFunction[]): ((callback: (err: void, result: {error?: Error, value?: T}) => void) => void)[]; + reflect(fn: AsyncFunction) : (callback: (err: void, result: {error?: Error, value?: T}) => void) => void; + reflectAll(tasks: AsyncFunction[]): ((callback: (err: void, result: {error?: Error, value?: T}) => void) => void)[]; - timeout(fn: AsyncFunction, milliseconds: number, info: any): AsyncFunction; + timeout(fn: AsyncFunction, milliseconds: number, info: any): AsyncFunction; - times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; - timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; - timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; - transform(arr: T[], iteratee: (acc: R[], item: T, key: string, callback: (error?: Error) => void) => void): void; - transform(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: string, callback: (error?: Error) => void) => void): void; - transform(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: Error) => void) => void): void; - transform(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: Error) => void) => void): void; + transform(arr: T[], iteratee: (acc: R[], item: T, key: string, callback: (error?: E) => void) => void): void; + transform(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: string, callback: (error?: E) => void) => void): void; + transform(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void): void; + transform(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void): void; - race(tasks: (AsyncFunction)[], callback: AsyncResultCallback) : void; + race(tasks: (AsyncFunction)[], callback: AsyncResultCallback) : void; // Utils memoize(fn: Function, hasher?: Function): Function; diff --git a/auth0-js/index.d.ts b/auth0-js/index.d.ts index 7e49961475..8026ccfc4f 100644 --- a/auth0-js/index.d.ts +++ b/auth0-js/index.d.ts @@ -84,7 +84,7 @@ interface Auth0Identity { interface Auth0DecodedHash { access_token: string; - id_token: string; + idToken: string; profile: Auth0UserProfile; state: any; } diff --git a/auth0/auth0-tests.ts b/auth0/auth0-tests.ts index 391dee655a..502a72eec1 100644 --- a/auth0/auth0-tests.ts +++ b/auth0/auth0-tests.ts @@ -49,3 +49,30 @@ auth }).catch((err) => { // Handle the error. }); + + +// Update a user +management + .updateUser({id: "user_id"}, {"email": "hi@me.co"}); + +// Update a user using callback +management + .updateUser({id: "user_id"}, {"email": "hi@me.co"}, (err: Error, users: auth0.User) => {}); + + +// Update user metadata +management + .updateUserMetadata({id: "user_id"}, {"key": "value"}); + +// Update user metadata using callback +management + .updateUserMetadata({id: "user_id"}, {"key": "value"}, (err: Error, users: auth0.User) => {}); + + +// Update app metadata +management + .updateAppMetadata({id: "user_id"}, {"key": "value"}); + +// Update app metadata using callback +management + .updateAppMetadata({id: "user_id"}, {"key": "value"}, (err: Error, users: auth0.User) => {}); diff --git a/auth0/index.d.ts b/auth0/index.d.ts index 019d9edc38..dad988a614 100644 --- a/auth0/index.d.ts +++ b/auth0/index.d.ts @@ -10,15 +10,18 @@ export interface ManagementClientOptions { domain?: string; } +export type UserMetadata = {}; +export type AppMetadata = {}; + export interface UserData { connection: string; email?: string; username?: string; password?: string; phone_number?: string; - user_metadata?: {}; + user_metadata?: UserMetadata; email_verified?: boolean; - app_metadata?: {}; + app_metadata?: AppMetadata; } export interface GetUsersData { @@ -43,8 +46,8 @@ export interface User { created_at?: string; updated_at?: string; identities?: Identity[]; - app_metadata?: {}; - user_metadata?: {}; + app_metadata?: AppMetadata; + user_metadata?: UserMetadata; picture?: string; name?: string; nickname?: string; @@ -53,6 +56,8 @@ export interface User { last_login?: string; logins_count?: number; blocked?: boolean; + given_name?: string; + family_name?: string; } export interface Identity { @@ -62,6 +67,10 @@ export interface Identity { isSocial: boolean; } +export interface UpdateUserParameters { + id: string; +} + export class ManagementClient { constructor(options: ManagementClientOptions); @@ -69,6 +78,12 @@ export class ManagementClient { getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void; createUser(data: UserData): Promise; createUser(data: UserData, cb: (err: Error, data: User) => void): void; + updateUser(params: UpdateUserParameters, data: User): Promise; + updateUser(params: UpdateUserParameters, data: User, cb: (err: Error, data: User) => void): void; + updateUserMetadata(params: UpdateUserParameters, data: UserMetadata): Promise; + updateUserMetadata(params: UpdateUserParameters, data: UserMetadata, cb: (err: Error, data: User) => void): void + updateAppMetadata(params: UpdateUserParameters, data: AppMetadata): Promise; + updateAppMetadata(params: UpdateUserParameters, data: AppMetadata, cb: (err: Error, data: User) => void): void } export interface AuthenticationClientOptions { @@ -86,4 +101,4 @@ export class AuthenticationClient { requestChangePasswordEmail(data: RequestChangePasswordEmailData): Promise; requestChangePasswordEmail(data: RequestChangePasswordEmailData, cb: (err: Error, message: string) => void): void; -} \ No newline at end of file +} diff --git a/aws4/index.d.ts b/aws4/index.d.ts index 88f54f2a3f..6028be5334 100644 --- a/aws4/index.d.ts +++ b/aws4/index.d.ts @@ -30,4 +30,4 @@ export class RequestSigner { formatPath(): string; } -export function sign(options?: any, credentials?: any): RequestSigner; +export function sign(options?: any, credentials?: any): any; diff --git a/azure-mobile-apps/index.d.ts b/azure-mobile-apps/index.d.ts index b13bfbb803..53dd5edae3 100644 --- a/azure-mobile-apps/index.d.ts +++ b/azure-mobile-apps/index.d.ts @@ -237,7 +237,7 @@ declare namespace Azure.MobileApps { interface SqlParameterDefinition { name: string; value: any; - } + } interface TableDefinition { access?: AccessType; diff --git a/bluebird-retry/index.d.ts b/bluebird-retry/index.d.ts index 2881d2065c..22c7b1c95e 100644 --- a/bluebird-retry/index.d.ts +++ b/bluebird-retry/index.d.ts @@ -16,6 +16,7 @@ declare namespace retry { max_interval?: number; timeout?: number; max_tries?: number; + predicate?: any; } } diff --git a/bluebird/bluebird-tests.ts b/bluebird/bluebird-tests.ts index 1591d1c3a5..ea1ea69882 100644 --- a/bluebird/bluebird-tests.ts +++ b/bluebird/bluebird-tests.ts @@ -336,6 +336,29 @@ fooOrBarProm = fooProm.caught(Promise.CancellationError, (reason: any) => { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +{ + class CustomError extends Error { + public customField: number; + } + fooProm = fooProm.catch(CustomError, reason => { + let a: number = reason.customField + }) +} + +{ + class CustomErrorWithConstructor extends Error { + constructor(public arg1: boolean, public arg2: number) { + super(); + }; + } + fooProm = fooProm.catch(CustomErrorWithConstructor, reason => { + let a: boolean = reason.arg1; + let b: number = reason.arg2; + }) +} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + barProm = fooProm.error((reason: any) => { return bar; }); diff --git a/bluebird/index.d.ts b/bluebird/index.d.ts index 10077179e8..3087abb2e5 100644 --- a/bluebird/index.d.ts +++ b/bluebird/index.d.ts @@ -65,14 +65,19 @@ declare class Bluebird implements Bluebird.Thenable, Bluebird.Inspection boolean, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; caught(predicate: (error: any) => boolean, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; caught(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; - catch(ErrorClass: Function, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - caught(ErrorClass: Function, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - catch(ErrorClass: Function, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; - caught(ErrorClass: Function, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + + catch(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + caught(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + + catch(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => U | Bluebird.Thenable): Bluebird; + caught(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => U | Bluebird.Thenable): Bluebird; + catch(predicate: Object, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; caught(predicate: Object, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; caught(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; diff --git a/bootstrap-fileinput/bootstrap-fileinput.d.ts b/bootstrap-fileinput/index.d.ts similarity index 100% rename from bootstrap-fileinput/bootstrap-fileinput.d.ts rename to bootstrap-fileinput/index.d.ts diff --git a/bootstrap-fileinput/tsconfig.json b/bootstrap-fileinput/tsconfig.json index 5b7c6fc2bf..126718d584 100644 --- a/bootstrap-fileinput/tsconfig.json +++ b/bootstrap-fileinput/tsconfig.json @@ -13,6 +13,6 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "bootstrap-fileinput.d.ts" + "index.d.ts" ] } \ No newline at end of file diff --git a/braintree-web/index.d.ts b/braintree-web/index.d.ts index e58cf7455b..d62ec01fd1 100644 --- a/braintree-web/index.d.ts +++ b/braintree-web/index.d.ts @@ -97,7 +97,7 @@ declare namespace BraintreeWeb { // billingContact // Billing contact information for the user. // countryCode -//Required.The merchants two- letter ISO 3166 country code. +//Required.The merchant’s two- letter ISO 3166 country code. // currencyCode // Required.The three- letter ISO 4217 currency code for the payment. // lineItems @@ -782,7 +782,7 @@ declare namespace BraintreeWeb { * }); * @returns {void} */ - on(event: string, handler: (() => any)): void; + on(event: string, handler: ((event: any) => any)): void; /** * Cleanly tear down anything set up by {@link module:braintree-web/hosted-fields.create|create} @@ -1740,4 +1740,4 @@ interface BraintreeStatic { VERSION: string; } -declare var braintree: BraintreeStatic; \ No newline at end of file +declare var braintree: BraintreeStatic; diff --git a/bunyan/index.d.ts b/bunyan/index.d.ts index 2983d8bb62..edf2e47cca 100644 --- a/bunyan/index.d.ts +++ b/bunyan/index.d.ts @@ -11,7 +11,7 @@ import { EventEmitter } from 'events'; declare class Logger extends EventEmitter { constructor(options: LoggerOptions); addStream(stream: Stream): void; - addSerializers(serializers:Serializers | StdSerializers):void; + addSerializers(serializers:Serializers | StdSerializers):void; child(options: LoggerOptions, simple?: boolean): Logger; child(obj: Object, simple?: boolean): Logger; reopenFileStreams(): void; @@ -58,18 +58,18 @@ interface LoggerOptions { src?: boolean; } - interface Serializer { - (input:any): any; - } +interface Serializer { + (input:any): any; +} interface Serializers { - [key:string]: Serializer; - } + [key: string]: Serializer +} - interface StdSerializers { - err: Serializer; - res: Serializer; - req: Serializer; +interface StdSerializers { + err: Serializer; + res: Serializer; + req: Serializer; } interface Stream { @@ -82,7 +82,7 @@ interface Stream { count?: number; } - export var stdSerializers:StdSerializers; +export declare var stdSerializers: StdSerializers; export declare var TRACE: number; export declare var DEBUG: number; diff --git a/cassandra-driver/index.d.ts b/cassandra-driver/index.d.ts index 041f9f84e2..9bf5fb7137 100644 --- a/cassandra-driver/index.d.ts +++ b/cassandra-driver/index.d.ts @@ -134,7 +134,7 @@ export namespace types { var LocalTime: LocalTimeStatic; var Long: _Long; var ResultSet: ResultSetStatic; - // var ResultStream: ResultStreamStatic; + // var ResultStream: ResultStreamStatic; var Row: RowStatic; var TimeUuid: TimeUuidStatic; var Tuple: TupleStatic; diff --git a/chai-dom/chai-dom-tests.ts b/chai-dom/chai-dom-tests.ts index 2fca54765e..61b3b3c600 100644 --- a/chai-dom/chai-dom-tests.ts +++ b/chai-dom/chai-dom-tests.ts @@ -1,5 +1,3 @@ -/// - import * as chai from 'chai'; import * as chaiDom from 'chai-dom'; diff --git a/chai-dom/chai-dom.d.ts b/chai-dom/index.d.ts similarity index 100% rename from chai-dom/chai-dom.d.ts rename to chai-dom/index.d.ts diff --git a/chai-dom/tsconfig.json b/chai-dom/tsconfig.json index 79855c3e09..1e6e575470 100644 --- a/chai-dom/tsconfig.json +++ b/chai-dom/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "chai-dom.d.ts", + "index.d.ts", "chai-dom-tests.ts" ] } \ No newline at end of file diff --git a/chai-enzyme/chai-enzyme-tests.tsx b/chai-enzyme/chai-enzyme-tests.tsx index 0e491a7ba7..a70f7e7f96 100644 --- a/chai-enzyme/chai-enzyme-tests.tsx +++ b/chai-enzyme/chai-enzyme-tests.tsx @@ -1,5 +1,4 @@ /// -/// /// /// diff --git a/chai-enzyme/chai-enzyme.d.ts b/chai-enzyme/index.d.ts similarity index 100% rename from chai-enzyme/chai-enzyme.d.ts rename to chai-enzyme/index.d.ts diff --git a/chai-enzyme/tsconfig.json b/chai-enzyme/tsconfig.json index 81fa4a5105..6c0238d9d2 100644 --- a/chai-enzyme/tsconfig.json +++ b/chai-enzyme/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "chai-enzyme.d.ts", + "index.d.ts", "chai-enzyme-tests.tsx" ] } \ No newline at end of file diff --git a/chai-oequal/chai-oequal-tests.ts b/chai-oequal/chai-oequal-tests.ts new file mode 100644 index 0000000000..ae7dbdc29f --- /dev/null +++ b/chai-oequal/chai-oequal-tests.ts @@ -0,0 +1,35 @@ +import Chai = require('chai'); +import ChaiOequal = require('chai-oequal'); + +Chai.use(ChaiOequal); + +import { + expect, + assert +} from 'chai'; + +expect({ + equals: () => true, +}).to.be.oequal({}); +expect({ + customequals: () => true, +}).to.be.oequal({}, 'customequals'); +expect({ + equals: () => true, +}).to.be.oeql({}); +expect({ + equals: () => true, +}).to.be.oeq({}); + +assert.oequal({ + equals: () => true, +}, {}); +assert.oequal({ + customequals: () => true, +}, {}, 'customequals'); +assert.oeql({ + equals: () => true, +}, {}); +assert.oeq({ + equals: () => true, +}, {}); diff --git a/chai-oequal/index.d.ts b/chai-oequal/index.d.ts new file mode 100644 index 0000000000..bf5f9e201f --- /dev/null +++ b/chai-oequal/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for chai-oequal +// Project: https://github.com/wrwrwr/chai-oequal +// Definitions by: Mizunashi Mana +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace Chai { + // For BDD APIs + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + oequal(result: any, method?: string): Equal; + oeql(result: any, method?: string): Equal; + oeq(result: any, method?: string): Equal; + } + + // For Assert APIs + interface Assert { + oequal(act: any, exp: any, method?: string): Equal; + oeql(act: any, exp: any, method?: string): Equal; + oeq(act: any, exp: any, method?: string): Equal; + } +} + +declare module 'chai-oequal' { + function chaiOequal(chai: any, utils: any): void; + export = chaiOequal; +} diff --git a/chai-oequal/tsconfig.json b/chai-oequal/tsconfig.json new file mode 100644 index 0000000000..cfeb14eeee --- /dev/null +++ b/chai-oequal/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "chai-oequal-tests.ts" + ] +} diff --git a/chai-oequal/tslint.json b/chai-oequal/tslint.json new file mode 100644 index 0000000000..cfdf2986e5 --- /dev/null +++ b/chai-oequal/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "no-single-declare-module": false + } +} diff --git a/codependency/codependency-tests.ts b/codependency/codependency-tests.ts new file mode 100644 index 0000000000..46f2db8d6d --- /dev/null +++ b/codependency/codependency-tests.ts @@ -0,0 +1,11 @@ +/// +/// + +let requirePeer = codependency.register(module), package: any; + requirePeer = codependency.register(module, {index: ["dependencies", "devDependencies"]}); + requirePeer = codependency.get("some-middleware"); + package = requirePeer("some-peer-dependency-package"); + package = requirePeer("some-peer-dependency-package", {optional: true}); + package = requirePeer("some-peer-dependency-package", {dontThrow: true}); + package = requirePeer("some-peer-dependency-package", {optional: true, dontThrow: true}); + package = requirePeer.resolve("peer-package-name"); \ No newline at end of file diff --git a/codependency/index.d.ts b/codependency/index.d.ts new file mode 100644 index 0000000000..0376bee4bb --- /dev/null +++ b/codependency/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for codependency v0.1.3 +// Project: https://github.com/Wizcorp/codependency +// Definitions by: Morgan Benton +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export as namespace codependency; + +interface DependencyInfo { + supportedRange: string|null; + installedVersion: string|null; + isInstalled: boolean|null; + isValid: boolean|null; + pkgPath: string; +} + +interface RequirePeerFunctionOptions { + optional?: boolean; + dontThrow?: boolean; +} + +interface RequirePeerFunction { + (name: string, options?: RequirePeerFunctionOptions): any; + resolve: (name: string) => DependencyInfo; +} + +export function register(baseModule: NodeModule, options?: {index: string[]}): RequirePeerFunction; +export function get(middlewareName: string): RequirePeerFunction; \ No newline at end of file diff --git a/codependency/package.json b/codependency/package.json new file mode 100644 index 0000000000..2fa5bde2e9 --- /dev/null +++ b/codependency/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/node": "^6.0.0" + } +} \ No newline at end of file diff --git a/codependency/tsconfig.json b/codependency/tsconfig.json new file mode 100644 index 0000000000..34636ce3d3 --- /dev/null +++ b/codependency/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "codependency-tests.ts" + ] +} \ No newline at end of file diff --git a/commander/commander-tests.ts b/commander/commander-tests.ts index f6f3918f6a..78bd873782 100644 --- a/commander/commander-tests.ts +++ b/commander/commander-tests.ts @@ -79,6 +79,13 @@ program console.log('unknown option is allowed'); }); +program + .version('0.0.1') + .arguments(' [env]') + .action(function (cmd, env) { + console.log(cmd, env); + }); + program.parse(process.argv); console.log('stuff'); diff --git a/commander/index.d.ts b/commander/index.d.ts index e082fcebb2..15a3246710 100644 --- a/commander/index.d.ts +++ b/commander/index.d.ts @@ -74,6 +74,11 @@ declare namespace commander { */ command(name:string, desc?:string, opts?: any):ICommand; + /** + * Set / get the arguments usage `str`. + */ + arguments(str: string):ICommand; + /** * Add an implicit `help [cmd]` subcommand * which invokes `--help` for the given command. diff --git a/commangular/commangular.d.ts b/commangular/index.d.ts similarity index 100% rename from commangular/commangular.d.ts rename to commangular/index.d.ts diff --git a/commangular/tsconfig.json b/commangular/tsconfig.json index e52f7e1a12..1cc876f08d 100644 --- a/commangular/tsconfig.json +++ b/commangular/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "commangular.d.ts", + "index.d.ts", "commangular-mock.d.ts" ] } \ No newline at end of file diff --git a/connect-mongo/index.d.ts b/connect-mongo/index.d.ts index df6a79b5ed..b469d08d00 100644 --- a/connect-mongo/index.d.ts +++ b/connect-mongo/index.d.ts @@ -74,6 +74,7 @@ declare namespace connectMongo { * (Default: 10) */ autoRemoveInterval?: number; + /** * don't save session if unmodified */ diff --git a/connect-redis/connect-redis-tests.ts b/connect-redis/connect-redis-tests.ts index 73e0e4d8f7..ed21f3b4be 100644 --- a/connect-redis/connect-redis-tests.ts +++ b/connect-redis/connect-redis-tests.ts @@ -1,4 +1,3 @@ -/// /// import * as connectRedis from "connect-redis"; diff --git a/connect-redis/connect-redis.d.ts b/connect-redis/index.d.ts similarity index 100% rename from connect-redis/connect-redis.d.ts rename to connect-redis/index.d.ts diff --git a/connect-redis/tsconfig.json b/connect-redis/tsconfig.json index 441b3c70c6..dadee4e1f8 100644 --- a/connect-redis/tsconfig.json +++ b/connect-redis/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "connect-redis.d.ts", + "index.d.ts", "connect-redis-tests.ts" ] } diff --git a/csv-parse/csv-parse-tests.ts b/csv-parse/csv-parse-tests.ts index 3f552f1319..21df979d82 100644 --- a/csv-parse/csv-parse-tests.ts +++ b/csv-parse/csv-parse-tests.ts @@ -1,5 +1,3 @@ -/// - import parse = require('csv-parse'); function callbackAPITest() { @@ -38,7 +36,7 @@ import fs = require('fs'); function pipeFunctionTest() { var transform = require('stream-transform'); - + var output:any = []; var parser = parse({delimiter: ':'}) var input = fs.createReadStream('/etc/passwd'); diff --git a/csv-parse/csv-parse.d.ts b/csv-parse/index.d.ts similarity index 100% rename from csv-parse/csv-parse.d.ts rename to csv-parse/index.d.ts diff --git a/csv-parse/tsconfig.json b/csv-parse/tsconfig.json index 9e359a8737..b3e05f504a 100644 --- a/csv-parse/tsconfig.json +++ b/csv-parse/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "csv-parse.d.ts", + "index.d.ts", "csv-parse-tests.ts" ] } \ No newline at end of file diff --git a/d3-box/d3-box-tests.ts b/d3-box/d3-box-tests.ts index 191962ff13..ab5ca799ba 100644 --- a/d3-box/d3-box-tests.ts +++ b/d3-box/d3-box-tests.ts @@ -1,6 +1,3 @@ -/// -/// - // Inspired by http://bl.ocks.org/mbostock/4061502 function iqr(k: number) { diff --git a/d3-box/d3-box.d.ts b/d3-box/index.d.ts similarity index 93% rename from d3-box/d3-box.d.ts rename to d3-box/index.d.ts index 4bc837df31..fdc304a68e 100644 --- a/d3-box/d3-box.d.ts +++ b/d3-box/index.d.ts @@ -3,9 +3,9 @@ // Definitions by: Linkun Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as d3 from "d3"; -declare namespace d3 { +declare module "d3" { export function box(): Box; interface Box { diff --git a/d3-box/package.json b/d3-box/package.json new file mode 100644 index 0000000000..ca67ffd471 --- /dev/null +++ b/d3-box/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/d3": "^3.5.36" + } +} \ No newline at end of file diff --git a/d3-box/tsconfig.json b/d3-box/tsconfig.json new file mode 100644 index 0000000000..ac2a5178dc --- /dev/null +++ b/d3-box/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "d3-box-tests.ts" + ] +} diff --git a/d3-geo/d3-geo-tests.ts b/d3-geo/d3-geo-tests.ts index b0c2adbb79..3d28bb610f 100644 --- a/d3-geo/d3-geo-tests.ts +++ b/d3-geo/d3-geo-tests.ts @@ -636,6 +636,15 @@ identityTransform = identityTransform.fitSize([960, 500], sampleExtendedFeature2 identityTransform = identityTransform.fitSize([960, 500], sampleFeatureCollection); identityTransform = identityTransform.fitSize([960, 500], sampleExtendedFeatureCollection); +let reflecting: boolean; + +identityTransform = identityTransform.reflectX(true); +// identityTransform = identityTransform.reflectX(5); // fails, wrong argument data type +reflecting = identityTransform.reflectX(); + +identityTransform = identityTransform.reflectY(true); +// identityTransform = identityTransform.reflectY(5); // fails, wrong argument data type +reflecting = identityTransform.reflectY(); // ---------------------------------------------------------------------- // Stream interface diff --git a/d3-geo/index.d.ts b/d3-geo/index.d.ts index f3222ce20e..9ab3ae74cd 100644 --- a/d3-geo/index.d.ts +++ b/d3-geo/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3-geo module v1.3.1 +// Type definitions for D3JS d3-geo module v1.4.0 // Project: https://github.com/d3/d3-geo/ // Definitions by: Hugues Stefanski , Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -1412,6 +1412,31 @@ export interface GeoIdentityTranform extends GeoStreamWrapper { */ fitSize(size: [number, number], object: ExtendedGeometryCollection): this; + /** + * Returns true if x-reflection is enabled, which defaults to false. + */ + reflectX(): boolean; + /** + * Sets whether or not the x-dimension is reflected (negated) in the output. + * + * @param reflect true = reflect x-dimension, false = do not reflect x-dimension. + */ + reflectX(reflect: boolean): this; + + /** + * Returns true if y-reflection is enabled, which defaults to false. + */ + reflectY(): boolean; + /** + * Sets whether or not the y-dimension is reflected (negated) in the output. + * + * This is especially useful for transforming from standard spatial reference systems, + * which treat positive y as pointing up, to display coordinate systems such as Canvas and SVG, + * which treat positive y as pointing down. + * + * @param reflect true = reflect y-dimension, false = do not reflect y-dimension. + */ + reflectY(reflect: boolean): this; /** * Returns the current scale factor. diff --git a/d3.slider/d3.slider-tests.ts b/d3.slider/d3.slider-tests.ts index e0e0473059..30f5900d41 100644 --- a/d3.slider/d3.slider-tests.ts +++ b/d3.slider/d3.slider-tests.ts @@ -1,6 +1,3 @@ -/// -/// - d3.select('#slider1').call(d3.slider()); d3.select('#slider2').call(d3.slider().value( [ 10, 25 ] )); d3.select('#slider3').call(d3.slider().axis(true).value( [ 10, 25 ] ) diff --git a/d3.slider/d3.slider.d.ts b/d3.slider/index.d.ts similarity index 94% rename from d3.slider/d3.slider.d.ts rename to d3.slider/index.d.ts index d459f4f04c..7b0dfcc5c2 100644 --- a/d3.slider/d3.slider.d.ts +++ b/d3.slider/index.d.ts @@ -3,9 +3,9 @@ // Definitions by: Linkun Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as d3 from "d3"; -declare namespace d3 { +declare module "d3" { export function slider(): Slider; interface Slider { diff --git a/d3.slider/package.json b/d3.slider/package.json new file mode 100644 index 0000000000..ca67ffd471 --- /dev/null +++ b/d3.slider/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/d3": "^3.5.36" + } +} \ No newline at end of file diff --git a/d3.slider/tsconfig.json b/d3.slider/tsconfig.json new file mode 100644 index 0000000000..c56fab950f --- /dev/null +++ b/d3.slider/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "d3.slider-tests.ts" + ] +} \ No newline at end of file diff --git a/d3kit/d3kit-tests.ts b/d3kit/d3kit-tests.ts index 5eab2a4e79..8e524a1f69 100644 --- a/d3kit/d3kit-tests.ts +++ b/d3kit/d3kit-tests.ts @@ -1,1112 +1,196 @@ -/// /// -/// -/// - -/* jshint expr: true */ - -var expect = chai.expect; -describe('Skeleton', function(){ - var element: Element, $element: d3.Selection, $svg: d3.Selection, skeleton: d3kit.Skeleton; - - beforeEach(function(done){ - element = document.body.appendChild(document.createElement('div')) as Element; - skeleton = new d3kit.Skeleton(element, null, ['custom1', 'custom2']); - $element = d3.select(element); - $svg = $element.select('svg'); - done(); - }); - - describe('new Skeleton()', function(){ - it('should create inside the element', function(){ - expect($element.select('svg').size()).to.be.equal(1); - }); - it('should create inside inside the element', function(){ - expect($element.select('svg').select('g').size()).to.be.equal(1); - }); - }); - - describe('#getCustomEventNames()', function(){ - it('should return custom event names', function(){ - expect(skeleton.getCustomEventNames()).to.deep.equal(['custom1', 'custom2']); - }); - }); - - describe('#getDispatcher()', function(){ - it('should return event dispatcher', function(){ - expect(skeleton.getDispatcher()).to.be.an('Object'); - expect(skeleton.getDispatcher().data).to.be.a('Function'); - }); - }); - - describe('#getInnerWidth()', function(){ - it('should return width of the skeleton excluding margin', function(){ - skeleton.options({ - margin: {left: 10, right: 10} - }); - skeleton.width(100); - expect(skeleton.getInnerWidth()).to.equal(80); - }); - }); - - describe('#getInnerHeight()', function(){ - it('should return height of the skeleton excluding margin', function(){ - skeleton.options({ - margin: {top: 10, bottom: 20} - }); - skeleton.height(100); - expect(skeleton.getInnerHeight()).to.equal(70); - }); - }); - - describe('#getLayerOrganizer()', function(){ - it('should return the LayerOrganizer', function(){ - expect(skeleton.getLayerOrganizer()).to.be.an('Object'); - }); - }); - - describe('#getRootG()', function(){ - it('should return d3 selection of the root ', function(){ - var g = skeleton.getRootG(); - expect(g.size()).to.equal(1); - expect((g[0][0] as Element).tagName).to.equal('g'); - }); - }); - - describe('#getSvg()', function(){ - it('should return d3 selection of the ', function(){ - var svg = skeleton.getSvg(); - expect(svg.size()).to.equal(1); - expect((svg[0][0] as Element).tagName).to.equal('svg'); - }); - }); - - describe('#data(data, doNotDispatch)', function(){ - it('should return data when called without argument', function(){ - skeleton.data({a: 1}); - expect(skeleton.data()).to.deep.equal({a: 1}); - }); - it('should set data when called with at least one argument', function(){ - skeleton.data('test'); - expect(skeleton.data()).to.equal('test'); - }); - it('after setting, should dispatch "data" event', function(done){ - skeleton.on('data.test', function(){ - // This block should be reached to pass the test. - expect(true).to.be.true; - done(); - }); - skeleton.data({a: 1}); - }); - it('after setting, should not dispatch "data" event if doNotDispatch is true', function(done){ - skeleton.on('data.test', function(){ - // This block should not be reached. - expect(true).to.be.false; - done(); - }); - skeleton.data({a: 1}, true); - setTimeout(done, 100); - }); - }); - - describe('#options(options, doNotDispatch)', function(){ - it('should return options when called without argument', function(){ - skeleton.options({a: 2}); - expect(skeleton.options()).to.include.keys(['a']); - expect(skeleton.options().a).to.equal(2); - }); - it('should set options when called with at least one argument', function(){ - skeleton.options({a: 1}); - expect(skeleton.options()).to.include.keys(['a']); - expect(skeleton.options().a).to.equal(1); - }); - it('should not overwrite but extend existing options when setting', function(){ - skeleton.options({a: 1}); - skeleton.options({b: 2}); - expect(skeleton.options()).to.include.keys(['a', 'b']); - expect(skeleton.options().a).to.equal(1); - expect(skeleton.options().b).to.equal(2); - }); - it('after setting, should dispatch "options" event', function(done){ - skeleton.on('options.test', function(){ - // This block should be reached to pass the test. - expect(true).to.be.true; - done(); - }); - skeleton.options({a: 1}); - }); - it('after setting, should not dispatch "options" event if doNotDispatch is true', function(done){ - skeleton.on('options.test', function(){ - // This block should not be reached. - expect(true).to.be.false; - done(); - }); - skeleton.options({a: 1}, true); - setTimeout(done, 100); - }); - }); - - describe('#margin(margin, doNotDispatch)', function(){ - it('should return margin when called without argument', function(){ - var margin = {left: 10, right: 10, top: 10, bottom: 10}; - skeleton.margin(margin); - expect(skeleton.margin()).to.deep.equal(margin); - }); - it('should set margin when called with at least one argument', function(){ - var margin = {left: 10, right: 10, top: 10, bottom: 10}; - skeleton.margin(margin); - - skeleton.margin({left: 20}); - expect(skeleton.margin().left).to.equal(20); - expect(skeleton.margin().right).to.equal(10); - skeleton.margin({right: 20}); - expect(skeleton.margin().right).to.equal(20); - skeleton.margin({top: 20}); - expect(skeleton.margin().top).to.equal(20); - skeleton.margin({bottom: 20}); - expect(skeleton.margin().bottom).to.equal(20); - }); - it('should update innerWidth after setting margin', function(){ - skeleton.width(100); - skeleton.margin({left: 10, right:10}); - expect(skeleton.getInnerWidth()).to.equal(80); - skeleton.margin({left: 15, right:15}); - expect(skeleton.getInnerWidth()).to.equal(70); - }); - it('should update innerHeight after setting margin', function(){ - skeleton.height(100); - skeleton.margin({top: 10, bottom:10}); - expect(skeleton.getInnerHeight()).to.equal(80); - skeleton.margin({top: 15, bottom:15}); - expect(skeleton.getInnerHeight()).to.equal(70); - }); - it('should update the root transform/translate', function(){ - skeleton.margin({left: 30, top: 30}); - skeleton.offset([0.5, 0.5]); - skeleton.margin({left: 10, top: 10}); - var translate = skeleton.getRootG().attr('transform'); - expect(translate).to.equal('translate(10.5,10.5)'); - }); - it('after setting, should dispatch "resize" event', function(done){ - skeleton.on('resize.test', function(){ - // This block should be reached to pass the test. - expect(true).to.be.true; - done(); - }); - skeleton.margin({left: 33}); - }); - it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ - skeleton.on('resize.test', function(){ - // This block should not be reached. - expect(true).to.be.false; - done(); - }); - skeleton.margin({left: 33}, true); - setTimeout(done, 100); - }); - }); - - describe('#offset(offset)', function(){ - it('should return offset when called without argument', function(){ - var offset = [1,1]; - skeleton.offset(offset); - expect(skeleton.offset()).to.deep.equal(offset); - }); - it('should set offset when called with at least one argument', function(){ - var offset = [1,1]; - skeleton.offset(offset); - skeleton.offset([2,3]); - expect(skeleton.offset()).to.deep.equal([2,3]); - }); - it('should update the root transform/translate', function(){ - skeleton.offset([0.5, 0.5]); - skeleton.margin({left: 10, top: 10}); - skeleton.offset([2,3]); - var translate = skeleton.getRootG().attr('transform'); - expect(translate).to.equal('translate(12,13)'); - }); - }); - - describe('#width(width, doNotDispatch)', function(){ - it('should return width when called without argument', function(){ - var w = $svg.attr('width'); - expect(skeleton.width()).to.equal(+w); - }); - it('should set width when called with Number as the first argument', function(){ - skeleton.width(300); - expect(+$svg.attr('width')).to.equal(300); - }); - it('should set width when called with a Number and "px" such as "100px" as the first argument', function(){ - skeleton.width('299px'); - expect(+$svg.attr('width')).to.equal(299); - }); - it('should set width to container\'s width when called with "auto" as the first argument', function(){ - var w = element.clientWidth; - skeleton.width('auto'); - expect(+$svg.attr('width')).to.equal(w); - }); - it('after setting, should dispatch "resize" event', function(done){ - skeleton.on('resize.test', function(){ - // This block should be reached to pass the test. - expect(true).to.be.true; - done(); - }); - skeleton.width(200); - }); - it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ - skeleton.on('resize.test', function(){ - // This block should not be reached. - expect(true).to.be.false; - done(); - }); - skeleton.width(200, true); - setTimeout(done, 100); - }); - }); - - describe('#height(height, doNotDispatch)', function(){ - it('should return height when called without argument', function(){ - var w = $svg.attr('height'); - expect(skeleton.height()).to.equal(+w); - }); - it('should set height when called with Number as the first argument', function(){ - skeleton.height(300); - expect(+$svg.attr('height')).to.equal(300); - }); - it('should set height when called with a Number and "px" such as "100px" as the first argument', function(){ - skeleton.height('299px'); - expect(+$svg.attr('height')).to.equal(299); - }); - it('should set height to container\'s height when called with "auto" as the first argument', function(){ - var w = element.clientHeight; - skeleton.height('auto'); - expect(+$svg.attr('height')).to.equal(w); - }); - it('after setting, should dispatch "resize" event', function(done){ - skeleton.on('resize.test', function(){ - // This block should be reached to pass the test. - expect(true).to.be.true; - done(); - }); - skeleton.height(200); - }); - it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ - skeleton.on('resize.test', function(){ - // This block should not be reached. - expect(true).to.be.false; - done(); - }); - skeleton.height(200, true); - setTimeout(done, 100); - }); - }); - - describe('#dimension(dimension, doNotDispatch)', function(){ - it('should return an array [width, height] when called without argument', function(){ - var dim = [+$svg.attr('width'), +$svg.attr('height')]; - expect(skeleton.dimension()).to.deep.equal(dim); - }); - it('should set width and height of the when called with an array [width, height] as the first argument', function(){ - skeleton.dimension([118, 118]); - expect([+$svg.attr('width'), +$svg.attr('height')]).to.deep.equal([118, 118]); - }); - it('after setting, should dispatch "resize" event', function(done){ - skeleton.on('resize.test', function(){ - // This block should be reached to pass the test. - expect(true).to.be.true; - done(); - }); - skeleton.dimension([150, 150]); - }); - it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ - skeleton.on('resize.test', function(){ - // This block should not be reached. - expect(true).to.be.false; - done(); - }); - skeleton.dimension([150, 150], true); - setTimeout(done, 100); - }); - }); - - describe('#hasData()', function(){ - it('should return true when data are not null nor undefined', function(){ - skeleton.data({}); - expect(skeleton.hasData()).to.be.true; - skeleton.data({test: 1}); - expect(skeleton.hasData()).to.be.true; - skeleton.data([]); - expect(skeleton.hasData()).to.be.true; - skeleton.data(['test']); - expect(skeleton.hasData()).to.be.true; - }); - it('should return false when data are null or undefined', function(){ - skeleton.data(null); - expect(skeleton.hasData()).to.be.false; - skeleton.data(undefined); - expect(skeleton.hasData()).to.be.false; - }); - }); - - describe('#hasNonZeroArea()', function(){ - it('should return true if \'s width & height excluding margin is more than zero', function(){ - skeleton.options({ - margin: {left: 10, right: 10} - }); - skeleton.width(80); - skeleton.options({ - margin: {top: 10, bottom: 20} - }); - skeleton.height(50); - expect(skeleton.hasNonZeroArea()).to.be.true; - }); - it('should return false otherwise', function(){ - skeleton.options({ - margin: {left: 10, right: 10} - }); - skeleton.width(20); - skeleton.options({ - margin: {top: 10, bottom: 20} - }); - skeleton.height(30); - expect(skeleton.hasNonZeroArea()).to.be.false; - }); - }); - - describe('#mixin({})', function(){ - it('should extend this skeleton with new fields/functions', function(){ - skeleton.mixin({ - a: 1, - b: 2 - }); - expect(skeleton).to.include.keys(['a', 'b']); - expect((skeleton).a).to.equal(1); - expect((skeleton).b).to.equal(2); - }); - it('should overwrite existing fields', function(){ - skeleton.mixin({ - b: 2 - }); - skeleton.mixin({ - b: 3 - }); - expect(skeleton).to.include.keys(['b']); - expect((skeleton).b).to.equal(3); - }); - it('should keep original fields if not overwritten', function(){ - skeleton.mixin({ - a: 1, - b: 2 - }); - skeleton.mixin({ - c: 20, - b: 3 - }); - expect(skeleton).to.include.keys(['a', 'b', 'c']); - expect((skeleton).a).to.equal(1); - expect((skeleton).b).to.equal(3); - expect((skeleton).c).to.equal(20); - }); - }); - - describe('#resizeToFitContainer(mode)', function(){ - it('when mode is "all" should resize to fit both width and height', function(){ - skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); - var w = element.clientWidth; - var h = element.clientHeight; - skeleton.resizeToFitContainer('all'); - expect(skeleton.dimension()).to.deep.equal([w, h]); - }); - it('when mode is "both" should resize to fit both width and height', function(){ - skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); - var w = element.clientWidth; - var h = element.clientHeight; - skeleton.resizeToFitContainer('both'); - expect(skeleton.dimension()).to.deep.equal([w, h]); - }); - it('when mode is "full" should resize to fit both width and height', function(){ - skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); - var w = element.clientWidth; - var h = element.clientHeight; - skeleton.resizeToFitContainer('full'); - expect(skeleton.dimension()).to.deep.equal([w, h]); - }); - it('when mode is "width" should resize width to fit container but keep original height', function(){ - var w1 = element.clientWidth/2; - var h1 = element.clientHeight/2; - - skeleton.dimension([w1, h1]); - - var w2 = element.clientWidth; - var h2 = element.clientHeight; - - skeleton.resizeToFitContainer('width'); - - expect(skeleton.width()).to.equal(Math.floor(w2)); - expect(skeleton.height()).to.equal(Math.floor(h1)); - expect(skeleton.width()).to.not.equal(w1); - expect(skeleton.height()).to.not.equal(h2); - }); - it('when mode is "height" should resize height to fit container but keep original width', function(){ - var w1 = element.clientWidth/2; - var h1 = element.clientHeight*2; - - skeleton.dimension([w1, h1]); - - var w2 = element.clientWidth; - var h2 = element.clientHeight; - - skeleton.resizeToFitContainer('height'); - - expect(skeleton.width()).to.equal(Math.floor(w1)); - expect(skeleton.height()).to.equal(Math.floor(h2)); - expect(skeleton.width()).to.not.equal(w2); - expect(skeleton.height()).to.not.equal(h1); - }); - }); - - describe('#resizeToAspectRatio(ratio)', function(){ - // todo - }); - - describe('#autoResize(mode)', function(){ - it('should return current mode when called without argument', function(){ - skeleton.autoResize(false); - expect(skeleton.autoResize()).to.be.false; - skeleton.autoResize('width'); - expect(skeleton.autoResize()).to.equal('width'); - }); - it('should enable auto resize when set mode to "width/height/both/etc.", similar to parameters of resizeToFitContainer()', function(done){ - // set initial size - skeleton.width(50); - skeleton.autoResize('width'); - setTimeout(function(){ - expect(skeleton.width()).to.equal(element.clientWidth); - done(); - }, 500); - }); - it('should disable auto resize when set mode to false', function(done){ - // set initial size - skeleton.width(50); - skeleton.autoResize('width'); - setTimeout(function(){ - expect(skeleton.width()).to.equal(element.clientWidth); - // disable resize and - skeleton.autoResize(false); - skeleton.width(50); - setTimeout(function(){ - expect(skeleton.width()).to.not.equal(element.clientWidth); - done(); - }, 500); - }, 500); - }); - }); - - describe('#autoResizeDetection(detection)', function(){ - // todo - }); - - describe('#autoResizeToAspectRatio(ratio)', function(){ - // todo - }); - - -}); - -describe.only('LayerOrganizer', function(){ - - describe('new LayerOrganizer(container) will create layers as by default', function(){ - var container: d3.Selection, layers: d3kit.LayerOrganizer; - before(function(done){ - container = d3.select('body').append('svg').append('g'); - layers = new d3kit.LayerOrganizer(container); - done(); - }); - - describe('#create(names)', function(){ - it('should create single layer given a String', function(){ - layers.create('single'); - expect(container.select('g.single-layer').size()).to.be.equal(1); - }); - - it('should create multiple layers given an array', function(){ - layers.create(['a', 'b', 'c']); - expect(container.select('g.a-layer').size()).to.be.equal(1); - expect(container.select('g.b-layer').size()).to.be.equal(1); - expect(container.select('g.c-layer').size()).to.be.equal(1); - }); - - it('should create nested layers given a plain Object with a String inside', function(){ - layers.create({d: 'e'}); - expect(container.select('g.d-layer').size()).to.be.equal(1); - expect(container.select('g.d-layer g.e-layer').size()).to.be.equal(1); - }); - - it('should create nested layers given a plain Object with an Array inside', function(){ - layers.create({f: ['g', 'h']}); - expect(container.select('g.f-layer').size()).to.be.equal(1); - expect(container.select('g.f-layer g.g-layer').size()).to.be.equal(1); - expect(container.select('g.f-layer g.h-layer').size()).to.be.equal(1); - }); - - it('should create multiple nested layers given an array of objects', function(){ - layers.create([{'i': ['x']}, {'j': 'x'}, {'k': ['x','y']}]); - expect(container.select('g.i-layer').size()).to.be.equal(1); - expect(container.select('g.j-layer').size()).to.be.equal(1); - expect(container.select('g.k-layer').size()).to.be.equal(1); - expect(container.select('g.i-layer g.x-layer').size()).to.be.equal(1); - expect(container.select('g.i-layer g.x-layer').size()).to.be.equal(1); - expect(container.select('g.k-layer g.x-layer').size()).to.be.equal(1); - expect(container.select('g.k-layer g.y-layer').size()).to.be.equal(1); - }); - - it('should create multi-level nested layers given a nested plain Object', function(){ - layers.create({ - l: [ - 'm', - {'n': [ - {'o': ['p']}, 'q' - ]} - ] - }); - expect(container.select('g.l-layer').size()).to.be.equal(1); - expect(container.select('g.l-layer g.m-layer').size()).to.be.equal(1); - expect(container.select('g.l-layer g.n-layer').size()).to.be.equal(1); - expect(container.select('g.l-layer g.n-layer g.o-layer').size()).to.be.equal(1); - expect(container.select('g.l-layer g.n-layer g.o-layer g.p-layer').size()).to.be.equal(1); - expect(container.select('g.l-layer g.n-layer g.q-layer').size()).to.be.equal(1); - }); - - }); - - describe('#has(name)', function(){ - it('should be able to check first-level layer', function(){ - expect(layers.has('single')).to.be.true; - expect(layers.has('test')).to.be.false; - }); - it('should be able to check second-level layer', function(){ - expect(layers.has('l.m')).to.be.true; - expect(layers.has('l.x')).to.be.false; - }); - it('should be able to check third-level layer', function(){ - expect(layers.has('l.n.q')).to.be.true; - expect(layers.has('l.n.x')).to.be.false; - }); - }); - - describe('#get(name)', function(){ - it('should be able to get first-level layer', function(){ - expect(layers.get('single')).to.exist; - expect(layers.get('test')).to.be.not.exist; - }); - it('should be able to get second-level layer', function(){ - expect(layers.get('l.m')).to.exist; - expect(layers.get('l.x')).to.not.exist; - }); - it('should be able to get third-level layer', function(){ - expect(layers.get('l.n.o')).to.exist; - expect(layers.get('l.n.x')).to.not.exist; - }); - }); - }); - - describe('new LayerOrganizer(container, tag) will create layers with the given tag instead of ', function(){ - var container: d3.Selection, layers: d3kit.LayerOrganizer; - before(function(done){ - container = d3.select('body').append('div'); - layers = new d3kit.LayerOrganizer(container, 'div'); - done(); - }); - - describe('#create(names)', function(){ - it('should create single layer given a String', function(){ - layers.create('single'); - expect(container.select('div.single-layer').size()).to.be.equal(1); - }); - - it('should create multiple layers given an array', function(){ - layers.create(['a', 'b', 'c']); - expect(container.select('div.a-layer').size()).to.be.equal(1); - expect(container.select('div.b-layer').size()).to.be.equal(1); - expect(container.select('div.c-layer').size()).to.be.equal(1); - }); - - it('should create nested layers given a plain Object with a String inside', function(){ - layers.create({d: 'e'}); - expect(container.select('div.d-layer').size()).to.be.equal(1); - expect(container.select('div.d-layer div.e-layer').size()).to.be.equal(1); - }); - - it('should create nested layers given a plain Object with an Array inside', function(){ - layers.create({f: ['g', 'h']}); - expect(container.select('div.f-layer').size()).to.be.equal(1); - expect(container.select('div.f-layer div.g-layer').size()).to.be.equal(1); - expect(container.select('div.f-layer div.h-layer').size()).to.be.equal(1); - }); - - it('should create multiple nested layers given an array of objects', function(){ - layers.create([{'i': ['x']}, {'j': 'x'}, {'k': ['x','y']}]); - expect(container.select('div.i-layer').size()).to.be.equal(1); - expect(container.select('div.j-layer').size()).to.be.equal(1); - expect(container.select('div.k-layer').size()).to.be.equal(1); - expect(container.select('div.i-layer div.x-layer').size()).to.be.equal(1); - expect(container.select('div.i-layer div.x-layer').size()).to.be.equal(1); - expect(container.select('div.k-layer div.x-layer').size()).to.be.equal(1); - expect(container.select('div.k-layer div.y-layer').size()).to.be.equal(1); - }); - - it('should create multi-level nested layers given a nested plain Object', function(){ - layers.create({ - l: [ - 'm', - {'n': [ - {'o': ['p']}, 'q' - ]} - ] - }); - expect(container.select('div.l-layer').size()).to.be.equal(1); - expect(container.select('div.l-layer div.m-layer').size()).to.be.equal(1); - expect(container.select('div.l-layer div.n-layer').size()).to.be.equal(1); - expect(container.select('div.l-layer div.n-layer div.o-layer').size()).to.be.equal(1); - expect(container.select('div.l-layer div.n-layer div.o-layer div.p-layer').size()).to.be.equal(1); - expect(container.select('div.l-layer div.n-layer div.q-layer').size()).to.be.equal(1); - }); - - }); - - describe('#has(name)', function(){ - it('should be able to check first-level layer', function(){ - expect(layers.has('single')).to.be.true; - expect(layers.has('test')).to.be.false; - }); - it('should be able to check second-level layer', function(){ - expect(layers.has('l.m')).to.be.true; - expect(layers.has('l.x')).to.be.false; - }); - it('should be able to check third-level layer', function(){ - expect(layers.has('l.n.q')).to.be.true; - expect(layers.has('l.n.x')).to.be.false; - }); - }); - - describe('#get(name)', function(){ - it('should be able to get first-level layer', function(){ - expect(layers.get('single')).to.exist; - expect(layers.get('test')).to.be.not.exist; - }); - it('should be able to get second-level layer', function(){ - expect(layers.get('l.m')).to.exist; - expect(layers.get('l.x')).to.not.exist; - }); - it('should be able to get third-level layer', function(){ - expect(layers.get('l.n.o')).to.exist; - expect(layers.get('l.n.x')).to.not.exist; - }); - }); - }); - -}); - -describe('Chartlet', function(){ - interface ConfigureFunction { - (parent: d3kit.Chartlet, child: d3kit.Chartlet): void; - } - var enter: d3kit.ChartletEventFunction, update: d3kit.ChartletEventFunction, exit: d3kit.ChartletEventFunction, chartlet: d3kit.Chartlet; - var customEvents: Array = ['fooEvent']; - var ChildChartlet: () => d3kit.Chartlet; - var ParentChartlet: (configureFunction: ConfigureFunction) => d3kit.Chartlet; - - var callback = function(selection?: d3.Selection, done?: any) { return (sel: d3.Selection) => {done();};}; - beforeEach(function(done){ - ChildChartlet = function() { - var chartlet = new d3kit.Chartlet(callback, callback, callback); - (chartlet).runTest = function (testFunction: any) { - testFunction(chartlet); - }; - return chartlet; - }; - - ParentChartlet = function(configureFunction: ConfigureFunction) { - var chartlet = new d3kit.Chartlet(callback, callback, callback); - var child = ChildChartlet(); - configureFunction(chartlet, child); - (chartlet).runTest = (child).runTest; - return chartlet; - }; - - enter = callback; - update = callback; - exit = callback; - chartlet = new d3kit.Chartlet(enter, update, exit, customEvents); - done(); - }); - - describe('new Chartlet(enter, update, exit, customEvents)', function(){ - it('should create a chartlet', function(){ - expect(chartlet).to.be.an('Object'); - expect(chartlet).to.include.keys(['property', 'on']); - expect(chartlet.enter).to.be.a('Function'); - expect(chartlet.update).to.be.a('Function'); - expect(chartlet.exit).to.be.a('Function'); - expect(function(){ chartlet.enter(); }).to.not.throw(Error); - expect(function(){ chartlet.update(); }).to.not.throw(Error); - expect(function(){ chartlet.exit(); }).to.not.throw(Error); - expect(chartlet.getCustomEventNames()).to.deep.equal(customEvents); - }); - it('arguments "update", "exit" and "customEvents" are optional', function(){ - var comp = new d3kit.Chartlet(enter); - expect(comp).to.be.an('Object'); - expect(comp).to.include.keys(['property', 'on']); - expect(comp.enter).to.be.a('Function'); - expect(comp.update).to.be.a('Function'); - expect(comp.exit).to.be.a('Function'); - expect(function(){ comp.enter(); }).to.not.throw(Error); - expect(function(){ comp.update(); }).to.not.throw(Error); - expect(function(){ comp.exit(); }).to.not.throw(Error); - }); - }); - - describe('#getDispatcher()', function(){ - it('should return a dispatcher', function(){ - var dispatcher = chartlet.getDispatcher(); - expect(dispatcher).to.exist; - }); - it('returned dispatcher should handle enter/update/exit events', function(){ - var dispatcher = chartlet.getDispatcher(); - expect(dispatcher).to.include.keys(['enterDone', 'updateDone', 'exitDone'].concat(customEvents)); - }); - }); - - describe('#getPropertyValue(name, d, i)', function(){ - it('should return computed value for specified property name, d and i', function(){ - var d = {a: 99}; - var i = 2; - - chartlet.property('foo', 1); - chartlet.property('bar', 'two'); - chartlet.property('baz', function(d:{a:number}, i: number) {return 3;}); - chartlet.property('qux', function(d:{a:number}, i: number) {return 'four';}); - chartlet.property('nux', function(d:{a:number}, i: number) {return d.a * i;}); - - expect(chartlet.getPropertyValue('foo', d, i)).to.equal(1); - expect(chartlet.getPropertyValue('bar', d, i)).to.equal('two'); - expect(chartlet.getPropertyValue('baz', d, i)).to.equal(3); - expect(chartlet.getPropertyValue('qux', d, i)).to.equal('four'); - expect(chartlet.getPropertyValue('nux', d, i)).to.equal(198); - }); - }); - - describe('#property(name, valueOrFn)', function(){ - describe('should act as a getter when called with one argument', function(){ - it('should always return a function', function(){ - chartlet.property('foo', 1); - expect(chartlet.property('foo')).to.be.a('Function'); - chartlet.property('bar', function(){ return 100; }); - expect(chartlet.property('bar')).to.be.a('Function'); - }); - it('should return a function that return undefined for unknown property name', function(){ - expect(chartlet.property('unknown name')).to.be.a('Function'); - expect(chartlet.property('unknown name')()).to.equal(undefined); - }); - }); - - describe('should act as a setter when called with two arguments', function(){ - it('should set specified property to a functor of given value', function(){ - chartlet.property('foo', 1); - expect(chartlet.property('foo')).to.be.a('Function'); - expect(chartlet.property('foo')()).to.equal(1); - chartlet.property('bar', function(){ return 100; }); - expect(chartlet.property('bar')).to.be.a('Function'); - expect(chartlet.property('bar')()).to.equal(100); - }); - it('should overwrite previous value when set property with the same name', function(){ - chartlet.property('foo', 1); - expect(chartlet.property('foo')()).to.equal(1); - chartlet.property('foo', 100); - expect(chartlet.property('foo')()).to.equal(100); - }); - }); - }); - - describe('#on(eventName, listener)', function(){ - it('event "enterDone" should be triggered after chartlet.enter() is completed.', function(done){ - chartlet.on('enterDone', function(){ return (sel: d3.Selection) => {done();} }); - chartlet.enter(); - }); - it('event "updateDone" should be triggered after chartlet.update() is completed.', function(done){ - chartlet.on('updateDone', function(){ return (sel: d3.Selection) => {done();} }); - chartlet.update(); - }); - it('event "exitDone" should be triggered after chartlet.exit() is completed.', function(done){ - chartlet.on('exitDone', function(){ return (sel: d3.Selection) => {done();} }); - chartlet.exit(); - }); - }); - - describe('#inheritPropertyFrom(parentChartlet, parentPropertyName, childPropertyName)', function(){ - it('it should cause a child to inherit a parent property', function() { - var parent = ParentChartlet(function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { - child.inheritPropertyFrom(parent, 'foo', 'bar'); - }) - .property('foo', function(d:number) {return 2 * d;}); - - (parent).runTest(function(child: d3kit.Chartlet) { - expect(child.getPropertyValue('bar', 4, 0)).to.be.equal(8); - }); - }); - - it('it should default to the parent property name', function() { - var parent = ParentChartlet( - function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { - child.inheritPropertyFrom(parent, 'foo'); - }) - .property('foo', function(d:number) {return 2 * d;}); - - (parent).runTest(function(child: d3kit.Chartlet) { - expect(child.getPropertyValue('foo', 4, 0)).to.be.equal(8); - }); - }); - }); - - describe('#inheritProperties(parentChartlet, parentPropertyNames, childPropertyNames)', function(){ - it('it should cause a child to inherit many parent properties', function() { - var parent = ParentChartlet( - function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { - child.inheritPropertiesFrom(parent, ['foo', 'bar', 'baz'], ['foo-x', 'bar-x', 'baz-x']); - }) - .property('foo', function(d:number) {return 2 * d;}) - .property('bar', function(d:number) {return 3 * d;}) - .property('baz', function(d:number) {return 4 * d;}); - - (parent).runTest(function(child: d3kit.Chartlet) { - expect(child.getPropertyValue('foo-x', 1, 0)).to.be.equal(2); - expect(child.getPropertyValue('bar-x', 1, 0)).to.be.equal(3); - expect(child.getPropertyValue('baz-x', 1, 0)).to.be.equal(4); - }); - }); - - it('it should default to the parent property names', function() { - var parent = ParentChartlet( - function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { - child.inheritPropertiesFrom(parent, ['foo', 'bar', 'baz']); - }) - .property('foo', function(d:number) {return 2 * d;}) - .property('bar', function(d:number) {return 3 * d;}) - .property('baz', function(d:number) {return 4 * d;}); - - (parent).runTest(function(child: d3kit.Chartlet) { - expect(child.getPropertyValue('foo', 1, 0)).to.be.equal(2); - expect(child.getPropertyValue('bar', 1, 0)).to.be.equal(3); - expect(child.getPropertyValue('baz', 1, 0)).to.be.equal(4); - }); - }); - }); - - describe('#publishEventsTo(foreignDispatcher)', function(){ - it('should map events to a foreignDispatcher', function(done) { - - var parent = new d3kit.Chartlet(callback, callback, callback, ['foo']); - parent.getDispatcher().on('foo', function(value:number) { - expect(value).to.be.equal(99); - done(); - }); - - var child = new d3kit.Chartlet(callback, callback, callback, ['foo']) - .publishEventsTo(parent.getDispatcher()); - - (child.getDispatcher()).foo(99); - }); - }); -}); - -describe('#createChart', function(){ - var Chart = d3kit.factory.createChart({}, ['test'], function(skeleton: d3kit.Skeleton){ - return skeleton; - }); - - it('should return a function to create a chart', function(){ - expect(Chart).to.be.a('Function'); - }); - - // // Don't think it's possible to define these in a d.ts file; skipping - // it('results should have function getCustomEvents()', function(){ - // expect(Chart.getCustomEvents).to.exist; - // expect(Chart.getCustomEvents()).to.deep.equal(['test']); - // }); -}); - -describe('d3kit.helper', function(){ - - describe('#dasherize(str)', function(){ - it('should convert input to dash-case', function(){ - expect(d3kit.helper.dasherize('camelCase')).to.equal('camel-case'); - }); - }); - - describe('#deepExtend(target, src1, src2, ...)', function(){ - it('should copy fields from sources into target', function(){ - expect(d3kit.helper.deepExtend({}, { - a: 1, - b: 2 - },{ - b: 3, - c: 4 - })).to.deep.equal({ - a: 1, - b: 3, - c: 4 - }); - - expect(d3kit.helper.deepExtend({}, { - a: 1, - b: 2 - },{ - b: 3, - c: 4 - }, null)).to.deep.equal({ - a: 1, - b: 3, - c: 4 - }); - }); - - it('should copy arrays and functions correctly from sources into target', function(){ - var fn1 = function(d:number){return d + 1;}; - var fn2 = function(d:number){return d + 2;}; - expect(d3kit.helper.deepExtend({}, { - a: fn1, - b: [1,2] - },{ - b: [3,4], - c: fn2 - })).to.deep.equal({ - a: fn1, - b: [3,4], - c: fn2 - }); - }); - - it('should perform "deep" copy', function(){ - var fn1 = function(d:number){return d + 1;}; - var fn2 = function(d:number){return d + 2;}; - expect(d3kit.helper.deepExtend({}, { - a: { d: fn1 }, - b: [1,2], - c: { f: 3 }, - h: { i: [1,2,3], j: [3,4,5] } - },{ - a: { e: 2 }, - b: [3,4], - c: { f: 4, g: fn2 }, - h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } - })).to.deep.equal({ - a: { d: fn1, e: 2 }, - b: [3,4], - c: { f: 4, g: fn2 }, - h: { i: [2,3,4], j: [3,4,5], k: [3,4,5], l: {m: 2} } - }); - }); - }); - - describe('#extend(target, src1, src2, ...)', function(){ - it('should copy fields from sources into target', function(){ - expect(d3kit.helper.extend({}, { - a: 1, - b: 2 - },{ - b: 3, - c: 4 - })).to.deep.equal({ - a: 1, - b: 3, - c: 4 - }); - - expect(d3kit.helper.extend({}, { - a: 1, - b: 2 - },{ - b: 3, - c: 4 - }, null)).to.deep.equal({ - a: 1, - b: 3, - c: 4 - }); - }); - - it('should copy arrays and functions correctly from sources into target', function(){ - var fn1 = function(d:number){return d + 1;}; - var fn2 = function(d:number){return d + 2;}; - expect(d3kit.helper.extend({}, { - a: fn1, - b: [1,2] - },{ - b: [3,4], - c: fn2 - })).to.deep.equal({ - a: fn1, - b: [3,4], - c: fn2 - }); - }); - - it('should NOT perform "deep" copy', function(){ - var fn1 = function(d:number){return d + 1;}; - var fn2 = function(d:number){return d + 2;}; - expect(d3kit.helper.extend({}, { - a: { d: fn1 }, - b: [1,2], - c: { f: 3 }, - h: { i: [1,2,3], j: [3,4,5] } - },{ - a: { e: 2 }, - b: [3,4], - c: { f: 4, g: fn2 }, - h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } - })).to.deep.equal({ - a: { e: 2 }, - b: [3,4], - c: { f: 4, g: fn2 }, - h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } - }); - }); - }); - - describe('#isFunction(function)', function(){ - it('should return true if the value is a function', function(){ - var fn1 = function(d:number){return d + 1;}; - function fn2(d:number){return d + 2;} - - expect(d3kit.helper.isFunction(fn1)).to.be.true; - expect(d3kit.helper.isFunction(fn2)).to.be.true; - }); - it('should return false if the value is not a function', function(){ - expect(d3kit.helper.isFunction(0)).to.be.false; - expect(d3kit.helper.isFunction(1)).to.be.false; - expect(d3kit.helper.isFunction(true)).to.be.false; - expect(d3kit.helper.isFunction('what')).to.be.false; - expect(d3kit.helper.isFunction(null)).to.be.false; - expect(d3kit.helper.isFunction(undefined)).to.be.false; - }); - }); - - describe('#isNumber(value)', function(){ - it('should return true for number', function(){ - expect(d3kit.helper.isNumber(1)).to.be.true; - expect(d3kit.helper.isNumber(0)).to.be.true; - expect(d3kit.helper.isNumber(-1)).to.be.true; - }); - it('should return false for string even if it is a number', function(){ - expect(d3kit.helper.isNumber('')).to.be.false; - expect(d3kit.helper.isNumber('1')).to.be.false; - expect(d3kit.helper.isNumber('0')).to.be.false; - expect(d3kit.helper.isNumber('what')).to.be.false; - }); - it('should return false for null and undefined', function(){ - expect(d3kit.helper.isNumber(null)).to.be.false; - expect(d3kit.helper.isNumber(undefined)).to.be.false; - }); - }); -}); +function test_abstract_chart() { + let el: Element, + chart: d3kit.AbstractChart, + options: d3kit.ChartOptions, + margins: d3kit.ChartMargin, + offsets: d3kit.ChartOffset, + defopts: d3kit.ChartOptions, + fitopts: d3kit.FitOptions, + watchop: d3kit.WatchOptions, + events: string[], + w: number, h:number, d: [number, number], a: any, b: boolean; + + // create a div, append to body, return Node as type Element + el = document.body.appendChild(document.createElement('div')) as Element; + + // create examples of margins, offsets, options, fit options, watch options + margins = { top: 20, right: 20, bottom: 20, left: 20}; + offsets = { x: 0.5, y: 0.5 }; + options = { initialWidth: 400, initialHeight: 300, margin: margins, offset: offsets }; + fitopts = { mode: 'basic', width: '90%', ratio: 4/3 }; + watchop = { mode: 'window', target: null, interval: 500 }; + + /** + * Test constructor + */ + chart = new d3kit.AbstractChart(el); // with element + chart = new d3kit.AbstractChart('div#chart'); // with selector + chart = new d3kit.AbstractChart(el, options); // with element+options + chart = new d3kit.AbstractChart('div#chart', options); // with selector+options + + /** + * Test static functions + */ + defopts = d3kit.AbstractChart.getDefaultOptions(); + events = d3kit.AbstractChart.getCustomEventNames(); + + /** + * Test getters + */ + w = chart.getInnerWidth(); + h = chart.getInnerHeight(); + w = chart.width(); + h = chart.height(); + d = chart.dimension(); + a = chart.data(); + margins = chart.margin(); + offsets = chart.offset(); + options = chart.options(); + events = chart.getCustomEventNames(); + + /** + * Test setters + */ + chart.width(w); + chart.height(h); + chart.dimension(d); + chart.data([1, 2, 3, 4, 5, 6]); + chart.margin(margins); + chart.offset(offsets); + chart.options(options); + + /** + * Test booleans + */ + b = chart.hasData(); + b = chart.hasNonZeroArea(); + + /** + * Test events + */ + chart.dimension(d).updateDimensionNow(); + chart.setupDispatcher(['click', 'mouseover']); + chart.fit(fitopts); // without watch options + chart.fit(fitopts, watchop); // with watch options + chart.stopFitWatcher(); + chart.on('mouseover', () => { chart.stopFitWatcher(); }); + chart.off('mouseover'); + chart.destroy(); +} + +function test_svgchart() { + let el: Element, + chart: d3kit.SvgChart, + options: d3kit.ChartOptions, + margins: d3kit.ChartMargin, + offsets: d3kit.ChartOffset, + svg: d3.Selection, + rootg: d3.Selection, + layers: d3kit.LayerOrganizer; + + // create a div, append to body, return Node as type Element + el = document.body.appendChild(document.createElement('div')) as Element; + + // create examples of margins, offsets, options, fit options, watch options + margins = { top: 20, right: 20, bottom: 20, left: 20}; + offsets = { x: 0.5, y: 0.5 }; + options = { initialWidth: 400, initialHeight: 300, margin: margins, offset: offsets }; + + /** + * Test constructor + */ + chart = new d3kit.SvgChart(el); // with element + chart = new d3kit.SvgChart('div#chart'); // with selector + chart = new d3kit.SvgChart(el, options); // with element+options + chart = new d3kit.SvgChart('div#chart', options); // with selector+options + + /** + * Test properties + */ + svg = chart.svg; + rootg = chart.rootG; + layers = chart.layers; +} + +function test_canvaschart() { + let el: Element, + chart: d3kit.CanvasChart, + options: d3kit.ChartOptions, + margins: d3kit.ChartMargin, + offsets: d3kit.ChartOffset, + context: CanvasRenderingContext2D; + + // create a div, append to body, return Node as type Element + el = document.body.appendChild(document.createElement('div')) as Element; + + // create examples of margins, offsets, options, fit options, watch options + margins = { top: 20, right: 20, bottom: 20, left: 20}; + offsets = { x: 0.5, y: 0.5 }; + options = { initialWidth: 400, initialHeight: 300, margin: margins, offset: offsets, pixelRatio: 1 }; + + /** + * Test constructor + */ + chart = new d3kit.CanvasChart(el); // with element + chart = new d3kit.CanvasChart('div#chart'); // with selector + chart = new d3kit.CanvasChart(el, options); // with element+options + chart = new d3kit.CanvasChart('div#chart', options); // with selector+options + + /** + * Test canvas chart functions + */ + context = chart.getContext2d(); + options = d3kit.CanvasChart.getDefaultOptions(); + chart.clear(); +} + +function test_layer_organizer() { + let selection: d3.Selection, + layer: d3.Selection, + layers: d3kit.LayerOrganizer, + hasXAxis: boolean; + + selection = d3.select('svg'); + + /** + * Test constructor + */ + layers = new d3kit.LayerOrganizer(selection); // without specifying tag + layers = new d3kit.LayerOrganizer(selection, 'div'); // specifying tag + + /** + * Test layer creation + */ + layers.create('graph'); + layers.create(['graph', 'highlight']); + layers.create({'graph': [{'axes':['x-axis', 'y-axis']}, {'labels':['x-label', 'y-label', 'title']}]}); + layers.create([{'axes':['x-axis', 'y-axis']}, {'labels':['x-label', 'y-label', 'title']}]); + + /** + * Test other layer organizer functions + */ + layer = layers.get('x-axis'); + hasXAxis = layers.has('x-axis'); +} + +function test_helper() { + let simple1: Object = { "one": 1 }, + simple2: Object = { "two": 2 }, + complex: Object = { "fruit": ["apple", "pear", "grape"], "prez": { "fn": "Barack", "ln": "Obama" } }, + merged1: Object, merged2: Object, + anObject: Object = {"this": "isanobject"}, isObj: boolean, + aFuncxn = () => "this is a function", isFunc: boolean, + kebabed: string, dbouncd: any, throtld: any; + + dbouncd = d3kit.helper.debounce(aFuncxn, 300); + merged1 = d3kit.helper.extend(simple1, simple2); + merged2 = d3kit.helper.deepExtend(simple1, complex); + aFuncxn = d3kit.helper.functor(aFuncxn); // with a function argument + aFuncxn = d3kit.helper.functor(simple1); // with a value argument + isObj = d3kit.helper.isObject(anObject); + isFunc = d3kit.helper.isFunction(aFuncxn); + kebabed = d3kit.helper.kebabCase("a string to convert to kebab case"); + throtld = d3kit.helper.throttle(aFuncxn, 300); +} diff --git a/d3kit/d3kit-v1.1.0-tests.ts b/d3kit/d3kit-v1.1.0-tests.ts new file mode 100644 index 0000000000..5eab2a4e79 --- /dev/null +++ b/d3kit/d3kit-v1.1.0-tests.ts @@ -0,0 +1,1112 @@ +/// +/// +/// +/// + +/* jshint expr: true */ + +var expect = chai.expect; +describe('Skeleton', function(){ + var element: Element, $element: d3.Selection, $svg: d3.Selection, skeleton: d3kit.Skeleton; + + beforeEach(function(done){ + element = document.body.appendChild(document.createElement('div')) as Element; + skeleton = new d3kit.Skeleton(element, null, ['custom1', 'custom2']); + $element = d3.select(element); + $svg = $element.select('svg'); + done(); + }); + + describe('new Skeleton()', function(){ + it('should create inside the element', function(){ + expect($element.select('svg').size()).to.be.equal(1); + }); + it('should create inside inside the element', function(){ + expect($element.select('svg').select('g').size()).to.be.equal(1); + }); + }); + + describe('#getCustomEventNames()', function(){ + it('should return custom event names', function(){ + expect(skeleton.getCustomEventNames()).to.deep.equal(['custom1', 'custom2']); + }); + }); + + describe('#getDispatcher()', function(){ + it('should return event dispatcher', function(){ + expect(skeleton.getDispatcher()).to.be.an('Object'); + expect(skeleton.getDispatcher().data).to.be.a('Function'); + }); + }); + + describe('#getInnerWidth()', function(){ + it('should return width of the skeleton excluding margin', function(){ + skeleton.options({ + margin: {left: 10, right: 10} + }); + skeleton.width(100); + expect(skeleton.getInnerWidth()).to.equal(80); + }); + }); + + describe('#getInnerHeight()', function(){ + it('should return height of the skeleton excluding margin', function(){ + skeleton.options({ + margin: {top: 10, bottom: 20} + }); + skeleton.height(100); + expect(skeleton.getInnerHeight()).to.equal(70); + }); + }); + + describe('#getLayerOrganizer()', function(){ + it('should return the LayerOrganizer', function(){ + expect(skeleton.getLayerOrganizer()).to.be.an('Object'); + }); + }); + + describe('#getRootG()', function(){ + it('should return d3 selection of the root ', function(){ + var g = skeleton.getRootG(); + expect(g.size()).to.equal(1); + expect((g[0][0] as Element).tagName).to.equal('g'); + }); + }); + + describe('#getSvg()', function(){ + it('should return d3 selection of the ', function(){ + var svg = skeleton.getSvg(); + expect(svg.size()).to.equal(1); + expect((svg[0][0] as Element).tagName).to.equal('svg'); + }); + }); + + describe('#data(data, doNotDispatch)', function(){ + it('should return data when called without argument', function(){ + skeleton.data({a: 1}); + expect(skeleton.data()).to.deep.equal({a: 1}); + }); + it('should set data when called with at least one argument', function(){ + skeleton.data('test'); + expect(skeleton.data()).to.equal('test'); + }); + it('after setting, should dispatch "data" event', function(done){ + skeleton.on('data.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.data({a: 1}); + }); + it('after setting, should not dispatch "data" event if doNotDispatch is true', function(done){ + skeleton.on('data.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.data({a: 1}, true); + setTimeout(done, 100); + }); + }); + + describe('#options(options, doNotDispatch)', function(){ + it('should return options when called without argument', function(){ + skeleton.options({a: 2}); + expect(skeleton.options()).to.include.keys(['a']); + expect(skeleton.options().a).to.equal(2); + }); + it('should set options when called with at least one argument', function(){ + skeleton.options({a: 1}); + expect(skeleton.options()).to.include.keys(['a']); + expect(skeleton.options().a).to.equal(1); + }); + it('should not overwrite but extend existing options when setting', function(){ + skeleton.options({a: 1}); + skeleton.options({b: 2}); + expect(skeleton.options()).to.include.keys(['a', 'b']); + expect(skeleton.options().a).to.equal(1); + expect(skeleton.options().b).to.equal(2); + }); + it('after setting, should dispatch "options" event', function(done){ + skeleton.on('options.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.options({a: 1}); + }); + it('after setting, should not dispatch "options" event if doNotDispatch is true', function(done){ + skeleton.on('options.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.options({a: 1}, true); + setTimeout(done, 100); + }); + }); + + describe('#margin(margin, doNotDispatch)', function(){ + it('should return margin when called without argument', function(){ + var margin = {left: 10, right: 10, top: 10, bottom: 10}; + skeleton.margin(margin); + expect(skeleton.margin()).to.deep.equal(margin); + }); + it('should set margin when called with at least one argument', function(){ + var margin = {left: 10, right: 10, top: 10, bottom: 10}; + skeleton.margin(margin); + + skeleton.margin({left: 20}); + expect(skeleton.margin().left).to.equal(20); + expect(skeleton.margin().right).to.equal(10); + skeleton.margin({right: 20}); + expect(skeleton.margin().right).to.equal(20); + skeleton.margin({top: 20}); + expect(skeleton.margin().top).to.equal(20); + skeleton.margin({bottom: 20}); + expect(skeleton.margin().bottom).to.equal(20); + }); + it('should update innerWidth after setting margin', function(){ + skeleton.width(100); + skeleton.margin({left: 10, right:10}); + expect(skeleton.getInnerWidth()).to.equal(80); + skeleton.margin({left: 15, right:15}); + expect(skeleton.getInnerWidth()).to.equal(70); + }); + it('should update innerHeight after setting margin', function(){ + skeleton.height(100); + skeleton.margin({top: 10, bottom:10}); + expect(skeleton.getInnerHeight()).to.equal(80); + skeleton.margin({top: 15, bottom:15}); + expect(skeleton.getInnerHeight()).to.equal(70); + }); + it('should update the root transform/translate', function(){ + skeleton.margin({left: 30, top: 30}); + skeleton.offset([0.5, 0.5]); + skeleton.margin({left: 10, top: 10}); + var translate = skeleton.getRootG().attr('transform'); + expect(translate).to.equal('translate(10.5,10.5)'); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.margin({left: 33}); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.margin({left: 33}, true); + setTimeout(done, 100); + }); + }); + + describe('#offset(offset)', function(){ + it('should return offset when called without argument', function(){ + var offset = [1,1]; + skeleton.offset(offset); + expect(skeleton.offset()).to.deep.equal(offset); + }); + it('should set offset when called with at least one argument', function(){ + var offset = [1,1]; + skeleton.offset(offset); + skeleton.offset([2,3]); + expect(skeleton.offset()).to.deep.equal([2,3]); + }); + it('should update the root transform/translate', function(){ + skeleton.offset([0.5, 0.5]); + skeleton.margin({left: 10, top: 10}); + skeleton.offset([2,3]); + var translate = skeleton.getRootG().attr('transform'); + expect(translate).to.equal('translate(12,13)'); + }); + }); + + describe('#width(width, doNotDispatch)', function(){ + it('should return width when called without argument', function(){ + var w = $svg.attr('width'); + expect(skeleton.width()).to.equal(+w); + }); + it('should set width when called with Number as the first argument', function(){ + skeleton.width(300); + expect(+$svg.attr('width')).to.equal(300); + }); + it('should set width when called with a Number and "px" such as "100px" as the first argument', function(){ + skeleton.width('299px'); + expect(+$svg.attr('width')).to.equal(299); + }); + it('should set width to container\'s width when called with "auto" as the first argument', function(){ + var w = element.clientWidth; + skeleton.width('auto'); + expect(+$svg.attr('width')).to.equal(w); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.width(200); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.width(200, true); + setTimeout(done, 100); + }); + }); + + describe('#height(height, doNotDispatch)', function(){ + it('should return height when called without argument', function(){ + var w = $svg.attr('height'); + expect(skeleton.height()).to.equal(+w); + }); + it('should set height when called with Number as the first argument', function(){ + skeleton.height(300); + expect(+$svg.attr('height')).to.equal(300); + }); + it('should set height when called with a Number and "px" such as "100px" as the first argument', function(){ + skeleton.height('299px'); + expect(+$svg.attr('height')).to.equal(299); + }); + it('should set height to container\'s height when called with "auto" as the first argument', function(){ + var w = element.clientHeight; + skeleton.height('auto'); + expect(+$svg.attr('height')).to.equal(w); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.height(200); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.height(200, true); + setTimeout(done, 100); + }); + }); + + describe('#dimension(dimension, doNotDispatch)', function(){ + it('should return an array [width, height] when called without argument', function(){ + var dim = [+$svg.attr('width'), +$svg.attr('height')]; + expect(skeleton.dimension()).to.deep.equal(dim); + }); + it('should set width and height of the when called with an array [width, height] as the first argument', function(){ + skeleton.dimension([118, 118]); + expect([+$svg.attr('width'), +$svg.attr('height')]).to.deep.equal([118, 118]); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.dimension([150, 150]); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.dimension([150, 150], true); + setTimeout(done, 100); + }); + }); + + describe('#hasData()', function(){ + it('should return true when data are not null nor undefined', function(){ + skeleton.data({}); + expect(skeleton.hasData()).to.be.true; + skeleton.data({test: 1}); + expect(skeleton.hasData()).to.be.true; + skeleton.data([]); + expect(skeleton.hasData()).to.be.true; + skeleton.data(['test']); + expect(skeleton.hasData()).to.be.true; + }); + it('should return false when data are null or undefined', function(){ + skeleton.data(null); + expect(skeleton.hasData()).to.be.false; + skeleton.data(undefined); + expect(skeleton.hasData()).to.be.false; + }); + }); + + describe('#hasNonZeroArea()', function(){ + it('should return true if \'s width & height excluding margin is more than zero', function(){ + skeleton.options({ + margin: {left: 10, right: 10} + }); + skeleton.width(80); + skeleton.options({ + margin: {top: 10, bottom: 20} + }); + skeleton.height(50); + expect(skeleton.hasNonZeroArea()).to.be.true; + }); + it('should return false otherwise', function(){ + skeleton.options({ + margin: {left: 10, right: 10} + }); + skeleton.width(20); + skeleton.options({ + margin: {top: 10, bottom: 20} + }); + skeleton.height(30); + expect(skeleton.hasNonZeroArea()).to.be.false; + }); + }); + + describe('#mixin({})', function(){ + it('should extend this skeleton with new fields/functions', function(){ + skeleton.mixin({ + a: 1, + b: 2 + }); + expect(skeleton).to.include.keys(['a', 'b']); + expect((skeleton).a).to.equal(1); + expect((skeleton).b).to.equal(2); + }); + it('should overwrite existing fields', function(){ + skeleton.mixin({ + b: 2 + }); + skeleton.mixin({ + b: 3 + }); + expect(skeleton).to.include.keys(['b']); + expect((skeleton).b).to.equal(3); + }); + it('should keep original fields if not overwritten', function(){ + skeleton.mixin({ + a: 1, + b: 2 + }); + skeleton.mixin({ + c: 20, + b: 3 + }); + expect(skeleton).to.include.keys(['a', 'b', 'c']); + expect((skeleton).a).to.equal(1); + expect((skeleton).b).to.equal(3); + expect((skeleton).c).to.equal(20); + }); + }); + + describe('#resizeToFitContainer(mode)', function(){ + it('when mode is "all" should resize to fit both width and height', function(){ + skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); + var w = element.clientWidth; + var h = element.clientHeight; + skeleton.resizeToFitContainer('all'); + expect(skeleton.dimension()).to.deep.equal([w, h]); + }); + it('when mode is "both" should resize to fit both width and height', function(){ + skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); + var w = element.clientWidth; + var h = element.clientHeight; + skeleton.resizeToFitContainer('both'); + expect(skeleton.dimension()).to.deep.equal([w, h]); + }); + it('when mode is "full" should resize to fit both width and height', function(){ + skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); + var w = element.clientWidth; + var h = element.clientHeight; + skeleton.resizeToFitContainer('full'); + expect(skeleton.dimension()).to.deep.equal([w, h]); + }); + it('when mode is "width" should resize width to fit container but keep original height', function(){ + var w1 = element.clientWidth/2; + var h1 = element.clientHeight/2; + + skeleton.dimension([w1, h1]); + + var w2 = element.clientWidth; + var h2 = element.clientHeight; + + skeleton.resizeToFitContainer('width'); + + expect(skeleton.width()).to.equal(Math.floor(w2)); + expect(skeleton.height()).to.equal(Math.floor(h1)); + expect(skeleton.width()).to.not.equal(w1); + expect(skeleton.height()).to.not.equal(h2); + }); + it('when mode is "height" should resize height to fit container but keep original width', function(){ + var w1 = element.clientWidth/2; + var h1 = element.clientHeight*2; + + skeleton.dimension([w1, h1]); + + var w2 = element.clientWidth; + var h2 = element.clientHeight; + + skeleton.resizeToFitContainer('height'); + + expect(skeleton.width()).to.equal(Math.floor(w1)); + expect(skeleton.height()).to.equal(Math.floor(h2)); + expect(skeleton.width()).to.not.equal(w2); + expect(skeleton.height()).to.not.equal(h1); + }); + }); + + describe('#resizeToAspectRatio(ratio)', function(){ + // todo + }); + + describe('#autoResize(mode)', function(){ + it('should return current mode when called without argument', function(){ + skeleton.autoResize(false); + expect(skeleton.autoResize()).to.be.false; + skeleton.autoResize('width'); + expect(skeleton.autoResize()).to.equal('width'); + }); + it('should enable auto resize when set mode to "width/height/both/etc.", similar to parameters of resizeToFitContainer()', function(done){ + // set initial size + skeleton.width(50); + skeleton.autoResize('width'); + setTimeout(function(){ + expect(skeleton.width()).to.equal(element.clientWidth); + done(); + }, 500); + }); + it('should disable auto resize when set mode to false', function(done){ + // set initial size + skeleton.width(50); + skeleton.autoResize('width'); + setTimeout(function(){ + expect(skeleton.width()).to.equal(element.clientWidth); + // disable resize and + skeleton.autoResize(false); + skeleton.width(50); + setTimeout(function(){ + expect(skeleton.width()).to.not.equal(element.clientWidth); + done(); + }, 500); + }, 500); + }); + }); + + describe('#autoResizeDetection(detection)', function(){ + // todo + }); + + describe('#autoResizeToAspectRatio(ratio)', function(){ + // todo + }); + + +}); + +describe.only('LayerOrganizer', function(){ + + describe('new LayerOrganizer(container) will create layers as by default', function(){ + var container: d3.Selection, layers: d3kit.LayerOrganizer; + before(function(done){ + container = d3.select('body').append('svg').append('g'); + layers = new d3kit.LayerOrganizer(container); + done(); + }); + + describe('#create(names)', function(){ + it('should create single layer given a String', function(){ + layers.create('single'); + expect(container.select('g.single-layer').size()).to.be.equal(1); + }); + + it('should create multiple layers given an array', function(){ + layers.create(['a', 'b', 'c']); + expect(container.select('g.a-layer').size()).to.be.equal(1); + expect(container.select('g.b-layer').size()).to.be.equal(1); + expect(container.select('g.c-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with a String inside', function(){ + layers.create({d: 'e'}); + expect(container.select('g.d-layer').size()).to.be.equal(1); + expect(container.select('g.d-layer g.e-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with an Array inside', function(){ + layers.create({f: ['g', 'h']}); + expect(container.select('g.f-layer').size()).to.be.equal(1); + expect(container.select('g.f-layer g.g-layer').size()).to.be.equal(1); + expect(container.select('g.f-layer g.h-layer').size()).to.be.equal(1); + }); + + it('should create multiple nested layers given an array of objects', function(){ + layers.create([{'i': ['x']}, {'j': 'x'}, {'k': ['x','y']}]); + expect(container.select('g.i-layer').size()).to.be.equal(1); + expect(container.select('g.j-layer').size()).to.be.equal(1); + expect(container.select('g.k-layer').size()).to.be.equal(1); + expect(container.select('g.i-layer g.x-layer').size()).to.be.equal(1); + expect(container.select('g.i-layer g.x-layer').size()).to.be.equal(1); + expect(container.select('g.k-layer g.x-layer').size()).to.be.equal(1); + expect(container.select('g.k-layer g.y-layer').size()).to.be.equal(1); + }); + + it('should create multi-level nested layers given a nested plain Object', function(){ + layers.create({ + l: [ + 'm', + {'n': [ + {'o': ['p']}, 'q' + ]} + ] + }); + expect(container.select('g.l-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.m-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer g.o-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer g.o-layer g.p-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer g.q-layer').size()).to.be.equal(1); + }); + + }); + + describe('#has(name)', function(){ + it('should be able to check first-level layer', function(){ + expect(layers.has('single')).to.be.true; + expect(layers.has('test')).to.be.false; + }); + it('should be able to check second-level layer', function(){ + expect(layers.has('l.m')).to.be.true; + expect(layers.has('l.x')).to.be.false; + }); + it('should be able to check third-level layer', function(){ + expect(layers.has('l.n.q')).to.be.true; + expect(layers.has('l.n.x')).to.be.false; + }); + }); + + describe('#get(name)', function(){ + it('should be able to get first-level layer', function(){ + expect(layers.get('single')).to.exist; + expect(layers.get('test')).to.be.not.exist; + }); + it('should be able to get second-level layer', function(){ + expect(layers.get('l.m')).to.exist; + expect(layers.get('l.x')).to.not.exist; + }); + it('should be able to get third-level layer', function(){ + expect(layers.get('l.n.o')).to.exist; + expect(layers.get('l.n.x')).to.not.exist; + }); + }); + }); + + describe('new LayerOrganizer(container, tag) will create layers with the given tag instead of ', function(){ + var container: d3.Selection, layers: d3kit.LayerOrganizer; + before(function(done){ + container = d3.select('body').append('div'); + layers = new d3kit.LayerOrganizer(container, 'div'); + done(); + }); + + describe('#create(names)', function(){ + it('should create single layer given a String', function(){ + layers.create('single'); + expect(container.select('div.single-layer').size()).to.be.equal(1); + }); + + it('should create multiple layers given an array', function(){ + layers.create(['a', 'b', 'c']); + expect(container.select('div.a-layer').size()).to.be.equal(1); + expect(container.select('div.b-layer').size()).to.be.equal(1); + expect(container.select('div.c-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with a String inside', function(){ + layers.create({d: 'e'}); + expect(container.select('div.d-layer').size()).to.be.equal(1); + expect(container.select('div.d-layer div.e-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with an Array inside', function(){ + layers.create({f: ['g', 'h']}); + expect(container.select('div.f-layer').size()).to.be.equal(1); + expect(container.select('div.f-layer div.g-layer').size()).to.be.equal(1); + expect(container.select('div.f-layer div.h-layer').size()).to.be.equal(1); + }); + + it('should create multiple nested layers given an array of objects', function(){ + layers.create([{'i': ['x']}, {'j': 'x'}, {'k': ['x','y']}]); + expect(container.select('div.i-layer').size()).to.be.equal(1); + expect(container.select('div.j-layer').size()).to.be.equal(1); + expect(container.select('div.k-layer').size()).to.be.equal(1); + expect(container.select('div.i-layer div.x-layer').size()).to.be.equal(1); + expect(container.select('div.i-layer div.x-layer').size()).to.be.equal(1); + expect(container.select('div.k-layer div.x-layer').size()).to.be.equal(1); + expect(container.select('div.k-layer div.y-layer').size()).to.be.equal(1); + }); + + it('should create multi-level nested layers given a nested plain Object', function(){ + layers.create({ + l: [ + 'm', + {'n': [ + {'o': ['p']}, 'q' + ]} + ] + }); + expect(container.select('div.l-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.m-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer div.o-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer div.o-layer div.p-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer div.q-layer').size()).to.be.equal(1); + }); + + }); + + describe('#has(name)', function(){ + it('should be able to check first-level layer', function(){ + expect(layers.has('single')).to.be.true; + expect(layers.has('test')).to.be.false; + }); + it('should be able to check second-level layer', function(){ + expect(layers.has('l.m')).to.be.true; + expect(layers.has('l.x')).to.be.false; + }); + it('should be able to check third-level layer', function(){ + expect(layers.has('l.n.q')).to.be.true; + expect(layers.has('l.n.x')).to.be.false; + }); + }); + + describe('#get(name)', function(){ + it('should be able to get first-level layer', function(){ + expect(layers.get('single')).to.exist; + expect(layers.get('test')).to.be.not.exist; + }); + it('should be able to get second-level layer', function(){ + expect(layers.get('l.m')).to.exist; + expect(layers.get('l.x')).to.not.exist; + }); + it('should be able to get third-level layer', function(){ + expect(layers.get('l.n.o')).to.exist; + expect(layers.get('l.n.x')).to.not.exist; + }); + }); + }); + +}); + +describe('Chartlet', function(){ + interface ConfigureFunction { + (parent: d3kit.Chartlet, child: d3kit.Chartlet): void; + } + var enter: d3kit.ChartletEventFunction, update: d3kit.ChartletEventFunction, exit: d3kit.ChartletEventFunction, chartlet: d3kit.Chartlet; + var customEvents: Array = ['fooEvent']; + var ChildChartlet: () => d3kit.Chartlet; + var ParentChartlet: (configureFunction: ConfigureFunction) => d3kit.Chartlet; + + var callback = function(selection?: d3.Selection, done?: any) { return (sel: d3.Selection) => {done();};}; + beforeEach(function(done){ + ChildChartlet = function() { + var chartlet = new d3kit.Chartlet(callback, callback, callback); + (chartlet).runTest = function (testFunction: any) { + testFunction(chartlet); + }; + return chartlet; + }; + + ParentChartlet = function(configureFunction: ConfigureFunction) { + var chartlet = new d3kit.Chartlet(callback, callback, callback); + var child = ChildChartlet(); + configureFunction(chartlet, child); + (chartlet).runTest = (child).runTest; + return chartlet; + }; + + enter = callback; + update = callback; + exit = callback; + chartlet = new d3kit.Chartlet(enter, update, exit, customEvents); + done(); + }); + + describe('new Chartlet(enter, update, exit, customEvents)', function(){ + it('should create a chartlet', function(){ + expect(chartlet).to.be.an('Object'); + expect(chartlet).to.include.keys(['property', 'on']); + expect(chartlet.enter).to.be.a('Function'); + expect(chartlet.update).to.be.a('Function'); + expect(chartlet.exit).to.be.a('Function'); + expect(function(){ chartlet.enter(); }).to.not.throw(Error); + expect(function(){ chartlet.update(); }).to.not.throw(Error); + expect(function(){ chartlet.exit(); }).to.not.throw(Error); + expect(chartlet.getCustomEventNames()).to.deep.equal(customEvents); + }); + it('arguments "update", "exit" and "customEvents" are optional', function(){ + var comp = new d3kit.Chartlet(enter); + expect(comp).to.be.an('Object'); + expect(comp).to.include.keys(['property', 'on']); + expect(comp.enter).to.be.a('Function'); + expect(comp.update).to.be.a('Function'); + expect(comp.exit).to.be.a('Function'); + expect(function(){ comp.enter(); }).to.not.throw(Error); + expect(function(){ comp.update(); }).to.not.throw(Error); + expect(function(){ comp.exit(); }).to.not.throw(Error); + }); + }); + + describe('#getDispatcher()', function(){ + it('should return a dispatcher', function(){ + var dispatcher = chartlet.getDispatcher(); + expect(dispatcher).to.exist; + }); + it('returned dispatcher should handle enter/update/exit events', function(){ + var dispatcher = chartlet.getDispatcher(); + expect(dispatcher).to.include.keys(['enterDone', 'updateDone', 'exitDone'].concat(customEvents)); + }); + }); + + describe('#getPropertyValue(name, d, i)', function(){ + it('should return computed value for specified property name, d and i', function(){ + var d = {a: 99}; + var i = 2; + + chartlet.property('foo', 1); + chartlet.property('bar', 'two'); + chartlet.property('baz', function(d:{a:number}, i: number) {return 3;}); + chartlet.property('qux', function(d:{a:number}, i: number) {return 'four';}); + chartlet.property('nux', function(d:{a:number}, i: number) {return d.a * i;}); + + expect(chartlet.getPropertyValue('foo', d, i)).to.equal(1); + expect(chartlet.getPropertyValue('bar', d, i)).to.equal('two'); + expect(chartlet.getPropertyValue('baz', d, i)).to.equal(3); + expect(chartlet.getPropertyValue('qux', d, i)).to.equal('four'); + expect(chartlet.getPropertyValue('nux', d, i)).to.equal(198); + }); + }); + + describe('#property(name, valueOrFn)', function(){ + describe('should act as a getter when called with one argument', function(){ + it('should always return a function', function(){ + chartlet.property('foo', 1); + expect(chartlet.property('foo')).to.be.a('Function'); + chartlet.property('bar', function(){ return 100; }); + expect(chartlet.property('bar')).to.be.a('Function'); + }); + it('should return a function that return undefined for unknown property name', function(){ + expect(chartlet.property('unknown name')).to.be.a('Function'); + expect(chartlet.property('unknown name')()).to.equal(undefined); + }); + }); + + describe('should act as a setter when called with two arguments', function(){ + it('should set specified property to a functor of given value', function(){ + chartlet.property('foo', 1); + expect(chartlet.property('foo')).to.be.a('Function'); + expect(chartlet.property('foo')()).to.equal(1); + chartlet.property('bar', function(){ return 100; }); + expect(chartlet.property('bar')).to.be.a('Function'); + expect(chartlet.property('bar')()).to.equal(100); + }); + it('should overwrite previous value when set property with the same name', function(){ + chartlet.property('foo', 1); + expect(chartlet.property('foo')()).to.equal(1); + chartlet.property('foo', 100); + expect(chartlet.property('foo')()).to.equal(100); + }); + }); + }); + + describe('#on(eventName, listener)', function(){ + it('event "enterDone" should be triggered after chartlet.enter() is completed.', function(done){ + chartlet.on('enterDone', function(){ return (sel: d3.Selection) => {done();} }); + chartlet.enter(); + }); + it('event "updateDone" should be triggered after chartlet.update() is completed.', function(done){ + chartlet.on('updateDone', function(){ return (sel: d3.Selection) => {done();} }); + chartlet.update(); + }); + it('event "exitDone" should be triggered after chartlet.exit() is completed.', function(done){ + chartlet.on('exitDone', function(){ return (sel: d3.Selection) => {done();} }); + chartlet.exit(); + }); + }); + + describe('#inheritPropertyFrom(parentChartlet, parentPropertyName, childPropertyName)', function(){ + it('it should cause a child to inherit a parent property', function() { + var parent = ParentChartlet(function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertyFrom(parent, 'foo', 'bar'); + }) + .property('foo', function(d:number) {return 2 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('bar', 4, 0)).to.be.equal(8); + }); + }); + + it('it should default to the parent property name', function() { + var parent = ParentChartlet( + function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertyFrom(parent, 'foo'); + }) + .property('foo', function(d:number) {return 2 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('foo', 4, 0)).to.be.equal(8); + }); + }); + }); + + describe('#inheritProperties(parentChartlet, parentPropertyNames, childPropertyNames)', function(){ + it('it should cause a child to inherit many parent properties', function() { + var parent = ParentChartlet( + function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertiesFrom(parent, ['foo', 'bar', 'baz'], ['foo-x', 'bar-x', 'baz-x']); + }) + .property('foo', function(d:number) {return 2 * d;}) + .property('bar', function(d:number) {return 3 * d;}) + .property('baz', function(d:number) {return 4 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('foo-x', 1, 0)).to.be.equal(2); + expect(child.getPropertyValue('bar-x', 1, 0)).to.be.equal(3); + expect(child.getPropertyValue('baz-x', 1, 0)).to.be.equal(4); + }); + }); + + it('it should default to the parent property names', function() { + var parent = ParentChartlet( + function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertiesFrom(parent, ['foo', 'bar', 'baz']); + }) + .property('foo', function(d:number) {return 2 * d;}) + .property('bar', function(d:number) {return 3 * d;}) + .property('baz', function(d:number) {return 4 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('foo', 1, 0)).to.be.equal(2); + expect(child.getPropertyValue('bar', 1, 0)).to.be.equal(3); + expect(child.getPropertyValue('baz', 1, 0)).to.be.equal(4); + }); + }); + }); + + describe('#publishEventsTo(foreignDispatcher)', function(){ + it('should map events to a foreignDispatcher', function(done) { + + var parent = new d3kit.Chartlet(callback, callback, callback, ['foo']); + parent.getDispatcher().on('foo', function(value:number) { + expect(value).to.be.equal(99); + done(); + }); + + var child = new d3kit.Chartlet(callback, callback, callback, ['foo']) + .publishEventsTo(parent.getDispatcher()); + + (child.getDispatcher()).foo(99); + }); + }); +}); + +describe('#createChart', function(){ + var Chart = d3kit.factory.createChart({}, ['test'], function(skeleton: d3kit.Skeleton){ + return skeleton; + }); + + it('should return a function to create a chart', function(){ + expect(Chart).to.be.a('Function'); + }); + + // // Don't think it's possible to define these in a d.ts file; skipping + // it('results should have function getCustomEvents()', function(){ + // expect(Chart.getCustomEvents).to.exist; + // expect(Chart.getCustomEvents()).to.deep.equal(['test']); + // }); +}); + +describe('d3kit.helper', function(){ + + describe('#dasherize(str)', function(){ + it('should convert input to dash-case', function(){ + expect(d3kit.helper.dasherize('camelCase')).to.equal('camel-case'); + }); + }); + + describe('#deepExtend(target, src1, src2, ...)', function(){ + it('should copy fields from sources into target', function(){ + expect(d3kit.helper.deepExtend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + })).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + + expect(d3kit.helper.deepExtend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + }, null)).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + }); + + it('should copy arrays and functions correctly from sources into target', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.deepExtend({}, { + a: fn1, + b: [1,2] + },{ + b: [3,4], + c: fn2 + })).to.deep.equal({ + a: fn1, + b: [3,4], + c: fn2 + }); + }); + + it('should perform "deep" copy', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.deepExtend({}, { + a: { d: fn1 }, + b: [1,2], + c: { f: 3 }, + h: { i: [1,2,3], j: [3,4,5] } + },{ + a: { e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } + })).to.deep.equal({ + a: { d: fn1, e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], j: [3,4,5], k: [3,4,5], l: {m: 2} } + }); + }); + }); + + describe('#extend(target, src1, src2, ...)', function(){ + it('should copy fields from sources into target', function(){ + expect(d3kit.helper.extend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + })).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + + expect(d3kit.helper.extend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + }, null)).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + }); + + it('should copy arrays and functions correctly from sources into target', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.extend({}, { + a: fn1, + b: [1,2] + },{ + b: [3,4], + c: fn2 + })).to.deep.equal({ + a: fn1, + b: [3,4], + c: fn2 + }); + }); + + it('should NOT perform "deep" copy', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.extend({}, { + a: { d: fn1 }, + b: [1,2], + c: { f: 3 }, + h: { i: [1,2,3], j: [3,4,5] } + },{ + a: { e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } + })).to.deep.equal({ + a: { e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } + }); + }); + }); + + describe('#isFunction(function)', function(){ + it('should return true if the value is a function', function(){ + var fn1 = function(d:number){return d + 1;}; + function fn2(d:number){return d + 2;} + + expect(d3kit.helper.isFunction(fn1)).to.be.true; + expect(d3kit.helper.isFunction(fn2)).to.be.true; + }); + it('should return false if the value is not a function', function(){ + expect(d3kit.helper.isFunction(0)).to.be.false; + expect(d3kit.helper.isFunction(1)).to.be.false; + expect(d3kit.helper.isFunction(true)).to.be.false; + expect(d3kit.helper.isFunction('what')).to.be.false; + expect(d3kit.helper.isFunction(null)).to.be.false; + expect(d3kit.helper.isFunction(undefined)).to.be.false; + }); + }); + + describe('#isNumber(value)', function(){ + it('should return true for number', function(){ + expect(d3kit.helper.isNumber(1)).to.be.true; + expect(d3kit.helper.isNumber(0)).to.be.true; + expect(d3kit.helper.isNumber(-1)).to.be.true; + }); + it('should return false for string even if it is a number', function(){ + expect(d3kit.helper.isNumber('')).to.be.false; + expect(d3kit.helper.isNumber('1')).to.be.false; + expect(d3kit.helper.isNumber('0')).to.be.false; + expect(d3kit.helper.isNumber('what')).to.be.false; + }); + it('should return false for null and undefined', function(){ + expect(d3kit.helper.isNumber(null)).to.be.false; + expect(d3kit.helper.isNumber(undefined)).to.be.false; + }); + }); +}); + diff --git a/d3kit/d3kit.d.ts b/d3kit/d3kit-v1.1.0.d.ts similarity index 100% rename from d3kit/d3kit.d.ts rename to d3kit/d3kit-v1.1.0.d.ts diff --git a/d3kit/index.d.ts b/d3kit/index.d.ts new file mode 100644 index 0000000000..18adf3c6c0 --- /dev/null +++ b/d3kit/index.d.ts @@ -0,0 +1,115 @@ +// Type definitions for d3Kit v3.1.2 +// Project: https://github.com/twitter/d3kit +// Definitions by: Morgan Benton +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export as namespace d3kit; + +export class AbstractChart { + container: Element; + constructor(selector: string|Element, options?: ChartOptions); + static getDefaultOptions(): ChartOptions; + static getCustomEventNames(): string[]; + setupDispatcher(customEventNames?: string[]): void; + getCustomEventNames(): string[]; + getInnerWidth(): number; + getInnerHeight(): number; + width(value: number): this; + width(): number; + height(value: number): this; + height(): number; + dimension(dimensions: [number, number]): this; + dimension(): [number, number]; + data(data: any): this; + data(): any; + margin(margins: ChartMargin): this; + margin(): ChartMargin; + offset(offset: ChartOffset): this; + offset(): ChartOffset; + options(options: ChartOptions): this; + options(): ChartOptions; + updateDimensionNow(): this; + hasData(): boolean; + hasNonZeroArea(): boolean; + fit(fitOptions: FitOptions, watchOptions?: WatchOptions): this; + stopFitWatcher(): this; + on(name: string, listener: () => void): this; + off(name: string): this; + destroy(): void; +} + +export interface ChartMargin { + top?: number; + right?: number; + bottom?: number; + left?: number; +} + +export interface ChartOffset { + x: number; + y: number; +} + +export interface ChartOptions { + initialWidth?: number; + initialHeight?: number; + margin?: ChartMargin; + offset?: ChartOffset; + pixelRatio?: number; +} + +// from https://github.com/kristw/slimfit +export interface FitOptions { + mode?: string; + width?: string|number; + height?: string|number; + ratio?: number; + maxWidth?: string|number; + maxHeight?: string|number; +} + +// from https://github.com/kristw/slimfit +export interface WatchOptions { + mode?: string; + target?: any; // lazy + interval?: number; +} + +export class SvgChart extends AbstractChart { + svg: d3.Selection; + rootG: d3.Selection; + layers: LayerOrganizer; + constructor(selector: string|Element, options?: ChartOptions); +} + +export class CanvasChart extends AbstractChart { + constructor(selector: string|Element, options?: ChartOptions); + static getDefaultOptions(): ChartOptions; + getContext2d(): CanvasRenderingContext2D; + clear(): this; +} + +export class LayerOrganizer { + constructor(container: d3.Selection, defaultTag?: string); + create(layerNames: string|Array|LayerConfig|Array): d3.Selection|Array>; + get(name: string): d3.Selection; + has(name: string): boolean; +} + +export interface LayerConfig { + [layerName: string]: string|string[]|LayerConfig|Array; +} + +export namespace helper { + function debounce(fn: (...args: Array) => void, delay: number): (...args: Array) => void; + function deepExtend(dest: Object, ...args: Object[]): Object; + function extend(dest: Object, ...args: Object[]): Object; + function functor(value: any): (...args: Array) => any; + function rebind(target: Object, source: Object): Object; + function isFunction(value: any): boolean; + function isObject(value: any): boolean; + function kebabCase(str: string): string; + function throttle(fn: (...args: Array) => void, delay: number): (...args: Array) => void; +} diff --git a/d3kit/package.json b/d3kit/package.json index 5e771f4dcd..8eabdc01d2 100644 --- a/d3kit/package.json +++ b/d3kit/package.json @@ -1,5 +1,5 @@ { "dependencies": { - "@types/d3": "^3.5.36" + "@types/d3": "^4.2.38" } } diff --git a/d3kit/tsconfig.json b/d3kit/tsconfig.json index 1937b920e2..ba1073cccf 100644 --- a/d3kit/tsconfig.json +++ b/d3kit/tsconfig.json @@ -6,7 +6,6 @@ "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ - "node_modules/@types", "../" ], "types": [], @@ -14,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "d3kit.d.ts", + "index.d.ts", "d3kit-tests.ts" ] } diff --git a/dat-gui/index.d.ts b/dat-gui/index.d.ts index 7d1e2147d7..a38699e0bb 100644 --- a/dat-gui/index.d.ts +++ b/dat-gui/index.d.ts @@ -43,20 +43,15 @@ declare namespace dat { updateDisplay(): void; // gui properties in dat/gui/GUI.js - parent(): GUI; - scrollable(): boolean; - autoPlace(): boolean; - preset(): string; - preset(s: string): void; - width(): number; - width(n: number): void; - name(): string; - name(s: string): void; - closed(): boolean; - closed(b: boolean): void; - load(): Object; - useLocalStorage(): boolean; - useLocalStorage(b: boolean): void; + readonly parent: GUI; + readonly scrollable: boolean; + readonly autoPlace: boolean; + preset: string; + width: number; + name: string; + closed: boolean; + readonly load: Object; + useLocalStorage: boolean; } export interface GUIParams{ diff --git a/daterangepicker/daterangepicker-tests.ts b/daterangepicker/daterangepicker-tests.ts index 0b8051b06a..38264bb0b3 100644 --- a/daterangepicker/daterangepicker-tests.ts +++ b/daterangepicker/daterangepicker-tests.ts @@ -1,4 +1,3 @@ -/// import moment = require("moment") function tests_simple() { diff --git a/daterangepicker/daterangepicker.d.ts b/daterangepicker/index.d.ts similarity index 98% rename from daterangepicker/daterangepicker.d.ts rename to daterangepicker/index.d.ts index 88cce7c0a2..68ae67c485 100644 --- a/daterangepicker/daterangepicker.d.ts +++ b/daterangepicker/index.d.ts @@ -167,6 +167,5 @@ declare namespace daterangepicker { } } -declare module "daterangepicker" { - export = daterangepicker; -} +export = daterangepicker; +export as namespace daterangepicker; diff --git a/daterangepicker/tsconfig.json b/daterangepicker/tsconfig.json index cbf48c5f61..77e00d0845 100644 --- a/daterangepicker/tsconfig.json +++ b/daterangepicker/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "daterangepicker.d.ts", + "index.d.ts", "daterangepicker-tests.ts" ] } \ No newline at end of file diff --git a/db.js/db.js-tests.ts b/db.js/db.js-tests.ts index e7fb297aed..169d5725d1 100644 --- a/db.js/db.js-tests.ts +++ b/db.js/db.js-tests.ts @@ -1,4 +1,4 @@ -// Test file for db.js Definition file +import db = require("db.js"); /* Type for use in tests */ diff --git a/db.js/index.d.ts b/db.js/index.d.ts index 83e21fa529..fa962dc0a3 100644 --- a/db.js/index.d.ts +++ b/db.js/index.d.ts @@ -7,7 +7,7 @@ declare module DbJs { interface ErrorListener { (err: Error): void; } - + interface OpenOptions { server: string; version: number; @@ -29,14 +29,14 @@ declare module DbJs { interface CountableQuery { count(): ExecutableQuery; } - + interface KeysQuery extends DescableQuery, ExecutableQuery, FilterableQuery, DistinctableQuery, MappableQuery { - } + } interface KeyableQuery { keys(): KeysQuery; } - + interface FilterQuery extends KeyableQuery, ExecutableQuery, FilterableQuery, DescableQuery, DistinctableQuery, ModifiableQuery, LimitableQuery, MappableQuery { } @@ -44,14 +44,14 @@ declare module DbJs { filter(index: string, value: TValue): FilterQuery; filter(filter: (value: T) => boolean): FilterQuery; } - - interface DescQuery extends KeyableQuery, CountableQuery, ExecutableQuery, FilterableQuery, DescableQuery, ModifiableQuery, MappableQuery { + + interface DescQuery extends KeyableQuery, CountableQuery, ExecutableQuery, FilterableQuery, DescableQuery, ModifiableQuery, MappableQuery { } interface DescableQuery { desc(): DescQuery; } - + interface DistinctQuery extends KeyableQuery, ExecutableQuery, FilterableQuery, DescableQuery, ModifiableQuery, MappableQuery, CountableQuery { } @@ -71,7 +71,7 @@ declare module DbJs { interface MappableQuery { map(fn: (value: T) => TMap): Query; } - + interface Query extends Promise, KeyableQuery, ExecutableQuery, FilterableQuery, DescableQuery, DistinctableQuery, ModifiableQuery, LimitableQuery, MappableQuery, CountableQuery { } @@ -93,11 +93,11 @@ declare module DbJs { getIndexedDB(): IDBDatabase; close(): void; } - + interface IndexAccessibleServer { [store: string]: TypedObjectStoreServer; } - + interface ObjectStoreServer { add(table: string, entity: T): Promise; add(table: string, ...entities: T[]): Promise; @@ -142,11 +142,11 @@ declare module DbJs { query(index: string): IndexQuery; count(key: any): Promise; } - + type Server = DbJs.IndexAccessibleServer & DbJs.ObjectStoreServer & DbJs.BaseServer; } -declare module "db" { +declare module "db.js" { var db: DbJs.DbJsStatic; export = db; } diff --git a/dc/dc-1.6.0.d.ts b/dc/dc-1.6.0.d.ts index 03b5e9039b..9938d3bc45 100644 --- a/dc/dc-1.6.0.d.ts +++ b/dc/dc-1.6.0.d.ts @@ -58,7 +58,15 @@ export interface ILegendwidget { export var events: IEvents; export interface IListener { - on: (eventName: string, fnctn: (c:T) => void) => T; + on: { + (event: "preRender", fnctn: (c: T) => any): T; + (event: "postRender", fnctn: (c: T) => any): T; + (event: "preRedraw", fnctn: (c: T) => any): T; + (event: "postRedraw", fnctn: (c: T) => any): T; + (event: "filtered", fnctn: (c: T, filter: any) => any): T; + (event: "zoomed", fnctn: (c: T, filter: any) => any): T; + (event: string, fnctn: (c: T, ...args: any[]) => any): T; + }; } export interface ImarginObj { diff --git a/dc/index.d.ts b/dc/index.d.ts index ffea80fa05..b0291d703c 100644 --- a/dc/index.d.ts +++ b/dc/index.d.ts @@ -160,7 +160,16 @@ declare namespace DC { legend: IGetSet; options(optionsObject: any): T; renderlet(fn: (chart: T) => any): T; - on(event: string, fn: (chart: T) => any): T; + + on(event: "renderlet", fn: (chart: T, filter: any) => any): T; + on(event: "pretransition", fn: (chart: T, filter: any) => any): T; + on(event: "preRender", fn: (chart: T) => any): T; + on(event: "postRender", fn: (chart: T) => any): T; + on(event: "preRedraw", fn: (chart: T) => any): T; + on(event: "postRedraw", fn: (chart: T) => any): T; + on(event: "filtered", fn: (chart: T, filter: any) => any): T; + on(event: "zoomed", fn: (chart: T, filter: any) => any): T; + on(event: string, fn: (chart: T, ...args: any[]) => any): T; } export interface Margins { diff --git a/df-visible/df-visible-tests.ts b/df-visible/df-visible-tests.ts index c5a8f1bf2b..b4fe92fdf3 100644 --- a/df-visible/df-visible-tests.ts +++ b/df-visible/df-visible-tests.ts @@ -1,5 +1,3 @@ -/// - // https://github.com/customd/jquery-visible/blob/master/examples/demo-basic.html $(function(){ diff --git a/df-visible/df-visible.d.ts b/df-visible/index.d.ts similarity index 100% rename from df-visible/df-visible.d.ts rename to df-visible/index.d.ts diff --git a/df-visible/tsconfig.json b/df-visible/tsconfig.json index 49c372fd65..93d23458ce 100644 --- a/df-visible/tsconfig.json +++ b/df-visible/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "df-visible.d.ts", + "index.d.ts", "df-visible-tests.ts" ] } \ No newline at end of file diff --git a/dva/dva.d.ts b/dva/index.d.ts similarity index 100% rename from dva/dva.d.ts rename to dva/index.d.ts diff --git a/dva/tsconfig.json b/dva/tsconfig.json index 8c73ec457e..b9093241bb 100644 --- a/dva/tsconfig.json +++ b/dva/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "dva.d.ts", + "index.d.ts", "dva-tests.tsx" ] } \ No newline at end of file diff --git a/elasticsearch/elasticsearch-tests.ts b/elasticsearch/elasticsearch-tests.ts index 62e45dfd58..c9be3c01ef 100644 --- a/elasticsearch/elasticsearch-tests.ts +++ b/elasticsearch/elasticsearch-tests.ts @@ -46,12 +46,12 @@ client.create({ }); client.cluster.getSettings({ - masterTimeout: 100 + masterTimeout: '100s' }, (err, response) => { }); client.cluster.health({ - masterTimeout: 100 + masterTimeout: '100s' }, (err, response) => { }); @@ -208,6 +208,33 @@ client.suggest({ }, function (error, response) { }); + +// first we do a search, and specify a scroll timeout +var allTitles: string[] = []; +client.search({ + index: 'myindex', + // Set to 30 seconds because we are calling right back + scroll: '30s', + searchType: 'query_then_fetch', + docvalueFields: ['title'], + q: 'title:test' +}, function getMoreUntilDone(error, response) { + // collect the title from each response + response.hits.hits.forEach(function (hit) { + allTitles.push(hit.fields.title); + }); + + if (response.hits.total !== allTitles.length) { + // now we can call scroll over and over + client.scroll({ + scrollId: response._scroll_id, + scroll: '30s' + }, getMoreUntilDone); + } else { + console.log('every "test" title', allTitles); + } +}); + client.indices.updateAliases({ body: { actions: [ diff --git a/elasticsearch/index.d.ts b/elasticsearch/index.d.ts index d7df27565f..f3ac0992c6 100644 --- a/elasticsearch/index.d.ts +++ b/elasticsearch/index.d.ts @@ -131,8 +131,14 @@ declare module Elasticsearch { failed: number; } + /** + * A string of a number and a time unit. A time unit is one of + * [d, h, m, s, ms, micros, nanos]. eg: "30s" for 30 seconds. + * These are incorrectly identified as `Date | number` in the docs as of 2016-11-15. + */ + export type TimeSpan = string; + export type NameList = string | string[] | boolean; - export type DateLike = Date | number; export type Refresh = boolean | "true" | "false" | "wait_for" | ""; export type VersionType = "internal" | "external" | "external_gte" | "force"; export type ExpandWildcards = "open" | "closed" | "none" | "all"; @@ -142,7 +148,7 @@ declare module Elasticsearch { waitForActiveShards?: string; refresh?: Refresh; routing?: string; - timeout?: DateLike; + timeout?: TimeSpan; type?: string; fields?: NameList; _source?: NameList; @@ -183,9 +189,9 @@ declare module Elasticsearch { waitForActiveShards?: string; parent?: string; refresh?: Refresh; - timeout?: DateLike; - timestamp?: DateLike; - ttl?: DateLike; + timeout?: TimeSpan; + timestamp?: Date | number; + ttl?: TimeSpan; version?: number; versionType?: VersionType; pipeline?: string; @@ -209,7 +215,7 @@ declare module Elasticsearch { parent?: string; refresh?: Refresh; routing?: string; - timeout?: DateLike; + timeout?: TimeSpan; version?: number; versionType?: VersionType; index: string; @@ -232,7 +238,7 @@ declare module Elasticsearch { parent?: string; refresh?: Refresh; routing?: string; - timeout?: DateLike; + timeout?: TimeSpan; version?: number; versionType?: VersionType; index: string; @@ -399,9 +405,9 @@ declare module Elasticsearch { parent?: string; refresh?: string; routing?: string; - timeout?: DateLike; - timestamp?: DateLike; - ttl?: DateLike; + timeout?: TimeSpan; + timestamp?: Date | number; + ttl?: TimeSpan; version?: number; versionType?: VersionType; pipeline?: string; @@ -481,7 +487,7 @@ declare module Elasticsearch { export interface ReindexParams extends GenericParams { refresh?: boolean; - timeout?: DateLike; + timeout?: TimeSpan; waitForActiveShards?: string; waitForCompletion?: boolean; requestsPerSecond?: number; @@ -537,7 +543,7 @@ declare module Elasticsearch { } export interface ScrollParams extends GenericParams { - scroll: DateLike; + scroll: TimeSpan; scrollId: string; } @@ -559,7 +565,7 @@ declare module Elasticsearch { preference?: string; q?: string; routing?: NameList; - scroll?: DateLike; + scroll?: TimeSpan; searchType?: "query_then_fetch" | "dfs_query_then_fetch"; size?: number; sort?: NameList; @@ -572,7 +578,7 @@ declare module Elasticsearch { suggestMode?: "missing" | "popular" | "always"; suggestSize?: number; suggestText?: string; - timeout?: DateLike; + timeout?: TimeSpan; trackScores?: boolean; version?: boolean; requestCache?: boolean; @@ -638,7 +644,7 @@ declare module Elasticsearch { expandWildcards?: ExpandWildcards; preference?: string; routing?: NameList; - scroll?: DateLike; + scroll?: TimeSpan; searchType?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; index: NameList; type: NameList; @@ -682,9 +688,9 @@ declare module Elasticsearch { refresh?: Refresh; retryOnConflict?: number; routing?: string; - timeout?: DateLike; - timestamp?: DateLike; - ttl?: DateLike; + timeout?: TimeSpan; + timestamp?: Date | number; + ttl?: TimeSpan; version?: number; versionType?: "internal" | "force"; id: string; @@ -712,9 +718,9 @@ declare module Elasticsearch { preference?: string; q?: string; routing?: NameList; - scroll?: DateLike; + scroll?: TimeSpan; searchType?: "query_then_fetch" | "dfs_query_then_fetch"; - searchTimeout?: DateLike; + searchTimeout?: TimeSpan; size?: number; sort?: NameList; _source?: NameList; @@ -726,7 +732,7 @@ declare module Elasticsearch { suggestMode?: "missing" | "popular" | "always"; suggestSize?: number; suggestText?: string; - timeout?: DateLike; + timeout?: TimeSpan; trackScores?: boolean; version?: boolean; versionType?: boolean; @@ -786,7 +792,7 @@ declare module Elasticsearch { export interface CatCommonParams extends GenericParams { format: string; local?: boolean; - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; h?: NameList; help?: boolean; v?: boolean; @@ -828,7 +834,7 @@ declare module Elasticsearch { export interface CatRecoveryParams extends GenericParams { format: string; bytes?: CatBytes; - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; h?: NameList; help?: boolean; v?: boolean; @@ -849,7 +855,7 @@ declare module Elasticsearch { export interface CatSnapshotsParams extends GenericParams { format: string; ignoreUnavailable?: boolean; - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; h?: NameList; help?: boolean; v?: boolean; @@ -899,15 +905,15 @@ declare module Elasticsearch { export interface ClusterGetSettingsParams extends GenericParams { flatSettings?: boolean; - masterTimeout?: DateLike; - timeout?: DateLike; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; includeDefaults?: boolean; } export interface ClusterHealthParams extends GenericParams { level?: "cluster" | "indices" | "shards"; local?: boolean; - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; waitForActiveShards?: string; waitForNodes?: string; waitForEvents?: "immediate" | "urgent" | "high" | "normal" | "low" | "languid"; @@ -918,13 +924,13 @@ declare module Elasticsearch { export interface ClusterPendingTasksParams extends GenericParams { local?: boolean; - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; } export interface ClusterPutSettingsParams extends GenericParams { flatSettings?: boolean; - masterTimeout?: DateLike; - timeout?: DateLike; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; } export interface ClusterRerouteParams extends GenericParams { @@ -932,13 +938,13 @@ declare module Elasticsearch { explain?: boolean; retryFailed?: boolean; metric?: NameList; - masterTimeout?: DateLike; - timeout?: DateLike; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; } export interface ClusterStateParams extends GenericParams { local?: boolean; - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; flatSettings?: boolean; ignoreUnavailable?: boolean; allowNoIndices?: boolean; @@ -950,7 +956,7 @@ declare module Elasticsearch { export interface ClusterStatsParams extends GenericParams { flatSettings?: boolean; human?: boolean; - timeout?: DateLike; + timeout?: TimeSpan; nodeId?: NameList; } @@ -1057,8 +1063,8 @@ declare module Elasticsearch { } export interface IndicesCloseParams extends GenericParams { - timeout?: DateLike; - masterTimeout?: DateLike; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; @@ -1067,28 +1073,28 @@ declare module Elasticsearch { export interface IndicesCreateParams extends GenericParams { waitForActiveShards?: string; - timeout?: DateLike; - masterTimeout?: DateLike; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; updateAllTypes?: boolean; index: string; } export interface IndicesDeleteParams extends GenericParams { - timeout?: DateLike; - masterTimeout?: DateLike; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; index: NameList; } export interface IndicesDeleteAliasParams extends GenericParams { - timeout?: DateLike; - masterTimeout?: DateLike; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; index: NameList; name: NameList; } export interface IndicesDeleteTemplateParams extends GenericParams { - timeout?: DateLike; - masterTimeout?: DateLike; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; name: string; } @@ -1105,8 +1111,8 @@ declare module Elasticsearch { } export interface IndicesExistsTemplateParams extends GenericParams { - timeout?: DateLike; - masterTimeout?: DateLike; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; name: NameList; } @@ -1197,7 +1203,7 @@ declare module Elasticsearch { export interface IndicesGetTemplateParams extends GenericParams { flatSettings?: boolean; - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; local?: boolean; name?: NameList; } @@ -1211,8 +1217,8 @@ declare module Elasticsearch { } export interface IndicesOpenParams extends GenericParams { - timeout?: DateLike; - masterTimeout?: DateLike; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; @@ -1220,15 +1226,15 @@ declare module Elasticsearch { } export interface IndicesPutAliasParams extends GenericParams { - timeout?: DateLike; - masterTimeout?: DateLike; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; index?: NameList; name: NameList; } export interface IndicesPutMappingParams extends GenericParams { - timeout?: DateLike; - masterTimeout?: DateLike; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; ignoreUnavailable?: boolean; allowNoIndices?: boolean; expandWildcards?: ExpandWildcards; @@ -1239,7 +1245,7 @@ declare module Elasticsearch { } export interface IndicesPutSettingsParams extends GenericParams { - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; preserveExisting?: boolean; ignoreUnavailable?: boolean; allowNoIndices?: boolean; @@ -1252,8 +1258,8 @@ declare module Elasticsearch { export interface IndicesPutTemplateParams extends GenericParams { order?: number; create?: boolean; - timeout?: DateLike; - masterTimeout?: DateLike; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; flatSettings?: boolean; name: string; body: any; @@ -1276,8 +1282,8 @@ declare module Elasticsearch { } export interface IndicesRolloverParams extends GenericParams { - timeout?: DateLike; - masterTimeout?: DateLike; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; waitForActiveShards?: number | string; alias?: string; newIndex?: string; @@ -1313,8 +1319,8 @@ declare module Elasticsearch { } export interface IndicesShrinkParams extends GenericParams { - timeout?: DateLike; - masterTimeout?: DateLike; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; waitForActiveShards?: string | number; index: string; target: string; @@ -1333,8 +1339,8 @@ declare module Elasticsearch { } export interface IndicesUpdateAliasesParams extends GenericParams { - timeout?: DateLike; - masterTimeout?: DateLike; + timeout?: TimeSpan; + masterTimeout?: TimeSpan; body: { actions: IndicesUpdateAliasesParamsAction[]; } @@ -1426,19 +1432,19 @@ declare module Elasticsearch { } export interface NodesHotThreadsParams extends GenericParams { - interval?: DateLike; + interval?: TimeSpan; snapshots?: number; threads?: number; ignoreIdleThreads?: boolean; type?: "cpu" | "wait" | "blocked"; - timeout?: DateLike; + timeout?: TimeSpan; nodeId: NameList; } export interface NodesInfoParams extends GenericParams { flatSettings?: boolean; human?: boolean; - timeout?: DateLike; + timeout?: TimeSpan; nodeId: NameList; metric?: NameList; } @@ -1451,7 +1457,7 @@ declare module Elasticsearch { human?: boolean; level?: "indices" | "node" | "shards"; types?: NameList; - timeout?: DateLike; + timeout?: TimeSpan; metric?: NameList; indexMetric?: NameList; nodeId?: NameList; @@ -1479,61 +1485,61 @@ declare module Elasticsearch { } export interface SnapshotCreateParams extends GenericParams { - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; waitForCompletion?: boolean; repository: string; snapshot: string; } export interface SnapshotCreateRepositoryParams extends GenericParams { - masterTimeout?: DateLike; - timeout?: DateLike; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; verify?: boolean; repository: string; } export interface SnapshotDeleteParams extends GenericParams { - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; repository: string; snapshot: string; } export interface SnapshotDeleteRepositoryParams extends GenericParams { - masterTimeout?: DateLike; - timeout?: DateLike; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; repository: string; } export interface SnapshotGetParams extends GenericParams { - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; ignoreUnavailable?: boolean; repository: string; snapshot: NameList; } export interface SnapshotGetRepositoryParams extends GenericParams { - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; local?: boolean; repository: NameList; } export interface SnapshotRestoreParams extends GenericParams { - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; waitForCompletion?: boolean; repository: string; snapshot: string; } export interface SnapshotStatusParams extends GenericParams { - masterTimeout?: DateLike; + masterTimeout?: TimeSpan; ignoreUnavailable?: boolean; repository: string; snapshot: NameList; } export interface SnapshotVerifyRepositoryParams extends GenericParams { - masterTimeout?: DateLike; - timeout?: DateLike; + masterTimeout?: TimeSpan; + timeout?: TimeSpan; repository: string; } diff --git a/electron/electron-tests.ts b/electron/electron-tests.ts new file mode 100644 index 0000000000..00b34d60b1 --- /dev/null +++ b/electron/electron-tests.ts @@ -0,0 +1,7 @@ +/// +/// + +import electron = require('electron'); +import child_process = require('child_process'); + +child_process.spawn(electron); diff --git a/electron/github-electron.d.ts b/electron/github-electron.d.ts new file mode 100644 index 0000000000..f87b50b362 --- /dev/null +++ b/electron/github-electron.d.ts @@ -0,0 +1,5765 @@ +// Type definitions for Electron v1.4.4 +// Project: http://electron.atom.io/ +// Definitions by: jedmao , rhysd , Milan Burda +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace Electron { + + interface Event { + preventDefault: Function; + sender: NodeJS.EventEmitter; + } + + type Point = { + x: number; + y: number; + } + + type Size = { + width: number; + height: number; + } + + type Rectangle = { + x: number; + y: number; + width: number; + height: number; + } + + interface Destroyable { + /** + * Destroys the object. + */ + destroy(): void; + /** + * @returns Whether the object is destroyed. + */ + isDestroyed(): boolean; + } + + // https://github.com/electron/electron/blob/master/docs/api/app.md + + /** + * The app module is responsible for controlling the application's lifecycle. + */ + interface App extends NodeJS.EventEmitter { + /** + * Emitted when the application has finished basic startup. + * On Windows and Linux, the will-finish-launching event + * is the same as the ready event; on macOS, this event represents + * the applicationWillFinishLaunching notification of NSApplication. + * You would usually set up listeners for the open-file and open-url events here, + * and start the crash reporter and auto updater. + * + * In most cases, you should just do everything in the ready event handler. + */ + on(event: 'will-finish-launching', listener: Function): this; + /** + * Emitted when Electron has finished initialization. + */ + on(event: 'ready', listener: (event: Event, launchInfo: Object) => void): this; + /** + * Emitted when all windows have been closed. + * + * If you do not subscribe to this event and all windows are closed, + * the default behavior is to quit the app; however, if you subscribe, + * you control whether the app quits or not. + * If the user pressed Cmd + Q, or the developer called app.quit(), + * Electron will first try to close all the windows and then emit the will-quit event, + * and in this case the window-all-closed event would not be emitted. + */ + on(event: 'window-all-closed', listener: Function): this; + /** + * Emitted before the application starts closing its windows. + * Calling event.preventDefault() will prevent the default behaviour, which is terminating the application. + */ + on(event: 'before-quit', listener: (event: Event) => void): this; + /** + * Emitted when all windows have been closed and the application will quit. + * Calling event.preventDefault() will prevent the default behaviour, which is terminating the application. + */ + on(event: 'will-quit', listener: (event: Event) => void): this; + /** + * Emitted when the application is quitting. + */ + on(event: 'quit', listener: (event: Event, exitCode: number) => void): this; + /** + * Emitted when the user wants to open a file with the application. + * The open-file event is usually emitted when the application is already open + * and the OS wants to reuse the application to open the file. + * open-file is also emitted when a file is dropped onto the dock and the application + * is not yet running. Make sure to listen for the open-file event very early + * in your application startup to handle this case (even before the ready event is emitted). + * + * You should call event.preventDefault() if you want to handle this event. + * + * Note: This is only implemented on macOS. + */ + on(event: 'open-file', listener: (event: Event, url: string) => void): this; + /** + * Emitted when the user wants to open a URL with the application. + * The URL scheme must be registered to be opened by your application. + * + * You should call event.preventDefault() if you want to handle this event. + * + * Note: This is only implemented on macOS. + */ + on(event: 'open-url', listener: (event: Event, url: string) => void): this; + /** + * Emitted when the application is activated, which usually happens when clicks on the applications’s dock icon. + * Note: This is only implemented on macOS. + */ + on(event: 'activate', listener: Function): this; + /** + * Emitted during Handoff when an activity from a different device wants to be resumed. + * You should call event.preventDefault() if you want to handle this event. + */ + on(event: 'continue-activity', listener: (event: Event, type: string, userInfo: Object) => void): this; + /** + * Emitted when a browserWindow gets blurred. + */ + on(event: 'browser-window-blur', listener: (event: Event, browserWindow: BrowserWindow) => void): this; + /** + * Emitted when a browserWindow gets focused. + */ + on(event: 'browser-window-focus', listener: (event: Event, browserWindow: BrowserWindow) => void): this; + /** + * Emitted when a new browserWindow is created. + */ + on(event: 'browser-window-created', listener: (event: Event, browserWindow: BrowserWindow) => void): this; + /** + * Emitted when a new webContents is created. + */ + on(event: 'web-contents-created', listener: (event: Event, webContents: WebContents) => void): this; + /** + * Emitted when failed to verify the certificate for url, to trust the certificate + * you should prevent the default behavior with event.preventDefault() and call callback(true). + */ + on(event: 'certificate-error', listener: (event: Event, + webContents: WebContents, + url: string, + error: string, + certificate: Certificate, + callback: (trust: boolean) => void + ) => void): this; + /** + * Emitted when a client certificate is requested. + * + * The url corresponds to the navigation entry requesting the client certificate + * and callback needs to be called with an entry filtered from the list. + * Using event.preventDefault() prevents the application from using the first certificate from the store. + */ + on(event: 'select-client-certificate', listener: (event: Event, + webContents: WebContents, + url: string, + certificateList: Certificate[], + callback: (certificate: Certificate) => void + ) => void): this; + /** + * Emitted when webContents wants to do basic auth. + * + * The default behavior is to cancel all authentications, to override this + * you should prevent the default behavior with event.preventDefault() + * and call callback(username, password) with the credentials. + */ + on(event: 'login', listener: (event: Event, + webContents: WebContents, + request: LoginRequest, + authInfo: LoginAuthInfo, + callback: (username: string, password: string) => void + ) => void): this; + /** + * Emitted when the gpu process crashes. + */ + on(event: 'gpu-process-crashed', listener: (event: Event, killed: boolean) => void): this; + /** + * Emitted when Chrome's accessibility support changes. + * + * Note: This API is only available on macOS and Windows. + */ + on(event: 'accessibility-support-changed', listener: (event: Event, accessibilitySupportEnabled: boolean) => void): this; + on(event: string, listener: Function): this; + /** + * Try to close all windows. The before-quit event will first be emitted. + * If all windows are successfully closed, the will-quit event will be emitted + * and by default the application would be terminated. + * + * This method guarantees all beforeunload and unload handlers are correctly + * executed. It is possible that a window cancels the quitting by returning + * false in beforeunload handler. + */ + quit(): void; + /** + * Exits immediately with exitCode. + * All windows will be closed immediately without asking user + * and the before-quit and will-quit events will not be emitted. + */ + exit(exitCode?: number): void; + /** + * Relaunches the app when current instance exits. + * + * By default the new instance will use the same working directory + * and command line arguments with current instance. + * When args is specified, the args will be passed as command line arguments instead. + * When execPath is specified, the execPath will be executed for relaunch instead of current app. + * + * Note that this method does not quit the app when executed, you have to call app.quit + * or app.exit after calling app.relaunch to make the app restart. + * + * When app.relaunch is called for multiple times, multiple instances + * will be started after current instance exited. + */ + relaunch(options?: { + args?: string[], + execPath?: string + }): void; + /** + * @returns Whether Electron has finished initializing. + */ + isReady(): boolean; + /** + * On Linux, focuses on the first visible window. + * On macOS, makes the application the active app. + * On Windows, focuses on the application’s first window. + */ + focus(): void; + /** + * Hides all application windows without minimizing them. + * Note: This is only implemented on macOS. + */ + hide(): void; + /** + * Shows application windows after they were hidden. Does not automatically focus them. + * Note: This is only implemented on macOS. + */ + show(): void; + /** + * Returns the current application directory. + */ + getAppPath(): string; + /** + * @returns The path to a special directory or file associated with name. + * On failure an Error would throw. + */ + getPath(name: AppPathName): string; + /** + * Overrides the path to a special directory or file associated with name. + * If the path specifies a directory that does not exist, the directory will + * be created by this method. On failure an Error would throw. + * + * You can only override paths of names defined in app.getPath. + * + * By default web pages' cookies and caches will be stored under userData + * directory, if you want to change this location, you have to override the + * userData path before the ready event of app module gets emitted. + */ + setPath(name: AppPathName, path: string): void; + /** + * @returns The version of loaded application, if no version is found in + * application's package.json, the version of current bundle or executable. + */ + getVersion(): string; + /** + * @returns The current application's name, the name in package.json would be used. + * Usually the name field of package.json is a short lowercased name, according to + * the spec of npm modules. So usually you should also specify a productName field, + * which is your application's full capitalized name, and it will be preferred over + * name by Electron. + */ + getName(): string; + /** + * Overrides the current application's name. + */ + setName(name: string): void; + /** + * @returns The current application locale. + */ + getLocale(): string; + /** + * Adds path to recent documents list. + * + * This list is managed by the system, on Windows you can visit the list from + * task bar, and on macOS you can visit it from dock menu. + * + * Note: This is only implemented on macOS and Windows. + */ + addRecentDocument(path: string): void; + /** + * Clears the recent documents list. + * + * Note: This is only implemented on macOS and Windows. + */ + clearRecentDocuments(): void; + /** + * Sets the current executable as the default handler for a protocol (aka URI scheme). + * Once registered, all links with your-protocol:// will be opened with the current executable. + * The whole link, including protocol, will be passed to your application as a parameter. + * + * On Windows you can provide optional parameters path, the path to your executable, + * and args, an array of arguments to be passed to your executable when it launches. + * + * @param protocol The name of your protocol, without ://. + * @param path Defaults to process.execPath. + * @param args Defaults to an empty array. + * + * Note: This is only implemented on macOS and Windows. + * On macOS, you can only register protocols that have been added to your app's info.plist. + */ + setAsDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; + /** + * Removes the current executable as the default handler for a protocol (aka URI scheme). + * + * @param protocol The name of your protocol, without ://. + * @param path Defaults to process.execPath. + * @param args Defaults to an empty array. + * + * Note: This is only implemented on macOS and Windows. + */ + removeAsDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; + /** + * @param protocol The name of your protocol, without ://. + * @param path Defaults to process.execPath. + * @param args Defaults to an empty array. + * + * @returns Whether the current executable is the default handler for a protocol (aka URI scheme). + * + * Note: This is only implemented on macOS and Windows. + */ + isDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; + /** + * Adds tasks to the Tasks category of JumpList on Windows. + * + * Note: This API is only available on Windows. + */ + setUserTasks(tasks: Task[]): boolean; + /** + * Note: This API is only available on Windows. + */ + getJumpListSettings(): JumpListSettings; + /** + * Sets or removes a custom Jump List for the application. + * + * If categories is null the previously set custom Jump List (if any) will be replaced + * by the standard Jump List for the app (managed by Windows). + * + * Note: This API is only available on Windows. + */ + setJumpList(categories: JumpListCategory[]): SetJumpListResult; + /** + * This method makes your application a Single Instance Application instead of allowing + * multiple instances of your app to run, this will ensure that only a single instance + * of your app is running, and other instances signal this instance and exit. + */ + makeSingleInstance(callback: (args: string[], workingDirectory: string) => void): boolean; + /** + * Releases all locks that were created by makeSingleInstance. This will allow + * multiple instances of the application to once again run side by side. + */ + releaseSingleInstance(): void; + /** + * Creates an NSUserActivity and sets it as the current activity. + * The activity is eligible for Handoff to another device afterward. + * + * @param type Uniquely identifies the activity. Maps to NSUserActivity.activityType. + * @param userInfo App-specific state to store for use by another device. + * @param webpageURL The webpage to load in a browser if no suitable app is + * installed on the resuming device. The scheme must be http or https. + * + * Note: This API is only available on macOS. + */ + setUserActivity(type: string, userInfo: Object, webpageURL?: string): void; + /** + * @returns The type of the currently running activity. + * + * Note: This API is only available on macOS. + */ + getCurrentActivityType(): string; + /** + * Changes the Application User Model ID to id. + * + * Note: This is only implemented on Windows. + */ + setAppUserModelId(id: string): void; + /** + * Imports the certificate in pkcs12 format into the platform certificate store. + * @param callback Called with the result of import operation, a value of 0 indicates success + * while any other value indicates failure according to chromium net_error_list. + * + * Note: This API is only available on Linux. + */ + importCertificate(options: ImportCertificateOptions, callback: (result: number) => void): void; + /** + * Disables hardware acceleration for current app. + * This method can only be called before app is ready. + */ + disableHardwareAcceleration(): void; + /** + * @returns whether current desktop environment is Unity launcher. (Linux) + * + * Note: This API is only available on Linux. + */ + isUnityRunning(): boolean; + /** + * Returns a Boolean, true if Chrome's accessibility support is enabled, false otherwise. + * This API will return true if the use of assistive technologies, such as screen readers, + * has been detected. + * See https://www.chromium.org/developers/design-documents/accessibility for more details. + * + * Note: This API is only available on macOS and Windows. + */ + isAccessibilitySupportEnabled(): boolean; + /** + * @returns an Object with the login item settings of the app. + * + * Note: This API is only available on macOS and Windows. + */ + getLoginItemSettings(): LoginItemSettings; + /** + * Set the app's login item settings. + * + * Note: This API is only available on macOS and Windows. + */ + setLoginItemSettings(settings: LoginItemSettings): void; + /** + * Set the about panel options. This will override the values defined in the app's .plist file. + * See the Apple docs for more details. + * + * Note: This API is only available on macOS. + */ + setAboutPanelOptions(options: AboutPanelOptions): void; + commandLine: CommandLine; + /** + * Note: This API is only available on macOS. + */ + dock: Dock; + } + + type AppPathName = 'home'|'appData'|'userData'|'temp'|'exe'|'module'|'desktop'|'documents'|'downloads'|'music'|'pictures'|'videos'|'pepperFlashSystemPlugin'; + + interface ImportCertificateOptions { + /** + * Path for the pkcs12 file. + */ + certificate: string; + /** + * Passphrase for the certificate. + */ + password: string; + } + + interface CommandLine { + /** + * Append a switch [with optional value] to Chromium's command line. + * + * Note: This will not affect process.argv, and is mainly used by developers + * to control some low-level Chromium behaviors. + */ + appendSwitch(_switch: string, value?: string): void; + /** + * Append an argument to Chromium's command line. The argument will quoted properly. + * + * Note: This will not affect process.argv. + */ + appendArgument(value: string): void; + } + + interface Dock { + /** + * When critical is passed, the dock icon will bounce until either the + * application becomes active or the request is canceled. + * + * When informational is passed, the dock icon will bounce for one second. + * However, the request remains active until either the application becomes + * active or the request is canceled. + * + * @param type The default is informational. + * @returns An ID representing the request. + */ + bounce(type?: 'critical' | 'informational'): number; + /** + * Cancel the bounce of id. + * + * Note: This API is only available on macOS. + */ + cancelBounce(id: number): void; + /** + * Bounces the Downloads stack if the filePath is inside the Downloads folder. + * + * Note: This API is only available on macOS. + */ + downloadFinished(filePath: string): void; + /** + * Sets the string to be displayed in the dock’s badging area. + * + * Note: This API is only available on macOS. + */ + setBadge(text: string): void; + /** + * Returns the badge string of the dock. + * + * Note: This API is only available on macOS. + */ + getBadge(): string; + /** + * Sets the counter badge for current app. Setting the count to 0 will hide the badge. + * + * @returns True when the call succeeded, otherwise returns false. + * + * Note: This API is only available on macOS and Linux. + */ + setBadgeCount(count: number): boolean; + /** + * @returns The current value displayed in the counter badge. + * + * Note: This API is only available on macOS and Linux. + */ + getBadgeCount(): number; + /** + * Hides the dock icon. + * + * Note: This API is only available on macOS. + */ + hide(): void; + /** + * Shows the dock icon. + * + * Note: This API is only available on macOS. + */ + show(): void; + /** + * @returns Whether the dock icon is visible. + * The app.dock.show() call is asynchronous so this method might not return true immediately after that call. + * + * Note: This API is only available on macOS. + */ + isVisible(): boolean; + /** + * Sets the application dock menu. + * + * Note: This API is only available on macOS. + */ + setMenu(menu: Menu): void; + /** + * Sets the image associated with this dock icon. + * + * Note: This API is only available on macOS. + */ + setIcon(icon: NativeImage | string): void; + } + + interface Task { + /** + * Path of the program to execute, usually you should specify process.execPath + * which opens current program. + */ + program: string; + /** + * The arguments of command line when program is executed. + */ + arguments: string; + /** + * The string to be displayed in a JumpList. + */ + title: string; + /** + * Description of this task. + */ + description?: string; + /** + * The absolute path to an icon to be displayed in a JumpList, it can be + * arbitrary resource file that contains an icon, usually you can specify + * process.execPath to show the icon of the program. + */ + iconPath: string; + /** + * The icon index in the icon file. If an icon file consists of two or more + * icons, set this value to identify the icon. If an icon file consists of + * one icon, this value is 0. + */ + iconIndex?: number; + } + + /** + * ok - Nothing went wrong. + * error - One or more errors occured, enable runtime logging to figure out the likely cause. + * invalidSeparatorError - An attempt was made to add a separator to a custom category in the Jump List. + * Separators are only allowed in the standard Tasks category. + * fileTypeRegistrationError - An attempt was made to add a file link to the Jump List + * for a file type the app isn't registered to handle. + * customCategoryAccessDeniedError - Custom categories can't be added to the Jump List + * due to user privacy or group policy settings. + */ + type SetJumpListResult = 'ok' | 'error' | 'invalidSeparatorError' | 'fileTypeRegistrationError' | 'customCategoryAccessDeniedError'; + + interface JumpListSettings { + /** + * The minimum number of items that will be shown in the Jump List. + */ + minItems: number; + /** + * Items that the user has explicitly removed from custom categories in the Jump List. + */ + removedItems: JumpListItem[]; + } + + interface JumpListCategory { + /** + * tasks - Items in this category will be placed into the standard Tasks category. + * frequent - Displays a list of files frequently opened by the app, the name of the category and its items are set by Windows. + * recent - Displays a list of files recently opened by the app, the name of the category and its items are set by Windows. + * custom - Displays tasks or file links, name must be set by the app. + */ + type?: 'tasks' | 'frequent' | 'recent' | 'custom'; + /** + * Must be set if type is custom, otherwise it should be omitted. + */ + name?: string; + /** + * Array of JumpListItem objects if type is tasks or custom, otherwise it should be omitted. + */ + items?: JumpListItem[]; + } + + interface JumpListItem { + /** + * task - A task will launch an app with specific arguments. + * separator - Can be used to separate items in the standard Tasks category. + * file - A file link will open a file using the app that created the Jump List. + */ + type: 'task' | 'separator' | 'file'; + /** + * Path of the file to open, should only be set if type is file. + */ + path?: string; + /** + * Path of the program to execute, usually you should specify process.execPath which opens the current program. + * Should only be set if type is task. + */ + program?: string; + /** + * The command line arguments when program is executed. Should only be set if type is task. + */ + args?: string; + /** + * The text to be displayed for the item in the Jump List. Should only be set if type is task. + */ + title?: string; + /** + * Description of the task (displayed in a tooltip). Should only be set if type is task. + */ + description?: string; + /** + * The absolute path to an icon to be displayed in a Jump List, which can be an arbitrary + * resource file that contains an icon (e.g. .ico, .exe, .dll). + * You can usually specify process.execPath to show the program icon. + */ + iconPath?: string; + /** + * The index of the icon in the resource file. If a resource file contains multiple icons + * this value can be used to specify the zero-based index of the icon that should be displayed + * for this task. If a resource file contains only one icon, this property should be set to zero. + */ + iconIndex?: number; + } + + interface LoginItemSettings { + /** + * True if the app is set to open at login. + */ + openAtLogin: boolean; + /** + * True if the app is set to open as hidden at login. This setting is only supported on macOS. + */ + openAsHidden: boolean; + /** + * True if the app was opened at login automatically. This setting is only supported on macOS. + */ + wasOpenedAtLogin?: boolean; + /** + * True if the app was opened as a hidden login item. This indicates that the app should not + * open any windows at startup. This setting is only supported on macOS. + */ + wasOpenedAsHidden?: boolean; + /** + * True if the app was opened as a login item that should restore the state from the previous session. + * This indicates that the app should restore the windows that were open the last time the app was closed. + * This setting is only supported on macOS. + */ + restoreState?: boolean; + } + + interface AboutPanelOptions { + /** + * The app's name. + */ + applicationName?: string; + /** + * The app's version. + */ + applicationVersion?: string; + /** + * Copyright information. + */ + copyright?: string; + /** + * Credit information. + */ + credits?: string; + /** + * The app's build version number. + */ + version?: string; + } + + // https://github.com/electron/electron/blob/master/docs/api/auto-updater.md + + /** + * This module provides an interface for the Squirrel auto-updater framework. + */ + interface AutoUpdater extends NodeJS.EventEmitter { + /** + * Emitted when there is an error while updating. + */ + on(event: 'error', listener: (error: Error) => void): this; + /** + * Emitted when checking if an update has started. + */ + on(event: 'checking-for-update', listener: Function): this; + /** + * Emitted when there is an available update. The update is downloaded automatically. + */ + on(event: 'update-available', listener: Function): this; + /** + * Emitted when there is no available update. + */ + on(event: 'update-not-available', listener: Function): this; + /** + * Emitted when an update has been downloaded. + * Note: On Windows only releaseName is available. + */ + on(event: 'update-downloaded', listener: (event: Event, releaseNotes: string, releaseName: string, releaseDate: Date, updateURL: string) => void): this; + on(event: string, listener: Function): this; + /** + * Set the url and initialize the auto updater. + */ + setFeedURL(url: string, requestHeaders?: Headers): void; + /** + * @returns The current update feed URL. + */ + getFeedURL(): string; + /** + * Ask the server whether there is an update, you have to call setFeedURL + * before using this API + */ + checkForUpdates(): void; + /** + * Restarts the app and installs the update after it has been downloaded. + * It should only be called after update-downloaded has been emitted. + */ + quitAndInstall(): void; + } + + // https://github.com/electron/electron/blob/master/docs/api/browser-window.md + + /** + * The BrowserWindow class gives you ability to create a browser window. + * You can also create a window without chrome by using Frameless Window API. + */ + class BrowserWindow extends NodeJS.EventEmitter implements Destroyable { + /** + * Emitted when the document changed its title, + * calling event.preventDefault() would prevent the native window’s title to change. + */ + on(event: 'page-title-updated', listener: (event: Event, title: string) => void): this; + /** + * Emitted when the window is going to be closed. It’s emitted before the beforeunload + * and unload event of the DOM. Calling event.preventDefault() will cancel the close. + */ + on(event: 'close', listener: (event: Event) => void): this; + /** + * Emitted when the window is closed. After you have received this event + * you should remove the reference to the window and avoid using it anymore. + */ + on(event: 'closed', listener: Function): this; + /** + * Emitted when the web page becomes unresponsive. + */ + on(event: 'unresponsive', listener: Function): this; + /** + * Emitted when the unresponsive web page becomes responsive again. + */ + on(event: 'responsive', listener: Function): this; + /** + * Emitted when the window loses focus. + */ + on(event: 'blur', listener: Function): this; + /** + * Emitted when the window gains focus. + */ + on(event: 'focus', listener: Function): this; + /** + * Emitted when the window is shown. + */ + on(event: 'show', listener: Function): this; + /** + * Emitted when the window is hidden. + */ + on(event: 'hide', listener: Function): this; + /** + * Emitted when the web page has been rendered and window can be displayed without visual flash. + */ + on(event: 'ready-to-show', listener: Function): this; + /** + * Emitted when window is maximized. + */ + on(event: 'maximize', listener: Function): this; + /** + * Emitted when the window exits from maximized state. + */ + on(event: 'unmaximize', listener: Function): this; + /** + * Emitted when the window is minimized. + */ + on(event: 'minimize', listener: Function): this; + /** + * Emitted when the window is restored from minimized state. + */ + on(event: 'restore', listener: Function): this; + /** + * Emitted when the window is getting resized. + */ + on(event: 'resize', listener: Function): this; + /** + * Emitted when the window is getting moved to a new position. + */ + on(event: 'move', listener: Function): this; + /** + * Emitted when the window enters full screen state. + */ + on(event: 'enter-full-screen', listener: Function): this; + /** + * Emitted when the window leaves full screen state. + */ + on(event: 'leave-full-screen', listener: Function): this; + /** + * Emitted when the window enters full screen state triggered by HTML API. + */ + on(event: 'enter-html-full-screen', listener: Function): this; + /** + * Emitted when the window leaves full screen state triggered by HTML API. + */ + on(event: 'leave-html-full-screen', listener: Function): this; + /** + * Emitted when an App Command is invoked. These are typically related + * to keyboard media keys or browser commands, as well as the "Back" / + * "Forward" buttons built into some mice on Windows. + * Note: This is only implemented on Windows. + */ + on(event: 'app-command', listener: (event: Event, command: string) => void): this; + /** + * Emitted when scroll wheel event phase has begun. + * Note: This is only implemented on macOS. + */ + on(event: 'scroll-touch-begin', listener: Function): this; + /** + * Emitted when scroll wheel event phase has ended. + * Note: This is only implemented on macOS. + */ + on(event: 'scroll-touch-end', listener: Function): this; + /** + * Emitted when scroll wheel event phase filed upon reaching the edge of element. + * Note: This is only implemented on macOS. + */ + on(event: 'scroll-touch-edge', listener: Function): this; + /** + * Emitted on 3-finger swipe. + * Note: This is only implemented on macOS. + */ + on(event: 'swipe', listener: (event: Event, direction: SwipeDirection) => void): this; + on(event: string, listener: Function): this; + /** + * Creates a new BrowserWindow with native properties as set by the options. + */ + constructor(options?: BrowserWindowOptions); + /** + * @returns All opened browser windows. + */ + static getAllWindows(): BrowserWindow[]; + /** + * @returns The window that is focused in this application. + */ + static getFocusedWindow(): BrowserWindow; + /** + * Find a window according to the webContents it owns. + */ + static fromWebContents(webContents: WebContents): BrowserWindow; + /** + * Find a window according to its ID. + */ + static fromId(id: number): BrowserWindow; + /** + * Adds devtools extension located at path. The extension will be remembered + * so you only need to call this API once, this API is not for programming use. + * @returns The extension's name. + * + * Note: This API cannot be called before the ready event of the app module is emitted. + */ + static addDevToolsExtension(path: string): string; + /** + * Remove a devtools extension. + * @param name The name of the devtools extension to remove. + * + * Note: This API cannot be called before the ready event of the app module is emitted. + */ + static removeDevToolsExtension(name: string): void; + /** + * @returns devtools extensions. + * + * Note: This API cannot be called before the ready event of the app module is emitted. + */ + static getDevToolsExtensions(): DevToolsExtensions; + /** + * The WebContents object this window owns, all web page related events and + * operations would be done via it. + * Note: Users should never store this object because it may become null when + * the renderer process (web page) has crashed. + */ + webContents: WebContents; + /** + * Get the unique ID of this window. + */ + id: number; + /** + * Force closing the window, the unload and beforeunload event won't be emitted + * for the web page, and close event would also not be emitted for this window, + * but it would guarantee the closed event to be emitted. + * You should only use this method when the renderer process (web page) has crashed. + */ + destroy(): void; + /** + * Try to close the window, this has the same effect with user manually clicking + * the close button of the window. The web page may cancel the close though, + * see the close event. + */ + close(): void; + /** + * Focus on the window. + */ + focus(): void; + /** + * Remove focus on the window. + */ + blur(): void; + /** + * @returns Whether the window is focused. + */ + isFocused(): boolean; + /** + * @returns Whether the window is destroyed. + */ + isDestroyed(): boolean; + /** + * Shows and gives focus to the window. + */ + show(): void; + /** + * Shows the window but doesn't focus on it. + */ + showInactive(): void; + /** + * Hides the window. + */ + hide(): void; + /** + * @returns Whether the window is visible to the user. + */ + isVisible(): boolean; + /** + * @returns Whether the window is a modal window. + */ + isModal(): boolean; + /** + * Maximizes the window. + */ + maximize(): void; + /** + * Unmaximizes the window. + */ + unmaximize(): void; + /** + * @returns Whether the window is maximized. + */ + isMaximized(): boolean; + /** + * Minimizes the window. On some platforms the minimized window will be + * shown in the Dock. + */ + minimize(): void; + /** + * Restores the window from minimized state to its previous state. + */ + restore(): void; + /** + * @returns Whether the window is minimized. + */ + isMinimized(): boolean; + /** + * Sets whether the window should be in fullscreen mode. + */ + setFullScreen(flag: boolean): void; + /** + * @returns Whether the window is in fullscreen mode. + */ + isFullScreen(): boolean; + /** + * This will have a window maintain an aspect ratio. + * The extra size allows a developer to have space, specified in pixels, + * not included within the aspect ratio calculations. + * This API already takes into account the difference between a window’s size and its content size. + * + * Note: This API is available only on macOS. + */ + setAspectRatio(aspectRatio: number, extraSize?: Size): void; + /** + * Resizes and moves the window to width, height, x, y. + */ + setBounds(options: Rectangle, animate?: boolean): void; + /** + * @returns The window's width, height, x and y values. + */ + getBounds(): Rectangle; + /** + * Resizes and moves the window's client area (e.g. the web page) to width, height, x, y. + */ + setContentBounds(options: Rectangle, animate?: boolean): void; + /** + * @returns The window's client area (e.g. the web page) width, height, x and y values. + */ + getContentBounds(): Rectangle; + /** + * Resizes the window to width and height. + */ + setSize(width: number, height: number, animate?: boolean): void; + /** + * @returns The window's width and height. + */ + getSize(): number[]; + /** + * Resizes the window's client area (e.g. the web page) to width and height. + */ + setContentSize(width: number, height: number, animate?: boolean): void; + /** + * @returns The window's client area's width and height. + */ + getContentSize(): number[]; + /** + * Sets the minimum size of window to width and height. + */ + setMinimumSize(width: number, height: number): void; + /** + * @returns The window's minimum width and height. + */ + getMinimumSize(): number[]; + /** + * Sets the maximum size of window to width and height. + */ + setMaximumSize(width: number, height: number): void; + /** + * @returns The window's maximum width and height. + */ + getMaximumSize(): number[]; + /** + * Sets whether the window can be manually resized by user. + */ + setResizable(resizable: boolean): void; + /** + * @returns Whether the window can be manually resized by user. + */ + isResizable(): boolean; + /** + * Sets whether the window can be moved by user. On Linux does nothing. + * Note: This API is available only on macOS and Windows. + */ + setMovable(movable: boolean): void; + /** + * Note: This API is available only on macOS and Windows. + * @returns Whether the window can be moved by user. On Linux always returns true. + */ + isMovable(): boolean; + /** + * Sets whether the window can be manually minimized by user. On Linux does nothing. + * Note: This API is available only on macOS and Windows. + */ + setMinimizable(minimizable: boolean): void; + /** + * Note: This API is available only on macOS and Windows. + * @returns Whether the window can be manually minimized by user. On Linux always returns true. + */ + isMinimizable(): boolean; + /** + * Sets whether the window can be manually maximized by user. On Linux does nothing. + * Note: This API is available only on macOS and Windows. + */ + setMaximizable(maximizable: boolean): void; + /** + * Note: This API is available only on macOS and Windows. + * @returns Whether the window can be manually maximized by user. On Linux always returns true. + */ + isMaximizable(): boolean; + /** + * Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. + */ + setFullScreenable(fullscreenable: boolean): void; + /** + * @returns Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. + */ + isFullScreenable(): boolean; + /** + * Sets whether the window can be manually closed by user. On Linux does nothing. + * Note: This API is available only on macOS and Windows. + */ + setClosable(closable: boolean): void; + /** + * Note: This API is available only on macOS and Windows. + * @returns Whether the window can be manually closed by user. On Linux always returns true. + */ + isClosable(): boolean; + /** + * Sets whether the window should show always on top of other windows. After + * setting this, the window is still a normal window, not a toolbox window + * which can not be focused on. + */ + setAlwaysOnTop(flag: boolean, level?: WindowLevel): void; + /** + * @returns Whether the window is always on top of other windows. + */ + isAlwaysOnTop(): boolean; + /** + * Moves window to the center of the screen. + */ + center(): void; + /** + * Moves window to x and y. + */ + setPosition(x: number, y: number, animate?: boolean): void; + /** + * @returns The window's current position. + */ + getPosition(): number[]; + /** + * Changes the title of native window to title. + */ + setTitle(title: string): void; + /** + * Note: The title of web page can be different from the title of the native window. + * @returns The title of the native window. + */ + getTitle(): string; + /** + * Changes the attachment point for sheets on macOS. + * Note: This API is available only on macOS. + */ + setSheetOffset(offsetY: number, offsetX?: number): void; + /** + * Starts or stops flashing the window to attract user's attention. + */ + flashFrame(flag: boolean): void; + /** + * Makes the window do not show in Taskbar. + */ + setSkipTaskbar(skip: boolean): void; + /** + * Enters or leaves the kiosk mode. + */ + setKiosk(flag: boolean): void; + /** + * @returns Whether the window is in kiosk mode. + */ + isKiosk(): boolean; + /** + * The native type of the handle is HWND on Windows, NSView* on macOS, + * and Window (unsigned long) on Linux. + * @returns The platform-specific handle of the window as Buffer. + */ + getNativeWindowHandle(): Buffer; + /** + * Hooks a windows message. The callback is called when the message is received in the WndProc. + * Note: This API is available only on Windows. + */ + hookWindowMessage(message: number, callback: Function): void; + /** + * @returns Whether the message is hooked. + */ + isWindowMessageHooked(message: number): boolean; + /** + * Unhook the window message. + */ + unhookWindowMessage(message: number): void; + /** + * Unhooks all of the window messages. + */ + unhookAllWindowMessages(): void; + /** + * Sets the pathname of the file the window represents, and the icon of the + * file will show in window's title bar. + * Note: This API is available only on macOS. + */ + setRepresentedFilename(filename: string): void; + /** + * Note: This API is available only on macOS. + * @returns The pathname of the file the window represents. + */ + getRepresentedFilename(): string; + /** + * Specifies whether the window’s document has been edited, and the icon in + * title bar will become grey when set to true. + * Note: This API is available only on macOS. + */ + setDocumentEdited(edited: boolean): void; + /** + * Note: This API is available only on macOS. + * @returns Whether the window's document has been edited. + */ + isDocumentEdited(): boolean; + focusOnWebView(): void; + blurWebView(): void; + /** + * Captures the snapshot of page within rect, upon completion the callback + * will be called. Omitting the rect would capture the whole visible page. + * Note: Be sure to read documents on remote buffer in remote if you are going + * to use this API in renderer process. + * @param callback Supplies the image that stores data of the snapshot. + */ + capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; + /** + * Captures the snapshot of page within rect, upon completion the callback + * will be called. Omitting the rect would capture the whole visible page. + * Note: Be sure to read documents on remote buffer in remote if you are going + * to use this API in renderer process. + * @param callback Supplies the image that stores data of the snapshot. + */ + capturePage(callback: (image: NativeImage) => void): void; + /** + * Same as webContents.loadURL(url). + */ + loadURL(url: string, options?: LoadURLOptions): void; + /** + * Same as webContents.reload. + */ + reload(): void; + /** + * Sets the menu as the window top menu. + * Note: This API is not available on macOS. + */ + setMenu(menu: Menu): void; + /** + * Sets the progress value in the progress bar. + * On Linux platform, only supports Unity desktop environment, you need to + * specify the *.desktop file name to desktopName field in package.json. + * By default, it will assume app.getName().desktop. + * @param progress Valid range is [0, 1.0]. If < 0, the progress bar is removed. + * If greater than 0, it becomes indeterminate. + */ + setProgressBar(progress: number, options?: { + /** + * Mode for the progress bar. + * Note: This is only implemented on Windows. + */ + mode: 'none' | 'normal' | 'indeterminate' | 'error' | 'paused' + }): void; + /** + * Sets a 16px overlay onto the current Taskbar icon, usually used to convey + * some sort of application status or to passively notify the user. + * Note: This API is only available on Windows 7 or above. + * @param overlay The icon to display on the bottom right corner of the Taskbar + * icon. If this parameter is null, the overlay is cleared + * @param description Provided to Accessibility screen readers. + */ + setOverlayIcon(overlay: NativeImage, description: string): void; + /** + * Sets whether the window should have a shadow. On Windows and Linux does nothing. + * Note: This API is available only on macOS. + */ + setHasShadow(hasShadow: boolean): void; + /** + * Note: This API is available only on macOS. + * @returns whether the window has a shadow. On Windows and Linux always returns true. + */ + hasShadow(): boolean; + /** + * Add a thumbnail toolbar with a specified set of buttons to the thumbnail image + * of a window in a taskbar button layout. + * @returns Whether the thumbnail has been added successfully. + * + * Note: This API is available only on Windows. + */ + setThumbarButtons(buttons: ThumbarButton[]): boolean; + /** + * Sets the region of the window to show as the thumbnail image displayed when hovering + * over the window in the taskbar. You can reset the thumbnail to be the entire window + * by specifying an empty region: {x: 0, y: 0, width: 0, height: 0}. + * + * Note: This API is available only on Windows. + */ + setThumbnailClip(region: Rectangle): boolean; + /** + * Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar. + * Note: This API is available only on Windows. + */ + setThumbnailToolTip(toolTip: string): boolean; + /** + * Same as webContents.showDefinitionForSelection(). + * Note: This API is available only on macOS. + */ + showDefinitionForSelection(): void; + /** + * Changes window icon. + * Note: This API is not available on macOS. + */ + setIcon(icon: NativeImage): void; + /** + * Sets whether the window menu bar should hide itself automatically. Once set + * the menu bar will only show when users press the single Alt key. + * If the menu bar is already visible, calling setAutoHideMenuBar(true) won't + * hide it immediately. + */ + setAutoHideMenuBar(hide: boolean): void; + /** + * @returns Whether menu bar automatically hides itself. + */ + isMenuBarAutoHide(): boolean; + /** + * Sets whether the menu bar should be visible. If the menu bar is auto-hide, + * users can still bring up the menu bar by pressing the single Alt key. + */ + setMenuBarVisibility(visibile: boolean): void; + /** + * @returns Whether the menu bar is visible. + */ + isMenuBarVisible(): boolean; + /** + * Sets whether the window should be visible on all workspaces. + * Note: This API does nothing on Windows. + */ + setVisibleOnAllWorkspaces(visible: boolean): void; + /** + * Note: This API always returns false on Windows. + * @returns Whether the window is visible on all workspaces. + */ + isVisibleOnAllWorkspaces(): boolean; + /** + * Makes the window ignore all mouse events. + * + * All mouse events happened in this window will be passed to the window below this window, + * but if this window has focus, it will still receive keyboard events. + */ + setIgnoreMouseEvents(ignore: boolean): void; + /** + * Prevents the window contents from being captured by other apps. + * + * On macOS it sets the NSWindow's sharingType to NSWindowSharingNone. + * On Windows it calls SetWindowDisplayAffinity with WDA_MONITOR. + */ + setContentProtection(enable: boolean): void; + /** + * Changes whether the window can be focused. + * Note: This API is available only on Windows. + */ + setFocusable(focusable: boolean): void; + /** + * Sets parent as current window's parent window, + * passing null will turn current window into a top-level window. + * Note: This API is not available on Windows. + */ + setParentWindow(parent: BrowserWindow): void; + /** + * @returns The parent window. + */ + getParentWindow(): BrowserWindow; + /** + * @returns All child windows. + */ + getChildWindows(): BrowserWindow[]; + } + + type WindowLevel = 'normal' | 'floating' | 'torn-off-menu' | 'modal-panel' | 'main-menu' | 'status' | 'pop-up-menu' | 'screen-saver' | 'dock'; + type SwipeDirection = 'up' | 'right' | 'down' | 'left'; + type ThumbarButtonFlags = 'enabled' | 'disabled' | 'dismissonclick' | 'nobackground' | 'hidden' | 'noninteractive'; + + interface ThumbarButton { + icon: NativeImage | string; + click: Function; + tooltip?: string; + flags?: ThumbarButtonFlags[]; + } + + interface DevToolsExtensions { + [name: string]: { + name: string; + value: string; + } + } + + interface WebPreferences { + /** + * Whether to enable DevTools. + * If it is set to false, can not use BrowserWindow.webContents.openDevTools() to open DevTools. + * Default: true. + */ + devTools?: boolean; + /** + * Whether node integration is enabled. + * Default: true. + */ + nodeIntegration?: boolean; + /** + * Specifies a script that will be loaded before other scripts run in the page. + * This script will always have access to node APIs no matter whether node integration is turned on or off. + * The value should be the absolute file path to the script. + * When node integration is turned off, the preload script can reintroduce + * Node global symbols back to the global scope. + */ + preload?: string; + /** + * Sets the session used by the page. Instead of passing the Session object directly, + * you can also choose to use the partition option instead, which accepts a partition string. + * When both session and partition are provided, session would be preferred. + * Default: the default session. + */ + session?: Session; + /** + * Sets the session used by the page according to the session’s partition string. + * If partition starts with persist:, the page will use a persistent session available + * to all pages in the app with the same partition. if there is no persist: prefix, + * the page will use an in-memory session. By assigning the same partition, + * multiple pages can share the same session. + * Default: the default session. + */ + partition?: string; + /** + * The default zoom factor of the page, 3.0 represents 300%. + * Default: 1.0. + */ + zoomFactor?: number; + /** + * Enables JavaScript support. + * Default: true. + */ + javascript?: boolean; + /** + * When setting false, it will disable the same-origin policy (Usually using testing + * websites by people), and set allowDisplayingInsecureContent and allowRunningInsecureContent + * to true if these two options are not set by user. + * Default: true. + */ + webSecurity?: boolean; + /** + * Allow an https page to display content like images from http URLs. + * Default: false. + */ + allowDisplayingInsecureContent?: boolean; + /** + * Allow a https page to run JavaScript, CSS or plugins from http URLs. + * Default: false. + */ + allowRunningInsecureContent?: boolean; + /** + * Enables image support. + * Default: true. + */ + images?: boolean; + /** + * Make TextArea elements resizable. + * Default: true. + */ + textAreasAreResizable?: boolean; + /** + * Enables WebGL support. + * Default: true. + */ + webgl?: boolean; + /** + * Enables WebAudio support. + * Default: true. + */ + webaudio?: boolean; + /** + * Whether plugins should be enabled. + * Default: false. + */ + plugins?: boolean; + /** + * Enables Chromium’s experimental features. + * Default: false. + */ + experimentalFeatures?: boolean; + /** + * Enables Chromium’s experimental canvas features. + * Default: false. + */ + experimentalCanvasFeatures?: boolean; + /** + * Enables DirectWrite font rendering system on Windows. + * Default: true. + */ + directWrite?: boolean; + /** + * Enables scroll bounce (rubber banding) effect on macOS. + * Default: false. + */ + scrollBounce?: boolean; + /** + * A list of feature strings separated by ",", like CSSVariables,KeyboardEventKey to enable. + */ + blinkFeatures?: string; + /** + * A list of feature strings separated by ",", like CSSVariables,KeyboardEventKey to disable. + */ + disableBlinkFeatures?: string; + /** + * Sets the default font for the font-family. + */ + defaultFontFamily?: { + /** + * Default: Times New Roman. + */ + standard?: string; + /** + * Default: Times New Roman. + */ + serif?: string; + /** + * Default: Arial. + */ + sansSerif?: string; + /** + * Default: Courier New. + */ + monospace?: string; + }; + /** + * Default: 16. + */ + defaultFontSize?: number; + /** + * Default: 13. + */ + defaultMonospaceFontSize?: number; + /** + * Default: 0. + */ + minimumFontSize?: number; + /** + * Default: ISO-8859-1. + */ + defaultEncoding?: string; + /** + * Whether to throttle animations and timers when the page becomes background. + * Default: true. + */ + backgroundThrottling?: boolean; + /** + * Whether to enable offscreen rendering for the browser window. + * Default: false. + */ + offscreen?: boolean; + /** + * Whether to enable Chromium OS-level sandbox. + * Default: false. + */ + sandbox?: boolean; + } + + interface BrowserWindowOptions { + /** + * Window’s width in pixels. + * Default: 800. + */ + width?: number; + /** + * Window’s height in pixels. + * Default: 600. + */ + height?: number; + /** + * Window’s left offset from screen. + * Default: center the window. + */ + x?: number; + /** + * Window’s top offset from screen. + * Default: center the window. + */ + y?: number; + /** + * The width and height would be used as web page’s size, which means + * the actual window’s size will include window frame’s size and be slightly larger. + * Default: false. + */ + useContentSize?: boolean; + /** + * Show window in the center of the screen. + * Default: true + */ + center?: boolean; + /** + * Window’s minimum width. + * Default: 0. + */ + minWidth?: number; + /** + * Window’s minimum height. + * Default: 0. + */ + minHeight?: number; + /** + * Window’s maximum width. + * Default: no limit. + */ + maxWidth?: number; + /** + * Window’s maximum height. + * Default: no limit. + */ + maxHeight?: number; + /** + * Whether window is resizable. + * Default: true. + */ + resizable?: boolean; + /** + * Whether window is movable. + * Note: This is not implemented on Linux. + * Default: true. + */ + movable?: boolean; + /** + * Whether window is minimizable. + * Note: This is not implemented on Linux. + * Default: true. + */ + minimizable?: boolean; + /** + * Whether window is maximizable. + * Note: This is not implemented on Linux. + * Default: true. + */ + maximizable?: boolean; + /** + * Whether window is closable. + * Note: This is not implemented on Linux. + * Default: true. + */ + closable?: boolean; + /** + * Whether the window can be focused. + * On Windows setting focusable: false also implies setting skipTaskbar: true. + * On Linux setting focusable: false makes the window stop interacting with wm, + * so the window will always stay on top in all workspaces. + * Default: true. + */ + focusable?: boolean; + /** + * Whether the window should always stay on top of other windows. + * Default: false. + */ + alwaysOnTop?: boolean; + /** + * Whether the window should show in fullscreen. + * When explicitly set to false the fullscreen button will be hidden or disabled on macOS. + * Default: false. + */ + fullscreen?: boolean; + /** + * Whether the window can be put into fullscreen mode. + * On macOS, also whether the maximize/zoom button should toggle full screen mode or maximize window. + * Default: true. + */ + fullscreenable?: boolean; + /** + * Whether to show the window in taskbar. + * Default: false. + */ + skipTaskbar?: boolean; + /** + * The kiosk mode. + * Default: false. + */ + kiosk?: boolean; + /** + * Default window title. + * Default: "Electron". + */ + title?: string; + /** + * The window icon, when omitted on Windows the executable’s icon would be used as window icon. + */ + icon?: NativeImage|string; + /** + * Whether window should be shown when created. + * Default: true. + */ + show?: boolean; + /** + * Specify false to create a Frameless Window. + * Default: true. + */ + frame?: boolean; + /** + * Specify parent window. + * Default: null. + */ + parent?: BrowserWindow; + /** + * Whether this is a modal window. This only works when the window is a child window. + * Default: false. + */ + modal?: boolean; + /** + * Whether the web view accepts a single mouse-down event that simultaneously activates the window. + * Default: false. + */ + acceptFirstMouse?: boolean; + /** + * Whether to hide cursor when typing. + * Default: false. + */ + disableAutoHideCursor?: boolean; + /** + * Auto hide the menu bar unless the Alt key is pressed. + * Default: true. + */ + autoHideMenuBar?: boolean; + /** + * Enable the window to be resized larger than screen. + * Default: false. + */ + enableLargerThanScreen?: boolean; + /** + * Window’s background color as Hexadecimal value, like #66CD00 or #FFF or #80FFFFFF (alpha is supported). + * Default: #FFF (white). + */ + backgroundColor?: string; + /** + * Whether window should have a shadow. + * Note: This is only implemented on macOS. + * Default: true. + */ + hasShadow?: boolean; + /** + * Forces using dark theme for the window. + * Note: Only works on some GTK+3 desktop environments. + * Default: false. + */ + darkTheme?: boolean; + /** + * Makes the window transparent. + * Default: false. + */ + transparent?: boolean; + /** + * The type of window, default is normal window. + */ + type?: BrowserWindowType; + /** + * The style of window title bar. + */ + titleBarStyle?: 'default' | 'hidden' | 'hidden-inset'; + /** + * Use WS_THICKFRAME style for frameless windows on Windows + */ + thickFrame?: boolean; + /** + * Settings of web page’s features. + */ + webPreferences?: WebPreferences; + } + + type BrowserWindowType = BrowserWindowTypeLinux | BrowserWindowTypeMac | BrowserWindowTypeWindows; + type BrowserWindowTypeLinux = 'desktop' | 'dock' | 'toolbar' | 'splash' | 'notification'; + type BrowserWindowTypeMac = 'desktop' | 'textured'; + type BrowserWindowTypeWindows = 'toolbar'; + + // https://github.com/electron/electron/blob/master/docs/api/clipboard.md + + /** + * The clipboard module provides methods to perform copy and paste operations. + */ + interface Clipboard { + /** + * @returns The contents of the clipboard as plain text. + */ + readText(type?: ClipboardType): string; + /** + * Writes the text into the clipboard as plain text. + */ + writeText(text: string, type?: ClipboardType): void; + /** + * @returns The contents of the clipboard as markup. + */ + readHTML(type?: ClipboardType): string; + /** + * Writes markup to the clipboard. + */ + writeHTML(markup: string, type?: ClipboardType): void; + /** + * @returns The contents of the clipboard as a NativeImage. + */ + readImage(type?: ClipboardType): NativeImage; + /** + * Writes the image into the clipboard. + */ + writeImage(image: NativeImage, type?: ClipboardType): void; + /** + * @returns The contents of the clipboard as RTF. + */ + readRTF(type?: ClipboardType): string; + /** + * Writes the text into the clipboard in RTF. + */ + writeRTF(text: string, type?: ClipboardType): void; + /** + * Clears everything in clipboard. + */ + clear(type?: ClipboardType): void; + /** + * @returns Array available formats for the clipboard type. + */ + availableFormats(type?: ClipboardType): string[]; + /** + * Returns whether the clipboard supports the format of specified data. + * Note: This API is experimental and could be removed in future. + * @returns Whether the clipboard has data in the specified format. + */ + has(format: string, type?: ClipboardType): boolean; + /** + * Reads the data in the clipboard of the specified format. + * Note: This API is experimental and could be removed in future. + */ + read(format: string, type?: ClipboardType): string | NativeImage; + /** + * Writes data to the clipboard. + */ + write(data: { + text?: string; + rtf?: string; + html?: string; + image?: NativeImage; + }, type?: ClipboardType): void; + /** + * @returns An Object containing title and url keys representing the bookmark in the clipboard. + * + * Note: This API is available on macOS and Windows. + */ + readBookmark(): Bookmark; + /** + * Writes the title and url into the clipboard as a bookmark. + * + * Note: This API is available on macOS and Windows. + */ + writeBookmark(title: string, url: string, type?: ClipboardType): void; + } + + type ClipboardType = '' | 'selection'; + + interface Bookmark { + title: string; + url: string; + } + + // https://github.com/electron/electron/blob/master/docs/api/content-tracing.md + + /** + * The content-tracing module is used to collect tracing data generated by the underlying Chromium content module. + * This module does not include a web interface so you need to open chrome://tracing/ + * in a Chrome browser and load the generated file to view the result. + */ + interface ContentTracing { + /** + * Get a set of category groups. The category groups can change as new code paths are reached. + * + * @param callback Called once all child processes have acknowledged the getCategories request. + */ + getCategories(callback: (categoryGroups: string[]) => void): void; + /** + * Start recording on all processes. Recording begins immediately locally and asynchronously + * on child processes as soon as they receive the EnableRecording request. + * + * @param callback Called once all child processes have acknowledged the startRecording request. + */ + startRecording(options: ContentTracingOptions, callback: Function): void; + /** + * Stop recording on all processes. Child processes typically are caching trace data and + * only rarely flush and send trace data back to the main process. That is because it may + * be an expensive operation to send the trace data over IPC, and we would like to avoid + * much runtime overhead of tracing. So, to end tracing, we must asynchronously ask all + * child processes to flush any pending trace data. + * + * @param resultFilePath Trace data will be written into this file if it is not empty, + * or into a temporary file. + * @param callback Called once all child processes have acknowledged the stopRecording request. + */ + stopRecording(resultFilePath: string, callback: (filePath: string) => void): void; + /** + * Start monitoring on all processes. Monitoring begins immediately locally and asynchronously + * on child processes as soon as they receive the startMonitoring request. + * + * @param callback Called once all child processes have acked to the startMonitoring request. + */ + startMonitoring(options: ContentTracingOptions, callback: Function): void; + /** + * Stop monitoring on all processes. + * + * @param callback Called once all child processes have acknowledged the stopMonitoring request. + */ + stopMonitoring(callback: Function): void; + /** + * Get the current monitoring traced data. Child processes typically are caching trace data + * and only rarely flush and send trace data back to the main process. That is because it may + * be an expensive operation to send the trace data over IPC, and we would like to avoid much + * runtime overhead of tracing. So, to end tracing, we must asynchronously ask all child + * processes to flush any pending trace data. + * + * @param callback Called once all child processes have acknowledged the captureMonitoringSnapshot request. + */ + captureMonitoringSnapshot(resultFilePath: string, callback: (filePath: string) => void): void; + /** + * Get the maximum usage across processes of trace buffer as a percentage of the full state. + * + * @param callback Called when the TraceBufferUsage value is determined. + */ + getTraceBufferUsage(callback: Function): void; + /** + * @param callback Called every time the given event occurs on any process. + */ + setWatchEvent(categoryName: string, eventName: string, callback: Function): void; + /** + * Cancel the watch event. This may lead to a race condition with the watch event callback if tracing is enabled. + */ + cancelWatchEvent(): void; + } + + interface ContentTracingOptions { + /** + * Filter to control what category groups should be traced. + * A filter can have an optional - prefix to exclude category groups + * that contain a matching category. Having both included and excluded + * category patterns in the same list is not supported. + * + * Examples: + * test_MyTest* + * test_MyTest*,test_OtherStuff + * -excluded_category1,-excluded_category2 + */ + categoryFilter: string; + /** + * Controls what kind of tracing is enabled, it is a comma-delimited list. + * + * Possible options are: + * record-until-full + * record-continuously + * trace-to-console + * enable-sampling + * enable-systrace + * + * The first 3 options are trace recoding modes and hence mutually exclusive. + * If more than one trace recording modes appear in the traceOptions string, + * the last one takes precedence. If none of the trace recording modes are specified, + * recording mode is record-until-full. + * + * The trace option will first be reset to the default option (record_mode set + * to record-until-full, enable_sampling and enable_systrace set to false) + * before options parsed from traceOptions are applied on it. + */ + traceOptions: string; + } + + // https://github.com/electron/electron/blob/master/docs/api/crash-reporter.md + + /** + * The crash-reporter module enables sending your app's crash reports. + */ + interface CrashReporter { + /** + * You are required to call this method before using other crashReporter APIs. + * + * Note: On macOS, Electron uses a new crashpad client, which is different from breakpad + * on Windows and Linux. To enable the crash collection feature, you are required to call + * the crashReporter.start API to initialize crashpad in the main process and in each + * renderer process from which you wish to collect crash reports. + */ + start(options: CrashReporterStartOptions): void; + /** + * @returns The crash report. When there was no crash report + * sent or the crash reporter is not started, null will be returned. + */ + getLastCrashReport(): CrashReport; + /** + * @returns All uploaded crash reports. + */ + getUploadedReports(): CrashReport[]; + } + + interface CrashReporterStartOptions { + /** + * Default: app.getName() + */ + productName?: string; + companyName: string; + /** + * URL that crash reports would be sent to as POST. + */ + submitURL: string; + /** + * Send the crash report without user interaction. + * Default: true. + */ + autoSubmit?: boolean; + /** + * Default: false. + */ + ignoreSystemCrashHandler?: boolean; + /** + * An object you can define that will be sent along with the report. + * Only string properties are sent correctly, nested objects are not supported. + */ + extra?: {[prop: string]: string}; + } + + interface CrashReport { + id: string; + date: Date; + } + + // https://github.com/electron/electron/blob/master/docs/api/desktop-capturer.md + + /** + * The desktopCapturer module can be used to get available sources + * that can be used to be captured with getUserMedia. + */ + interface DesktopCapturer { + /** + * Starts a request to get all desktop sources. + * + * Note: There is no guarantee that the size of source.thumbnail is always + * the same as the thumnbailSize in options. It also depends on the scale of the screen or window. + */ + getSources(options: DesktopCapturerOptions, callback: (error: Error, sources: DesktopCapturerSource[]) => any): void; + } + + interface DesktopCapturerOptions { + /** + * The types of desktop sources to be captured. + */ + types?: ('screen' | 'window')[]; + /** + * The suggested size that thumbnail should be scaled. + * Default: {width: 150, height: 150} + */ + thumbnailSize?: Size; + } + + interface DesktopCapturerSource { + /** + * The id of the captured window or screen used in navigator.webkitGetUserMedia. + * The format looks like window:XX or screen:XX where XX is a random generated number. + */ + id: string; + /** + * The described name of the capturing screen or window. + * If the source is a screen, the name will be Entire Screen or Screen ; + * if it is a window, the name will be the window’s title. + */ + name: string; + /** + * A thumbnail image. + */ + thumbnail: NativeImage; + } + + // https://github.com/electron/electron/blob/master/docs/api/dialog.md + + /** + * The dialog module provides APIs to show native system dialogs, such as opening files or alerting, + * so web applications can deliver the same user experience as native applications. + */ + interface Dialog { + /** + * Note: On Windows and Linux an open dialog can not be both a file selector and a directory selector, + * so if you set properties to ['openFile', 'openDirectory'] on these platforms, a directory selector will be shown. + * + * @param callback If supplied, the API call will be asynchronous. + * @returns On success, returns an array of file paths chosen by the user, + * otherwise returns undefined. + */ + showOpenDialog(browserWindow: BrowserWindow, options: OpenDialogOptions, callback?: (fileNames: string[]) => void): string[]; + /** + * Note: On Windows and Linux an open dialog can not be both a file selector and a directory selector, + * so if you set properties to ['openFile', 'openDirectory'] on these platforms, a directory selector will be shown. + * + * @param callback If supplied, the API call will be asynchronous. + * @returns On success, returns an array of file paths chosen by the user, + * otherwise returns undefined. + */ + showOpenDialog(options: OpenDialogOptions, callback?: (fileNames: string[]) => void): string[]; + /** + * @param callback If supplied, the API call will be asynchronous. + * @returns On success, returns the path of file chosen by the user, otherwise + * returns undefined. + */ + showSaveDialog(browserWindow: BrowserWindow, options: SaveDialogOptions, callback?: (fileName: string) => void): string; + /** + * @param callback If supplied, the API call will be asynchronous. + * @returns On success, returns the path of file chosen by the user, otherwise + * returns undefined. + */ + showSaveDialog(options: SaveDialogOptions, callback?: (fileName: string) => void): string; + /** + * Shows a message box. It will block until the message box is closed. + * @param callback If supplied, the API call will be asynchronous. + * @returns The index of the clicked button. + */ + showMessageBox(browserWindow: BrowserWindow, options: ShowMessageBoxOptions, callback?: (response: number) => void): number; + /** + * Shows a message box. It will block until the message box is closed. + * @param callback If supplied, the API call will be asynchronous. + * @returns The index of the clicked button. + */ + showMessageBox(options: ShowMessageBoxOptions, callback?: (response: number) => void): number; + /** + * Displays a modal dialog that shows an error message. + * + * This API can be called safely before the ready event the app module emits, + * it is usually used to report errors in early stage of startup. + * If called before the app readyevent on Linux, the message will be emitted to stderr, + * and no GUI dialog will appear. + */ + showErrorBox(title: string, content: string): void; + } + + interface OpenDialogOptions { + title?: string; + defaultPath?: string; + /** + * Custom label for the confirmation button, when left empty the default label will be used. + */ + buttonLabel?: string; + /** + * File types that can be displayed or selected. + */ + filters?: { + name: string; + /** + * Extensions without wildcards or dots (e.g. 'png' is good but '.png' and '*.png' are bad). + * To show all files, use the '*' wildcard (no other wildcard is supported). + */ + extensions: string[]; + }[]; + /** + * Contains which features the dialog should use. + */ + properties?: ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory' | 'showHiddenFiles')[]; + } + + interface SaveDialogOptions { + title?: string; + defaultPath?: string; + /** + * Custom label for the confirmation button, when left empty the default label will be used. + */ + buttonLabel?: string; + /** + * File types that can be displayed, see dialog.showOpenDialog for an example. + */ + filters?: { + name: string; + extensions: string[]; + }[]; + } + + interface ShowMessageBoxOptions { + /** + * On Windows, "question" displays the same icon as "info", unless you set an icon using the "icon" option. + */ + type?: 'none' | 'info' | 'error' | 'question' | 'warning'; + /** + * Texts for buttons. On Windows, an empty array will result in one button labeled "OK". + */ + buttons?: string[]; + /** + * Index of the button in the buttons array which will be selected by default when the message box opens. + */ + defaultId?: number; + /** + * Title of the message box (some platforms will not show it). + */ + title?: string; + /** + * Contents of the message box. + */ + message?: string; + /** + * Extra information of the message. + */ + detail?: string; + icon?: NativeImage; + /** + * The value will be returned when user cancels the dialog instead of clicking the buttons of the dialog. + * By default it is the index of the buttons that have "cancel" or "no" as label, + * or 0 if there is no such buttons. On macOS and Windows the index of "Cancel" button + * will always be used as cancelId, not matter whether it is already specified. + */ + cancelId?: number; + /** + * On Windows Electron will try to figure out which one of the buttons are common buttons + * (like "Cancel" or "Yes"), and show the others as command links in the dialog. + * This can make the dialog appear in the style of modern Windows apps. + * If you don’t like this behavior, you can set noLink to true. + */ + noLink?: boolean; + } + + // https://github.com/electron/electron/blob/master/docs/api/download-item.md + + /** + * DownloadItem represents a download item in Electron. + */ + interface DownloadItem extends NodeJS.EventEmitter { + /** + * Emitted when the download has been updated and is not done. + */ + on(event: 'updated', listener: (event: Event, state: 'progressing' | 'interrupted') => void): this; + /** + * Emits when the download is in a terminal state. This includes a completed download, + * a cancelled download (via downloadItem.cancel()), and interrupted download that can’t be resumed. + */ + on(event: 'done', listener: (event: Event, state: 'completed' | 'cancelled' | 'interrupted') => void): this; + on(event: string, listener: Function): this; + /** + * Set the save file path of the download item. + * Note: The API is only available in session’s will-download callback function. + * If user doesn’t set the save path via the API, Electron will use the original + * routine to determine the save path (Usually prompts a save dialog). + */ + setSavePath(path: string): void; + /** + * @returns The save path of the download item. + * This will be either the path set via downloadItem.setSavePath(path) or the path selected from the shown save dialog. + */ + getSavePath(): string; + /** + * Pauses the download. + */ + pause(): void; + /** + * @returns Whether the download is paused. + */ + isPaused(): boolean; + /** + * Resumes the download that has been paused. + */ + resume(): void; + /** + * @returns Whether the download can resume. + */ + canResume(): boolean; + /** + * Cancels the download operation. + */ + cancel(): void; + /** + * @returns The origin url where the item is downloaded from. + */ + getURL(): string; + /** + * @returns The mime type. + */ + getMimeType(): string; + /** + * @returns Whether the download has user gesture. + */ + hasUserGesture(): boolean; + /** + * @returns The file name of the download item. + * Note: The file name is not always the same as the actual one saved in local disk. + * If user changes the file name in a prompted download saving dialog, + * the actual name of saved file will be different. + */ + getFilename(): string; + /** + * @returns The total size in bytes of the download item. If the size is unknown, it returns 0. + */ + getTotalBytes(): number; + /** + * @returns The received bytes of the download item. + */ + getReceivedBytes(): number; + /** + * @returns The Content-Disposition field from the response header. + */ + getContentDisposition(): string; + /** + * @returns The current state. + */ + getState(): 'progressing' | 'completed' | 'cancelled' | 'interrupted'; + } + + // https://github.com/electron/electron/blob/master/docs/api/global-shortcut.md + + /** + * The globalShortcut module can register/unregister a global keyboard shortcut + * with the operating system so that you can customize the operations for various shortcuts. + * Note: The shortcut is global; it will work even if the app does not have the keyboard focus. + * You should not use this module until the ready event of the app module is emitted. + */ + interface GlobalShortcut { + /** + * Registers a global shortcut of accelerator. + * @param accelerator Represents a keyboard shortcut. It can contain modifiers + * and key codes, combined by the "+" character. + * @param callback Called when the registered shortcut is pressed by the user. + */ + register(accelerator: string, callback: Function): void; + /** + * @param accelerator Represents a keyboard shortcut. It can contain modifiers + * and key codes, combined by the "+" character. + * @returns Whether the accelerator is registered. + */ + isRegistered(accelerator: string): boolean; + /** + * Unregisters the global shortcut of keycode. + * @param accelerator Represents a keyboard shortcut. It can contain modifiers + * and key codes, combined by the "+" character. + */ + unregister(accelerator: string): void; + /** + * Unregisters all the global shortcuts. + */ + unregisterAll(): void; + } + + // https://github.com/electron/electron/blob/master/docs/api/ipc-main.md + + /** + * The ipcMain module handles asynchronous and synchronous messages + * sent from a renderer process (web page). + * Messages sent from a renderer will be emitted to this module. + */ + interface IpcMain extends NodeJS.EventEmitter { + addListener(channel: string, listener: IpcMainEventListener): this; + on(channel: string, listener: IpcMainEventListener): this; + once(channel: string, listener: IpcMainEventListener): this; + removeListener(channel: string, listener: IpcMainEventListener): this; + removeAllListeners(channel?: string): this; + } + + type IpcMainEventListener = (event: IpcMainEvent, ...args: any[]) => void; + + interface IpcMainEvent { + /** + * Set this to the value to be returned in a synchronous message. + */ + returnValue?: any; + /** + * Returns the webContents that sent the message, you can call sender.send + * to reply to the asynchronous message. + */ + sender: WebContents; + } + + // https://github.com/electron/electron/blob/master/docs/api/ipc-renderer.md + + /** + * The ipcRenderer module provides a few methods so you can send synchronous + * and asynchronous messages from the render process (web page) to the main process. + * You can also receive replies from the main process. + */ + interface IpcRenderer extends NodeJS.EventEmitter { + addListener(channel: string, listener: IpcRendererEventListener): this; + on(channel: string, listener: IpcRendererEventListener): this; + once(channel: string, listener: IpcRendererEventListener): this; + removeListener(channel: string, listener: IpcRendererEventListener): this; + removeAllListeners(channel?: string): this; + /** + * Send ...args to the renderer via channel in asynchronous message, the main + * process can handle it by listening to the channel event of ipc module. + */ + send(channel: string, ...args: any[]): void; + /** + * Send ...args to the renderer via channel in synchronous message, and returns + * the result sent from main process. The main process can handle it by listening + * to the channel event of ipc module, and returns by setting event.returnValue. + * Note: Usually developers should never use this API, since sending synchronous + * message would block the whole renderer process. + * @returns The result sent from the main process. + */ + sendSync(channel: string, ...args: any[]): any; + /** + * Like ipc.send but the message will be sent to the host page instead of the main process. + * This is mainly used by the page in to communicate with host page. + */ + sendToHost(channel: string, ...args: any[]): void; + } + + type IpcRendererEventListener = (event: IpcRendererEvent, ...args: any[]) => void; + + interface IpcRendererEvent { + /** + * You can call sender.send to reply to the asynchronous message. + */ + sender: IpcRenderer; + } + + // https://github.com/electron/electron/blob/master/docs/api/menu-item.md + // https://github.com/electron/electron/blob/master/docs/api/accelerator.md + + /** + * The MenuItem allows you to add items to an application or context menu. + */ + class MenuItem { + /** + * Create a new menu item. + */ + constructor(options: MenuItemOptions); + + click: (menuItem: MenuItem, browserWindow: BrowserWindow, event: Event) => void; + /** + * Read-only property. + */ + type: MenuItemType; + /** + * Read-only property. + */ + role: MenuItemRole | MenuItemRoleMac; + /** + * Read-only property. + */ + accelerator: string; + /** + * Read-only property. + */ + icon: NativeImage | string; + /** + * Read-only property. + */ + submenu: Menu | MenuItemOptions[]; + + label: string; + sublabel: string; + enabled: boolean; + visible: boolean; + checked: boolean; + } + + type MenuItemType = 'normal' | 'separator' | 'submenu' | 'checkbox' | 'radio'; + type MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteandmatchstyle' | 'selectall' | 'delete' | 'minimize' | 'close' | 'quit' | 'togglefullscreen' | 'resetzoom' | 'zoomin' | 'zoomout'; + type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'startspeaking' | 'stopspeaking' | 'front' | 'zoom' | 'window' | 'help' | 'services'; + + interface MenuItemOptions { + /** + * Callback when the menu item is clicked. + */ + click?: (menuItem: MenuItem, browserWindow: BrowserWindow) => void; + /** + * Can be normal, separator, submenu, checkbox or radio. + */ + type?: MenuItemType; + label?: string; + sublabel?: string; + /** + * An accelerator is string that represents a keyboard shortcut, it can contain + * multiple modifiers and key codes, combined by the + character. + * + * Examples: + * CommandOrControl+A + * CommandOrControl+Shift+Z + * + * Platform notice: + * On Linux and Windows, the Command key would not have any effect, + * you can use CommandOrControl which represents Command on macOS and Control on + * Linux and Windows to define some accelerators. + * + * Use Alt instead of Option. The Option key only exists on macOS, whereas + * the Alt key is available on all platforms. + * + * The Super key is mapped to the Windows key on Windows and Linux and Cmd on macOS. + * + * Available modifiers: + * Command (or Cmd for short) + * Control (or Ctrl for short) + * CommandOrControl (or CmdOrCtrl for short) + * Alt + * Option + * AltGr + * Shift + * Super + * + * Available key codes: + * 0 to 9 + * A to Z + * F1 to F24 + * Punctuations like ~, !, @, #, $, etc. + * Plus + * Space + * Tab + * Backspace + * Delete + * Insert + * Return (or Enter as alias) + * Up, Down, Left and Right + * Home and End + * PageUp and PageDown + * Escape (or Esc for short) + * VolumeUp, VolumeDown and VolumeMute + * MediaNextTrack, MediaPreviousTrack, MediaStop and MediaPlayPause + * PrintScreen + */ + accelerator?: string; + /** + * In Electron for the APIs that take images, you can pass either file paths + * or NativeImage instances. When passing null, an empty image will be used. + */ + icon?: NativeImage|string; + /** + * If false, the menu item will be greyed out and unclickable. + */ + enabled?: boolean; + /** + * If false, the menu item will be entirely hidden. + */ + visible?: boolean; + /** + * Should only be specified for 'checkbox' or 'radio' type menu items. + */ + checked?: boolean; + /** + * Should be specified for submenu type menu item, when it's specified the + * type: 'submenu' can be omitted for the menu item + */ + submenu?: Menu|MenuItemOptions[]; + /** + * Unique within a single menu. If defined then it can be used as a reference + * to this item by the position attribute. + */ + id?: string; + /** + * This field allows fine-grained definition of the specific location within + * a given menu. + */ + position?: string; + /** + * Define the action of the menu item, when specified the click property will be ignored + */ + role?: MenuItemRole | MenuItemRoleMac; + } + + // https://github.com/electron/electron/blob/master/docs/api/menu.md + + /** + * The Menu class is used to create native menus that can be used as application + * menus and context menus. This module is a main process module which can be used + * in a render process via the remote module. + * + * Each menu consists of multiple menu items, and each menu item can have a submenu. + */ + class Menu extends NodeJS.EventEmitter { + /** + * Creates a new menu. + */ + constructor(); + /** + * Sets menu as the application menu on macOS. On Windows and Linux, the menu + * will be set as each window's top menu. + */ + static setApplicationMenu(menu: Menu): void; + /** + * @returns The application menu if set, or null if not set. + */ + static getApplicationMenu(): Menu; + /** + * Sends the action to the first responder of application. + * This is used for emulating default Cocoa menu behaviors, + * usually you would just use the role property of MenuItem. + * + * Note: This method is macOS only. + */ + static sendActionToFirstResponder(action: string): void; + /** + * @param template Generally, just an array of options for constructing MenuItem. + * You can also attach other fields to element of the template, and they will + * become properties of the constructed menu items. + */ + static buildFromTemplate(template: MenuItemOptions[]): Menu; + /** + * Pops up this menu as a context menu in the browserWindow. You can optionally + * provide a (x,y) coordinate to place the menu at, otherwise it will be placed + * at the current mouse cursor position. + * @param x Horizontal coordinate where the menu will be placed. + * @param y Vertical coordinate where the menu will be placed. + */ + popup(browserWindow?: BrowserWindow, x?: number, y?: number): void; + /** + * Appends the menuItem to the menu. + */ + append(menuItem: MenuItem): void; + /** + * Inserts the menuItem to the pos position of the menu. + */ + insert(position: number, menuItem: MenuItem): void; + /** + * @returns an array containing the menu’s items. + */ + items: MenuItem[]; + } + + // https://github.com/electron/electron/blob/master/docs/api/native-image.md + + /** + * This class is used to represent an image. + */ + class NativeImage { + /** + * Creates an empty NativeImage instance. + */ + static createEmpty(): NativeImage; + /** + * Creates a new NativeImage instance from file located at path. + * This method returns an empty image if the path does not exist, cannot be read, or is not a valid image. + */ + static createFromPath(path: string): NativeImage; + /** + * Creates a new NativeImage instance from buffer. + * @param scaleFactor 1.0 by default. + */ + static createFromBuffer(buffer: Buffer, scaleFactor?: number): NativeImage; + /** + * Creates a new NativeImage instance from dataURL + */ + static createFromDataURL(dataURL: string): NativeImage; + /** + * @returns Buffer that contains the image's PNG encoded data. + */ + toPNG(): Buffer; + /** + * @returns Buffer that contains the image's JPEG encoded data. + */ + toJPEG(quality: number): Buffer; + /** + * @returns Buffer that contains a copy of the image's raw bitmap pixel data. + */ + toBitmap(): Buffer; + /** + * @returns Buffer that contains the image's raw bitmap pixel data. + * + * The difference between getBitmap() and toBitmap() is, getBitmap() does not copy the bitmap data, + * so you have to use the returned Buffer immediately in current event loop tick, + * otherwise the data might be changed or destroyed. + */ + getBitmap(): Buffer; + /** + * @returns The data URL of the image. + */ + toDataURL(): string; + /** + * The native type of the handle is NSImage* on macOS. + * Note: This is only implemented on macOS. + * @returns The platform-specific handle of the image as Buffer. + */ + getNativeHandle(): Buffer; + /** + * @returns Whether the image is empty. + */ + isEmpty(): boolean; + /** + * @returns The size of the image. + */ + getSize(): Size; + /** + * Marks the image as template image. + */ + setTemplateImage(option: boolean): void; + /** + * Returns a boolean whether the image is a template image. + */ + isTemplateImage(): boolean; + /** + * @param rect The area of the image to crop + * @returns The cropped image. + */ + crop(rect: Rectangle): NativeImage; + /** + * @returns The resized image. + * If only the height or the width are specified then the current aspect ratio will be preserved in the resized image. + */ + resize(options: { + width?: number; + height?: number; + /** + * The desired quality of the resized image. + * Default: best. + */ + quality?: 'good' | 'better' | 'best'; + }): NativeImage; + /** + * @returns The image's aspect ratio. + */ + getAspectRatio(): number; + } + + // https://github.com/electron/electron/blob/master/docs/api/power-monitor.md + + /** + * The power-monitor module is used to monitor power state changes. + * You should not use this module until the ready event of the app module is emitted. + */ + interface PowerMonitor extends NodeJS.EventEmitter { + /** + * Emitted when the system is suspending. + */ + on(event: 'suspend', listener: Function): this; + /** + * Emitted when system is resuming. + */ + on(event: 'resume', listener: Function): this; + /** + * Emitted when the system changes to AC power. + */ + on(event: 'on-ac', listener: Function): this; + /** + * Emitted when system changes to battery power. + */ + on(event: 'on-battery', listener: Function): this; + on(event: string, listener: Function): this; + } + + // https://github.com/electron/electron/blob/master/docs/api/power-save-blocker.md + + /** + * The powerSaveBlocker module is used to block the system from entering + * low-power (sleep) mode and thus allowing the app to keep the system and screen active. + */ + interface PowerSaveBlocker { + /** + * Starts preventing the system from entering lower-power mode. + * @returns The blocker ID that is assigned to this power blocker. + * Note: prevent-display-sleep has higher has precedence over prevent-app-suspension. + */ + start(type: 'prevent-app-suspension' | 'prevent-display-sleep'): number; + /** + * @param id The power save blocker id returned by powerSaveBlocker.start. + * Stops the specified power save blocker. + */ + stop(id: number): void; + /** + * @param id The power save blocker id returned by powerSaveBlocker.start. + * @returns Whether the corresponding powerSaveBlocker has started. + */ + isStarted(id: number): boolean; + } + + // https://github.com/electron/electron/blob/master/docs/api/protocol.md + + /** + * The protocol module can register a custom protocol or intercept an existing protocol. + */ + interface Protocol { + /** + * Registers custom schemes as standard schemes. + */ + registerStandardSchemes(schemes: string[]): void; + /** + * Registers custom schemes to handle service workers. + */ + registerServiceWorkerSchemes(schemes: string[]): void; + /** + * Registers a protocol of scheme that will send the file as a response. + */ + registerFileProtocol(scheme: string, handler: FileProtocolHandler, completion?: (error: Error) => void): void; + /** + * Registers a protocol of scheme that will send a Buffer as a response. + */ + registerBufferProtocol(scheme: string, handler: BufferProtocolHandler, completion?: (error: Error) => void): void; + /** + * Registers a protocol of scheme that will send a String as a response. + */ + registerStringProtocol(scheme: string, handler: StringProtocolHandler, completion?: (error: Error) => void): void; + /** + * Registers a protocol of scheme that will send an HTTP request as a response. + */ + registerHttpProtocol(scheme: string, handler: HttpProtocolHandler, completion?: (error: Error) => void): void; + /** + * Unregisters the custom protocol of scheme. + */ + unregisterProtocol(scheme: string, completion?: (error: Error) => void): void; + /** + * The callback will be called with a boolean that indicates whether there is already a handler for scheme. + */ + isProtocolHandled(scheme: string, callback: (handled: boolean) => void): void; + /** + * Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a file as a response. + */ + interceptFileProtocol(scheme: string, handler: FileProtocolHandler, completion?: (error: Error) => void): void; + /** + * Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a Buffer as a response. + */ + interceptBufferProtocol(scheme: string, handler: BufferProtocolHandler, completion?: (error: Error) => void): void; + /** + * Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a String as a response. + */ + interceptStringProtocol(scheme: string, handler: StringProtocolHandler, completion?: (error: Error) => void): void; + /** + * Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a new HTTP request as a response. + */ + interceptHttpProtocol(scheme: string, handler: HttpProtocolHandler, completion?: (error: Error) => void): void; + /** + * Remove the interceptor installed for scheme and restore its original handler. + */ + uninterceptProtocol(scheme: string, completion?: (error: Error) => void): void; + } + + type FileProtocolHandler = (request: ProtocolRequest, callback: FileProtocolCallback) => void; + type BufferProtocolHandler = (request: ProtocolRequest, callback: BufferProtocolCallback) => void; + type StringProtocolHandler = (request: ProtocolRequest, callback: StringProtocolCallback) => void; + type HttpProtocolHandler = (request: ProtocolRequest, callback: HttpProtocolCallback) => void; + + interface ProtocolRequest { + url: string; + referrer: string; + method: string; + uploadData?: { + /** + * Content being sent. + */ + bytes: Buffer, + /** + * Path of file being uploaded. + */ + file: string, + /** + * UUID of blob data. Use session.getBlobData method to retrieve the data. + */ + blobUUID: string; + }[]; + } + + interface ProtocolCallback { + (error: number): void; + (obj: { + error: number + }): void; + (): void; + } + + interface FileProtocolCallback extends ProtocolCallback { + (filePath: string): void; + (obj: { + path: string + }): void; + } + + interface BufferProtocolCallback extends ProtocolCallback { + (buffer: Buffer): void; + (obj: { + data: Buffer, + mimeType: string, + charset?: string + }): void; + } + + interface StringProtocolCallback extends ProtocolCallback { + (str: string): void; + (obj: { + data: Buffer, + mimeType: string, + charset?: string + }): void; + } + + interface HttpProtocolCallback extends ProtocolCallback { + (redirectRequest: { + url: string; + method: string; + session?: Object; + uploadData?: { + contentType: string; + data: string; + }; + }): void; + } + + // https://github.com/electron/electron/blob/master/docs/api/remote.md + + /** + * The remote module provides a simple way to do inter-process communication (IPC) + * between the renderer process (web page) and the main process. + */ + interface Remote extends CommonElectron { + /** + * @returns The object returned by require(module) in the main process. + */ + require(module: string): any; + /** + * @returns The BrowserWindow object which this web page belongs to. + */ + getCurrentWindow(): BrowserWindow; + /** + * @returns The WebContents object of this web page. + */ + getCurrentWebContents(): WebContents; + /** + * @returns The global variable of name (e.g. global[name]) in the main process. + */ + getGlobal(name: string): any; + /** + * Returns the process object in the main process. This is the same as + * remote.getGlobal('process'), but gets cached. + */ + process: NodeJS.Process; + } + + // https://github.com/electron/electron/blob/master/docs/api/screen.md + + /** + * The Display object represents a physical display connected to the system. + * A fake Display may exist on a headless system, or a Display may correspond to a remote, virtual display. + */ + interface Display { + /** + * Unique identifier associated with the display. + */ + id: number; + bounds: Rectangle; + workArea: Rectangle; + size: Size; + workAreaSize: Size; + /** + * Output device’s pixel scale factor. + */ + scaleFactor: number; + /** + * Can be 0, 90, 180, 270, represents screen rotation in clock-wise degrees. + */ + rotation: number; + touchSupport: 'available' | 'unavailable' | 'unknown'; + } + + type DisplayMetrics = 'bounds' | 'workArea' | 'scaleFactor' | 'rotation'; + + /** + * The screen module retrieves information about screen size, displays, cursor position, etc. + * You can not use this module until the ready event of the app module is emitted. + */ + interface Screen extends NodeJS.EventEmitter { + /** + * Emitted when newDisplay has been added. + */ + on(event: 'display-added', listener: (event: Event, newDisplay: Display) => void): this; + /** + * Emitted when oldDisplay has been removed. + */ + on(event: 'display-removed', listener: (event: Event, oldDisplay: Display) => void): this; + /** + * Emitted when one or more metrics change in a display. + */ + on(event: 'display-metrics-changed', listener: (event: Event, display: Display, changedMetrics: DisplayMetrics[]) => void): this; + on(event: string, listener: Function): this; + /** + * @returns The current absolute position of the mouse pointer. + */ + getCursorScreenPoint(): Point; + /** + * @returns The primary display. + */ + getPrimaryDisplay(): Display; + /** + * @returns An array of displays that are currently available. + */ + getAllDisplays(): Display[]; + /** + * @returns The display nearest the specified point. + */ + getDisplayNearestPoint(point: Point): Display; + /** + * @returns The display that most closely intersects the provided bounds. + */ + getDisplayMatching(rect: Rectangle): Display; + } + + // https://github.com/electron/electron/blob/master/docs/api/session.md + + /** + * The session module can be used to create new Session objects. + * You can also access the session of existing pages by using + * the session property of webContents which is a property of BrowserWindow. + */ + class Session extends NodeJS.EventEmitter { + /** + * @returns a new Session instance from partition string. + */ + static fromPartition(partition: string, options?: FromPartitionOptions): Session; + /** + * @returns the default session object of the app. + */ + static defaultSession: Session; + /** + * Emitted when Electron is about to download item in webContents. + * Calling event.preventDefault() will cancel the download + * and item will not be available from next tick of the process. + */ + on(event: 'will-download', listener: (event: Event, item: DownloadItem, webContents: WebContents) => void): this; + on(event: string, listener: Function): this; + /** + * The cookies gives you ability to query and modify cookies. + */ + cookies: SessionCookies; + /** + * @returns the session’s current cache size. + */ + getCacheSize(callback: (size: number) => void): void; + /** + * Clears the session’s HTTP cache. + */ + clearCache(callback: Function): void; + /** + * Clears the data of web storages. + */ + clearStorageData(callback: Function): void; + /** + * Clears the data of web storages. + */ + clearStorageData(options: ClearStorageDataOptions, callback: Function): void; + /** + * Writes any unwritten DOMStorage data to disk. + */ + flushStorageData(): void; + /** + * Sets the proxy settings. + */ + setProxy(config: ProxyConfig, callback: Function): void; + /** + * Resolves the proxy information for url. + */ + resolveProxy(url: URL, callback: (proxy: string) => void): void; + /** + * Sets download saving directory. + * By default, the download directory will be the Downloads under the respective app folder. + */ + setDownloadPath(path: string): void; + /** + * Emulates network with the given configuration for the session. + */ + enableNetworkEmulation(options: NetworkEmulationOptions): void; + /** + * Disables any network emulation already active for the session. + * Resets to the original network configuration. + */ + disableNetworkEmulation(): void; + /** + * Sets the certificate verify proc for session, the proc will be called + * whenever a server certificate verification is requested. + * + * Calling setCertificateVerifyProc(null) will revert back to default certificate verify proc. + */ + setCertificateVerifyProc(proc: (hostname: string, cert: Certificate, callback: (accepted: boolean) => void) => void): void; + /** + * Sets the handler which can be used to respond to permission requests for the session. + */ + setPermissionRequestHandler(handler: (webContents: WebContents, permission: Permission, callback: (allow: boolean) => void) => void): void; + /** + * Clears the host resolver cache. + */ + clearHostResolverCache(callback: Function): void; + /** + * Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication. + * @param domains Comma-seperated list of servers for which integrated authentication is enabled. + */ + allowNTLMCredentialsForDomains(domains: string): void; + /** + * Overrides the userAgent and acceptLanguages for this session. + * The acceptLanguages must a comma separated ordered list of language codes, for example "en-US,fr,de,ko,zh-CN,ja". + * This doesn't affect existing WebContents, and each WebContents can use webContents.setUserAgent to override the session-wide user agent. + */ + setUserAgent(userAgent: string, acceptLanguages?: string): void; + /** + * @returns The user agent for this session. + */ + getUserAgent(): string; + /** + * Returns the blob data associated with the identifier. + */ + getBlobData(identifier: string, callback: (result: Buffer) => void): void; + /** + * The webRequest API set allows to intercept and modify contents of a request at various stages of its lifetime. + */ + webRequest: WebRequest; + /** + * @returns An instance of protocol module for this session. + */ + protocol: Protocol; + } + + type Permission = 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal'; + + interface FromPartitionOptions { + /** + * Whether to enable cache. + */ + cache?: boolean; + } + + interface ClearStorageDataOptions { + /** + * Should follow window.location.origin’s representation scheme://host:port. + */ + origin?: string; + /** + * The types of storages to clear. + */ + storages?: ('appcache' | 'cookies' | 'filesystem' | 'indexdb' | 'localstorage' | 'shadercache' | 'websql' | 'serviceworkers')[]; + /** + * The types of quotas to clear. + */ + quotas?: ('temporary' | 'persistent' | 'syncable')[]; + } + + interface ProxyConfig { + /** + * The URL associated with the PAC file. + */ + pacScript: string; + /** + * Rules indicating which proxies to use. + */ + proxyRules: string; + /** + * Rules indicating which URLs should bypass the proxy settings. + */ + proxyBypassRules: string; + } + + interface NetworkEmulationOptions { + /** + * Whether to emulate network outage. + * Default: false. + */ + offline?: boolean; + /** + * RTT in ms. + * Default: 0, which will disable latency throttling. + */ + latency?: number; + /** + * Download rate in Bps. + * Default: 0, which will disable download throttling. + */ + downloadThroughput?: number; + /** + * Upload rate in Bps. + * Default: 0, which will disable upload throttling. + */ + uploadThroughput?: number; + } + + interface CookieFilter { + /** + * Retrieves cookies which are associated with url. Empty implies retrieving cookies of all urls. + */ + url?: string; + /** + * Filters cookies by name. + */ + name?: string; + /** + * Retrieves cookies whose domains match or are subdomains of domains. + */ + domain?: string; + /** + * Retrieves cookies whose path matches path. + */ + path?: string; + /** + * Filters cookies by their Secure property. + */ + secure?: boolean; + /** + * Filters out session or persistent cookies. + */ + session?: boolean; + } + + interface Cookie { + /** + * Emitted when a cookie is changed because it was added, edited, removed, or expired. + */ + on(event: 'changed', listener: (event: Event, cookie: Cookie, cause: CookieChangedCause) => void): this; + on(event: string, listener: Function): this; + /** + * The name of the cookie. + */ + name: string; + /** + * The value of the cookie. + */ + value: string; + /** + * The domain of the cookie. + */ + domain: string; + /** + * Whether the cookie is a host-only cookie. + */ + hostOnly: string; + /** + * The path of the cookie. + */ + path: string; + /** + * Whether the cookie is marked as secure. + */ + secure: boolean; + /** + * Whether the cookie is marked as HTTP only. + */ + httpOnly: boolean; + /** + * Whether the cookie is a session cookie or a persistent cookie with an expiration date. + */ + session: boolean; + /** + * The expiration date of the cookie as the number of seconds since the UNIX epoch. + * Not provided for session cookies. + */ + expirationDate?: number; + } + + type CookieChangedCause = 'explicit' | 'overwrite' | 'expired' | 'evicted' | 'expired-overwrite'; + + interface CookieDetails { + /** + * The URL associated with the cookie. + */ + url: string; + /** + * The name of the cookie. + * Default: empty. + */ + name?: string; + /** + * The value of the cookie. + * Default: empty. + */ + value?: string; + /** + * The domain of the cookie. + * Default: empty. + */ + domain?: string; + /** + * The path of the cookie. + * Default: empty. + */ + path?: string; + /** + * Whether the cookie should be marked as secure. + * Default: false. + */ + secure?: boolean; + /** + * Whether the cookie should be marked as HTTP only. + * Default: false. + */ + httpOnly?: boolean; + /** + * The expiration date of the cookie as the number of seconds since the UNIX epoch. + * If omitted, the cookie becomes a session cookie. + */ + expirationDate?: number; + } + + interface SessionCookies { + /** + * Sends a request to get all cookies matching filter. + */ + get(filter: CookieFilter, callback: (error: Error, cookies: Cookie[]) => void): void; + /** + * Sets the cookie with details. + */ + set(details: CookieDetails, callback: (error: Error) => void): void; + /** + * Removes the cookies matching url and name. + */ + remove(url: string, name: string, callback: (error: Error) => void): void; + } + + /** + * Each API accepts an optional filter and a listener, the listener will be called when the API's event has happened. + * Passing null as listener will unsubscribe from the event. + * + * The filter will be used to filter out the requests that do not match the URL patterns. + * If the filter is omitted then all requests will be matched. + * + * For certain events the listener is passed with a callback, + * which should be called with an response object when listener has done its work. + */ + interface WebRequest { + /** + * The listener will be called when a request is about to occur. + */ + onBeforeRequest(listener: (details: WebRequest.BeforeRequestDetails, callback: WebRequest.BeforeRequestCallback) => void): void; + /** + * The listener will be called when a request is about to occur. + */ + onBeforeRequest(filter: WebRequest.Filter, listener: (details: WebRequest.BeforeRequestDetails, callback: WebRequest.BeforeRequestCallback) => void): void; + /** + * The listener will be called before sending an HTTP request, once the request headers are available. + * This may occur after a TCP connection is made to the server, but before any http data is sent. + */ + onBeforeSendHeaders(listener: (details: WebRequest.BeforeSendHeadersDetails, callback: WebRequest.BeforeSendHeadersCallback) => void): void; + /** + * The listener will be called before sending an HTTP request, once the request headers are available. + * This may occur after a TCP connection is made to the server, but before any http data is sent. + */ + onBeforeSendHeaders(filter: WebRequest.Filter, listener: (details: WebRequest.BeforeSendHeadersDetails, callback: WebRequest.BeforeSendHeadersCallback) => void): void; + /** + * The listener will be called just before a request is going to be sent to the server, + * modifications of previous onBeforeSendHeaders response are visible by the time this listener is fired. + */ + onSendHeaders(listener: (details: WebRequest.SendHeadersDetails) => void): void; + /** + * The listener will be called just before a request is going to be sent to the server, + * modifications of previous onBeforeSendHeaders response are visible by the time this listener is fired. + */ + onSendHeaders(filter: WebRequest.Filter, listener: (details: WebRequest.SendHeadersDetails) => void): void; + /** + * The listener will be called when HTTP response headers of a request have been received. + */ + onHeadersReceived(listener: (details: WebRequest.HeadersReceivedDetails, callback: WebRequest.HeadersReceivedCallback) => void): void; + /** + * The listener will be called when HTTP response headers of a request have been received. + */ + onHeadersReceived(filter: WebRequest.Filter, listener: (details: WebRequest.HeadersReceivedDetails, callback: WebRequest.HeadersReceivedCallback) => void): void; + /** + * The listener will be called when first byte of the response body is received. + * For HTTP requests, this means that the status line and response headers are available. + */ + onResponseStarted(listener: (details: WebRequest.ResponseStartedDetails) => void): void; + /** + * The listener will be called when first byte of the response body is received. + * For HTTP requests, this means that the status line and response headers are available. + */ + onResponseStarted(filter: WebRequest.Filter, listener: (details: WebRequest.ResponseStartedDetails) => void): void; + /** + * The listener will be called when a server initiated redirect is about to occur. + */ + onBeforeRedirect(listener: (details: WebRequest.BeforeRedirectDetails) => void): void; + /** + * The listener will be called when a server initiated redirect is about to occur. + */ + onBeforeRedirect(filter: WebRequest.Filter, listener: (details: WebRequest.BeforeRedirectDetails) => void): void; + /** + * The listener will be called when a request is completed. + */ + onCompleted(listener: (details: WebRequest.CompletedDetails) => void): void; + /** + * The listener will be called when a request is completed. + */ + onCompleted(filter: WebRequest.Filter, listener: (details: WebRequest.CompletedDetails) => void): void; + /** + * The listener will be called when an error occurs. + */ + onErrorOccurred(listener: (details: WebRequest.ErrorOccurredDetails) => void): void; + /** + * The listener will be called when an error occurs. + */ + onErrorOccurred(filter: WebRequest.Filter, listener: (details: WebRequest.ErrorOccurredDetails) => void): void; + } + + namespace WebRequest { + interface Filter { + urls: string[]; + } + + interface Details { + id: number; + url: string; + method: string; + resourceType: string; + timestamp: number; + } + + interface UploadData { + /** + * Content being sent. + */ + bytes: Buffer; + /** + * Path of file being uploaded. + */ + file: string; + /** + * UUID of blob data. Use session.getBlobData method to retrieve the data. + */ + blobUUID: string; + } + + interface BeforeRequestDetails extends Details { + uploadData?: UploadData[]; + } + + type BeforeRequestCallback = (response: { + cancel?: boolean; + /** + * The original request is prevented from being sent or completed, and is instead redirected to the given URL. + */ + redirectURL?: string; + }) => void; + + interface BeforeSendHeadersDetails extends Details { + requestHeaders: Headers; + } + + type BeforeSendHeadersCallback = (response: { + cancel?: boolean; + /** + * When provided, request will be made with these headers. + */ + requestHeaders?: Headers; + }) => void; + + interface SendHeadersDetails extends Details { + requestHeaders: Headers; + } + + interface HeadersReceivedDetails extends Details { + statusLine: string; + statusCode: number; + responseHeaders: Headers; + } + + type HeadersReceivedCallback = (response: { + cancel?: boolean; + /** + * When provided, the server is assumed to have responded with these headers. + */ + responseHeaders?: Headers; + /** + * Should be provided when overriding responseHeaders to change header status + * otherwise original response header's status will be used. + */ + statusLine?: string; + }) => void; + + interface ResponseStartedDetails extends Details { + responseHeaders: Headers; + fromCache: boolean; + statusCode: number; + statusLine: string; + } + + interface BeforeRedirectDetails extends Details { + redirectURL: string; + statusCode: number; + ip?: string; + fromCache: boolean; + responseHeaders: Headers; + } + + interface CompletedDetails extends Details { + responseHeaders: Headers; + fromCache: boolean; + statusCode: number; + statusLine: string; + } + + interface ErrorOccurredDetails extends Details { + fromCache: boolean; + error: string; + } + } + + // https://github.com/electron/electron/blob/master/docs/api/shell.md + + /** + * The shell module provides functions related to desktop integration. + */ + interface Shell { + /** + * Show the given file in a file manager. If possible, select the file. + * @returns Whether the item was successfully shown. + */ + showItemInFolder(fullPath: string): boolean; + /** + * Open the given file in the desktop's default manner. + * @returns Whether the item was successfully shown. + */ + openItem(fullPath: string): boolean; + /** + * Open the given external protocol URL in the desktop's default manner + * (e.g., mailto: URLs in the default mail user agent). + * @returns Whether an application was available to open the URL. + */ + openExternal(url: string, options?: { + /** + * Bring the opened application to the foreground. + * Default: true. + */ + activate: boolean; + }): boolean; + /** + * Move the given file to trash. + * @returns Whether the item was successfully moved to the trash. + */ + moveItemToTrash(fullPath: string): boolean; + /** + * Play the beep sound. + */ + beep(): void; + /** + * Creates or updates a shortcut link at shortcutPath. + * + * Note: This API is available only on Windows. + */ + writeShortcutLink(shortcutPath: string, options: ShortcutLinkOptions): boolean; + /** + * Creates or updates a shortcut link at shortcutPath. + * + * Note: This API is available only on Windows. + */ + writeShortcutLink(shortcutPath: string, operation: 'create' | 'update' | 'replace', options: ShortcutLinkOptions): boolean; + /** + * Resolves the shortcut link at shortcutPath. + * An exception will be thrown when any error happens. + * + * Note: This API is available only on Windows. + */ + readShortcutLink(shortcutPath: string): ShortcutLinkOptions; + } + + interface ShortcutLinkOptions { + /** + * The target to launch from this shortcut. + */ + target: string; + /** + * The working directory. + * Default: empty. + */ + cwd?: string; + /** + * The arguments to be applied to target when launching from this shortcut. + * Default: empty. + */ + args?: string; + /** + * The description of the shortcut. + * Default: empty. + */ + description?: string; + /** + * The path to the icon, can be a DLL or EXE. icon and iconIndex have to be set together. + * Default: empty, which uses the target's icon. + */ + icon?: string; + /** + * The resource ID of icon when icon is a DLL or EXE. + * Default: 0. + */ + iconIndex?: number; + /** + * The Application User Model ID. + * Default: empty. + */ + appUserModelId?: string; + } + + // https://github.com/electron/electron/blob/master/docs/api/system-preferences.md + + type SystemColor = + '3d-dark-shadow' | // Dark shadow for three-dimensional display elements. + '3d-face' | // Face color for three-dimensional display elements and for dialog box backgrounds. + '3d-highlight' | // Highlight color for three-dimensional display elements. + '3d-light' | // Light color for three-dimensional display elements. + '3d-shadow' | // Shadow color for three-dimensional display elements. + 'active-border' | // Active window border. + 'active-caption' | // Active window title bar. Specifies the left side color in the color gradient of an active window's title bar if the gradient effect is enabled. + 'active-caption-gradient' | // Right side color in the color gradient of an active window's title bar. + 'app-workspace' | // Background color of multiple document interface (MDI) applications. + 'button-text' | // Text on push buttons. + 'caption-text' | // Text in caption, size box, and scroll bar arrow box. + 'desktop' | // Desktop background color. + 'disabled-text' | // Grayed (disabled) text. + 'highlight' | // Item(s) selected in a control. + 'highlight-text' | // Text of item(s) selected in a control. + 'hotlight' | // Color for a hyperlink or hot-tracked item. + 'inactive-border' | // Inactive window border. + 'inactive-caption' | // Inactive window caption. Specifies the left side color in the color gradient of an inactive window's title bar if the gradient effect is enabled. + 'inactive-caption-gradient' | // Right side color in the color gradient of an inactive window's title bar. + 'inactive-caption-text' | // Color of text in an inactive caption. + 'info-background' | // Background color for tooltip controls. + 'info-text' | // Text color for tooltip controls. + 'menu' | // Menu background. + 'menu-highlight' | // The color used to highlight menu items when the menu appears as a flat menu. + 'menubar' | // The background color for the menu bar when menus appear as flat menus. + 'menu-text' | // Text in menus. + 'scrollbar' | // Scroll bar gray area. + 'window' | // Window background. + 'window-frame' | // Window frame. + 'window-text'; // Text in windows. + + /** + * Get system preferences. + */ + interface SystemPreferences { + /** + * Note: This is only implemented on Windows. + */ + on(event: 'accent-color-changed', listener: (event: Event, newColor: string) => void): this; + /** + * Note: This is only implemented on Windows. + */ + on(event: 'color-changed', listener: (event: Event) => void): this; + /** + * Note: This is only implemented on Windows. + */ + on(event: 'inverted-color-scheme-changed', listener: ( + event: Event, + /** + * @param invertedColorScheme true if an inverted color scheme, such as a high contrast theme, is being used, false otherwise. + */ + invertedColorScheme: boolean + ) => void): this; + on(event: string, listener: Function): this; + /** + * @returns Whether the system is in Dark Mode. + * + * Note: This is only implemented on macOS. + */ + isDarkMode(): boolean; + /** + * @returns Whether the Swipe between pages setting is on. + * + * Note: This is only implemented on macOS. + */ + isSwipeTrackingFromScrollEventsEnabled(): boolean; + /** + * Posts event as native notifications of macOS. + * The userInfo contains the user information dictionary sent along with the notification. + * + * Note: This is only implemented on macOS. + */ + postNotification(event: string, userInfo: Object): void; + /** + * Posts event as native notifications of macOS. + * The userInfo contains the user information dictionary sent along with the notification. + * + * Note: This is only implemented on macOS. + */ + postLocalNotification(event: string, userInfo: Object): void; + /** + * Subscribes to native notifications of macOS, callback will be called when the corresponding event happens. + * The id of the subscriber is returned, which can be used to unsubscribe the event. + * + * Note: This is only implemented on macOS. + */ + subscribeNotification(event: string, callback: (event: Event, userInfo: Object) => void): number; + /** + * Removes the subscriber with id. + * + * Note: This is only implemented on macOS. + */ + unsubscribeNotification(id: number): void; + /** + * Same as subscribeNotification, but uses NSNotificationCenter for local defaults. + */ + subscribeLocalNotification(event: string, callback: (event: Event, userInfo: Object) => void): number; + /** + * Same as unsubscribeNotification, but removes the subscriber from NSNotificationCenter. + */ + unsubscribeLocalNotification(id: number): void; + /** + * Get the value of key in system preferences. + * + * Note: This is only implemented on macOS. + */ + getUserDefault(key: string, type: 'string' | 'boolean' | 'integer' | 'float' | 'double' | 'url' | 'array' | 'dictionary'): any; + /** + * @returns Whether DWM composition (Aero Glass) is enabled. + * + * Note: This is only implemented on Windows. + */ + isAeroGlassEnabled(): boolean; + /** + * @returns The users current system wide color preference in the form of an RGBA hexadecimal string. + * + * Note: This is only implemented on Windows. + */ + getAccentColor(): string; + /** + * @returns true if an inverted color scheme, such as a high contrast theme, is active, false otherwise. + * + * Note: This is only implemented on Windows. + */ + isInvertedColorScheme(): boolean; + /** + * @returns The system color setting in RGB hexadecimal form (#ABCDEF). See the Windows docs for more details. + * + * Note: This is only implemented on Windows. + */ + getColor(color: SystemColor): string; + } + + // https://github.com/electron/electron/blob/master/docs/api/tray.md + + /** + * A Tray represents an icon in an operating system's notification area. + */ + class Tray extends NodeJS.EventEmitter implements Destroyable { + /** + * Emitted when the tray icon is clicked. + * Note: The bounds payload is only implemented on macOS and Windows. + */ + on(event: 'click', listener: (modifiers: Modifiers, bounds: Rectangle) => void): this; + /** + * Emitted when the tray icon is right clicked. + * Note: This is only implemented on macOS and Windows. + */ + on(event: 'right-click', listener: (modifiers: Modifiers, bounds: Rectangle) => void): this; + /** + * Emitted when the tray icon is double clicked. + * Note: This is only implemented on macOS and Windows. + */ + on(event: 'double-click', listener: (modifiers: Modifiers, bounds: Rectangle) => void): this; + /** + * Emitted when the tray balloon shows. + * Note: This is only implemented on Windows. + */ + on(event: 'balloon-show', listener: Function): this; + /** + * Emitted when the tray balloon is clicked. + * Note: This is only implemented on Windows. + */ + on(event: 'balloon-click', listener: Function): this; + /** + * Emitted when the tray balloon is closed because of timeout or user manually closes it. + * Note: This is only implemented on Windows. + */ + on(event: 'balloon-closed', listener: Function): this; + /** + * Emitted when any dragged items are dropped on the tray icon. + * Note: This is only implemented on macOS. + */ + on(event: 'drop', listener: Function): this; + /** + * Emitted when dragged files are dropped in the tray icon. + * Note: This is only implemented on macOS + */ + on(event: 'drop-files', listener: (event: Event, files: string[]) => void): this; + /** + * Emitted when dragged text is dropped in the tray icon. + * Note: This is only implemented on macOS + */ + on(event: 'drop-text', listener: (event: Event, text: string) => void): this; + /** + * Emitted when a drag operation enters the tray icon. + * Note: This is only implemented on macOS + */ + on(event: 'drag-enter', listener: Function): this; + /** + * Emitted when a drag operation exits the tray icon. + * Note: This is only implemented on macOS + */ + on(event: 'drag-leave', listener: Function): this; + /** + * Emitted when a drag operation ends on the tray or ends at another location. + * Note: This is only implemented on macOS + */ + on(event: 'drag-end', listener: Function): this; + on(event: string, listener: Function): this; + /** + * Creates a new tray icon associated with the image. + */ + constructor(image: NativeImage|string); + /** + * Destroys the tray icon immediately. + */ + destroy(): void; + /** + * Sets the image associated with this tray icon. + */ + setImage(image: NativeImage|string): void; + /** + * Sets the image associated with this tray icon when pressed. + */ + setPressedImage(image: NativeImage): void; + /** + * Sets the hover text for this tray icon. + */ + setToolTip(toolTip: string): void; + /** + * Sets the title displayed aside of the tray icon in the status bar. + * Note: This is only implemented on macOS. + */ + setTitle(title: string): void; + /** + * Sets when the tray's icon background becomes highlighted. + * Note: This is only implemented on macOS. + */ + setHighlightMode(mode: 'selection' | 'always' | 'never'): void; + /** + * Displays a tray balloon. + * Note: This is only implemented on Windows. + */ + displayBalloon(options?: { + icon?: NativeImage; + title?: string; + content?: string; + }): void; + /** + * Pops up the context menu of tray icon. When menu is passed, + * the menu will showed instead of the tray's context menu. + * The position is only available on Windows, and it is (0, 0) by default. + * Note: This is only implemented on macOS and Windows. + */ + popUpContextMenu(menu?: Menu, position?: Point): void; + /** + * Sets the context menu for this icon. + */ + setContextMenu(menu: Menu): void; + /** + * @returns The bounds of this tray icon. + */ + getBounds(): Rectangle; + /** + * @returns Whether the tray icon is destroyed. + */ + isDestroyed(): boolean; + } + + interface Modifiers { + altKey: boolean; + shiftKey: boolean; + ctrlKey: boolean; + metaKey: boolean; + } + + interface DragItem { + /** + * The absolute path of the file to be dragged + */ + file: string; + /** + * The image showing under the cursor when dragging. + */ + icon: NativeImage; + } + + // https://github.com/electron/electron/blob/master/docs/api/web-contents.md + + interface WebContentsStatic { + /** + * @returns An array of all WebContents instances. This will contain web contents for all windows, + * webviews, opened devtools, and devtools extension background pages. + */ + getAllWebContents(): WebContents[]; + /** + * @returns The web contents that is focused in this application, otherwise returns null. + */ + getFocusedWebContents(): WebContents; + /** + * Find a WebContents instance according to its ID. + */ + fromId(id: number): WebContents; + } + + /** + * A WebContents is responsible for rendering and controlling a web page. + */ + interface WebContents extends NodeJS.EventEmitter { + /** + * Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, + * and the onload event was dispatched. + */ + on(event: 'did-finish-load', listener: Function): this; + /** + * This event is like did-finish-load but emitted when the load failed or was cancelled, + * e.g. window.stop() is invoked. + */ + on(event: 'did-fail-load', listener: (event: Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => void): this; + /** + * Emitted when a frame has done navigation. + */ + on(event: 'did-frame-finish-load', listener: (event: Event, isMainFrame: boolean) => void): this; + /** + * Corresponds to the points in time when the spinner of the tab started spinning. + */ + on(event: 'did-start-loading', listener: Function): this; + /** + * Corresponds to the points in time when the spinner of the tab stopped spinning. + */ + on(event: 'did-stop-loading', listener: Function): this; + /** + * Emitted when details regarding a requested resource are available. + * status indicates the socket connection to download the resource. + */ + on(event: 'did-get-response-details', listener: (event: Event, + status: boolean, + newURL: string, + originalURL: string, + httpResponseCode: number, + requestMethod: string, + referrer: string, + headers: Headers, + resourceType: string + ) => void): this; + /** + * Emitted when a redirect is received while requesting a resource. + */ + on(event: 'did-get-redirect-request', listener: (event: Event, + oldURL: string, + newURL: string, + isMainFrame: boolean, + httpResponseCode: number, + requestMethod: string, + referrer: string, + headers: Headers + ) => void): this; + /** + * Emitted when the document in the given frame is loaded. + */ + on(event: 'dom-ready', listener: (event: Event) => void): this; + /** + * Emitted when page receives favicon URLs. + */ + on(event: 'page-favicon-updated', listener: (event: Event, favicons: string[]) => void): this; + /** + * Emitted when the page requests to open a new window for a url. + * It could be requested by window.open or an external link like . + * + * By default a new BrowserWindow will be created for the url. + * + * Calling event.preventDefault() will prevent creating new windows. + * In such case, the event.newGuest may be set with a reference + * to a BrowserWindow instance to make it used by the Electron's runtime. + */ + on(event: 'new-window', listener: (event: WebContents.NewWindowEvent, + url: string, + frameName: string, + disposition: NewWindowDisposition, + /** + * The options which will be used for creating the new BrowserWindow. + */ + options: BrowserWindowOptions, + /** + * The non-standard features (features not handled by Chromium or Electron) given to window.open(). + */ + additionalFeatures: string[] + ) => void): this; + /** + * Emitted when a user or the page wants to start navigation. + * It can happen when the window.location object is changed or a user clicks a link in the page. + * + * This event will not emit when the navigation is started programmatically with APIs like + * webContents.loadURL and webContents.back. + * + * It is also not emitted for in-page navigations, such as clicking anchor links + * or updating the window.location.hash. Use did-navigate-in-page event for this purpose. + * + * Calling event.preventDefault() will prevent the navigation. + */ + on(event: 'will-navigate', listener: (event: Event, url: string) => void): this; + /** + * Emitted when a navigation is done. + * + * This event is not emitted for in-page navigations, such as clicking anchor links + * or updating the window.location.hash. Use did-navigate-in-page event for this purpose. + */ + on(event: 'did-navigate', listener: (event: Event, url: string) => void): this; + /** + * Emitted when an in-page navigation happened. + * + * When in-page navigation happens, the page URL changes but does not cause + * navigation outside of the page. Examples of this occurring are when anchor links + * are clicked or when the DOM hashchange event is triggered. + */ + on(event: 'did-navigate-in-page', listener: (event: Event, url: string, isMainFrame: boolean) => void): this; + /** + * Emitted when the renderer process has crashed. + */ + on(event: 'crashed', listener: (event: Event, killed: boolean) => void): this; + /** + * Emitted when a plugin process has crashed. + */ + on(event: 'plugin-crashed', listener: (event: Event, name: string, version: string) => void): this; + /** + * Emitted when webContents is destroyed. + */ + on(event: 'destroyed', listener: Function): this; + /** + * Emitted when DevTools is opened. + */ + on(event: 'devtools-opened', listener: Function): this; + /** + * Emitted when DevTools is closed. + */ + on(event: 'devtools-closed', listener: Function): this; + /** + * Emitted when DevTools is focused / opened. + */ + on(event: 'devtools-focused', listener: Function): this; + /** + * Emitted when failed to verify the certificate for url. + * The usage is the same with the "certificate-error" event of app. + */ + on(event: 'certificate-error', listener: (event: Event, + url: string, + error: string, + certificate: Certificate, + callback: (trust: boolean) => void + ) => void): this; + /** + * Emitted when a client certificate is requested. + * The usage is the same with the "select-client-certificate" event of app. + */ + on(event: 'select-client-certificate', listener: (event: Event, + url: string, + certificateList: Certificate[], + callback: (certificate: Certificate) => void + ) => void): this; + /** + * Emitted when webContents wants to do basic auth. + * The usage is the same with the "login" event of app. + */ + on(event: 'login', listener: (event: Event, + request: LoginRequest, + authInfo: LoginAuthInfo, + callback: (username: string, password: string) => void + ) => void): this; + /** + * Emitted when a result is available for webContents.findInPage request. + */ + on(event: 'found-in-page', listener: (event: Event, result: FoundInPageResult) => void): this; + /** + * Emitted when media starts playing. + */ + on(event: 'media-started-playing', listener: Function): this; + /** + * Emitted when media is paused or done playing. + */ + on(event: 'media-paused', listener: Function): this; + /** + * Emitted when a page’s theme color changes. This is usually due to encountering a meta tag: + * + */ + on(event: 'did-change-theme-color', listener: Function): this; + /** + * Emitted when mouse moves over a link or the keyboard moves the focus to a link. + */ + on(event: 'update-target-url', listener: (event: Event, url: string) => void): this; + /** + * Emitted when the cursor’s type changes. + * If the type parameter is custom, the image parameter will hold the custom cursor image + * in a NativeImage, and scale, size and hotspot will hold additional information about the custom cursor. + */ + on(event: 'cursor-changed', listener: (event: Event, type: CursorType, image?: NativeImage, scale?: number, size?: Size, hotspot?: Point) => void): this; + /** + * Emitted when there is a new context menu that needs to be handled. + */ + on(event: 'context-menu', listener: (event: Event, params: ContextMenuParams) => void): this; + /** + * Emitted when bluetooth device needs to be selected on call to navigator.bluetooth.requestDevice. + * To use navigator.bluetooth api webBluetooth should be enabled. + * If event.preventDefault is not called, first available device will be selected. + * callback should be called with deviceId to be selected, + * passing empty string to callback will cancel the request. + */ + on(event: 'select-bluetooth-device', listener: (event: Event, deviceList: BluetoothDevice[], callback: (deviceId: string) => void) => void): this; + /** + * Emitted when a new frame is generated. Only the dirty area is passed in the buffer. + */ + on(event: 'paint', listener: (event: Event, dirtyRect: Rectangle, image: NativeImage) => void): this; + on(event: string, listener: Function): this; + /** + * Loads the url in the window. + * @param url Must contain the protocol prefix (e.g., the http:// or file://). + */ + loadURL(url: string, options?: LoadURLOptions): void; + /** + * Initiates a download of the resource at url without navigating. + * The will-download event of session will be triggered. + */ + downloadURL(url: string): void; + /** + * @returns The URL of current web page. + */ + getURL(): string; + /** + * @returns The title of web page. + */ + getTitle(): string; + /** + * @returns The favicon of the web page. + */ + getFavicon(): NativeImage; + /** + * @returns Whether web page is still loading resources. + */ + isLoading(): boolean; + /** + * @returns Whether the main frame (and not just iframes or frames within it) is still loading. + */ + isLoadingMainFrame(): boolean; + /** + * @returns Whether web page is waiting for a first-response for the main + * resource of the page. + */ + isWaitingForResponse(): boolean; + /** + * Stops any pending navigation. + */ + stop(): void; + /** + * Reloads current page. + */ + reload(): void; + /** + * Reloads current page and ignores cache. + */ + reloadIgnoringCache(): void; + /** + * @returns Whether the web page can go back. + */ + canGoBack(): boolean; + /** + * @returns Whether the web page can go forward. + */ + canGoForward(): boolean; + /** + * @returns Whether the web page can go to offset. + */ + canGoToOffset(offset: number): boolean; + /** + * Clears the navigation history. + */ + clearHistory(): void; + /** + * Makes the web page go back. + */ + goBack(): void; + /** + * Makes the web page go forward. + */ + goForward(): void; + /** + * Navigates to the specified absolute index. + */ + goToIndex(index: number): void; + /** + * Navigates to the specified offset from the "current entry". + */ + goToOffset(offset: number): void; + /** + * @returns Whether the renderer process has crashed. + */ + isCrashed(): boolean; + /** + * Overrides the user agent for this page. + */ + setUserAgent(userAgent: string): void; + /** + * @returns The user agent for this web page. + */ + getUserAgent(): string; + /** + * Injects CSS into this page. + */ + insertCSS(css: string): void; + /** + * Evaluates code in page. + * @param code Code to evaluate. + */ + executeJavaScript(code: string, userGesture?: boolean, callback?: (result: any) => void): void; + /** + * Mute the audio on the current web page. + */ + setAudioMuted(muted: boolean): void; + /** + * @returns Whether this page has been muted. + */ + isAudioMuted(): boolean; + /** + * Changes the zoom factor to the specified factor. + * Zoom factor is zoom percent divided by 100, so 300% = 3.0. + */ + setZoomFactor(factor: number): void; + /** + * Sends a request to get current zoom factor. + */ + getZoomFactor(callback: (zoomFactor: number) => void): void; + /** + * Changes the zoom level to the specified level. + * The original size is 0 and each increment above or below represents + * zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. + */ + setZoomLevel(level: number): void; + /** + * Sends a request to get current zoom level. + */ + getZoomLevel(callback: (zoomLevel: number) => void): void; + /** + * Sets the maximum and minimum zoom level. + */ + setZoomLevelLimits(minimumLevel: number, maximumLevel: number): void; + /** + * Executes the editing command undo in web page. + */ + undo(): void; + /** + * Executes the editing command redo in web page. + */ + redo(): void; + /** + * Executes the editing command cut in web page. + */ + cut(): void; + /** + * Executes the editing command copy in web page. + */ + copy(): void; + /** + * Copy the image at the given position to the clipboard. + */ + copyImageAt(x: number, y: number): void; + /** + * Executes the editing command paste in web page. + */ + paste(): void; + /** + * Executes the editing command pasteAndMatchStyle in web page. + */ + pasteAndMatchStyle(): void; + /** + * Executes the editing command delete in web page. + */ + delete(): void; + /** + * Executes the editing command selectAll in web page. + */ + selectAll(): void; + /** + * Executes the editing command unselect in web page. + */ + unselect(): void; + /** + * Executes the editing command replace in web page. + */ + replace(text: string): void; + /** + * Executes the editing command replaceMisspelling in web page. + */ + replaceMisspelling(text: string): void; + /** + * Inserts text to the focused element. + */ + insertText(text: string): void; + /** + * Starts a request to find all matches for the text in the web page. + * The result of the request can be obtained by subscribing to found-in-page event. + * @returns The request id used for the request. + */ + findInPage(text: string, options?: FindInPageOptions): number; + /** + * Stops any findInPage request for the webContents with the provided action. + */ + stopFindInPage(action: StopFindInPageAtion): void; + /** + * Checks if any serviceworker is registered. + */ + hasServiceWorker(callback: (hasServiceWorker: boolean) => void): void; + /** + * Unregisters any serviceworker if present. + */ + unregisterServiceWorker(callback: (isFulfilled: boolean) => void): void; + /** + * Prints window's web page. When silent is set to false, Electron will pick up system's default printer and default settings for printing. + * Calling window.print() in web page is equivalent to call WebContents.print({silent: false, printBackground: false}). + * Note: On Windows, the print API relies on pdf.dll. If your application doesn't need print feature, you can safely remove pdf.dll in saving binary size. + */ + print(options?: PrintOptions): void; + /** + * Prints windows' web page as PDF with Chromium's preview printing custom settings. + */ + printToPDF(options: PrintToPDFOptions, callback: (error: Error, data: Buffer) => void): void; + /** + * Adds the specified path to DevTools workspace. + */ + addWorkSpace(path: string): void; + /** + * Removes the specified path from DevTools workspace. + */ + removeWorkSpace(path: string): void; + /** + * Opens the developer tools. + */ + openDevTools(options?: { + /** + * Opens the devtools with specified dock state. Defaults to last used dock state. + */ + mode?: 'right' | 'bottom' | 'undocked' | 'detach' + }): void; + /** + * Closes the developer tools. + */ + closeDevTools(): void; + /** + * Returns whether the developer tools are opened. + */ + isDevToolsOpened(): boolean; + /** + * Returns whether the developer tools are focussed. + */ + isDevToolsFocused(): boolean; + /** + * Toggle the developer tools. + */ + toggleDevTools(): void; + /** + * Starts inspecting element at position (x, y). + */ + inspectElement(x: number, y: number): void; + /** + * Opens the developer tools for the service worker context. + */ + inspectServiceWorker(): void; + /** + * Send args.. to the web page via channel in asynchronous message, the web page + * can handle it by listening to the channel event of ipc module. + * Note: + * 1. The IPC message handler in web pages do not have a event parameter, + * which is different from the handlers on the main process. + * 2. There is no way to send synchronous messages from the main process + * to a renderer process, because it would be very easy to cause dead locks. + */ + send(channel: string, ...args: any[]): void; + /** + * Enable device emulation with the given parameters. + */ + enableDeviceEmulation(parameters: DeviceEmulationParameters): void; + /** + * Disable device emulation. + */ + disableDeviceEmulation(): void; + /** + * Sends an input event to the page. + */ + sendInputEvent(event: SendInputEvent): void; + /** + * Begin subscribing for presentation events and captured frames, + * The callback will be called when there is a presentation event. + */ + beginFrameSubscription(onlyDirty: boolean, callback: BeginFrameSubscriptionCallback): void; + /** + * Begin subscribing for presentation events and captured frames, + * The callback will be called when there is a presentation event. + */ + beginFrameSubscription(callback: BeginFrameSubscriptionCallback): void; + /** + * End subscribing for frame presentation events. + */ + endFrameSubscription(): void; + /** + * @returns If the process of saving page has been initiated successfully. + */ + savePage(fullPath: string, saveType: 'HTMLOnly' | 'HTMLComplete' | 'MHTML', callback?: (eror: Error) => void): boolean; + /** + * Shows pop-up dictionary that searches the selected word on the page. + * Note: This API is available only on macOS. + */ + showDefinitionForSelection(): void; + /** + * @returns Whether offscreen rendering is enabled. + */ + isOffscreen(): boolean; + /** + * If offscreen rendering is enabled and not painting, start painting. + */ + startPainting(): void; + /** + * If offscreen rendering is enabled and painting, stop painting. + */ + stopPainting(): void; + /** + * If offscreen rendering is enabled returns whether it is currently painting. + */ + isPainting(): boolean; + /** + * If offscreen rendering is enabled sets the frame rate to the specified number. + * Only values between 1 and 60 are accepted. + */ + setFrameRate(fps: number): void; + /** + * If offscreen rendering is enabled returns the current frame rate. + */ + getFrameRate(): number; + /** + * If offscreen rendering is enabled invalidates the frame and generates a new one through the 'paint' event. + */ + invalidate(): void; + /** + * Sets the item as dragging item for current drag-drop operation. + */ + startDrag(item: DragItem): void; + /** + * Captures a snapshot of the page within rect. + */ + capturePage(callback: (image: NativeImage) => void): void; + /** + * Captures a snapshot of the page within rect. + */ + capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; + /** + * @returns The unique ID of this WebContents. + */ + id: number; + /** + * @returns The session object used by this webContents. + */ + session: Session; + /** + * @returns The WebContents that might own this WebContents. + */ + hostWebContents: WebContents; + /** + * @returns The WebContents of DevTools for this WebContents. + * Note: Users should never store this object because it may become null + * when the DevTools has been closed. + */ + devToolsWebContents: WebContents; + /** + * @returns Debugger API + */ + debugger: Debugger; + } + + namespace WebContents { + interface NewWindowEvent extends Event { + newGuest?: BrowserWindow; + } + } + + interface BeginFrameSubscriptionCallback { + ( + /** + * The frameBuffer is a Buffer that contains raw pixel data. + * On most machines, the pixel data is effectively stored in 32bit BGRA format, + * but the actual representation depends on the endianness of the processor + * (most modern processors are little-endian, on machines with big-endian + * processors the data is in 32bit ARGB format). + */ + frameBuffer: Buffer, + /** + * The dirtyRect is an object with x, y, width, height properties that describes which part of the page was repainted. + * If onlyDirty is set to true, frameBuffer will only contain the repainted area. onlyDirty defaults to false. + */ + dirtyRect?: Rectangle + ): void + } + + interface ContextMenuParams { + /** + * x coordinate + */ + x: number; + /** + * y coordinate + */ + y: number; + /** + * URL of the link that encloses the node the context menu was invoked on. + */ + linkURL: string; + /** + * Text associated with the link. May be an empty string if the contents of the link are an image. + */ + linkText: string; + /** + * URL of the top level page that the context menu was invoked on. + */ + pageURL: string; + /** + * URL of the subframe that the context menu was invoked on. + */ + frameURL: string; + /** + * Source URL for the element that the context menu was invoked on. + * Elements with source URLs are images, audio and video. + */ + srcURL: string; + /** + * Type of the node the context menu was invoked on. + */ + mediaType: 'none' | 'image' | 'audio' | 'video' | 'canvas' | 'file' | 'plugin'; + /** + * Parameters for the media element the context menu was invoked on. + */ + mediaFlags: { + /** + * Whether the media element has crashed. + */ + inError: boolean; + /** + * Whether the media element is paused. + */ + isPaused: boolean; + /** + * Whether the media element is muted. + */ + isMuted: boolean; + /** + * Whether the media element has audio. + */ + hasAudio: boolean; + /** + * Whether the media element is looping. + */ + isLooping: boolean; + /** + * Whether the media element's controls are visible. + */ + isControlsVisible: boolean; + /** + * Whether the media element's controls are toggleable. + */ + canToggleControls: boolean; + /** + * Whether the media element can be rotated. + */ + canRotate: boolean; + } + /** + * Whether the context menu was invoked on an image which has non-empty contents. + */ + hasImageContents: boolean; + /** + * Whether the context is editable. + */ + isEditable: boolean; + /** + * These flags indicate whether the renderer believes it is able to perform the corresponding action. + */ + editFlags: { + /** + * Whether the renderer believes it can undo. + */ + canUndo: boolean; + /** + * Whether the renderer believes it can redo. + */ + canRedo: boolean; + /** + * Whether the renderer believes it can cut. + */ + canCut: boolean; + /** + * Whether the renderer believes it can copy + */ + canCopy: boolean; + /** + * Whether the renderer believes it can paste. + */ + canPaste: boolean; + /** + * Whether the renderer believes it can delete. + */ + canDelete: boolean; + /** + * Whether the renderer believes it can select all. + */ + canSelectAll: boolean; + } + /** + * Text of the selection that the context menu was invoked on. + */ + selectionText: string; + /** + * Title or alt text of the selection that the context was invoked on. + */ + titleText: string; + /** + * The misspelled word under the cursor, if any. + */ + misspelledWord: string; + /** + * The character encoding of the frame on which the menu was invoked. + */ + frameCharset: string; + /** + * If the context menu was invoked on an input field, the type of that field. + */ + inputFieldType: 'none' | 'plainText' | 'password' | 'other'; + /** + * Input source that invoked the context menu. + */ + menuSourceType: 'none' | 'mouse' | 'keyboard' | 'touch' | 'touchMenu'; + } + + interface BluetoothDevice { + deviceName: string; + deviceId: string; + } + + interface Headers { + [key: string]: string; + } + + type NewWindowDisposition = 'default' | 'foreground-tab' | 'background-tab' | 'new-window' | 'save-to-disk' | 'other'; + + /** + * Specifies the action to take place when ending webContents.findInPage request. + * 'clearSelection' - Clear the selection. + * 'keepSelection' - Translate the selection into a normal selection. + * 'activateSelection' - Focus and click the selection node. + */ + type StopFindInPageAtion = 'clearSelection' | 'keepSelection' | 'activateSelection'; + + type CursorType = 'default' | 'crosshair' | 'pointer' | 'text' | 'wait' | 'help' | 'e-resize' | 'n-resize' | 'ne-resize' | 'nw-resize' | 's-resize' | 'se-resize' | 'sw-resize' | 'w-resize' | 'ns-resize' | 'ew-resize' | 'nesw-resize' | 'nwse-resize' | 'col-resize' | 'row-resize' | 'm-panning' | 'e-panning' | 'n-panning' | 'ne-panning' | 'nw-panning' | 's-panning' | 'se-panning' |'sw-panning' | 'w-panning' | 'move' | 'vertical-text' | 'cell' | 'context-menu' | 'alias' | 'progress' | 'nodrop' | 'copy' | 'none' | 'not-allowed' | 'zoom-in' | 'zoom-out' | 'grab' | 'grabbing' | 'custom'; + + interface LoadURLOptions { + /** + * HTTP Referrer URL. + */ + httpReferrer?: string; + /** + * User agent originating the request. + */ + userAgent?: string; + /** + * Extra headers separated by "\n" + */ + extraHeaders?: string; + } + + interface PrintOptions { + /** + * Don't ask user for print settings. + * Defaults: false. + */ + silent?: boolean; + /** + * Also prints the background color and image of the web page. + * Defaults: false. + */ + printBackground?: boolean; + } + + interface PrintToPDFOptions { + /** + * Specify the type of margins to use. + * 0 - default + * 1 - none + * 2 - minimum + * Default: 0 + */ + marginsType?: number; + /** + * Specify page size of the generated PDF. + * Default: A4. + */ + pageSize?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid' | Size; + /** + * Whether to print CSS backgrounds. + * Default: false. + */ + printBackground?: boolean; + /** + * Whether to print selection only. + * Default: false. + */ + printSelectionOnly?: boolean; + /** + * true for landscape, false for portrait. + * Default: false. + */ + landscape?: boolean; + } + + interface Certificate { + /** + * PEM encoded data. + */ + data: string; + /** + * Issuer's Common Name. + */ + issuerName: string; + /** + * Subject's Common Name. + */ + subjectName: string; + /** + * Hex value represented string. + */ + serialNumber: string; + /** + * Start date of the certificate being valid in seconds. + */ + validStart: number; + /** + * End date of the certificate being valid in seconds. + */ + validExpiry: number; + /** + * Fingerprint of the certificate. + */ + fingerprint: string; + } + + interface LoginRequest { + method: string; + url: string; + referrer: string; + } + + interface LoginAuthInfo { + isProxy: boolean; + scheme: string; + host: string; + port: number; + realm: string; + } + + interface FindInPageOptions { + /** + * Whether to search forward or backward, defaults to true + */ + forward?: boolean; + /** + * Whether the operation is first request or a follow up, defaults to false. + */ + findNext?: boolean; + /** + * Whether search should be case-sensitive, defaults to false. + */ + matchCase?: boolean; + /** + * Whether to look only at the start of words. defaults to false. + */ + wordStart?: boolean; + /** + * When combined with wordStart, accepts a match in the middle of a word + * if the match begins with an uppercase letter followed by a lowercase + * or non-letter. Accepts several other intra-word matches, defaults to false. + */ + medialCapitalAsWordStart?: boolean; + } + + interface FoundInPageResult { + requestId: number; + /** + * Indicates if more responses are to follow. + */ + finalUpdate: boolean; + /** + * Position of the active match. + */ + activeMatchOrdinal?: number; + /** + * Number of Matches. + */ + matches?: number; + /** + * Coordinates of first match region. + */ + selectionArea?: Rectangle; + } + + interface DeviceEmulationParameters { + /** + * Specify the screen type to emulated + * Default: desktop + */ + screenPosition?: 'desktop' | 'mobile'; + /** + * Set the emulated screen size (screenPosition == mobile) + */ + screenSize?: Size; + /** + * Position the view on the screen (screenPosition == mobile) + * Default: {x: 0, y: 0} + */ + viewPosition?: Point; + /** + * Set the device scale factor (if zero defaults to original device scale factor) + * Default: 0 + */ + deviceScaleFactor: number; + /** + * Set the emulated view size (empty means no override). + */ + viewSize?: Size; + /** + * Whether emulated view should be scaled down if necessary to fit into available space + * Default: false + */ + fitToView?: boolean; + /** + * Offset of the emulated view inside available space (not in fit to view mode) + * Default: {x: 0, y: 0} + */ + offset?: Point; + /** + * Scale of emulated view inside available space (not in fit to view mode) + * Default: 1 + */ + scale: number; + } + + interface SendInputEvent { + type: 'mouseDown' | 'mouseUp' | 'mouseEnter' | 'mouseLeave' | 'contextMenu' | 'mouseWheel' | 'mouseMove' | 'keyDown' | 'keyUp' | 'char'; + modifiers: ('shift' | 'control' | 'alt' | 'meta' | 'isKeypad' | 'isAutoRepeat' | 'leftButtonDown' | 'middleButtonDown' | 'rightButtonDown' | 'capsLock' | 'numLock' | 'left' | 'right')[]; + } + + interface SendInputKeyboardEvent extends SendInputEvent { + keyCode: string; + } + + interface SendInputMouseEvent extends SendInputEvent { + x: number; + y: number; + button?: 'left' | 'middle' | 'right'; + globalX?: number; + globalY?: number; + movementX?: number; + movementY?: number; + clickCount?: number; + } + + interface SendInputMouseWheelEvent extends SendInputEvent { + deltaX?: number; + deltaY?: number; + wheelTicksX?: number; + wheelTicksY?: number; + accelerationRatioX?: number; + accelerationRatioY?: number; + hasPreciseScrollingDeltas?: boolean; + canScroll?: boolean; + } + + /** + * Debugger API serves as an alternate transport for remote debugging protocol. + */ + interface Debugger extends NodeJS.EventEmitter { + /** + * Attaches the debugger to the webContents. + * @param protocolVersion Requested debugging protocol version. + */ + attach(protocolVersion?: string): void; + /** + * @returns Whether a debugger is attached to the webContents. + */ + isAttached(): boolean; + /** + * Detaches the debugger from the webContents. + */ + detach(): void; + /** + * Send given command to the debugging target. + * @param method Method name, should be one of the methods defined by the remote debugging protocol. + * @param commandParams JSON object with request parameters. + * @param callback Response defined by the ‘returns’ attribute of the command description in the remote debugging protocol. + */ + sendCommand(method: string, commandParams?: any, callback?: (error: Error, result: any) => void): void; + /** + * Emitted when debugging session is terminated. This happens either when + * webContents is closed or devtools is invoked for the attached webContents. + */ + on(event: 'detach', listener: (event: Event, reason: string) => void): this; + /** + * Emitted whenever debugging target issues instrumentation event. + * Event parameters defined by the ‘parameters’ attribute in the remote debugging protocol. + */ + on(event: 'message', listener: (event: Event, method: string, params: any) => void): this; + on(event: string, listener: Function): this; + } + + // https://github.com/electron/electron/blob/master/docs/api/web-frame.md + + /** + * The web-frame module allows you to customize the rendering of the current web page. + */ + interface WebFrame { + /** + * Changes the zoom factor to the specified factor, zoom factor is + * zoom percent / 100, so 300% = 3.0. + */ + setZoomFactor(factor: number): void; + /** + * @returns The current zoom factor. + */ + getZoomFactor(): number; + /** + * Changes the zoom level to the specified level, 0 is "original size", and each + * increment above or below represents zooming 20% larger or smaller to default + * limits of 300% and 50% of original size, respectively. + */ + setZoomLevel(level: number): void; + /** + * @returns The current zoom level. + */ + getZoomLevel(): number; + /** + * Sets the maximum and minimum zoom level. + */ + setZoomLevelLimits(minimumLevel: number, maximumLevel: number): void; + /** + * Sets a provider for spell checking in input fields and text areas. + */ + setSpellCheckProvider(language: string, autoCorrectWord: boolean, provider: { + /** + * @returns Whether the word passed is correctly spelled. + */ + spellCheck: (text: string) => boolean; + }): void; + /** + * Sets the scheme as secure scheme. Secure schemes do not trigger mixed content + * warnings. For example, https and data are secure schemes because they cannot be + * corrupted by active network attackers. + */ + registerURLSchemeAsSecure(scheme: string): void; + /** + * Resources will be loaded from this scheme regardless of the current page’s Content Security Policy. + */ + registerURLSchemeAsBypassingCSP(scheme: string): void; + /** + * Registers the scheme as secure, bypasses content security policy for resources, + * allows registering ServiceWorker and supports fetch API. + */ + registerURLSchemeAsPrivileged(scheme: string): void; + /** + * Inserts text to the focused element. + */ + insertText(text: string): void; + /** + * Evaluates `code` in page. + * In the browser window some HTML APIs like `requestFullScreen` can only be + * invoked by a gesture from the user. Setting `userGesture` to `true` will remove + * this limitation. + */ + executeJavaScript(code: string, userGesture?: boolean, callback?: (result: any) => void): void; + /** + * @returns Object describing usage information of Blink’s internal memory caches. + */ + getResourceUsage(): ResourceUsages; + /** + * Attempts to free memory that is no longer being used (like images from a previous navigation). + */ + clearCache(): void; + } + + interface ResourceUsages { + fonts: ResourceUsage; + images: ResourceUsage; + cssStyleSheets: ResourceUsage; + xslStyleSheets: ResourceUsage; + scripts: ResourceUsage; + other: ResourceUsage; + } + + interface ResourceUsage { + count: number; + decodedSize: number; + liveSize: number; + purgeableSize: number; + purgedSize: number; + size: number; + } + + // https://github.com/electron/electron/blob/master/docs/api/web-view-tag.md + + /** + * Use the webview tag to embed 'guest' content (such as web pages) in your Electron app. + * The guest content is contained within the webview container. + * An embedded page within your app controls how the guest content is laid out and rendered. + * + * Unlike an iframe, the webview runs in a separate process than your app. + * It doesn't have the same permissions as your web page and all interactions between your app + * and embedded content will be asynchronous. This keeps your app safe from the embedded content. + */ + interface WebViewElement extends HTMLElement { + /** + * Returns the visible URL. Writing to this attribute initiates top-level navigation. + * Assigning src its own value will reload the current page. + * The src attribute can also accept data URLs, such as data:text/plain,Hello, world!. + */ + src: string; + /** + * If "on", the webview container will automatically resize within the bounds specified + * by the attributes minwidth, minheight, maxwidth, and maxheight. + * These constraints do not impact the webview unless autosize is enabled. + * When autosize is enabled, the webview container size cannot be less than + * the minimum values or greater than the maximum. + */ + autosize: string; + /** + * If "on", the guest page in webview will have node integration and can use node APIs + * like require and process to access low level system resources. + */ + nodeintegration: string; + /** + * If "on", the guest page in webview will be able to use browser plugins. + */ + plugins: string; + /** + * Specifies a script that will be loaded before other scripts run in the guest page. + * The protocol of script's URL must be either file: or asar:, + * because it will be loaded by require in guest page under the hood. + * + * When the guest page doesn't have node integration this script will still have access to all Node APIs, + * but global objects injected by Node will be deleted after this script has finished executing. + */ + preload: string; + /** + * Sets the referrer URL for the guest page. + */ + httpreferrer: string; + /** + * Sets the user agent for the guest page before the page is navigated to. + * Once the page is loaded, use the setUserAgent method to change the user agent. + */ + useragent: string; + /** + * If "on", the guest page will have web security disabled. + */ + disablewebsecurity: string; + /** + * Sets the session used by the page. If partition starts with persist:, + * the page will use a persistent session available to all pages in the app with the same partition. + * If there is no persist: prefix, the page will use an in-memory session. + * By assigning the same partition, multiple pages can share the same session. + * If the partition is unset then default session of the app will be used. + * + * This value can only be modified before the first navigation, + * since the session of an active renderer process cannot change. + * Subsequent attempts to modify the value will fail with a DOM exception. + */ + partition: string; + /** + * If "on", the guest page will be allowed to open new windows. + */ + allowpopups: string; + /** + * A list of strings which specifies the blink features to be enabled separated by ,. + */ + blinkfeatures: string; + /** + * A list of strings which specifies the blink features to be disabled separated by ,. + */ + disableblinkfeatures: string; + /** + * A value that links the webview to a specific webContents. + * When a webview first loads a new webContents is created and this attribute is set + * to its instance identifier. Setting this attribute on a new or existing webview connects + * it to the existing webContents that currently renders in a different webview. + * + * The existing webview will see the destroy event and will then create a new webContents when a new url is loaded. + */ + guestinstance: string; + /** + * Loads the url in the webview, the url must contain the protocol prefix, e.g. the http:// or file://. + */ + loadURL(url: string, options?: LoadURLOptions): void; + /** + * @returns URL of guest page. + */ + getURL(): string; + /** + * @returns The title of guest page. + */ + getTitle(): string; + /** + * @returns Whether the web page is destroyed. + */ + isDestroyed(): boolean; + /** + * @returns Whether the web page is focused. + */ + isFocused(): boolean; + /** + * @returns Whether guest page is still loading resources. + */ + isLoading(): boolean; + /** + * Returns a boolean whether the guest page is waiting for a first-response for the main resource of the page. + */ + isWaitingForResponse(): boolean; + /** + * Stops any pending navigation. + */ + stop(): void; + /** + * Reloads the guest page. + */ + reload(): void; + /** + * Reloads the guest page and ignores cache. + */ + reloadIgnoringCache(): void; + /** + * @returns Whether the guest page can go back. + */ + canGoBack(): boolean; + /** + * @returns Whether the guest page can go forward. + */ + canGoForward(): boolean; + /** + * @returns Whether the guest page can go to offset. + */ + canGoToOffset(offset: number): boolean; + /** + * Clears the navigation history. + */ + clearHistory(): void; + /** + * Makes the guest page go back. + */ + goBack(): void; + /** + * Makes the guest page go forward. + */ + goForward(): void; + /** + * Navigates to the specified absolute index. + */ + goToIndex(index: number): void; + /** + * Navigates to the specified offset from the "current entry". + */ + goToOffset(offset: number): void; + /** + * @returns Whether the renderer process has crashed. + */ + isCrashed(): boolean; + /** + * Overrides the user agent for the guest page. + */ + setUserAgent(userAgent: string): void; + /** + * @returns The user agent for guest page. + */ + getUserAgent(): string; + /** + * Injects CSS into the guest page. + */ + insertCSS(css: string): void; + /** + * Evaluates code in page. If userGesture is set, it will create the user gesture context in the page. + * HTML APIs like requestFullScreen, which require user action, can take advantage of this option for automation. + */ + executeJavaScript(code: string, userGesture?: boolean, callback?: (result: any) => void): void; + /** + * Opens a DevTools window for guest page. + */ + openDevTools(): void; + /** + * Closes the DevTools window of guest page. + */ + closeDevTools(): void; + /** + * @returns Whether guest page has a DevTools window attached. + */ + isDevToolsOpened(): boolean; + /** + * @returns Whether DevTools window of guest page is focused. + */ + isDevToolsFocused(): boolean; + /** + * Starts inspecting element at position (x, y) of guest page. + */ + inspectElement(x: number, y: number): void; + /** + * Opens the DevTools for the service worker context present in the guest page. + */ + inspectServiceWorker(): void; + /** + * Set guest page muted. + */ + setAudioMuted(muted: boolean): void; + /** + * @returns Whether guest page has been muted. + */ + isAudioMuted(): boolean; + /** + * Executes editing command undo in page. + */ + undo(): void; + /** + * Executes editing command redo in page. + */ + redo(): void; + /** + * Executes editing command cut in page. + */ + cut(): void; + /** + * Executes editing command copy in page. + */ + copy(): void; + /** + * Executes editing command paste in page. + */ + paste(): void; + /** + * Executes editing command pasteAndMatchStyle in page. + */ + pasteAndMatchStyle(): void; + /** + * Executes editing command delete in page. + */ + delete(): void; + /** + * Executes editing command selectAll in page. + */ + selectAll(): void; + /** + * Executes editing command unselect in page. + */ + unselect(): void; + /** + * Executes editing command replace in page. + */ + replace(text: string): void; + /** + * Executes editing command replaceMisspelling in page. + */ + replaceMisspelling(text: string): void; + /** + * Inserts text to the focused element. + */ + insertText(text: string): void; + /** + * Starts a request to find all matches for the text in the web page. + * The result of the request can be obtained by subscribing to found-in-page event. + * @returns The request id used for the request. + */ + findInPage(text: string, options?: FindInPageOptions): number; + /** + * Stops any findInPage request for the webview with the provided action. + */ + stopFindInPage(action: StopFindInPageAtion): void; + /** + * Prints webview's web page. Same with webContents.print([options]). + */ + print(options?: PrintOptions): void; + /** + * Prints webview's web page as PDF, Same with webContents.printToPDF(options, callback) + */ + printToPDF(options: PrintToPDFOptions, callback: (error: Error, data: Buffer) => void): void; + /** + * Send an asynchronous message to renderer process via channel, you can also send arbitrary arguments. + * The renderer process can handle the message by listening to the channel event with the ipcRenderer module. + * See webContents.send for examples. + */ + send(channel: string, ...args: any[]): void; + /** + * Sends an input event to the page. + * See webContents.sendInputEvent for detailed description of event object. + */ + sendInputEvent(event: SendInputEvent): void + /** + * Changes the zoom factor to the specified factor. + * Zoom factor is zoom percent divided by 100, so 300% = 3.0. + */ + setZoomFactor(factor: number): void; + /** + * Changes the zoom level to the specified level. + * The original size is 0 and each increment above or below represents + * zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. + */ + setZoomLevel(level: number): void; + /** + * Shows pop-up dictionary that searches the selected word on the page. + * Note: This API is available only on macOS. + */ + showDefinitionForSelection(): void; + /** + * @returns The WebContents associated with this webview. + */ + getWebContents(): WebContents; + /** + * Captures a snapshot of the webview's page. Same as webContents.capturePage([rect, ]callback). + */ + capturePage(callback: (image: NativeImage) => void): void; + /** + * Captures a snapshot of the webview's page. Same as webContents.capturePage([rect, ]callback). + */ + capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; + /** + * Fired when a load has committed. This includes navigation within the current document + * as well as subframe document-level loads, but does not include asynchronous resource loads. + */ + addEventListener(type: 'load-commit', listener: (event: WebViewElement.LoadCommitEvent) => void, useCapture?: boolean): void; + /** + * Fired when the navigation is done, i.e. the spinner of the tab will stop spinning, and the onload event is dispatched. + */ + addEventListener(type: 'did-finish-load', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * This event is like did-finish-load, but fired when the load failed or was cancelled, e.g. window.stop() is invoked. + */ + addEventListener(type: 'did-fail-load', listener: (event: WebViewElement.DidFailLoadEvent) => void, useCapture?: boolean): void; + /** + * Fired when a frame has done navigation. + */ + addEventListener(type: 'did-frame-finish-load', listener: (event: WebViewElement.DidFrameFinishLoadEvent) => void, useCapture?: boolean): void; + /** + * Corresponds to the points in time when the spinner of the tab starts spinning. + */ + addEventListener(type: 'did-start-loading', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * Corresponds to the points in time when the spinner of the tab stops spinning. + */ + addEventListener(type: 'did-stop-loading', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * Fired when details regarding a requested resource is available. + * status indicates socket connection to download the resource. + */ + addEventListener(type: 'did-get-response-details', listener: (event: WebViewElement.DidGetResponseDetails) => void, useCapture?: boolean): void; + /** + * Fired when a redirect was received while requesting a resource. + */ + addEventListener(type: 'did-get-redirect-request', listener: (event: WebViewElement.DidGetRedirectRequestEvent) => void, useCapture?: boolean): void; + /** + * Fired when document in the given frame is loaded. + */ + addEventListener(type: 'dom-ready', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * Fired when page title is set during navigation. explicitSet is false when title is synthesized from file URL. + */ + addEventListener(type: 'page-title-updated', listener: (event: WebViewElement.PageTitleUpdatedEvent) => void, useCapture?: boolean): void; + /** + * Fired when page receives favicon URLs. + */ + addEventListener(type: 'page-favicon-updated', listener: (event: WebViewElement.PageFaviconUpdatedEvent) => void, useCapture?: boolean): void; + /** + * Fired when page enters fullscreen triggered by HTML API. + */ + addEventListener(type: 'enter-html-full-screen', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * Fired when page leaves fullscreen triggered by HTML API. + */ + addEventListener(type: 'leave-html-full-screen', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * Fired when the guest window logs a console message. + */ + addEventListener(type: 'console-message', listener: (event: WebViewElement.ConsoleMessageEvent) => void, useCapture?: boolean): void; + /** + * Fired when a result is available for webview.findInPage request. + */ + addEventListener(type: 'found-in-page', listener: (event: WebViewElement.FoundInPageEvent) => void, useCapture?: boolean): void; + /** + * Fired when the guest page attempts to open a new browser window. + */ + addEventListener(type: 'new-window', listener: (event: WebViewElement.NewWindowEvent) => void, useCapture?: boolean): void; + /** + * Emitted when a user or the page wants to start navigation. + * It can happen when the window.location object is changed or a user clicks a link in the page. + * + * This event will not emit when the navigation is started programmatically with APIs + * like .loadURL and .back. + * + * It is also not emitted during in-page navigation, such as clicking anchor links + * or updating the window.location.hash. Use did-navigate-in-page event for this purpose. + * + * Calling event.preventDefault() does NOT have any effect. + */ + addEventListener(type: 'will-navigate', listener: (event: WebViewElement.WillNavigateEvent) => void, useCapture?: boolean): void; + /** + * Emitted when a navigation is done. + * + * This event is not emitted for in-page navigations, such as clicking anchor links + * or updating the window.location.hash. Use did-navigate-in-page event for this purpose. + */ + addEventListener(type: 'did-navigate', listener: (event: WebViewElement.DidNavigateEvent) => void, useCapture?: boolean): void; + /** + * Emitted when an in-page navigation happened. + * + * When in-page navigation happens, the page URL changes but does not cause + * navigation outside of the page. Examples of this occurring are when anchor links + * are clicked or when the DOM hashchange event is triggered. + */ + addEventListener(type: 'did-navigate-in-page', listener: (event: WebViewElement.DidNavigateInPageEvent) => void, useCapture?: boolean): void; + /** + * Fired when the guest page attempts to close itself. + */ + addEventListener(type: 'close', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * Fired when the guest page has sent an asynchronous message to embedder page. + */ + addEventListener(type: 'ipc-message', listener: (event: WebViewElement.IpcMessageEvent) => void, useCapture?: boolean): void; + /** + * Fired when the renderer process is crashed. + */ + addEventListener(type: 'crashed', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * Fired when the gpu process is crashed. + */ + addEventListener(type: 'gpu-crashed', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * Fired when a plugin process is crashed. + */ + addEventListener(type: 'plugin-crashed', listener: (event: WebViewElement.PluginCrashedEvent) => void, useCapture?: boolean): void; + /** + * Fired when the WebContents is destroyed. + */ + addEventListener(type: 'destroyed', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * Emitted when media starts playing. + */ + addEventListener(type: 'media-started-playing', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * Emitted when media is paused or done playing. + */ + addEventListener(type: 'media-paused', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * Emitted when a page's theme color changes. This is usually due to encountering a meta tag: + * + */ + addEventListener(type: 'did-change-theme-color', listener: (event: WebViewElement.DidChangeThemeColorEvent) => void, useCapture?: boolean): void; + /** + * Emitted when mouse moves over a link or the keyboard moves the focus to a link. + */ + addEventListener(type: 'update-target-url', listener: (event: WebViewElement.UpdateTargetUrlEvent) => void, useCapture?: boolean): void; + /** + * Emitted when DevTools is opened. + */ + addEventListener(type: 'devtools-opened', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * Emitted when DevTools is closed. + */ + addEventListener(type: 'devtools-closed', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + /** + * Emitted when DevTools is focused / opened. + */ + addEventListener(type: 'devtools-focused', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + addEventListener(type: string, listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; + } + + namespace WebViewElement { + type Event = ElectronPrivate.GlobalEvent; + + interface LoadCommitEvent extends Event { + url: string; + isMainFrame: boolean; + } + + interface DidFailLoadEvent extends Event { + errorCode: number; + errorDescription: string; + validatedURL: string; + isMainFrame: boolean; + } + + interface DidFrameFinishLoadEvent extends Event { + isMainFrame: boolean; + } + + interface DidGetResponseDetails extends Event { + status: boolean; + newURL: string; + originalURL: string; + httpResponseCode: number; + requestMethod: string; + referrer: string; + headers: Headers; + resourceType: string; + } + + interface DidGetRedirectRequestEvent extends Event { + oldURL: string; + newURL: string; + isMainFrame: boolean; + httpResponseCode: number; + requestMethod: string; + referrer: string; + headers: Headers; + } + + interface PageTitleUpdatedEvent extends Event { + title: string; + explicitSet: string; + } + + interface PageFaviconUpdatedEvent extends Event { + favicons: string[]; + } + + interface ConsoleMessageEvent extends Event { + level: number; + message: string; + line: number; + sourceId: string; + } + + interface FoundInPageEvent extends Event { + result: FoundInPageResult; + } + + interface NewWindowEvent extends Event { + url: string; + frameName: string; + disposition: NewWindowDisposition; + options: BrowserWindowOptions; + } + + interface WillNavigateEvent extends Event { + url: string; + } + + interface DidNavigateEvent extends Event { + url: string; + } + + interface DidNavigateInPageEvent extends Event { + url: string; + isMainFrame: boolean; + } + + interface IpcMessageEvent extends Event { + channel: string; + args: any[]; + } + + interface PluginCrashedEvent extends Event { + name: string; + version: string; + } + + interface DidChangeThemeColorEvent extends Event { + themeColor: string; + } + + interface UpdateTargetUrlEvent extends Event { + url: string; + } + } + + /** + * The BrowserWindowProxy object is returned from window.open and provides limited functionality with the child window. + */ + interface BrowserWindowProxy { + /** + * Removes focus from the child window. + */ + blur(): void; + /** + * Forcefully closes the child window without calling its unload event. + */ + close(): void; + /** + * Set to true after the child window gets closed. + */ + closed: boolean; + /** + * Evaluates the code in the child window. + */ + eval(code: string): void; + /** + * Focuses the child window (brings the window to front). + */ + focus(): void; + /** + * Sends a message to the child window with the specified origin or * for no origin preference. + * In addition to these methods, the child window implements window.opener object with no + * properties and a single method. + */ + postMessage(message: string, targetOrigin: string): void; + /** + * Invokes the print dialog on the child window. + */ + print(): void; + } + + // https://github.com/electron/electron/blob/master/docs/api/synopsis.md + + interface CommonElectron { + clipboard: Electron.Clipboard; + crashReporter: Electron.CrashReporter; + nativeImage: typeof Electron.NativeImage; + shell: Electron.Shell; + + app: Electron.App; + autoUpdater: Electron.AutoUpdater; + BrowserWindow: typeof Electron.BrowserWindow; + contentTracing: Electron.ContentTracing; + dialog: Electron.Dialog; + ipcMain: Electron.IpcMain; + globalShortcut: Electron.GlobalShortcut; + Menu: typeof Electron.Menu; + MenuItem: typeof Electron.MenuItem; + powerMonitor: Electron.PowerMonitor; + powerSaveBlocker: Electron.PowerSaveBlocker; + protocol: Electron.Protocol; + screen: Electron.Screen; + session: typeof Electron.Session; + systemPreferences: Electron.SystemPreferences; + Tray: typeof Electron.Tray; + webContents: Electron.WebContentsStatic; + } + + interface ElectronMainAndRenderer extends CommonElectron { + desktopCapturer: Electron.DesktopCapturer; + ipcRenderer: Electron.IpcRenderer; + remote: Electron.Remote; + webFrame: Electron.WebFrame; + } +} + +declare namespace ElectronPrivate { + type GlobalEvent = Event; +} + +interface Document { + createElement(tagName: 'webview'): Electron.WebViewElement; +} + +// https://github.com/electron/electron/blob/master/docs/api/window-open.md + +interface Window { + /** + * Creates a new window. + */ + open(url: string, frameName?: string, features?: string): Electron.BrowserWindowProxy; +} + +// https://github.com/electron/electron/blob/master/docs/api/file-object.md + +interface File { + /** + * Exposes the real path of the filesystem. + */ + path: string; +} + +// https://github.com/electron/electron/blob/master/docs/api/process.md + +declare namespace NodeJS { + + interface ProcessVersions { + /** + * Electron's version string. + */ + electron: string; + /** + * Chrome's version string. + */ + chrome: string; + } + + interface Process { + /** + * Setting this to true can disable the support for asar archives in Node's built-in modules. + */ + noAsar?: boolean; + /** + * Process's type + */ + type: 'browser' | 'renderer'; + /** + * Path to JavaScript source code. + */ + resourcesPath: string; + /** + * For Mac App Store build, this value is true, for other builds it is undefined. + */ + mas?: boolean; + /** + * If the app is running as a Windows Store app (appx), this value is true, for other builds it is undefined. + */ + windowsStore?: boolean; + /** + * When app is started by being passed as parameter to the default app, + * this value is true in the main process, otherwise it is undefined. + */ + defaultApp?: boolean; + /** + * Emitted when Electron has loaded its internal initialization script + * and is beginning to load the web page or the main script. + */ + on(event: 'loaded', listener: Function): this; + on(event: string, listener: Function): this; + /** + * Causes the main thread of the current process crash; + */ + crash(): void; + /** + * Causes the main thread of the current process hang. + */ + hang(): void; + /** + * Sets the file descriptor soft limit to maxDescriptors or the OS hard limit, + * whichever is lower for the current process. + * + * Note: This API is only available on macOS and Linux. + */ + setFdLimit(maxDescriptors: number): void; + /** + * @returns Object giving memory usage statistics about the current process. + * Note: All statistics are reported in Kilobytes. + */ + getProcessMemoryInfo(): ProcessMemoryInfo; + /** + * @returns Object giving memory usage statistics about the entire system. + * Note: All statistics are reported in Kilobytes. + */ + getSystemMemoryInfo(): SystemMemoryInfo; + } + + interface ProcessMemoryInfo { + /** + * The amount of memory currently pinned to actual physical RAM. + */ + workingSetSize: number; + /** + * The maximum amount of memory that has ever been pinned to actual physical RAM. + */ + peakWorkingSetSize: number; + /** + * The amount of memory not shared by other processes, such as JS heap or HTML content. + */ + privateBytes: number; + /** + * The amount of memory shared between processes, typically memory consumed by the Electron code itself. + */ + sharedBytes: number; + } + + interface SystemMemoryInfo { + /** + * The total amount of physical memory available to the system. + */ + total: number; + /** + * The total amount of memory not being used by applications or disk cache. + */ + free: number; + /** + * The total amount of swap memory available to the system. + */ + swapTotal: number; + /** + * The free amount of swap memory available to the system. + */ + swapFree: number; + } +} + +declare module 'electron' { + var electron: Electron.ElectronMainAndRenderer; + export = electron; +} + +interface NodeRequireFunction { + (moduleName: 'electron'): Electron.ElectronMainAndRenderer; +} diff --git a/electron/index.d.ts b/electron/index.d.ts index d55b47df4c..864c9991eb 100644 --- a/electron/index.d.ts +++ b/electron/index.d.ts @@ -2913,7 +2913,9 @@ declare namespace Electron { * - Each header name produces an array-valued property on the headers object. * - Each header value is pushed into the array associated with its header name. */ - headers: Headers; + headers: { + [key: string]: string[] + }; /** * A string indicating the HTTP protocol version number. Typical values are ‘1.0’ or ‘1.1’. */ diff --git a/epub/epub-tests.ts b/epub/epub-tests.ts index 6e61a26634..a69c543908 100644 --- a/epub/epub-tests.ts +++ b/epub/epub-tests.ts @@ -1,4 +1,3 @@ -/// import EPub = require("epub"); var epub = new EPub("./file.epub"); diff --git a/epub/epub.d.ts b/epub/index.d.ts similarity index 100% rename from epub/epub.d.ts rename to epub/index.d.ts diff --git a/epub/tsconfig.json b/epub/tsconfig.json index eda2b3868b..d1f91f6e53 100644 --- a/epub/tsconfig.json +++ b/epub/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "epub.d.ts", + "index.d.ts", "epub-tests.ts" ] } \ No newline at end of file diff --git a/eventemitter2/index.d.ts b/eventemitter2/index.d.ts index 0372b675dc..33ffe20b09 100644 --- a/eventemitter2/index.d.ts +++ b/eventemitter2/index.d.ts @@ -23,7 +23,7 @@ interface EventEmitter2Configuration { * max listeners that can be assigned to an event, default 10. */ maxListeners?: number; - + /** * show event name in memory leak message when more than maximum amount of listeners is assigned, default false */ diff --git a/exorcist/exorcist-tests.ts b/exorcist/exorcist-tests.ts index 26a1be0e07..3ac0d35c28 100644 --- a/exorcist/exorcist-tests.ts +++ b/exorcist/exorcist-tests.ts @@ -1,5 +1,3 @@ -/// - import exorcist = require("exorcist"); module ExorcistTest { diff --git a/exorcist/exorcist.d.ts b/exorcist/index.d.ts similarity index 100% rename from exorcist/exorcist.d.ts rename to exorcist/index.d.ts diff --git a/exorcist/tsconfig.json b/exorcist/tsconfig.json index e0ca3628a8..c57b04865a 100644 --- a/exorcist/tsconfig.json +++ b/exorcist/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "exorcist.d.ts", + "index.d.ts", "exorcist-tests.ts" ] } \ No newline at end of file diff --git a/express-domain-middleware/express-domain-middleware-tests.ts b/express-domain-middleware/express-domain-middleware-tests.ts index 446b732353..b506726ada 100644 --- a/express-domain-middleware/express-domain-middleware-tests.ts +++ b/express-domain-middleware/express-domain-middleware-tests.ts @@ -1,2 +1 @@ -/// import fn = require('express-domain-middleware'); diff --git a/express-domain-middleware/express-domain-middleware.d.ts b/express-domain-middleware/index.d.ts similarity index 100% rename from express-domain-middleware/express-domain-middleware.d.ts rename to express-domain-middleware/index.d.ts diff --git a/express-domain-middleware/tsconfig.json b/express-domain-middleware/tsconfig.json index 456e26404a..48ef657c86 100644 --- a/express-domain-middleware/tsconfig.json +++ b/express-domain-middleware/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "express-domain-middleware.d.ts", + "index.d.ts", "express-domain-middleware-tests.ts" ] } \ No newline at end of file diff --git a/fb/index.d.ts b/fb/index.d.ts index f641fa9820..a968d9f3c0 100644 --- a/fb/index.d.ts +++ b/fb/index.d.ts @@ -29,13 +29,13 @@ interface PageTabDialogParams { interface RequestsDialogParams { method: string; // "apprequests" - app_id: string; + app_id?: string; redirect_uri?: string; to?: string; message: string; action_type?: string; // "send" | "askfor" | "turn" object_id?: string; - filters: string /* "app_users" | "app_non_users" */ | { + filters: string[] | { name: string; user_ids: string[]; }; diff --git a/fbemitter/fbemitter-tests.ts b/fbemitter/fbemitter-tests.ts index 11e1ce74a5..2085f9ac51 100644 --- a/fbemitter/fbemitter-tests.ts +++ b/fbemitter/fbemitter-tests.ts @@ -2,6 +2,7 @@ /// /// /// + 'use strict'; /** diff --git a/fill-pdf/fill-pdf-tests.ts b/fill-pdf/fill-pdf-tests.ts index e5b34cd943..44b4f23531 100644 --- a/fill-pdf/fill-pdf-tests.ts +++ b/fill-pdf/fill-pdf-tests.ts @@ -1,5 +1,3 @@ -/// - import * as fillPdf from 'fill-pdf'; var formData: fillPdf.FormData = { FieldName: 'Text to put into form field' }; diff --git a/fill-pdf/fill-pdf.d.ts b/fill-pdf/index.d.ts similarity index 100% rename from fill-pdf/fill-pdf.d.ts rename to fill-pdf/index.d.ts diff --git a/fill-pdf/tsconfig.json b/fill-pdf/tsconfig.json index 51c99ab9de..6190a7ae98 100644 --- a/fill-pdf/tsconfig.json +++ b/fill-pdf/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "fill-pdf.d.ts", + "index.d.ts", "fill-pdf-tests.ts" ] } \ No newline at end of file diff --git a/finalhandler/index.d.ts b/finalhandler/index.d.ts index 07bbe63c91..a238c0d2a5 100644 --- a/finalhandler/index.d.ts +++ b/finalhandler/index.d.ts @@ -5,7 +5,6 @@ /// - import {ServerRequest, ServerResponse} from "http"; declare function finalHandler(req: ServerRequest, res: ServerResponse, options?: finalHandler.Options): (err: any) => void; diff --git a/fluent-ffmpeg/fluent-ffmpeg-tests.ts b/fluent-ffmpeg/fluent-ffmpeg-tests.ts index 8b1031ff58..112d6de09b 100644 --- a/fluent-ffmpeg/fluent-ffmpeg-tests.ts +++ b/fluent-ffmpeg/fluent-ffmpeg-tests.ts @@ -1,5 +1,3 @@ -/// - import ffmpeg = require("fluent-ffmpeg") let source: string, format: string, output: string diff --git a/fluent-ffmpeg/fluent-ffmpeg.d.ts b/fluent-ffmpeg/index.d.ts similarity index 100% rename from fluent-ffmpeg/fluent-ffmpeg.d.ts rename to fluent-ffmpeg/index.d.ts diff --git a/fluent-ffmpeg/tsconfig.json b/fluent-ffmpeg/tsconfig.json index 3e2fd3a624..e5256168e5 100644 --- a/fluent-ffmpeg/tsconfig.json +++ b/fluent-ffmpeg/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "fluent-ffmpeg.d.ts", + "index.d.ts", "fluent-ffmpeg-tests.ts" ] } \ No newline at end of file diff --git a/form-data/form-data-tests.ts b/form-data/form-data-tests.ts index 2df21510c0..6d1b9d6cb9 100644 --- a/form-data/form-data-tests.ts +++ b/form-data/form-data-tests.ts @@ -132,3 +132,10 @@ import * as ImportUsingES6Syntax from 'form-data'; console.log(json); }); } + +() => { + var form = new FormData(); + form.getLength((err: Error, length: number): void => { + // nothing + }); +} diff --git a/form-data/index.d.ts b/form-data/index.d.ts index 606ffdbd4a..e4bd6ca2e1 100644 --- a/form-data/index.d.ts +++ b/form-data/index.d.ts @@ -5,15 +5,18 @@ // Imported from: https://github.com/soywiz/typescript-node-definitions/form-data.d.ts +/// + export = FormData; -declare class FormData { +import * as stream from "stream"; + +declare class FormData extends stream.Readable { append(key: string, value: any, options?: any): void; getHeaders(): FormData.Dictionary; - // TODO expand pipe - pipe(to: any): any; submit(params: string | Object, callback: (error: any, response: any) => void): any; getBoundary(): string; + getLength(callback: (err: Error, length: number) => void): void; } declare namespace FormData { diff --git a/fs-extra/index.d.ts b/fs-extra/index.d.ts index 5d53a4d28f..c24ee5a49d 100644 --- a/fs-extra/index.d.ts +++ b/fs-extra/index.d.ts @@ -18,6 +18,9 @@ export declare function copySync(src: string, dest: string): void; export declare function copySync(src: string, dest: string, filter: CopyFilter): void; export declare function copySync(src: string, dest: string, options: CopyOptions): void; +export declare function move(src: string, dest: string, callback?: (err: Error) => void): void; +export declare function move(src: string, dest: string, options: MoveOptions, callback?: (err: Error) => void): void; + export declare function createFile(file: string, callback?: (err: Error) => void): void; export declare function createFileSync(file: string): void; @@ -89,6 +92,11 @@ export interface CopyOptions { limit?: number; } +export interface MoveOptions { + clobber? : boolean; + limit?: number; +} + export interface OpenOptions { encoding?: string; flag?: string; diff --git a/fullcalendar/index.d.ts b/fullcalendar/index.d.ts index fc687696f1..21f0e4a9be 100644 --- a/fullcalendar/index.d.ts +++ b/fullcalendar/index.d.ts @@ -136,7 +136,13 @@ export interface Options extends AgendaOptions, EventDraggingResizingOptions, Dr eventAfterAllRender?: (view: ViewObject) => void; eventDestroy?: (event: EventObject, element: JQuery, view: ViewObject) => void; - //scheduler options + //scheduler options + resourceAreaWidth?:number, + schedulerLicenseKey?:string, + customButtons?:any, + resourceLabelText?:any, + resourceColumns?:any, + displayEventTime?:any, } /** diff --git a/fullpage.js/fullpage.js-tests.ts b/fullpage.js/fullpage.js-tests.ts index 31e66fdd60..b8990ea9c8 100644 --- a/fullpage.js/fullpage.js-tests.ts +++ b/fullpage.js/fullpage.js-tests.ts @@ -1,5 +1,3 @@ -/// - function test_public_methods() { $(() => { $('#fullpage').fullpage({ diff --git a/fullpage.js/fullpage.js.d.ts b/fullpage.js/index.d.ts similarity index 100% rename from fullpage.js/fullpage.js.d.ts rename to fullpage.js/index.d.ts diff --git a/fullpage.js/tsconfig.json b/fullpage.js/tsconfig.json index 0e6588b0f4..736b4b1050 100644 --- a/fullpage.js/tsconfig.json +++ b/fullpage.js/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "fullpage.js.d.ts", + "index.d.ts", "fullpage.js-tests.ts" ] } \ No newline at end of file diff --git a/fuse/index.d.ts b/fuse/index.d.ts index 9f1de6ff03..5376144e22 100644 --- a/fuse/index.d.ts +++ b/fuse/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Fuse.js 2.2.0 +// Type definitions for Fuse.js 2.5.0 // Project: https://github.com/krisk/Fuse // Definitions by: Greg Smith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -9,7 +9,8 @@ declare class Fuse { } declare namespace fuse { - interface IFuseOptions extends ISearchOptions { + interface IFuseOptions { + id?: string; caseSensitive?: boolean; include?: string[]; shouldSort?: boolean; @@ -18,9 +19,9 @@ declare namespace fuse { getFn?: (obj: any, path: string) => any; keys?: string[] | { name:string; weight:number} []; verbose?:boolean; - } - - interface ISearchOptions { + tokenize?: boolean; + tokenSeparator? : RegExp; + matchAllTokens?: boolean; location?: number; distance?: number; threshold?: number; diff --git a/gapi/index.d.ts b/gapi/index.d.ts index 6d7e18a12e..54806755e8 100644 --- a/gapi/index.d.ts +++ b/gapi/index.d.ts @@ -127,27 +127,7 @@ declare namespace gapi.auth { } declare namespace gapi.client { - /** - * Loads the client library interface to a particular API. If a callback is not provided, a promise is returned. - * @param name The name of the API to load. - * @param version The version of the API to load. - * @return promise The promise that get's resolved after the request is finished. - */ - export function load(name: string, version: string): Promise - - /** - * Loads the client library interface to a particular API. The new API interface will be in the form gapi.client.api.collection.method. - * @param name The name of the API to load. - * @param version The version of the API to load - * @param callback the function that is called once the API interface is loaded - * @param url optional, the url of your app - if using Google's APIs, don't set it - */ - export function load(name: string, version: string, callback: () => any, url?: string): void; - /** - * Creates a HTTP request for making RESTful requests. - * An object encapsulating the various arguments for this method. - */ - export function request(args: { + interface RequestOptions { /** * The URL to handle the request */ @@ -172,7 +152,29 @@ declare namespace gapi.client { * If supplied, the request is executed immediately and no gapi.client.HttpRequest object is returned */ callback?: () => any; - }): HttpRequest; + } + + /** + * Loads the client library interface to a particular API. If a callback is not provided, a promise is returned. + * @param name The name of the API to load. + * @param version The version of the API to load. + * @return promise The promise that get's resolved after the request is finished. + */ + export function load(name: string, version: string): Promise + + /** + * Loads the client library interface to a particular API. The new API interface will be in the form gapi.client.api.collection.method. + * @param name The name of the API to load. + * @param version The version of the API to load + * @param callback the function that is called once the API interface is loaded + * @param url optional, the url of your app - if using Google's APIs, don't set it + */ + export function load(name: string, version: string, callback: () => any, url?: string): void; + /** + * Creates a HTTP request for making RESTful requests. + * An object encapsulating the various arguments for this method. + */ + export function request(args: RequestOptions): HttpRequest; /** * Creates an RPC Request directly. The method name and version identify the method to be executed and the RPC params are provided upon RPC creation. * @param method The method to be executed. diff --git a/gl-matrix/gl-matrix-tests.ts b/gl-matrix/gl-matrix-tests.ts index 5df2220f72..6325ff5cd4 100644 --- a/gl-matrix/gl-matrix-tests.ts +++ b/gl-matrix/gl-matrix-tests.ts @@ -33,6 +33,11 @@ let outMat3 = mat3.create(); let outMat4 = mat4.create(); let outQuat = quat.create(); +let outMat2Null: mat2 | null; +let outMat2dNull: mat2d | null; +let outMat3Null: mat3 | null; +let outMat4Null: mat4 | null; + // vec2 outVec2 = vec2.create(); outVec2 = vec2.clone(vec2A); @@ -180,7 +185,7 @@ outMat2 = mat2.identity(outMat2); outMat2 = mat2.fromValues(1, 2, 3, 4); outMat2 = mat2.set(outMat2, 1, 2, 3, 4); outMat2 = mat2.transpose(outMat2, mat2A); -outMat2 = mat2.invert(outMat2, mat2A); +outMat2Null = mat2.invert(outMat2, mat2A); outMat2 = mat2.adjoint(outMat2, mat2A); outVal = mat2.determinant(mat2A); outMat2 = mat2.multiply(outMat2, mat2A, mat2B); @@ -210,7 +215,7 @@ outMat2d = mat2d.copy(outMat2d, mat2dA); outMat2d = mat2d.identity(outMat2d); outMat2d = mat2d.fromValues(1, 2, 3, 4, 5, 6); outMat2d = mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6); -outMat2d = mat2d.invert(outMat2d, mat2dA); +outMat2dNull = mat2d.invert(outMat2d, mat2dA); outVal = mat2d.determinant(mat2dA); outMat2d = mat2d.multiply(outMat2d, mat2dA, mat2dB); outMat2d = mat2d.mul(outMat2d, mat2dA, mat2dB); @@ -239,7 +244,7 @@ outMat3 = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); outMat3 = mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9); outMat3 = mat3.identity(outMat3); outMat3 = mat3.transpose(outMat3, mat3A); -outMat3 = mat3.invert(outMat3, mat3A); +outMat3Null = mat3.invert(outMat3, mat3A); outMat3 = mat3.adjoint(outMat3, mat3A); outVal = mat3.determinant(mat3A); outMat3 = mat3.multiply(outMat3, mat3A, mat3B); @@ -252,7 +257,7 @@ outMat3 = mat3.fromRotation(outMat3, Math.PI); outMat3 = mat3.fromScaling(outMat3, vec2A); outMat3 = mat3.fromMat2d(outMat3, mat2dA); outMat3 = mat3.fromQuat(outMat3, quatA); -outMat3 = mat3.normalFromMat4(outMat3, mat4A); +outMat3Null = mat3.normalFromMat4(outMat3, mat4A); outStr = mat3.str(mat3A); outVal = mat3.frob(mat3A); outMat3 = mat3.add(outMat3, mat3A, mat3B); @@ -271,19 +276,19 @@ outMat4 = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16) outMat4 = mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); outMat4 = mat4.identity(outMat4); outMat4 = mat4.transpose(outMat4, mat4A); -outMat4 = mat4.invert(outMat4, mat4A); +outMat4Null = mat4.invert(outMat4, mat4A); outMat4 = mat4.adjoint(outMat4, mat4A); outVal = mat4.determinant(mat4A); outMat4 = mat4.multiply(outMat4, mat4A, mat4B); outMat4 = mat4.mul(outMat4, mat4A, mat4B); outMat4 = mat4.translate(outMat4, mat4A, vec3A); outMat4 = mat4.scale(outMat4, mat4A, vec3A); -outMat4 = mat4.rotate(outMat4, mat4A, Math.PI, vec3A); +outMat4Null = mat4.rotate(outMat4, mat4A, Math.PI, vec3A); outMat4 = mat4.rotateX(outMat4, mat4A, Math.PI); outMat4 = mat4.rotateY(outMat4, mat4A, Math.PI); outMat4 = mat4.rotateZ(outMat4, mat4A, Math.PI); outMat4 = mat4.fromTranslation(outMat4, vec3A); -outMat4 = mat4.fromRotation(outMat4, Math.PI, vec3A); +outMat4Null = mat4.fromRotation(outMat4, Math.PI, vec3A); outMat4 = mat4.fromScaling(outMat4, vec3A); outMat4 = mat4.fromXRotation(outMat4, Math.PI); outMat4 = mat4.fromYRotation(outMat4, Math.PI); @@ -529,7 +534,7 @@ outMat2 = _mat2.identity(outMat2); outMat2 = _mat2.fromValues(1, 2, 3, 4); outMat2 = _mat2.set(outMat2, 1, 2, 3, 4); outMat2 = _mat2.transpose(outMat2, mat2A); -outMat2 = _mat2.invert(outMat2, mat2A); +outMat2Null = _mat2.invert(outMat2, mat2A); outMat2 = _mat2.adjoint(outMat2, mat2A); outVal = _mat2.determinant(mat2A); outMat2 = _mat2.multiply(outMat2, mat2A, mat2B); @@ -559,7 +564,7 @@ outMat2d = _mat2d.copy(outMat2d, mat2dA); outMat2d = _mat2d.identity(outMat2d); outMat2d = _mat2d.fromValues(1, 2, 3, 4, 5, 6); outMat2d = _mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6); -outMat2d = _mat2d.invert(outMat2d, mat2dA); +outMat2dNull = _mat2d.invert(outMat2d, mat2dA); outVal = _mat2d.determinant(mat2dA); outMat2d = _mat2d.multiply(outMat2d, mat2dA, mat2dB); outMat2d = _mat2d.mul(outMat2d, mat2dA, mat2dB); @@ -588,7 +593,7 @@ outMat3 = _mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); outMat3 = _mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9); outMat3 = _mat3.identity(outMat3); outMat3 = _mat3.transpose(outMat3, mat3A); -outMat3 = _mat3.invert(outMat3, mat3A); +outMat3Null = _mat3.invert(outMat3, mat3A); outMat3 = _mat3.adjoint(outMat3, mat3A); outVal = _mat3.determinant(mat3A); outMat3 = _mat3.multiply(outMat3, mat3A, mat3B); @@ -601,7 +606,7 @@ outMat3 = _mat3.fromRotation(outMat3, Math.PI); outMat3 = _mat3.fromScaling(outMat3, vec2A); outMat3 = _mat3.fromMat2d(outMat3, mat2dA); outMat3 = _mat3.fromQuat(outMat3, quatA); -outMat3 = _mat3.normalFromMat4(outMat3, mat4A); +outMat3Null = _mat3.normalFromMat4(outMat3, mat4A); outStr = _mat3.str(mat3A); outVal = _mat3.frob(mat3A); outMat3 = _mat3.add(outMat3, mat3A, mat3B); @@ -620,19 +625,19 @@ outMat4 = _mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 outMat4 = _mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); outMat4 = _mat4.identity(outMat4); outMat4 = _mat4.transpose(outMat4, mat4A); -outMat4 = _mat4.invert(outMat4, mat4A); +outMat4Null = _mat4.invert(outMat4, mat4A); outMat4 = _mat4.adjoint(outMat4, mat4A); outVal = _mat4.determinant(mat4A); outMat4 = _mat4.multiply(outMat4, mat4A, mat4B); outMat4 = _mat4.mul(outMat4, mat4A, mat4B); outMat4 = _mat4.translate(outMat4, mat4A, vec3A); outMat4 = _mat4.scale(outMat4, mat4A, vec3A); -outMat4 = _mat4.rotate(outMat4, mat4A, Math.PI, vec3A); +outMat4Null = _mat4.rotate(outMat4, mat4A, Math.PI, vec3A); outMat4 = _mat4.rotateX(outMat4, mat4A, Math.PI); outMat4 = _mat4.rotateY(outMat4, mat4A, Math.PI); outMat4 = _mat4.rotateZ(outMat4, mat4A, Math.PI); outMat4 = _mat4.fromTranslation(outMat4, vec3A); -outMat4 = _mat4.fromRotation(outMat4, Math.PI, vec3A); +outMat4Null = _mat4.fromRotation(outMat4, Math.PI, vec3A); outMat4 = _mat4.fromScaling(outMat4, vec3A); outMat4 = _mat4.fromXRotation(outMat4, Math.PI); outMat4 = _mat4.fromYRotation(outMat4, Math.PI); diff --git a/gl-matrix/index.d.ts b/gl-matrix/index.d.ts index b8a6694e40..89f28934b8 100644 --- a/gl-matrix/index.d.ts +++ b/gl-matrix/index.d.ts @@ -1384,7 +1384,7 @@ declare module 'gl-matrix' { * @param a the source matrix * @returns out */ - public static invert(out: mat2, a: mat2): mat2; + public static invert(out: mat2, a: mat2): mat2 | null; /** * Calculates the adjugate of a mat2 @@ -1638,7 +1638,7 @@ declare module 'gl-matrix' { * @param a the source matrix * @returns out */ - public static invert(out: mat2d, a: mat2d): mat2d; + public static invert(out: mat2d, a: mat2d): mat2d | null; /** * Calculates the determinant of a mat2d @@ -1918,7 +1918,7 @@ declare module 'gl-matrix' { * @param a the source matrix * @returns out */ - public static invert(out: mat3, a: mat3): mat3; + public static invert(out: mat3, a: mat3): mat3 | null; /** * Calculates the adjugate of a mat3 @@ -2054,7 +2054,7 @@ declare module 'gl-matrix' { * * @returns out */ - public static normalFromMat4(out: mat3, a: mat4): mat3; + public static normalFromMat4(out: mat3, a: mat4): mat3 | null; /** * Returns a string representation of a mat3 @@ -2242,7 +2242,7 @@ declare module 'gl-matrix' { * @param a the source matrix * @returns out */ - public static invert(out: mat4, a: mat4): mat4; + public static invert(out: mat4, a: mat4): mat4 | null; /** * Calculates the adjugate of a mat4 diff --git a/gl-matrix/tsconfig.json b/gl-matrix/tsconfig.json index 5350b55fb6..4a5a2ae6bb 100644 --- a/gl-matrix/tsconfig.json +++ b/gl-matrix/tsconfig.json @@ -3,7 +3,7 @@ "module": "commonjs", "target": "es6", "noImplicitAny": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -16,4 +16,4 @@ "index.d.ts", "gl-matrix-tests.ts" ] -} \ No newline at end of file +} diff --git a/google-drive-realtime-api/index.d.ts b/google-drive-realtime-api/index.d.ts index 025ce08a86..6cfd9b1cc1 100644 --- a/google-drive-realtime-api/index.d.ts +++ b/google-drive-realtime-api/index.d.ts @@ -16,8 +16,9 @@ // gapi is a global var introduced by https://apis.google.com/js/api.js declare namespace gapi.drive.realtime { + export type CollaborativeObjectType = 'EditableString' | 'Map' | 'List' - type GoogEventHandler = ((evt:ObjectChangedEvent) => void) | ((e:Event) => void) | EventListener; + export type GoogEventHandler = ((evt:ObjectChangedEvent) => void) | ((e:Event) => void) | EventListener; // Complete // https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.Collaborator @@ -65,7 +66,7 @@ declare namespace gapi.drive.realtime { // see gapi.drive.realtime.CollaborrativeType for possible values; for custom collaborative objects, this value is // application-defined. // Addition: the possible values for standard objects are EditableString, List, and Map. - type:string; + type:CollaborativeObjectType; // Adds an event listener to the event target. The same handler can only be added once per the type. // Even if you add the same handler multiple times using the same type then it will only be called once @@ -107,9 +108,9 @@ declare namespace gapi.drive.realtime { // Complete // https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.CollaborativeMap export class CollaborativeMap extends CollaborativeObject { - size:string; + size:number; - static type:string; // equals "Map" + static type:'Map'; // Removes all entries. clear():void; @@ -154,7 +155,7 @@ declare namespace gapi.drive.realtime { // The text of this collaborative string. Reading from this property is equivalent to calling getText(). Writing to this property is equivalent to calling setText(). text:string; - static type:string; // equals "EditableString" + static type:'EditableString'; // Appends a string to the end of this one. append(text:string):void; @@ -186,7 +187,7 @@ declare namespace gapi.drive.realtime { // The length of a list cannot be extended in this way. length:number; - static type:string; // equals "List" + static type:"List"; // Returns a copy of the contents of this collaborative list as an array. // Changes to the returned object will not affect the original collaborative list. @@ -344,9 +345,68 @@ declare namespace gapi.drive.realtime { undo():void; } + export type EventType = 'object_changed' | 'values_set' | 'values_added' | 'values_removed' | 'value_changed' | + 'text_inserted' | 'text_deleted' | 'collaborator_joined' | 'collaborator_left' | 'reference_shifted' | + 'document_save_state_changed' | 'undo_redo_state_changed' | 'attribute_changed'; + export const EventType:{ + // A collaborative object has changed. This event wraps a specific event, and bubbles to ancestors. + // Defaults to object_changed. + OBJECT_CHANGED:'object_changed' + + // Values in a list are changed in place. + // Defaults to values_set. + VALUES_SET:'values_set', + + // New values have been added to the list. + // values_added + VALUES_ADDED:'values_added' + + // Values have been removed from the list. + // values_removed + VALUES_REMOVED:'values_removed' + + // A map or custom object value has changed. Note this could be a new value or deleted value. + // value_changed + VALUE_CHANGED:'value_changed' + + // Text has been inserted into a string. + // text_inserted + TEXT_INSERTED:'text_inserted' + + // Text has been removed from a string. + // text_deleted + TEXT_DELETED:'text_deleted' + + // A new collaborator joined the document. Listen on the gapi.drive.realtime.Document for these changes. + // collaborator_joined + COLLABORATOR_JOINED:'collaborator_joined' + + // A collaborator left the document. Listen on the gapi.drive.realtime.Document for these changes. + // collaborator_left + COLLABORATOR_LEFT:'collaborator_left' + + // An index reference changed. + // reference_shifted + REFERENCE_SHIFTED:'reference_shifted' + + // The document save state changed. Listen on the gapi.drive.realtime.Document for these changes. + // document_save_state_changed + DOCUMENT_SAVE_STATE_CHANGED:'document_save_state_changed' + + // The model canUndo/canRedo state changed. Listen on the gapi.drive.realtime.Model for these changes. + // undo_redo_state_changed + UNDO_REDO_STATE_CHANGED:'undo_redo_state_changed' + + // A metadata attribute of the document changed. This is fired on changes to: + // gapi.drive.realtime.Attribute.IS_READ_ONLY + // Listen on the gapi.drive.realtime.Document for these changes. + // attribute_changed + ATTRIBUTE_CHANGED:'attribute_changed' + } + // Complete // https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.BaseModelEvent - interface BaseModelEvent { + export interface BaseModelEvent { // Whether this event bubbles. bubbles : boolean; @@ -373,7 +433,7 @@ declare namespace gapi.drive.realtime { target : CollaborativeObject; // The type of the event. - type : string; + type : EventType; // The user id of the user that initiated this event. userId : string; @@ -399,6 +459,7 @@ declare namespace gapi.drive.realtime { Array of string The list of names from the hierarchy of compound operations that initiated the event. Value must not be null. + isLocal boolean True if the event originated in the local session. @@ -417,7 +478,7 @@ declare namespace gapi.drive.realtime { // Complete // https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.ObjectChangedEvent - interface ObjectChangedEvent extends BaseModelEvent { + export interface ObjectChangedEvent extends BaseModelEvent { // parameters as in BaseModelEvent above except for addition of: // events: // Array of gapi.drive.realtime.BaseModelEvent @@ -435,7 +496,7 @@ declare namespace gapi.drive.realtime { new (target:CollaborativeObject, sessionId:string, userId:string, compoundOperationNames:string[], isLocal:boolean, isUndo:boolean, isRedo:boolean, index:number, values:V[], movedFromList:CollaborativeList, movedFromIndex:number):ValuesAddedEvent; - + // The index of the first added value index:number; @@ -523,7 +584,7 @@ declare namespace gapi.drive.realtime { "missing_property" | "not_found" | "forbidden" | "server_error" | "client_error" | "token_refresh_required" | "invalid_element_type" | "no_write_permission" | "fatal_network_error" | "unexpected_element"; - export var ErrorType : { + export const ErrorType : { // Another user created the document's initial state after // gapi.drive.realtime.load was called but before the local // creation was saved. @@ -627,12 +688,12 @@ declare namespace gapi.drive.realtime { opt_initializerFn? : (m:Model) => void, opt_errorFn? : (e:gapi.drive.realtime.Error) => void ) : Document; - + /* Loads an existing file by id. https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime#.load - + @Param fileId {string} Id of the file to load. - + @Param onLoaded {function(non-null gapi.drive.realtime.Document)} A callback that will be called when the realtime document is ready. The created or opened realtime document object will be passed to this function. @@ -649,8 +710,22 @@ declare namespace gapi.drive.realtime { fileId:string, onLoaded? : (d:Document) => void, opt_initializerFn? : (m:Model) => void, - opt_errorFn? : (e:gapi.drive.realtime.Error) => void + opt_errorFn? : (e:Error) => void ):void; + + export function loadAppDataDocument( + onLoaded:(x:Document) => void, + opt_initializerFn?:(x:Model) => void, + opt_errorFn?:(e:Error) => void + ):void + + // Loads an in-memory document from a json string. + // This document does not talk to the server and will only exist in memory for as long as the browser session exists. + export function loadFromJson( + json:string, + opt_errorFn?:(e:Error) => void + ):Document + } @@ -674,29 +749,21 @@ declare namespace gapi.drive.realtime.databinding { } -declare namespace gapi.drive.realtime.EventType { - export var TEXT_INSERTED: string - export var TEXT_DELETED: string - export var OBJECT_CHANGED: string - // List - export var VALUES_ADDED:string; - export var VALUES_REMOVED:string; - export var VALUES_SET:string; -} - - // rtclient is a global var introduced by realtime-client-utils.js declare namespace rtclient { // INCOMPLETE export interface RealtimeLoader { start():void; load():void; + handleErrors(e:gapi.drive.realtime.Error):void; } interface RealtimeLoaderFactory { new (options:LoaderOptions) : RealtimeLoader; } // *********************************** + // NOTE THIS IS OUT OF DATE. realtime-client-utils.js has been rewritten, with the new version "Realtime Utils 1.0.0". + // Will add typings for the new version later. // The remainder of this file types some (not all) things in realtime-client-utils.js, found here: // https://developers.google.com/google-apps/realtime/realtime-quickstart // and diff --git a/google-libphonenumber/index.d.ts b/google-libphonenumber/index.d.ts index 28f72f67a3..0c0e1efda3 100644 --- a/google-libphonenumber/index.d.ts +++ b/google-libphonenumber/index.d.ts @@ -1,6 +1,5 @@ // Type definitions for libphonenumber v7.4.3 -// Project: https://github.com/googlei18n/libphonenumber -// Project: https://github.com/seegno/google-libphonenumber +// Project: https://github.com/googlei18n/libphonenumber, https://github.com/seegno/google-libphonenumber // Definitions by: Leon Yu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/graphql/index.d.ts b/graphql/index.d.ts index 0e93923c1d..14b29144eb 100644 --- a/graphql/index.d.ts +++ b/graphql/index.d.ts @@ -1,11 +1,11 @@ -// Type definitions for graphql v0.7.0 +// Type definitions for graphql v0.8.2 // Project: https://www.npmjs.com/package/graphql -// Definitions by: TonyYang , Caleb Meredith +// Definitions by: TonyYang , Caleb Meredith , Dominic Watson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************* - * * - * MODULES * + * * + * MODULES * * * *************************************/ /////////////////////////// @@ -29,12 +29,16 @@ declare module "graphql" { // Execute GraphQL queries. export { execute, + defaultFieldResolver, + responsePathAsArray, + ExecutionResult, } from 'graphql/execution'; // Validate GraphQL queries. export { validate, + ValidationContext, specifiedRules, } from 'graphql/validation'; @@ -43,6 +47,8 @@ declare module "graphql" { export { GraphQLError, formatError, + GraphQLFormattedError, + GraphQLErrorLocation, } from 'graphql/error'; @@ -70,6 +76,9 @@ declare module "graphql" { // Print a GraphQLSchema to GraphQL Schema language. printSchema, + // Print a GraphQLType to GraphQL Schema language. + printType, + // Create a GraphQLType from a GraphQL language AST. typeFromAST, @@ -102,12 +111,32 @@ declare module "graphql" { // Asserts a string is a valid GraphQL name. assertValidName, + + BreakingChange, + + IntrospectionDirective, + IntrospectionEnumType, + IntrospectionEnumValue, + IntrospectionField, + IntrospectionInputObjectType, + IntrospectionInputValue, + IntrospectionInterfaceType, + IntrospectionListTypeRef, + IntrospectionNamedTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionObjectType, + IntrospectionQuery, + IntrospectionScalarType, + IntrospectionSchema, + IntrospectionType, + IntrospectionTypeRef, + IntrospectionUnionType, } from 'graphql/utilities'; } declare module "graphql/graphql" { - import { GraphQLError } from 'graphql/error/GraphQLError'; import { GraphQLSchema } from 'graphql/type/schema'; + import { ExecutionResult } from 'graphql/execution/execute'; /** * This is the primary entry point function for fulfilling GraphQL operations @@ -142,18 +171,7 @@ declare module "graphql/graphql" { [key: string]: any }, operationName?: string - ): Promise; - - /** - * The result of a GraphQL parse, validation and execution. - * - * `data` is the result of a successful execution of the query. - * `errors` is included when any errors occurred as a non-empty array. - */ - type GraphQLResult = { - data?: Object; - errors?: Array; - } + ): Promise; } /////////////////////////// @@ -177,8 +195,8 @@ declare module "graphql/language/index" { export { getLocation } from 'graphql/language/location'; import * as Kind from 'graphql/language/kinds'; export { Kind }; - export { createLexer, TokenKind } from 'graphql/language/lexer'; - export { parse, parseValue, parseType } from 'graphql/language/parser'; + export { createLexer, TokenKind, Lexer } from 'graphql/language/lexer'; + export { parse, parseValue, parseType, ParseOptions } from 'graphql/language/parser'; export { print } from 'graphql/language/printer'; export { Source } from 'graphql/language/source'; export { visit, visitInParallel, visitWithTypeInfo, BREAK } from 'graphql/language/visitor'; @@ -286,46 +304,46 @@ declare module "graphql/language/ast" { /** * The list of all possible AST node types. */ - export type Node = Name - | Document - | OperationDefinition - | VariableDefinition - | Variable - | SelectionSet - | Field - | Argument - | FragmentSpread - | InlineFragment - | FragmentDefinition - | IntValue - | FloatValue - | StringValue - | BooleanValue - | EnumValue - | ListValue - | ObjectValue - | ObjectField - | Directive - | NamedType - | ListType - | NonNullType - | SchemaDefinition - | OperationTypeDefinition - | ScalarTypeDefinition - | ObjectTypeDefinition - | FieldDefinition - | InputValueDefinition - | InterfaceTypeDefinition - | UnionTypeDefinition - | EnumTypeDefinition - | EnumValueDefinition - | InputObjectTypeDefinition - | TypeExtensionDefinition - | DirectiveDefinition + export type ASTNode = NameNode + | DocumentNode + | OperationDefinitionNode + | VariableDefinitionNode + | VariableNode + | SelectionSetNode + | FieldNode + | ArgumentNode + | FragmentSpreadNode + | InlineFragmentNode + | FragmentDefinitionNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode + | ObjectFieldNode + | DirectiveNode + | NamedTypeNode + | ListTypeNode + | NonNullTypeNode + | SchemaDefinitionNode + | OperationTypeDefinitionNode + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | FieldDefinitionNode + | InputValueDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | EnumValueDefinitionNode + | InputObjectTypeDefinitionNode + | TypeExtensionDefinitionNode + | DirectiveDefinitionNode; // Name - export type Name = { + export type NameNode = { kind: 'Name'; loc?: Location; value: string; @@ -333,306 +351,306 @@ declare module "graphql/language/ast" { // Document - export type Document = { + export type DocumentNode = { kind: 'Document'; loc?: Location; - definitions: Array; + definitions: Array; } - export type Definition = OperationDefinition - | FragmentDefinition - | TypeSystemDefinition // experimental non-spec addition. + export type DefinitionNode = OperationDefinitionNode + | FragmentDefinitionNode + | TypeSystemDefinitionNode // experimental non-spec addition. - export type OperationDefinition = { + export type OperationDefinitionNode = { kind: 'OperationDefinition'; loc?: Location; - operation: OperationType; - name?: Name; - variableDefinitions?: Array; - directives?: Array; - selectionSet: SelectionSet; + operation: OperationTypeNode; + name?: NameNode; + variableDefinitions?: Array; + directives?: Array; + selectionSet: SelectionSetNode; } // Note: subscription is an experimental non-spec addition. - export type OperationType = 'query' | 'mutation' | 'subscription'; + export type OperationTypeNode = 'query' | 'mutation' | 'subscription'; - export type VariableDefinition = { + export type VariableDefinitionNode = { kind: 'VariableDefinition'; loc?: Location; - variable: Variable; - type: Type; - defaultValue?: Value; + variable: VariableNode; + type: TypeNode; + defaultValue?: ValueNode; } - export type Variable = { + export type VariableNode = { kind: 'Variable'; loc?: Location; - name: Name; + name: NameNode; } - export type SelectionSet = { + export type SelectionSetNode = { kind: 'SelectionSet'; loc?: Location; - selections: Array; + selections: Array; } - export type Selection = Field - | FragmentSpread - | InlineFragment + export type SelectionNode = FieldNode + | FragmentSpreadNode + | InlineFragmentNode - export type Field = { + export type FieldNode = { kind: 'Field'; loc?: Location; - alias?: Name; - name: Name; - arguments?: Array; - directives?: Array; - selectionSet?: SelectionSet; + alias?: NameNode; + name: NameNode; + arguments?: Array; + directives?: Array; + selectionSet?: SelectionSetNode; } - export type Argument = { + export type ArgumentNode = { kind: 'Argument'; loc?: Location; - name: Name; - value: Value; + name: NameNode; + value: ValueNode; } // Fragments - export type FragmentSpread = { + export type FragmentSpreadNode = { kind: 'FragmentSpread'; loc?: Location; - name: Name; - directives?: Array; + name: NameNode; + directives?: Array; } - export type InlineFragment = { + export type InlineFragmentNode = { kind: 'InlineFragment'; loc?: Location; - typeCondition?: NamedType; - directives?: Array; - selectionSet: SelectionSet; + typeCondition?: NamedTypeNode; + directives?: Array; + selectionSet: SelectionSetNode; } - export type FragmentDefinition = { + export type FragmentDefinitionNode = { kind: 'FragmentDefinition'; loc?: Location; - name: Name; - typeCondition: NamedType; - directives?: Array; - selectionSet: SelectionSet; + name: NameNode; + typeCondition: NamedTypeNode; + directives?: Array; + selectionSet: SelectionSetNode; } // Values - export type Value = Variable - | IntValue - | FloatValue - | StringValue - | BooleanValue - | EnumValue - | ListValue - | ObjectValue + export type ValueNode = VariableNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode - export type IntValue = { + export type IntValueNode = { kind: 'IntValue'; loc?: Location; value: string; } - export type FloatValue = { + export type FloatValueNode = { kind: 'FloatValue'; loc?: Location; value: string; } - export type StringValue = { + export type StringValueNode = { kind: 'StringValue'; loc?: Location; value: string; } - export type BooleanValue = { + export type BooleanValueNode = { kind: 'BooleanValue'; loc?: Location; value: boolean; } - export type EnumValue = { + export type EnumValueNode = { kind: 'EnumValue'; loc?: Location; value: string; } - export type ListValue = { + export type ListValueNode = { kind: 'ListValue'; loc?: Location; - values: Array; + values: Array; } - export type ObjectValue = { + export type ObjectValueNode = { kind: 'ObjectValue'; loc?: Location; - fields: Array; + fields: Array; } - export type ObjectField = { + export type ObjectFieldNode = { kind: 'ObjectField'; loc?: Location; - name: Name; - value: Value; + name: NameNode; + value: ValueNode; } // Directives - export type Directive = { + export type DirectiveNode = { kind: 'Directive'; loc?: Location; - name: Name; - arguments?: Array; + name: NameNode; + arguments?: Array; } // Type Reference - export type Type = NamedType - | ListType - | NonNullType + export type TypeNode = NamedTypeNode + | ListTypeNode + | NonNullTypeNode - export type NamedType = { + export type NamedTypeNode = { kind: 'NamedType'; loc?: Location; - name: Name; + name: NameNode; }; - export type ListType = { + export type ListTypeNode = { kind: 'ListType'; loc?: Location; - type: Type; + type: TypeNode; } - export type NonNullType = { + export type NonNullTypeNode = { kind: 'NonNullType'; loc?: Location; - type: NamedType | ListType; + type: NamedTypeNode | ListTypeNode; } // Type System Definition - export type TypeSystemDefinition = SchemaDefinition - | TypeDefinition - | TypeExtensionDefinition - | DirectiveDefinition + export type TypeSystemDefinitionNode = SchemaDefinitionNode + | TypeDefinitionNode + | TypeExtensionDefinitionNode + | DirectiveDefinitionNode - export type SchemaDefinition = { + export type SchemaDefinitionNode = { kind: 'SchemaDefinition'; loc?: Location; - directives: Array; - operationTypes: Array; + directives: Array; + operationTypes: Array; } - export type OperationTypeDefinition = { + export type OperationTypeDefinitionNode = { kind: 'OperationTypeDefinition'; loc?: Location; - operation: OperationType; - type: NamedType; + operation: OperationTypeNode; + type: NamedTypeNode; } - export type TypeDefinition = ScalarTypeDefinition - | ObjectTypeDefinition - | InterfaceTypeDefinition - | UnionTypeDefinition - | EnumTypeDefinition - | InputObjectTypeDefinition + export type TypeDefinitionNode = ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | InputObjectTypeDefinitionNode - export type ScalarTypeDefinition = { + export type ScalarTypeDefinitionNode = { kind: 'ScalarTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; + name: NameNode; + directives?: Array; } - export type ObjectTypeDefinition = { + export type ObjectTypeDefinitionNode = { kind: 'ObjectTypeDefinition'; loc?: Location; - name: Name; - interfaces?: Array; - directives?: Array; - fields: Array; + name: NameNode; + interfaces?: Array; + directives?: Array; + fields: Array; } - export type FieldDefinition = { + export type FieldDefinitionNode = { kind: 'FieldDefinition'; loc?: Location; - name: Name; - arguments: Array; - type: Type; - directives?: Array; + name: NameNode; + arguments: Array; + type: TypeNode; + directives?: Array; } - export type InputValueDefinition = { + export type InputValueDefinitionNode = { kind: 'InputValueDefinition'; loc?: Location; - name: Name; - type: Type; - defaultValue?: Value; - directives?: Array; + name: NameNode; + type: TypeNode; + defaultValue?: ValueNode; + directives?: Array; } - export type InterfaceTypeDefinition = { + export type InterfaceTypeDefinitionNode = { kind: 'InterfaceTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; - fields: Array; + name: NameNode; + directives?: Array; + fields: Array; } - export type UnionTypeDefinition = { + export type UnionTypeDefinitionNode = { kind: 'UnionTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; - types: Array; + name: NameNode; + directives?: Array; + types: Array; } - export type EnumTypeDefinition = { + export type EnumTypeDefinitionNode = { kind: 'EnumTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; - values: Array; + name: NameNode; + directives?: Array; + values: Array; } - export type EnumValueDefinition = { + export type EnumValueDefinitionNode = { kind: 'EnumValueDefinition'; loc?: Location; - name: Name; - directives?: Array; + name: NameNode; + directives?: Array; } - export type InputObjectTypeDefinition = { + export type InputObjectTypeDefinitionNode = { kind: 'InputObjectTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; - fields: Array; + name: NameNode; + directives?: Array; + fields: Array; } - export type TypeExtensionDefinition = { + export type TypeExtensionDefinitionNode = { kind: 'TypeExtensionDefinition'; loc?: Location; - definition: ObjectTypeDefinition; + definition: ObjectTypeDefinitionNode; } - export type DirectiveDefinition = { + export type DirectiveDefinitionNode = { kind: 'DirectiveDefinition'; loc?: Location; - name: Name; - arguments?: Array; - locations: Array; + name: NameNode; + arguments?: Array; + locations: Array; } } @@ -664,6 +682,7 @@ declare module "graphql/language/kinds" { const FLOAT: 'FloatValue'; const STRING: 'StringValue'; const BOOLEAN: 'BooleanValue'; + const NULL: 'NullValue'; const ENUM: 'EnumValue'; const LIST: 'ListValue'; const OBJECT: 'ObjectValue'; @@ -801,7 +820,7 @@ declare module "graphql/language/location" { } declare module "graphql/language/parser" { - import { NamedType, Type, Value, Document } from "graphql/language/ast"; + import { NamedTypeNode, TypeNode, ValueNode, DocumentNode } from "graphql/language/ast"; import { Source } from "graphql/language/source"; import { Lexer } from "graphql/language/lexer"; @@ -824,7 +843,7 @@ declare module "graphql/language/parser" { function parse( source: string | Source, options?: ParseOptions - ): Document; + ): DocumentNode; /** * Given a string containing a GraphQL value, parse the AST for that value. @@ -836,9 +855,9 @@ declare module "graphql/language/parser" { function parseValue( source: Source | string, options?: ParseOptions - ): Value; + ): ValueNode; - function parseConstValue(lexer: Lexer): Value; + function parseConstValue(lexer: Lexer): ValueNode; /** * Type : @@ -846,12 +865,20 @@ declare module "graphql/language/parser" { * - ListType * - NonNullType */ - function parseType(lexer: Lexer): Type; + function parseType(lexer: Lexer): TypeNode; + + /** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ + function parseTypeReference(lexer: Lexer): TypeNode; /** * NamedType : Name */ - function parseNamedType(lexer: Lexer): NamedType; + function parseNamedType(lexer: Lexer): NamedTypeNode; } declare module "graphql/language/printer" { @@ -889,6 +916,7 @@ declare module "graphql/language/visitor" { FloatValue: number[]; StringValue: string[]; BooleanValue: boolean[]; + NullValue: null[], EnumValue: any[]; ListValue: string[]; ObjectValue: string[]; @@ -980,14 +1008,15 @@ declare module "graphql/type/index" { TypeNameMetaFieldDef, } from 'graphql/type/introspection'; + export { DirectiveLocationEnum } from 'graphql/type/directives'; } declare module "graphql/type/definition" { import { - OperationDefinition, - Field, - FragmentDefinition, - Value, + OperationDefinitionNode, + FieldNode, + FragmentDefinitionNode, + ValueNode, } from 'graphql/language/ast'; import { GraphQLSchema } from 'graphql/type/schema'; @@ -1006,6 +1035,8 @@ declare module "graphql/type/definition" { export function isType(type: any): type is GraphQLType; + export function assertType(type: any): GraphQLType; + /** * These types may be used as input types for arguments and directives. */ @@ -1023,6 +1054,8 @@ declare module "graphql/type/definition" { export function isInputType(type: GraphQLType): type is GraphQLInputType; + export function assertInputType(type: GraphQLType): GraphQLInputType; + /** * These types may be used as output types as the result of fields. */ @@ -1044,6 +1077,8 @@ declare module "graphql/type/definition" { export function isOutputType(type: GraphQLType): type is GraphQLOutputType; + export function assertOutputType(type: GraphQLType): GraphQLOutputType; + /** * These types may describe types which may be leaf values. */ @@ -1053,6 +1088,8 @@ declare module "graphql/type/definition" { export function isLeafType(type: GraphQLType): type is GraphQLLeafType; + export function assertLeafType(type: GraphQLType): GraphQLLeafType; + /** * These types may describe the parent context of a selection set. */ @@ -1063,6 +1100,8 @@ declare module "graphql/type/definition" { export function isCompositeType(type: GraphQLType): type is GraphQLCompositeType; + export function assertCompositeType(type: GraphQLType): GraphQLCompositeType; + /** * These types may describe the parent context of a selection set. */ @@ -1072,6 +1111,8 @@ declare module "graphql/type/definition" { export function isAbstractType(type: GraphQLType): type is GraphQLAbstractType; + export function assertAbstractType(type: GraphQLType): GraphQLAbstractType; + /** * These types can all accept null as a value. */ @@ -1136,7 +1177,7 @@ declare module "graphql/type/definition" { parseValue(value: any): any; // Parses an externally provided literal value to use as an input. - parseLiteral(valueAST: Value): any; + parseLiteral(valueNode: ValueNode): any; toString(): string; } @@ -1146,7 +1187,7 @@ declare module "graphql/type/definition" { description?: string; serialize: (value: any) => TInternal; parseValue?: (value: any) => TExternal; - parseLiteral?: (valueAST: Value) => TInternal; + parseLiteral?: (valueNode: ValueNode) => TInternal; } /** @@ -1189,60 +1230,62 @@ declare module "graphql/type/definition" { class GraphQLObjectType { name: string; description: string; - isTypeOf: GraphQLIsTypeOfFn; + isTypeOf: GraphQLIsTypeOfFn; - constructor(config: GraphQLObjectTypeConfig); - getFields(): GraphQLFieldDefinitionMap; + constructor(config: GraphQLObjectTypeConfig); + getFields(): GraphQLFieldMap; getInterfaces(): Array; toString(): string; } // - export interface GraphQLObjectTypeConfig { + export interface GraphQLObjectTypeConfig { name: string; interfaces?: Thunk>; - fields: Thunk>; - isTypeOf?: GraphQLIsTypeOfFn; + fields: Thunk>; + isTypeOf?: GraphQLIsTypeOfFn; description?: string } - export type GraphQLTypeResolveFn = ( - value: any, - context: any, + export type GraphQLTypeResolver = ( + value: TSource, + context: TContext, info: GraphQLResolveInfo ) => GraphQLObjectType; - export type GraphQLIsTypeOfFn = ( - source: any, - context: any, + export type GraphQLIsTypeOfFn = ( + source: TSource, + context: TContext, info: GraphQLResolveInfo ) => boolean; - export type GraphQLFieldResolveFn = ( + export type GraphQLFieldResolver = ( source: TSource, args: { [argName: string]: any }, - context: any, + context: TContext, info: GraphQLResolveInfo ) => any; export interface GraphQLResolveInfo { fieldName: string; - fieldASTs: Array; + fieldNodes: Array; returnType: GraphQLOutputType; parentType: GraphQLCompositeType; - path: Array; + path: ResponsePath; schema: GraphQLSchema; - fragments: { [fragmentName: string]: FragmentDefinition }; + fragments: { [fragmentName: string]: FragmentDefinitionNode }; rootValue: any; - operation: OperationDefinition; + operation: OperationDefinitionNode; variableValues: { [variableName: string]: any }; } - export interface GraphQLFieldConfig { + export type ResponsePath = { prev: ResponsePath, key: string | number } | void; + + export interface GraphQLFieldConfig { type: GraphQLOutputType; args?: GraphQLFieldConfigArgumentMap; - resolve?: GraphQLFieldResolveFn; + resolve?: GraphQLFieldResolver; deprecationReason?: string; description?: string; } @@ -1257,18 +1300,18 @@ declare module "graphql/type/definition" { description?: string; } - export interface GraphQLFieldConfigMap { - [fieldName: string]: GraphQLFieldConfig; + export interface GraphQLFieldConfigMap { + [fieldName: string]: GraphQLFieldConfig; } - export interface GraphQLFieldDefinition { + export interface GraphQLField { name: string; description: string; type: GraphQLOutputType; args: Array; - resolve: GraphQLFieldResolveFn; - isDeprecated: boolean; - deprecationReason: string; + resolve?: GraphQLFieldResolver; + isDeprecated?: boolean; + deprecationReason?: string; } export interface GraphQLArgument { @@ -1278,8 +1321,8 @@ declare module "graphql/type/definition" { description?: string; } - export interface GraphQLFieldDefinitionMap { - [fieldName: string]: GraphQLFieldDefinition; + export interface GraphQLFieldMap { + [fieldName: string]: GraphQLField; } /** @@ -1303,24 +1346,24 @@ declare module "graphql/type/definition" { class GraphQLInterfaceType { name: string; description: string; - resolveType: GraphQLTypeResolveFn; + resolveType: GraphQLTypeResolver; - constructor(config: GraphQLInterfaceTypeConfig); + constructor(config: GraphQLInterfaceTypeConfig); - getFields(): GraphQLFieldDefinitionMap; + getFields(): GraphQLFieldMap; toString(): string; } - export interface GraphQLInterfaceTypeConfig { + export interface GraphQLInterfaceTypeConfig { name: string, - fields: Thunk>, + fields: Thunk>, /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing * Object type. */ - resolveType?: GraphQLTypeResolveFn, + resolveType?: GraphQLTypeResolver, description?: string } @@ -1350,16 +1393,16 @@ declare module "graphql/type/definition" { class GraphQLUnionType { name: string; description: string; - resolveType: GraphQLTypeResolveFn; + resolveType: GraphQLTypeResolver; - constructor(config: GraphQLUnionTypeConfig); + constructor(config: GraphQLUnionTypeConfig); getTypes(): Array; toString(): string; } - export interface GraphQLUnionTypeConfig { + export interface GraphQLUnionTypeConfig { name: string, types: Thunk>, /** @@ -1367,7 +1410,7 @@ declare module "graphql/type/definition" { * the default implementation will call `isTypeOf` on each implementing * Object type. */ - resolveType?: GraphQLTypeResolveFn; + resolveType?: GraphQLTypeResolver; description?: string; } @@ -1397,10 +1440,10 @@ declare module "graphql/type/definition" { description: string; constructor(config: GraphQLEnumTypeConfig); - getValues(): Array; + getValues(): Array; serialize(value: any): string; parseValue(value: any): any; - parseLiteral(valueAST: Value): any; + parseLiteral(valueNode: ValueNode): any; toString(): string; } @@ -1420,7 +1463,7 @@ declare module "graphql/type/definition" { description?: string; } - export interface GraphQLEnumValueDefinition { + export interface GraphQLEnumValue { name: string; description: string; deprecationReason: string; @@ -1451,7 +1494,7 @@ declare module "graphql/type/definition" { name: string; description: string; constructor(config: GraphQLInputObjectTypeConfig); - getFields(): GraphQLInputFieldDefinitionMap; + getFields(): GraphQLInputFieldMap; toString(): string; } @@ -1471,15 +1514,15 @@ declare module "graphql/type/definition" { [fieldName: string]: GraphQLInputFieldConfig; } - export interface GraphQLInputFieldDefinition { + export interface GraphQLInputField { name: string; type: GraphQLInputType; defaultValue?: any; description?: string; } - export interface GraphQLInputFieldDefinitionMap { - [fieldName: string]: GraphQLInputFieldDefinition; + export interface GraphQLInputFieldMap { + [fieldName: string]: GraphQLInputField; } /** @@ -1623,7 +1666,7 @@ declare module "graphql/type/introspection" { GraphQLList, GraphQLNonNull, } from 'graphql/type/definition'; - import { GraphQLFieldDefinition } from 'graphql/type/definition'; + import { GraphQLField } from 'graphql/type/definition'; const __Schema: GraphQLObjectType; const __Directive: GraphQLObjectType; @@ -1647,12 +1690,12 @@ declare module "graphql/type/introspection" { const __TypeKind: GraphQLEnumType; /** - * Note that these are GraphQLFieldDefinition and not GraphQLFieldConfig, + * Note that these are GraphQLField and not GraphQLFieldConfig, * so the format for args is different. */ - const SchemaMetaFieldDef: GraphQLFieldDefinition; - const TypeMetaFieldDef: GraphQLFieldDefinition; - const TypeNameMetaFieldDef: GraphQLFieldDefinition; + const SchemaMetaFieldDef: GraphQLField; + const TypeMetaFieldDef: GraphQLField; + const TypeNameMetaFieldDef: GraphQLField; } declare module "graphql/type/scalars" { @@ -1748,7 +1791,7 @@ declare module "graphql/validation" { } declare module "graphql/validation/index" { - export { validate } from 'graphql/validation/validate'; + export { validate, ValidationContext } from 'graphql/validation/validate'; export { specifiedRules } from 'graphql/validation/specifiedRules'; } @@ -1765,19 +1808,19 @@ declare module "graphql/validation/specifiedRules" { declare module "graphql/validation/validate" { import { GraphQLError } from 'graphql/error'; import { - Document, - OperationDefinition, - Variable, - SelectionSet, - FragmentSpread, - FragmentDefinition, + DocumentNode, + OperationDefinitionNode, + VariableNode, + SelectionSetNode, + FragmentSpreadNode, + FragmentDefinitionNode, } from 'graphql/language/ast'; import { GraphQLSchema } from 'graphql/type/schema'; import { GraphQLInputType, GraphQLOutputType, GraphQLCompositeType, - GraphQLFieldDefinition, + GraphQLField, GraphQLArgument } from 'graphql/type/definition'; import { GraphQLDirective } from 'graphql/type/directives'; @@ -1801,7 +1844,7 @@ declare module "graphql/validation/validate" { */ function validate( schema: GraphQLSchema, - ast: Document, + ast: DocumentNode, rules?: Array ): Array; @@ -1814,13 +1857,13 @@ declare module "graphql/validation/validate" { function visitUsingRules( schema: GraphQLSchema, typeInfo: TypeInfo, - documentAST: Document, + documentAST: DocumentNode, rules: Array ): Array; - type HasSelectionSet = OperationDefinition | FragmentDefinition; + type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; interface VariableUsage { - node: Variable, + node: VariableNode, type: GraphQLInputType } @@ -1830,27 +1873,27 @@ declare module "graphql/validation/validate" { * validation rule. */ export class ValidationContext { - constructor(schema: GraphQLSchema, ast: Document, typeInfo: TypeInfo); + constructor(schema: GraphQLSchema, ast: DocumentNode, typeInfo: TypeInfo); reportError(error: GraphQLError): void; getErrors(): Array; getSchema(): GraphQLSchema; - getDocument(): Document; + getDocument(): DocumentNode; - getFragment(name: string): FragmentDefinition; + getFragment(name: string): FragmentDefinitionNode; - getFragmentSpreads(node: SelectionSet): Array; + getFragmentSpreads(node: SelectionSetNode): Array; getRecursivelyReferencedFragments( - operation: OperationDefinition - ): Array; + operation: OperationDefinitionNode + ): Array; - getVariableUsages(node: HasSelectionSet): Array; + getVariableUsages(node: NodeWithSelectionSet): Array; getRecursiveVariableUsages( - operation: OperationDefinition + operation: OperationDefinitionNode ): Array; getType(): GraphQLOutputType; @@ -1859,7 +1902,7 @@ declare module "graphql/validation/validate" { getInputType(): GraphQLInputType; - getFieldDef(): GraphQLFieldDefinition; + getFieldDef(): GraphQLField; getDirective(): GraphQLDirective; @@ -1877,20 +1920,21 @@ declare module "graphql/execution" { } declare module "graphql/execution/index" { - export { execute } from 'graphql/execution/execute'; + export { execute, defaultFieldResolver, responsePathAsArray, ExecutionResult } from 'graphql/execution/execute'; } declare module "graphql/execution/execute" { import { GraphQLError, locatedError } from 'graphql/error'; import { GraphQLSchema } from 'graphql/type/schema'; + import { GraphQLField, GraphQLFieldResolver, ResponsePath } from 'graphql/type/definition'; import { - Directive, - Document, - OperationDefinition, - SelectionSet, - Field, - InlineFragment, - FragmentDefinition + DirectiveNode, + DocumentNode, + OperationDefinitionNode, + SelectionSetNode, + FieldNode, + InlineFragmentNode, + FragmentDefinitionNode, } from 'graphql/language/ast'; /** * Data that must be available at all points during query execution. @@ -1900,9 +1944,9 @@ declare module "graphql/execution/execute" { */ interface ExecutionContext { schema: GraphQLSchema; - fragments: { [key: string]: FragmentDefinition }; + fragments: { [key: string]: FragmentDefinitionNode }; rootValue: any; - operation: OperationDefinition; + operation: OperationDefinitionNode; variableValues: { [key: string]: any }; errors: Array; } @@ -1912,8 +1956,8 @@ declare module "graphql/execution/execute" { * query, `errors` is null if no errors occurred, and is a * non-empty array if an error occurred. */ - interface ExecutionResult { - data: Object; + export interface ExecutionResult { + data?: {[key: string]: any}; errors?: Array; } @@ -1927,20 +1971,39 @@ declare module "graphql/execution/execute" { */ function execute( schema: GraphQLSchema, - documentAST: Document, + document: DocumentNode, rootValue?: any, contextValue?: any, variableValues?: { [key: string]: any }, operationName?: string - ): Promise + ): Promise; + + /** + * Given a ResponsePath (found in the `path` entry in the information provided + * as the last argument to a field resolver), return an Array of the path keys. + */ + export function responsePathAsArray( + path: ResponsePath + ): Array; + + function addPath(prev: ResponsePath, key: string | number): any; + + /** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context. + */ + export const defaultFieldResolver: GraphQLFieldResolver; } declare module "graphql/execution/values" { - import { GraphQLInputType, GraphQLArgument } from 'graphql/type/definition'; + import { GraphQLInputType, GraphQLField, GraphQLArgument } from 'graphql/type/definition'; + import { GraphQLDirective } from 'graphql/type/directives'; import { GraphQLSchema } from 'graphql/type/schema'; - import { Argument, VariableDefinition } from 'graphql/language/ast'; + import { FieldNode, DirectiveNode, VariableDefinitionNode } from 'graphql/language/ast'; /** * Prepares an object map of variableValues of the correct type based on the * provided variable definitions and arbitrary input. If the input cannot be @@ -1948,7 +2011,7 @@ declare module "graphql/execution/values" { */ function getVariableValues( schema: GraphQLSchema, - definitionASTs: Array, + varDefNodes: Array, inputs: { [key: string]: any } ): { [key: string]: any } @@ -1957,8 +2020,8 @@ declare module "graphql/execution/values" { * definitions and list of argument AST nodes. */ function getArgumentValues( - argDefs: Array, - argASTs: Array, + def: GraphQLField | GraphQLDirective, + node: FieldNode | DirectiveNode, variableValues?: { [key: string]: any } ): { [key: string]: any }; } @@ -1974,7 +2037,7 @@ declare module "graphql/error/index" { export { GraphQLError } from 'graphql/error/GraphQLError'; export { syntaxError } from 'graphql/error/syntaxError'; export { locatedError } from 'graphql/error/locatedError'; - export { formatError } from 'graphql/error/formatError'; + export { formatError, GraphQLFormattedError, GraphQLErrorLocation } from 'graphql/error/formatError'; } declare module "graphql/error/formatError" { @@ -1988,7 +2051,8 @@ declare module "graphql/error/formatError" { type GraphQLFormattedError = { message: string, - locations: Array + locations: Array, + path: Array }; type GraphQLErrorLocation = { @@ -1999,7 +2063,7 @@ declare module "graphql/error/formatError" { declare module "graphql/error/GraphQLError" { import { getLocation } from 'graphql/language'; - import { Node } from 'graphql/language/ast'; + import { ASTNode } from 'graphql/language/ast'; import { Source } from 'graphql/language/source'; /** @@ -2027,7 +2091,7 @@ declare module "graphql/error/GraphQLError" { * * Enumerable, and appears in the result of JSON.stringify(). */ - locations: Array<{ line: number, column: number }> | void; + locations?: Array<{ line: number, column: number }> | void; /** * An array describing the JSON-path into the execution response which @@ -2035,28 +2099,37 @@ declare module "graphql/error/GraphQLError" { * * Enumerable, and appears in the result of JSON.stringify(). */ - path: Array | void; + path?: Array | void; /** * An array of GraphQL AST Nodes corresponding to this error. */ - nodes: Array | void; + nodes?: Array | void; /** * The source GraphQL document corresponding to this error. */ - source: Source | void; + source?: Source | void; /** * An array of character offsets within the source GraphQL document * which correspond to this error. */ - positions: Array | void; + positions?: Array | void; /** * The original error thrown from a field resolver during execution. */ - originalError: Error; + originalError?: Error; + + constructor( + message: string, + nodes?: Array, + source?: Source, + positions?: Array, + path?: Array, + originalError?: Error, + ); } } @@ -2100,6 +2173,25 @@ declare module "graphql/utilities" { declare module "graphql/utilities/index" { // The GraphQL query recommended for a full schema introspection. export { introspectionQuery } from 'graphql/utilities/introspectionQuery'; + export { + IntrospectionQuery, + IntrospectionSchema, + IntrospectionType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionNamedTypeRef, + IntrospectionListTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionField, + IntrospectionInputValue, + IntrospectionEnumValue, + IntrospectionDirective, + } from 'graphql/utilities/introspectionQuery'; // Gets the target Operation from a Document export { getOperationAST } from 'graphql/utilities/getOperationAST'; @@ -2114,7 +2206,7 @@ declare module "graphql/utilities/index" { export { extendSchema } from 'graphql/utilities/extendSchema'; // Print a GraphQLSchema to GraphQL Schema language. - export { printSchema, printIntrospectionSchema } from 'graphql/utilities/schemaPrinter'; + export { printSchema, printType, printIntrospectionSchema } from 'graphql/utilities/schemaPrinter'; // Create a GraphQLType from a GraphQL language AST. export { typeFromAST } from 'graphql/utilities/typeFromAST'; @@ -2150,6 +2242,10 @@ declare module "graphql/utilities/index" { // Asserts that a string is a valid GraphQL name export { assertValidName } from 'graphql/utilities/assertValidName'; + + // Compares two GraphQLSchemas and detects breaking changes. + export { findBreakingChanges } from 'graphql/utilities/findBreakingChanges'; + export { BreakingChange } from 'graphql/utilities/findBreakingChanges'; } declare module "graphql/utilities/assertValidName" { @@ -2159,14 +2255,14 @@ declare module "graphql/utilities/assertValidName" { declare module "graphql/utilities/astFromValue" { import { - Value, - //IntValue, - //FloatValue, - //StringValue, - //BooleanValue, - //EnumValue, - //ListValue, - //ObjectValue, + ValueNode, + //IntValueNode, + //FloatValueNode, + //StringValueNode, + //BooleanValueNode, + //EnumValueNode, + //ListValueNode, + //ObjectValueNode, } from 'graphql/language/ast'; import { GraphQLInputType } from 'graphql/type/definition'; @@ -2190,11 +2286,11 @@ declare module "graphql/utilities/astFromValue" { export function astFromValue( value: any, type: GraphQLInputType - ): Value // Warning: there is a code in bottom: throw new TypeError + ): ValueNode // Warning: there is a code in bottom: throw new TypeError } declare module "graphql/utilities/buildASTSchema" { - import { Document, Location } from 'graphql/language/ast'; + import { DocumentNode, Location } from 'graphql/language/ast'; import { Source } from 'graphql/language/source'; import { GraphQLSchema } from 'graphql/type/schema'; @@ -2208,7 +2304,7 @@ declare module "graphql/utilities/buildASTSchema" { * Given that AST it constructs a GraphQLSchema. The resulting schema * has no resolve methods, so execution will use default resolvers. */ - function buildASTSchema(ast: Document): GraphQLSchema; + function buildASTSchema(ast: DocumentNode): GraphQLSchema; /** * Given an ast node, returns its string description based on a contiguous @@ -2253,17 +2349,17 @@ declare module "graphql/utilities/buildClientSchema" { } declare module "graphql/utilities/concatAST" { - import { Document } from 'graphql/language/ast'; + import { DocumentNode } from 'graphql/language/ast'; /** * Provided a collection of ASTs, presumably each from different files, * concatenate the ASTs together into batched AST, useful for validating many * GraphQL source files which together represent one conceptual application. */ - function concatAST(asts: Array): Document; + function concatAST(asts: Array): DocumentNode; } declare module "graphql/utilities/extendSchema" { - import { Document } from 'graphql/language/ast'; + import { DocumentNode } from 'graphql/language/ast'; import { GraphQLSchema } from 'graphql/type/schema'; /** @@ -2280,12 +2376,102 @@ declare module "graphql/utilities/extendSchema" { */ function extendSchema( schema: GraphQLSchema, - documentAST: Document + documentAST: DocumentNode ): GraphQLSchema; } +declare module "graphql/utilities/findBreakingChanges" { + import { + getNamedType, + GraphQLScalarType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLInterfaceType, + GraphQLObjectType, + GraphQLUnionType, + GraphQLNamedType, + } from 'graphql/type/definition'; + import { GraphQLSchema } from 'graphql/type/schema'; + + export const BreakingChangeType: { + FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND', + FIELD_REMOVED: 'FIELD_REMOVED', + TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND', + TYPE_REMOVED: 'TYPE_REMOVED', + TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION', + VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM', + }; + + type BreakingChangeKey = 'FIELD_CHANGED_KIND' + | 'FIELD_REMOVED' + | 'TYPE_CHANGED_KIND' + | 'TYPE_REMOVED' + | 'TYPE_REMOVED_FROM_UNION' + | 'VALUE_REMOVED_FROM_ENUM'; + + export type BreakingChange = { + type: BreakingChangeKey; + description: string; + }; + + /** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + */ + export function findBreakingChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing an entire type. + */ + export function findRemovedTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to changing the type of a type. + */ + export function findTypesThatChangedKind( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to the fields on a type. This includes if + * a field has been removed from a type or if a field has changed type. + */ + export function findFieldsThatChangedType( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array; + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing types from a union type. + */ + export function findTypesRemovedFromUnions( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array; + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing values from an enum type. + */ + export function findValuesRemovedFromEnums( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array; +} + declare module "graphql/utilities/getOperationAST" { - import { Document, OperationDefinition } from 'graphql/language/ast'; + import { DocumentNode, OperationDefinitionNode } from 'graphql/language/ast'; /** * Returns an operation AST given a document AST and optionally an operation @@ -2293,9 +2479,9 @@ declare module "graphql/utilities/getOperationAST" { * provided in the document. */ export function getOperationAST( - documentAST: Document, + documentAST: DocumentNode, operationName: string - ): OperationDefinition; + ): OperationDefinitionNode; } declare module "graphql/utilities/introspectionQuery" { @@ -2526,7 +2712,7 @@ declare module "graphql/utilities/isValidJSValue" { } declare module "graphql/utilities/isValidLiteralValue" { - import { Value } from 'graphql/language/ast'; + import { ValueNode } from 'graphql/language/ast'; import { GraphQLInputType } from 'graphql/type/definition'; /** @@ -2538,27 +2724,30 @@ declare module "graphql/utilities/isValidLiteralValue" { */ function isValidLiteralValue( type: GraphQLInputType, - valueAST: Value + valueNode: ValueNode ): Array } declare module "graphql/utilities/schemaPrinter" { import { GraphQLSchema } from 'graphql/type/schema'; + import { GraphQLType } from 'graphql/type/definition'; function printSchema(schema: GraphQLSchema): string; function printIntrospectionSchema(schema: GraphQLSchema): string; + + function printType(type: GraphQLType): string } declare module "graphql/utilities/separateOperations" { import { - Document, - OperationDefinition, + DocumentNode, + OperationDefinitionNode, } from 'graphql/language/ast'; function separateOperations( - documentAST: Document - ): { [operationName: string]: Document } + documentAST: DocumentNode + ): { [operationName: string]: DocumentNode } } declare module "graphql/utilities/typeComparators" { @@ -2603,31 +2792,73 @@ declare module "graphql/utilities/typeComparators" { } declare module "graphql/utilities/typeFromAST" { - import { Type } from 'graphql/language/ast'; + import { TypeNode } from 'graphql/language/ast'; import { GraphQLType, GraphQLNullableType } from 'graphql/type/definition'; import { GraphQLSchema } from 'graphql/type/schema'; function typeFromAST( schema: GraphQLSchema, - inputTypeAST: Type + typeNode: TypeNode ): GraphQLType } declare module "graphql/utilities/TypeInfo" { - class TypeInfo { } + import { GraphQLSchema } from 'graphql/type/schema'; + import { + GraphQLOutputType, + GraphQLCompositeType, + GraphQLInputType, + GraphQLField, + GraphQLArgument, + GraphQLType, + } from 'graphql/type/definition'; + import { GraphQLDirective } from 'graphql/type/directives'; + import { ASTNode, FieldNode } from 'graphql/language/ast'; + + /** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ + class TypeInfo { + constructor( + schema: GraphQLSchema, + // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant codebases. You should never need to use it. + // It may disappear in the future. + getFieldDefFn: getFieldDef + ); + + getType(): GraphQLOutputType; + getParentType(): GraphQLCompositeType; + getInputType(): GraphQLInputType; + getFieldDef(): GraphQLField; + getDirective(): GraphQLDirective; + getArgument(): GraphQLArgument; + enter(node: ASTNode): any; + leave(node: ASTNode): any; + } + + export interface getFieldDef { + ( + schema: GraphQLSchema, + parentType: GraphQLType, + fieldNode: FieldNode + ): GraphQLField + } } declare module "graphql/utilities/valueFromAST" { import { GraphQLInputType } from 'graphql/type/definition'; import { - Value, - Variable, - ListValue, - ObjectValue + ValueNode, + VariableNode, + ListValueNode, + ObjectValueNode } from 'graphql/language/ast'; function valueFromAST( - valueAST: Value, + valueNode: ValueNode, type: GraphQLInputType, variables?: { [key: string]: any diff --git a/greensock/index.d.ts b/greensock/index.d.ts index 95c2ad6a4c..881fb1cd92 100644 --- a/greensock/index.d.ts +++ b/greensock/index.d.ts @@ -161,7 +161,7 @@ declare class TimelineLite extends SimpleTimeline { static exportRoot(vars?: Object, omitDelayedCalls?: boolean): TimelineLite; from(target: Object, duration: number, vars: Object, position?: any): TimelineLite; fromTo(target: Object, duration: number, fromVars: Object, toVars: Object, position?: any): TimelineLite; - getChildren(nested?: boolean, tweens?: boolean, timelines?: boolean, ignoreBeforeTime?: number): Tween | Timeline[]; + getChildren(nested?: boolean, tweens?: boolean, timelines?: boolean, ignoreBeforeTime?: number): (Tween | Timeline)[]; getLabelTime(label: string): number; getTweensOf(target: Object, nested?: boolean): Tween[]; recent(): Animation; diff --git a/gulp-angular-templatecache/gulp-angular-templatecache.d.ts b/gulp-angular-templatecache/index.d.ts similarity index 100% rename from gulp-angular-templatecache/gulp-angular-templatecache.d.ts rename to gulp-angular-templatecache/index.d.ts diff --git a/gulp-angular-templatecache/tsconfig.json b/gulp-angular-templatecache/tsconfig.json index 6b3a7a2fa2..4a33a52943 100644 --- a/gulp-angular-templatecache/tsconfig.json +++ b/gulp-angular-templatecache/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "gulp-angular-templatecache.d.ts", + "index.d.ts", "gulp-angular-templatecache-tests.ts" ] } \ No newline at end of file diff --git a/gulp-help-doc/gulp-help-doc.d.ts b/gulp-help-doc/index.d.ts similarity index 100% rename from gulp-help-doc/gulp-help-doc.d.ts rename to gulp-help-doc/index.d.ts diff --git a/gulp-help-doc/tsconfig.json b/gulp-help-doc/tsconfig.json index f7206b7785..ba2c2857a0 100644 --- a/gulp-help-doc/tsconfig.json +++ b/gulp-help-doc/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "gulp-help-doc.d.ts", + "index.d.ts", "gulp-help-doc-tests.ts" ] } \ No newline at end of file diff --git a/gulp-insert/gulp-insert.d.ts b/gulp-insert/index.d.ts similarity index 100% rename from gulp-insert/gulp-insert.d.ts rename to gulp-insert/index.d.ts diff --git a/gulp-insert/tsconfig.json b/gulp-insert/tsconfig.json index 109f4aaa90..6de90874d4 100644 --- a/gulp-insert/tsconfig.json +++ b/gulp-insert/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "gulp-insert.d.ts", + "index.d.ts", "gulp-insert-tests.ts" ] } \ No newline at end of file diff --git a/halogen/halogen-clip-loader-tests.tsx b/halogen/halogen-clip-loader-tests.tsx new file mode 100644 index 0000000000..884e1caec6 --- /dev/null +++ b/halogen/halogen-clip-loader-tests.tsx @@ -0,0 +1,18 @@ +import * as React from "react"; +import * as Halogen from "halogen"; + +class HalogenTests_ClipLoader_withNoProps extends React.Component, {}>{ + render() { + return ( + + ) + } +} + +class HalogenTests_ClipLoader_withAllProps extends React.Component, {}>{ + render() { + return ( + + ) + } +} diff --git a/halogen/halogen-fade-loader-tests.tsx b/halogen/halogen-fade-loader-tests.tsx new file mode 100644 index 0000000000..63781098eb --- /dev/null +++ b/halogen/halogen-fade-loader-tests.tsx @@ -0,0 +1,19 @@ +import * as React from "react"; +import * as Halogen from "halogen"; + +class HalogenTests_FadeLoader_withNoProps extends React.Component, {}>{ + render() { + return ( + + ) + } +} + +class HalogenTests_FadeLoader_withAllProps extends React.Component, {}>{ + render() { + return ( + + ) + } +} diff --git a/halogen/halogen-pacman-loader-tests.tsx b/halogen/halogen-pacman-loader-tests.tsx new file mode 100644 index 0000000000..7ccd294918 --- /dev/null +++ b/halogen/halogen-pacman-loader-tests.tsx @@ -0,0 +1,18 @@ +import * as React from "react"; +import * as Halogen from "halogen"; + +class HalogenTests_PacmanLoader_withNoProps extends React.Component, {}>{ + render() { + return ( + + ) + } +} + +class HalogenTests_PacmanLoader_withAllProps extends React.Component, {}>{ + render() { + return ( + + ) + } +} diff --git a/halogen/halogen-rotate-loader-tests.tsx b/halogen/halogen-rotate-loader-tests.tsx new file mode 100644 index 0000000000..82b4b2b380 --- /dev/null +++ b/halogen/halogen-rotate-loader-tests.tsx @@ -0,0 +1,18 @@ +import * as React from "react"; +import * as Halogen from "halogen"; + +class HalogenTests_RotateLoader_withNoProps extends React.Component, {}>{ + render() { + return ( + + ) + } +} + +class HalogenTests_RotateLoader_withAllProps extends React.Component, {}>{ + render() { + return ( + + ) + } +} diff --git a/halogen/index.d.ts b/halogen/index.d.ts new file mode 100644 index 0000000000..909812ff4b --- /dev/null +++ b/halogen/index.d.ts @@ -0,0 +1,88 @@ +// Type definitions for halogen +// Project: https://github.com/yuanyan/halogen +// Definitions by: Vincent Rouffiat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as react from "react"; + +export = Halogen; + +declare namespace Halogen { + + type VerticalAlign = "baseline" | "length" | "sub" | "super" | "top" | "text-top" | "middle" | "bottom" | "text-bottom" | "initial" | "inherit"; + + interface HalogenCommonProps { + loading?: boolean; + color?: string; + id?: string; + className?: string; + verticalAlign?: VerticalAlign; + } + + interface SizeLoaderProps extends HalogenCommonProps { + size?: string; + } + + interface MarginLoaderProps extends HalogenCommonProps { + margin?: T; + size?: T; + } + + interface RadiusLoaderProps extends MarginLoaderProps { + height?: string; + width?: string; + radius?: string; + } + + /** + * React components + */ + type PulseLoader = react.Component, {}>; + export const PulseLoader: react.ComponentClass>; + + type RotateLoader = react.Component, {}>; + export const RotateLoader: react.ComponentClass>; + + type BeatLoader = react.Component, {}>; + export const BeatLoader: react.ComponentClass>; + + type RiseLoader = react.Component, {}>; + export const RiseLoader: react.ComponentClass>; + + type SyncLoader = react.Component, {}>; + export const SyncLoader: react.ComponentClass>; + + type GridLoader = react.Component, {}>; + export const GridLoader: react.ComponentClass>; + + type ClipLoader = react.Component; + export const ClipLoader: react.ComponentClass; + + type SquareLoader = react.Component; + export const SquareLoader: react.ComponentClass; + + type DotLoader = react.Component; + export const DotLoader: react.ComponentClass; + + type PacmanLoader = react.Component, {}>; + export const PacmanLoader: react.ComponentClass>; + + type MoonLoader = react.Component; + export const MoonLoader: react.ComponentClass; + + type RingLoader = react.Component; + export const RingLoader: react.ComponentClass; + + type BounceLoader = react.Component; + export const BounceLoader: react.ComponentClass; + + type SkewLoader = react.Component; + export const SkewLoader: react.ComponentClass; + + type FadeLoader = react.Component; + export const FadeLoader: react.ComponentClass; + + type ScaleLoader = react.Component; + export const ScaleLoader: react.ComponentClass; + +} diff --git a/typescript/tsconfig.json b/halogen/tsconfig.json similarity index 62% rename from typescript/tsconfig.json rename to halogen/tsconfig.json index 79b9eb6b27..9765d85cfc 100644 --- a/typescript/tsconfig.json +++ b/halogen/tsconfig.json @@ -3,16 +3,20 @@ "module": "commonjs", "target": "es6", "noImplicitAny": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "jsx": "react" }, "files": [ "index.d.ts" + ], + "include": [ + "halogen-*-loader-tests.tsx" ] } \ No newline at end of file diff --git a/halogen/tslint.json b/halogen/tslint.json new file mode 100644 index 0000000000..fdc7cdc370 --- /dev/null +++ b/halogen/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} \ No newline at end of file diff --git a/handsontable/handsontable-tests.ts b/handsontable/handsontable-tests.ts index d062f9c629..6d55abd960 100644 --- a/handsontable/handsontable-tests.ts +++ b/handsontable/handsontable-tests.ts @@ -267,6 +267,7 @@ function test_HandsontableMethods() { hot.loadData([]); hot.populateFromArray(123, 123, [], 123, 123, 'foo', 'foo', 'foo', []); hot.propToCol('foo'); + hot.propToCol(123); hot.removeCellMeta(123, 123, 'foo'); hot.removeHook('foo', function() {}); hot.render(); diff --git a/handsontable/index.d.ts b/handsontable/index.d.ts index 7a82509baa..363fa3124d 100644 --- a/handsontable/index.d.ts +++ b/handsontable/index.d.ts @@ -266,7 +266,7 @@ declare namespace ht { listen(): void; loadData(data: any[]): void; populateFromArray(row: number, col: number, input: any[], endRow?: number, endCol?: number, source?: string, method?: string, direction?: string, deltas?: any[]): any; - propToCol(prop: string): number; + propToCol(prop: string | number): number; removeCellMeta(row: number, col: number, key: string): void; removeHook(key: string, callback: Function): void; render(): void; @@ -290,3 +290,9 @@ declare namespace ht { declare var Handsontable: { new (element: Element, options: ht.Options): ht.Methods; }; + +declare module "handsontable" { + export var Handsontable: { + new (element: Element, options: ht.Options): ht.Methods; + }; +} diff --git a/hapi-decorators/hapi-decorators-tests.ts b/hapi-decorators/hapi-decorators-tests.ts index 57d0c1a232..2a05f67e4d 100644 --- a/hapi-decorators/hapi-decorators-tests.ts +++ b/hapi-decorators/hapi-decorators-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as hapi from 'hapi'; import { controller, get, post, put, cache, config, route, validate, Controller } from 'hapi-decorators'; diff --git a/hapi-decorators/tsconfig.json b/hapi-decorators/tsconfig.json index a763c6c6cd..3c7877c976 100644 --- a/hapi-decorators/tsconfig.json +++ b/hapi-decorators/tsconfig.json @@ -17,4 +17,4 @@ "index.d.ts", "hapi-decorators-tests.ts" ] -} \ No newline at end of file +} diff --git a/hapi/hapi-8.2.0.d.ts b/hapi/hapi-8.2.0.d.ts index d3f51873d9..9a9355412d 100644 --- a/hapi/hapi-8.2.0.d.ts +++ b/hapi/hapi-8.2.0.d.ts @@ -304,9 +304,9 @@ export interface ISessionHandler { export interface IStrictSessionHandler { (request: Request, reply: IStrictReply): void; -} + } -export interface IRequestHandler { + export interface IRequestHandler { (request: Request): T; } diff --git a/hapi/hapi-tests.ts b/hapi/hapi-tests.ts index 2ee355e9d1..97c4a77b44 100644 --- a/hapi/hapi-tests.ts +++ b/hapi/hapi-tests.ts @@ -116,8 +116,8 @@ server.route([{ server.route({ method: 'GET', path: '/hello6', - handler: function (request, reply) { - request.log('info', { route: '/hello' }, Date.now()); + handler: function (request: Hapi.Request, reply: Hapi.IReply) { + request.log('info', { route: '/hello' }, Date.now()); reply('hello world'); } }); diff --git a/hellosign-embedded/index.d.ts b/hellosign-embedded/index.d.ts index 45b70774ff..c1b0a7fd02 100644 --- a/hellosign-embedded/index.d.ts +++ b/hellosign-embedded/index.d.ts @@ -3,10 +3,66 @@ // Definitions by: Brian Surowiec // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module HelloSign { - interface MessageEvent { - event: string; + interface SignedMessageEvent { + event: 'signature_request_signed'; + signature_id: string; } + interface DeclinedMessageEvent { + event: 'signature_request_declined'; + signature_id: string; + } + + interface CanceledMessageEvent { + event: 'signature_request_canceled'; + } + + interface SentMessageEvent { + event: 'signature_request_sent'; + signature_request_id: string; + signature_request_info: { + title: string; + message: string; + signatures: Array<{ + signature_id: string; + signer_email_address: string; + signer_name: string; + order: number; + status_code: string; + signed_at: number; + last_viewed_at: number; + last_reminded_at: number; + has_pin: boolean; + }>; + cc_email_addresses: Array; + }; + } + + interface TemplateCreatedMessageEvent { + event: 'template_created'; + template_id: string; + template_info: { + title: string; + message: string; + signer_roles: Array<{ + name: string; + order: number; + }>; + cc_roles: Array<{ + name: string; + }>; + }; + } + + interface ErrorMessageEvent { + event: 'error'; + description: string; + } + + type MessageEvent = SignedMessageEvent | DeclinedMessageEvent | + CanceledMessageEvent | SentMessageEvent | TemplateCreatedMessageEvent | + ErrorMessageEvent; + interface ClientCultures { /** * English (United States) @@ -169,6 +225,20 @@ declare module HelloSign { */ EVENT_CANCELED: string; + /** + * The user sent a signature request + * + * @default signature_request_sent + */ + EVENT_SENT: string; + + /** + * The template was created or edited + * + * @default template_created + */ + EVENT_TEMPLATE_CREATED: string; + /** * An error occurred in the iFrame * diff --git a/highcharts/highstock.d.ts b/highcharts/highstock.d.ts index f312286745..332ea3d5ca 100644 --- a/highcharts/highstock.d.ts +++ b/highcharts/highstock.d.ts @@ -28,10 +28,10 @@ declare namespace __Highstock { } interface RangeSelectorButton { - type: string; //Defines the timespan, can be one of 'millisecond', 'second', 'minute', 'day', 'week', 'month', 'ytd' (year to date), 'year' and 'all'. - count?: number; - text: string; - dataGrouping?: any; //not sure how this works + type: string; //Defines the timespan, can be one of 'millisecond', 'second', 'minute', 'day', 'week', 'month', 'ytd' (year to date), 'year' and 'all'. + count?: number; + text: string; + dataGrouping?: any; //not sure how this works } interface RangeSelectorOptions { @@ -59,24 +59,24 @@ declare namespace __Highstock { } interface ScrollbarOptions { - barBackgroundColor?: string; - barBorderColor?: string; - barBorderRadius?: number; - barBorderWidth?: number; - buttonArrowColor?: string; - buttonBackgroundColor?: string; - buttonBorderColor?: string; - buttonBorderRadius?: number; - buttonBorderWidth?: number; - enabled?: boolean; - height?: number; - liveRedraw?: boolean; - minWidth?: number; - rifleColor?: string; - trackBackgroundColor?: string; - trackBorderColor?: string; - trackBorderRadius?: number; - trackBorderWidth?: number; + barBackgroundColor?: string; + barBorderColor?: string; + barBorderRadius?: number; + barBorderWidth?: number; + buttonArrowColor?: string; + buttonBackgroundColor?: string; + buttonBorderColor?: string; + buttonBorderRadius?: number; + buttonBorderWidth?: number; + enabled?: boolean; + height?: number; + liveRedraw?: boolean; + minWidth?: number; + rifleColor?: string; + trackBackgroundColor?: string; + trackBorderColor?: string; + trackBorderRadius?: number; + trackBorderWidth?: number; } interface Options extends Highcharts.Options { @@ -119,3 +119,4 @@ interface JQuery { highcharts(type: string, options: Highcharts.Options): JQuery; highcharts(type: string, options: Highcharts.Options, callback: (chart: Highcharts.ChartObject) => void): JQuery; } + diff --git a/history/index.d.ts b/history/index.d.ts index b099b9beaa..6b61fa1b77 100644 --- a/history/index.d.ts +++ b/history/index.d.ts @@ -1,10 +1,8 @@ // Type definitions for history v2.0.0 -// Project: https://github.com/rackt/history +// Project: https://github.com/mjackson/history // Definitions by: Sergey Buturlakin , Nathan Brown // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// types based on https://github.com/rackt/history/blob/master/docs/Terms.md - export as namespace History; export type Action = string; diff --git a/html-pdf/html-pdf.d.ts b/html-pdf/index.d.ts similarity index 100% rename from html-pdf/html-pdf.d.ts rename to html-pdf/index.d.ts diff --git a/html-pdf/tsconfig.json b/html-pdf/tsconfig.json index b3b3941f12..7eafce4004 100644 --- a/html-pdf/tsconfig.json +++ b/html-pdf/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "html-pdf.d.ts", + "index.d.ts", "html-pdf-tests.ts" ] } \ No newline at end of file diff --git a/html-webpack-plugin/html-webpack-plugin-tests.ts b/html-webpack-plugin/html-webpack-plugin-tests.ts index 9aac8c9b98..9d4ec35e11 100644 --- a/html-webpack-plugin/html-webpack-plugin-tests.ts +++ b/html-webpack-plugin/html-webpack-plugin-tests.ts @@ -1,5 +1,3 @@ -/// - import {Configuration} from "webpack"; import HtmlWebpackPlugin = require("html-webpack-plugin"); diff --git a/html-webpack-plugin/html-webpack-plugin.d.ts b/html-webpack-plugin/index.d.ts similarity index 100% rename from html-webpack-plugin/html-webpack-plugin.d.ts rename to html-webpack-plugin/index.d.ts diff --git a/html-webpack-plugin/tsconfig.json b/html-webpack-plugin/tsconfig.json index ea542ae271..b19027e8f0 100644 --- a/html-webpack-plugin/tsconfig.json +++ b/html-webpack-plugin/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "html-webpack-plugin.d.ts", + "index.d.ts", "html-webpack-plugin-tests.ts" ] } \ No newline at end of file diff --git a/http-errors/index.d.ts b/http-errors/index.d.ts index 7766aa3508..883fbf0ac1 100644 --- a/http-errors/index.d.ts +++ b/http-errors/index.d.ts @@ -3,89 +3,90 @@ // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module 'http-errors' { + namespace createHttpError { -declare namespace createHttpError { + // See https://github.com/jshttp/http-errors/blob/1.3.1/index.js#L42 + interface HttpError extends Error { + status: number; + statusCode: number; + expose: boolean; + } - // See https://github.com/jshttp/http-errors/blob/1.3.1/index.js#L42 - interface HttpError extends Error { - status: number; - statusCode: number; - expose: boolean; + type HttpErrorConstructor = new(msg?: string) => HttpError; + + interface CreateHttpError { + // See https://github.com/Microsoft/TypeScript/issues/227#issuecomment-50092674 + [code: string]: new () => HttpError; + + (...args: Array): HttpError; + + Continue: HttpErrorConstructor; + SwitchingProtocols: HttpErrorConstructor; + Processing: HttpErrorConstructor; + OK: HttpErrorConstructor; + Created: HttpErrorConstructor; + Accepted: HttpErrorConstructor; + NonAuthoritativeInformation: HttpErrorConstructor; + NoContent: HttpErrorConstructor; + ResetContent: HttpErrorConstructor; + PartialContent: HttpErrorConstructor; + MultiStatus: HttpErrorConstructor; + AlreadyReported: HttpErrorConstructor; + IMUsed: HttpErrorConstructor; + MultipleChoices: HttpErrorConstructor; + MovedPermanently: HttpErrorConstructor; + Found: HttpErrorConstructor; + SeeOther: HttpErrorConstructor; + NotModified: HttpErrorConstructor; + UseProxy: HttpErrorConstructor; + Unused: HttpErrorConstructor; + TemporaryRedirect: HttpErrorConstructor; + PermanentRedirect: HttpErrorConstructor; + BadRequest: HttpErrorConstructor; + Unauthorized: HttpErrorConstructor; + PaymentRequired: HttpErrorConstructor; + Forbidden: HttpErrorConstructor; + NotFound: HttpErrorConstructor; + MethodNotAllowed: HttpErrorConstructor; + NotAcceptable: HttpErrorConstructor; + ProxyAuthenticationRequired: HttpErrorConstructor; + RequestTimeout: HttpErrorConstructor; + Conflict: HttpErrorConstructor; + Gone: HttpErrorConstructor; + LengthRequired: HttpErrorConstructor; + PreconditionFailed: HttpErrorConstructor; + PayloadTooLarge: HttpErrorConstructor; + URITooLong: HttpErrorConstructor; + UnsupportedMediaType: HttpErrorConstructor; + RangeNotSatisfiable: HttpErrorConstructor; + ExpectationFailed: HttpErrorConstructor; + ImATeapot: HttpErrorConstructor; + MisdirectedRequest: HttpErrorConstructor; + UnprocessableEntity: HttpErrorConstructor; + Locked: HttpErrorConstructor; + FailedDependency: HttpErrorConstructor; + UnorderedCollection: HttpErrorConstructor; + UpgradeRequired: HttpErrorConstructor; + PreconditionRequired: HttpErrorConstructor; + TooManyRequests: HttpErrorConstructor; + RequestHeaderFieldsTooLarge: HttpErrorConstructor; + UnavailableForLegalReasons: HttpErrorConstructor; + InternalServerError: HttpErrorConstructor; + NotImplemented: HttpErrorConstructor; + BadGateway: HttpErrorConstructor; + ServiceUnavailable: HttpErrorConstructor; + GatewayTimeout: HttpErrorConstructor; + HTTPVersionNotSupported: HttpErrorConstructor; + VariantAlsoNegotiates: HttpErrorConstructor; + InsufficientStorage: HttpErrorConstructor; + LoopDetected: HttpErrorConstructor; + BandwidthLimitExceeded: HttpErrorConstructor; + NotExtended: HttpErrorConstructor; + NetworkAuthenticationRequired: HttpErrorConstructor; + } } - - type HttpErrorConstructor = new(msg?: string) => HttpError; - interface CreateHttpError { - // See https://github.com/Microsoft/TypeScript/issues/227#issuecomment-50092674 - [code: string]: new () => HttpError; - - (...args: Array): HttpError; - - Continue: HttpErrorConstructor; - SwitchingProtocols: HttpErrorConstructor; - Processing: HttpErrorConstructor; - OK: HttpErrorConstructor; - Created: HttpErrorConstructor; - Accepted: HttpErrorConstructor; - NonAuthoritativeInformation: HttpErrorConstructor; - NoContent: HttpErrorConstructor; - ResetContent: HttpErrorConstructor; - PartialContent: HttpErrorConstructor; - MultiStatus: HttpErrorConstructor; - AlreadyReported: HttpErrorConstructor; - IMUsed: HttpErrorConstructor; - MultipleChoices: HttpErrorConstructor; - MovedPermanently: HttpErrorConstructor; - Found: HttpErrorConstructor; - SeeOther: HttpErrorConstructor; - NotModified: HttpErrorConstructor; - UseProxy: HttpErrorConstructor; - Unused: HttpErrorConstructor; - TemporaryRedirect: HttpErrorConstructor; - PermanentRedirect: HttpErrorConstructor; - BadRequest: HttpErrorConstructor; - Unauthorized: HttpErrorConstructor; - PaymentRequired: HttpErrorConstructor; - Forbidden: HttpErrorConstructor; - NotFound: HttpErrorConstructor; - MethodNotAllowed: HttpErrorConstructor; - NotAcceptable: HttpErrorConstructor; - ProxyAuthenticationRequired: HttpErrorConstructor; - RequestTimeout: HttpErrorConstructor; - Conflict: HttpErrorConstructor; - Gone: HttpErrorConstructor; - LengthRequired: HttpErrorConstructor; - PreconditionFailed: HttpErrorConstructor; - PayloadTooLarge: HttpErrorConstructor; - URITooLong: HttpErrorConstructor; - UnsupportedMediaType: HttpErrorConstructor; - RangeNotSatisfiable: HttpErrorConstructor; - ExpectationFailed: HttpErrorConstructor; - ImATeapot: HttpErrorConstructor; - MisdirectedRequest: HttpErrorConstructor; - UnprocessableEntity: HttpErrorConstructor; - Locked: HttpErrorConstructor; - FailedDependency: HttpErrorConstructor; - UnorderedCollection: HttpErrorConstructor; - UpgradeRequired: HttpErrorConstructor; - PreconditionRequired: HttpErrorConstructor; - TooManyRequests: HttpErrorConstructor; - RequestHeaderFieldsTooLarge: HttpErrorConstructor; - UnavailableForLegalReasons: HttpErrorConstructor; - InternalServerError: HttpErrorConstructor; - NotImplemented: HttpErrorConstructor; - BadGateway: HttpErrorConstructor; - ServiceUnavailable: HttpErrorConstructor; - GatewayTimeout: HttpErrorConstructor; - HTTPVersionNotSupported: HttpErrorConstructor; - VariantAlsoNegotiates: HttpErrorConstructor; - InsufficientStorage: HttpErrorConstructor; - LoopDetected: HttpErrorConstructor; - BandwidthLimitExceeded: HttpErrorConstructor; - NotExtended: HttpErrorConstructor; - NetworkAuthenticationRequired: HttpErrorConstructor; - } + var createHttpError: createHttpError.CreateHttpError; + export = createHttpError; } - -declare var createHttpError: createHttpError.CreateHttpError; -export = createHttpError; diff --git a/i18next/index.d.ts b/i18next/index.d.ts index 39e0f2a1a2..03dcb9daac 100644 --- a/i18next/index.d.ts +++ b/i18next/index.d.ts @@ -130,6 +130,8 @@ declare namespace i18n { on(languageChanged: 'languageChanged', listener: (lng: string) => void): void; off(event: string, listener: () => void): void; + + options: Options; } } diff --git a/icepick/icepick-tests.ts b/icepick/icepick-tests.ts index 8c7b654492..5458509d42 100644 --- a/icepick/icepick-tests.ts +++ b/icepick/icepick-tests.ts @@ -27,7 +27,7 @@ class Foo {} // assoc(collection, key, value) { let coll = { a: 1, b: 2 }; - let newColl = i.assoc(coll, "b", 3); // {a: 1, b: 3} + let newColl = i.assoc(coll, "b", 3); // {a: 1, b: 3} let arr = ["a", "b", "c"]; let newArr = i.assoc(arr, 2, "d"); // ["a", "b", "d"] @@ -36,7 +36,7 @@ class Foo {} // alias: set(collection, key, value) { let coll = { a: 1, b: 2 }; - let newColl = i.set(coll, "b", 3); // {a: 1, b: 3} + let newColl = i.set(coll, "b", 3); // {a: 1, b: 3} let arr = ["a", "b", "c"]; let newArr = i.set(arr, 2, "d"); // ["a", "b", "d"] @@ -70,7 +70,7 @@ class Foo {} } }; - let newColl = i.assocIn(coll, ["c", "d"], "baz"); + let newColl = i.assocIn(coll, ["c", "d"], "baz"); let coll2 = {}; let newColl2 = i.assocIn(coll2, ["a", "b", "c"], 1); @@ -86,7 +86,7 @@ class Foo {} } }; - let newColl = i.setIn(coll, ["c", "d"], "baz"); + let newColl = i.setIn(coll, ["c", "d"], "baz"); let coll2 = {}; let newColl2 = i.setIn(coll2, ["a", "b", "c"], 1); @@ -99,7 +99,7 @@ class Foo {} { b: 2 } ]); - let result = i.getIn(coll, [1, "b"]); // 2 + let result = i.getIn(coll, [1, "b"]) as number; // 2 } // updateIn(collection, path, callback) @@ -166,9 +166,13 @@ class Foo {} }; let result = i.chain(o) - .assocIn(["a", 2], 4) + .assocIn(["a", 2], 4) + .setIn(["a", 1], 5) + .updateIn(["d"], function(d) { return d * 2 }) .merge({ b: { c: 2, c2: 3 } }) - .assoc("e", 2) + .assoc("e", 2) + .set("f", 3) .dissoc("d") - .value(); + .getIn(['a', 0]) + .value() as number; } diff --git a/icepick/index.d.ts b/icepick/index.d.ts index 184f0e12b1..bffe424d1b 100644 --- a/icepick/index.d.ts +++ b/icepick/index.d.ts @@ -1,15 +1,15 @@ -// Type definitions for icepick v1.1.0 +// Type definitions for icepick v1.3.0 // Project: https://github.com/aearly/icepick -// Definitions by: Nathan Brown +// Definitions by: Nathan Brown , Tobias Cohen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export declare function freeze(collection: T): T; export declare function thaw(collection: T): T; -export declare function assoc(collection: T, key: number | string, value: any): T; +export declare function assoc(collection: T, key: number | string, value: V): T; export declare function dissoc(collection: T, key: number | string): T; -export declare function assocIn(collection: T, path: Array, value: any): T; -export declare function getIn(collection: any, path: Array): Result; +export declare function assocIn(collection: T, path: Array, value: V): T; +export declare function getIn(collection: T, path: Array): any; export declare function updateIn(collection: T, path: Array, callback: (value: V) => V): T; export {assoc as set}; @@ -44,17 +44,17 @@ interface IcepickWrapper { freeze(): IcepickWrapper; thaw(): IcepickWrapper; - assoc(key: number | string, value: any): IcepickWrapper; - set(key: number | string, value: any): IcepickWrapper; + assoc(key: number | string, value: V): IcepickWrapper; + set(key: number | string, value: V): IcepickWrapper; dissoc(key: number | string): IcepickWrapper; unset(key: number | string): IcepickWrapper; - assocIn(path: Array, value: any): IcepickWrapper; - setIn(path: Array, value: any): IcepickWrapper; + assocIn(path: Array, value: V): IcepickWrapper; + setIn(path: Array, value: V): IcepickWrapper; - getIn(collection: any, path: Array): IcepickWrapper; - updateIn(collection: T, path: Array, callback: (value: V) => V): IcepickWrapper; + getIn(path: Array): IcepickWrapper; + updateIn(path: Array, callback: (value: V) => V): IcepickWrapper; assign(source1: S1): IcepickWrapper; assign(s1: S1, s2: S2): IcepickWrapper; diff --git a/imagemapster/imagemapster.d.ts b/imagemapster/index.d.ts similarity index 100% rename from imagemapster/imagemapster.d.ts rename to imagemapster/index.d.ts diff --git a/imagemapster/tsconfig.json b/imagemapster/tsconfig.json index 02230dff2f..e0bcab265e 100644 --- a/imagemapster/tsconfig.json +++ b/imagemapster/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "imagemapster.d.ts", + "index.d.ts", "imagemapster-tests.ts" ] } \ No newline at end of file diff --git a/inquirer/index.d.ts b/inquirer/index.d.ts index b60dfef00d..618da5593d 100644 --- a/inquirer/index.d.ts +++ b/inquirer/index.d.ts @@ -111,7 +111,7 @@ declare namespace inquirer { * A key/value hash containing the client answers in each prompt. */ interface Answers { - [key: string]: any; + [key: string]: any; } namespace ui { diff --git a/intl-tel-input/intl-tel-input.d.ts b/intl-tel-input/index.d.ts similarity index 100% rename from intl-tel-input/intl-tel-input.d.ts rename to intl-tel-input/index.d.ts diff --git a/intl-tel-input/tsconfig.json b/intl-tel-input/tsconfig.json index 2290a860c8..2186d90c1d 100644 --- a/intl-tel-input/tsconfig.json +++ b/intl-tel-input/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "intl-tel-input.d.ts", + "index.d.ts", "intl-tel-input-tests.ts" ] } \ No newline at end of file diff --git a/inversify-express-utils/inversify-express-utils.d.ts b/inversify-express-utils/index.d.ts similarity index 100% rename from inversify-express-utils/inversify-express-utils.d.ts rename to inversify-express-utils/index.d.ts diff --git a/inversify-express-utils/tsconfig.json b/inversify-express-utils/tsconfig.json index c7e399100e..1a136bbfe3 100644 --- a/inversify-express-utils/tsconfig.json +++ b/inversify-express-utils/tsconfig.json @@ -14,7 +14,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "inversify-express-utils.d.ts", + "index.d.ts", "inversify-express-utils-tests.ts" ] } \ No newline at end of file diff --git a/istanbul-middleware/istanbul-middleware.d.ts b/istanbul-middleware/index.d.ts similarity index 100% rename from istanbul-middleware/istanbul-middleware.d.ts rename to istanbul-middleware/index.d.ts diff --git a/istanbul-middleware/tsconfig.json b/istanbul-middleware/tsconfig.json index e755a0b80e..95df263847 100644 --- a/istanbul-middleware/tsconfig.json +++ b/istanbul-middleware/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "istanbul-middleware.d.ts", + "index.d.ts", "istanbul-middleware-tests.ts" ] } \ No newline at end of file diff --git a/jquery-handsontable/index.d.ts b/jquery-handsontable/index.d.ts index 7b4deaabdf..bdbd5b713a 100644 --- a/jquery-handsontable/index.d.ts +++ b/jquery-handsontable/index.d.ts @@ -292,6 +292,11 @@ declare namespace Handsontable { */ manualRowResize?: boolean; + /** + * Turns on Manual row move, if set to a boolean or define initial row order, if set to an array of row indexes. + */ + manualRowMove?: boolean; + /** * Setting to true enables the copyPaste plugin, which enables the copying and pasting to the clipboard. */ diff --git a/jquery-mousewheel/jquery-mousewheel.d.ts b/jquery-mousewheel/index.d.ts similarity index 100% rename from jquery-mousewheel/jquery-mousewheel.d.ts rename to jquery-mousewheel/index.d.ts diff --git a/jquery-mousewheel/tsconfig.json b/jquery-mousewheel/tsconfig.json index 0c0c88bcb6..6c4ffbe27a 100644 --- a/jquery-mousewheel/tsconfig.json +++ b/jquery-mousewheel/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "jquery-mousewheel.d.ts", + "index.d.ts", "jquery-mousewheel-tests.ts" ] } \ No newline at end of file diff --git a/jquery-param/index.d.ts b/jquery-param/index.d.ts new file mode 100644 index 0000000000..4e1031da2f --- /dev/null +++ b/jquery-param/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for jquery-param v1.0.0 +// Project: https://github.com/knowledgecode/jquery-param +// Definitions by: Pat Sissons + +export as namespace param; + +export = param; + +declare function param(obj: any): string; diff --git a/jquery-param/jquery-param-tests.ts b/jquery-param/jquery-param-tests.ts new file mode 100644 index 0000000000..cdea4dd342 --- /dev/null +++ b/jquery-param/jquery-param-tests.ts @@ -0,0 +1,3 @@ +import param = require('jquery-param'); + +const test1 = param({ a: 'A', b: 'B', c: 'C' }); diff --git a/jquery-param/tsconfig.json b/jquery-param/tsconfig.json new file mode 100644 index 0000000000..cd5ade28aa --- /dev/null +++ b/jquery-param/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jquery-param-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery-truncate-html/jquery-truncate-html.d.ts b/jquery-truncate-html/index.d.ts similarity index 100% rename from jquery-truncate-html/jquery-truncate-html.d.ts rename to jquery-truncate-html/index.d.ts diff --git a/jquery-truncate-html/tsconfig.json b/jquery-truncate-html/tsconfig.json index a282bbf024..d265c19db1 100644 --- a/jquery-truncate-html/tsconfig.json +++ b/jquery-truncate-html/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "jquery-truncate-html.d.ts", + "index.d.ts", "jquery-truncate-html-tests.ts" ] } \ No newline at end of file diff --git a/jquery.contextmenu/index.d.ts b/jquery.contextmenu/index.d.ts index 5748c76edc..64db123173 100644 --- a/jquery.contextmenu/index.d.ts +++ b/jquery.contextmenu/index.d.ts @@ -25,7 +25,8 @@ interface JQueryContextMenuOptions { hide?: () => void; }; callback?: (key: any, options: any) => any; - items: any; + items?: any; + build?: (triggerElement: JQuery, e: Event) => any; reposition?: boolean; className?: string; itemClickEvent?: string; diff --git a/jsoneditor/jsoneditor.d.ts b/jsoneditor/index.d.ts similarity index 100% rename from jsoneditor/jsoneditor.d.ts rename to jsoneditor/index.d.ts diff --git a/jsoneditor/jsoneditor-tests.ts b/jsoneditor/jsoneditor-tests.ts index 99bbb51b92..3c8b66d76b 100644 --- a/jsoneditor/jsoneditor-tests.ts +++ b/jsoneditor/jsoneditor-tests.ts @@ -1,5 +1,3 @@ -/// - import JSONEditor, {JSONEditorMode, JSONEditorNode, JSONEditorOptions} from 'jsoneditor'; let options: JSONEditorOptions; diff --git a/jsoneditor/tsconfig.json b/jsoneditor/tsconfig.json index ac1de683cd..55b5ac9998 100644 --- a/jsoneditor/tsconfig.json +++ b/jsoneditor/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "jsoneditor.d.ts", + "index.d.ts", "jsoneditor-tests.ts" ] } \ No newline at end of file diff --git a/jstree/index.d.ts b/jstree/index.d.ts index 7b924bfd2d..377f34fbc4 100644 --- a/jstree/index.d.ts +++ b/jstree/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for jsTree v3.3.2 +// Type definitions for jsTree v3.3.3 // Project: http://www.jstree.com/ // Definitions by: Adam Pluciński // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// 1 commit bb0473ae8cfc205585b6404ef86f650df2f6996e 2016-08-15 +// 1 commit 26e99ad5ec27c1a594ed57974cb16e0987482fd5 2016-11-19 /// @@ -374,6 +374,12 @@ interface JSTreeStaticDefaultsCoreThemes { */ icons?: boolean; + /** + * a boolean indicating if node ellipsis should be shown - this only works with a fixed with on the container + * @name $.jstree.defaults.core.themes.ellipsis + */ + ellipsis?: boolean; + /** * a boolean indicating if the tree background is striped * @name $.jstree.defaults.core.themes.stripes @@ -429,7 +435,7 @@ interface JSTreeStaticDefaultsCheckbox { * @name $.jstree.defaults.checkbox.cascade * @plugin checkbox */ - cascade: boolean; + cascade: string; /** * This setting controls if checkbox are bound to the general tree selection @@ -737,6 +743,11 @@ interface JSTree extends JQuery { */ teardown: () => void; + /** + * Create prototype node + */ + _create_prototype_node: () => HTMLElement; + /** * bind all events. Used internally. * @private @@ -1567,6 +1578,24 @@ interface JSTree extends JQuery { */ toggle_icons: () => void; + /** + * show the node ellipsis + * @name show_icons() + */ + show_ellipsis: () => void; + + /** + * hide the node ellipsis + * @name hide_ellipsis() + */ + hide_ellipsis: () => void; + + /** + * toggle the node ellipsis + * @name toggle_icons() + */ + toggle_ellipsis: () => void; + /** * set the node icon for a node * @name set_icon(obj, icon) diff --git a/jstree/jstree-tests.ts b/jstree/jstree-tests.ts index e82115c645..bd35406c71 100644 --- a/jstree/jstree-tests.ts +++ b/jstree/jstree-tests.ts @@ -114,3 +114,15 @@ tree.get_path('nodeId'); tree.get_path('nodeId', '/'); tree.get_path('nodeId', '/', true); + + +var coreThemes: JSTreeStaticDefaultsCoreThemes = { + ellipsis:true +}; + +// tree with new theme elipsis +var treeWithNewCoreProperties = $('#treeWithNewEllipsisProperties').jstree({ + core: { + themes: coreThemes + } +}); diff --git a/jsuite/jsuite.d.ts b/jsuite/index.d.ts similarity index 100% rename from jsuite/jsuite.d.ts rename to jsuite/index.d.ts diff --git a/jsuite/tsconfig.json b/jsuite/tsconfig.json index 0742f18c9f..79b9eb6b27 100644 --- a/jsuite/tsconfig.json +++ b/jsuite/tsconfig.json @@ -13,6 +13,6 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "jsuite.d.ts" + "index.d.ts" ] } \ No newline at end of file diff --git a/kafka-node/index.d.ts b/kafka-node/index.d.ts index 347cc066f0..049278ac51 100644 --- a/kafka-node/index.d.ts +++ b/kafka-node/index.d.ts @@ -66,6 +66,8 @@ export declare class Offset { fetch(payloads: Array, cb: (error: any, data: any) => any): void; commit(groupId: string, payloads: Array, cb: (error: any, data: any) => any): void; fetchCommits(groupId: string, payloads: Array, cb: (error: any, data: any) => any): void; + fetchLatestOffsets(topics: Array, cb: (error: any, data: any) => any): void; + on(eventName: string, cb: (error: any) => any): void; } export declare class KeyedMessage { @@ -100,6 +102,8 @@ export interface ConsumerOptions { export interface Topic { topic: string; offset?: number; + encoding?: string; + autoCommit?: boolean; } export interface OffsetRequest { diff --git a/karma-chai-sinon/karma-chai-sinon.d.ts b/karma-chai-sinon/index.d.ts similarity index 100% rename from karma-chai-sinon/karma-chai-sinon.d.ts rename to karma-chai-sinon/index.d.ts diff --git a/karma-chai-sinon/tsconfig.json b/karma-chai-sinon/tsconfig.json index aef2986498..a7f480c167 100644 --- a/karma-chai-sinon/tsconfig.json +++ b/karma-chai-sinon/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "karma-chai-sinon.d.ts", + "index.d.ts", "karma-chai-sinon-tests.ts" ] } \ No newline at end of file diff --git a/kefir/index.d.ts b/kefir/index.d.ts index d445be74ad..93d1c6c14f 100644 --- a/kefir/index.d.ts +++ b/kefir/index.d.ts @@ -16,6 +16,17 @@ export interface Observer { end?: () => void; } +export interface Subscription { + unsubscribe(): void; + closed: boolean; // Actually, `readonly` but it's avaiable in tsc starting with 2.0.0 +} + +export interface Observer { + value?: (value: T) => void; + error?: (error: S) => void; + end?: () => void; +} + export interface Observable { // Subscribe / add side effects onValue(callback: (value: T) => void): void; diff --git a/kendo-ui/index.d.ts b/kendo-ui/index.d.ts index 43af9f8305..fb033d78ec 100644 --- a/kendo-ui/index.d.ts +++ b/kendo-ui/index.d.ts @@ -1026,6 +1026,8 @@ declare namespace kendo.data { class DataSource extends Observable{ options: DataSourceOptions; + transports: any; + static create(options?: DataSourceOptions): DataSource; constructor(options?: DataSourceOptions); diff --git a/knex/index.d.ts b/knex/index.d.ts index 905841283d..0b69f64109 100644 --- a/knex/index.d.ts +++ b/knex/index.d.ts @@ -326,9 +326,9 @@ declare namespace Knex { } interface Transaction extends QueryBuilder { - commit: any; - rollback: any; - raw: Knex.RawBuilder; + commit: any; + rollback: any; + raw: Knex.RawBuilder; } // @@ -349,37 +349,39 @@ declare namespace Knex { } interface TableBuilder { - increments(columnName?: string): ColumnBuilder; - bigIncrements(columnName?: string): ColumnBuilder; - dropColumn(columnName: string): TableBuilder; - dropColumns(...columnNames: string[]): TableBuilder; - renameColumn(from: string, to: string): ColumnBuilder; - integer(columnName: string): ColumnBuilder; - bigInteger(columnName: string): ColumnBuilder; - text(columnName: string, textType?: string): ColumnBuilder; - string(columnName: string, length?: number): ColumnBuilder; - float(columnName: string, precision?: number, scale?: number): ColumnBuilder; - decimal(columnName: string, precision?: number, scale?: number): ColumnBuilder; - boolean(columnName: string): ColumnBuilder; - date(columnName: string): ColumnBuilder; - dateTime(columnName: string): ColumnBuilder; - time(columnName: string): ColumnBuilder; - timestamp(columnName: string): ColumnBuilder; - timestamps(): ColumnBuilder; - binary(columnName: string): ColumnBuilder; - enum(columnName: string, values: Value[]): ColumnBuilder; - enu(columnName: string, values: Value[]): ColumnBuilder; - json(columnName: string): ColumnBuilder; - jsonb(columnName: string): ColumnBuilder; - uuid(columnName: string): ColumnBuilder; - comment(val: string): TableBuilder; - specificType(columnName: string, type: string): ColumnBuilder; - primary(columnNames: string[]) : TableBuilder; - index(columnNames: string[], indexName?: string, indexType?: string) : TableBuilder; - unique(columnNames: string[], indexName?: string) : TableBuilder; - foreign(column: string): ForeignConstraintBuilder; - foreign(columns: string[]): MultikeyForeignConstraintBuilder; - dropForeign(columnNames: string[], foreignKeyName?: string): TableBuilder; + increments(columnName?: string): ColumnBuilder; + bigIncrements(columnName?: string): ColumnBuilder; + dropColumn(columnName: string): TableBuilder; + dropColumns(...columnNames: string[]): TableBuilder; + renameColumn(from: string, to: string): ColumnBuilder; + integer(columnName: string): ColumnBuilder; + bigInteger(columnName: string): ColumnBuilder; + text(columnName: string, textType?: string): ColumnBuilder; + string(columnName: string, length?: number): ColumnBuilder; + float(columnName: string, precision?: number, scale?: number): ColumnBuilder; + decimal(columnName: string, precision?: number, scale?: number): ColumnBuilder; + boolean(columnName: string): ColumnBuilder; + date(columnName: string): ColumnBuilder; + dateTime(columnName: string): ColumnBuilder; + time(columnName: string): ColumnBuilder; + timestamp(columnName: string): ColumnBuilder; + timestamps(): ColumnBuilder; + binary(columnName: string): ColumnBuilder; + enum(columnName: string, values: Value[]): ColumnBuilder; + enu(columnName: string, values: Value[]): ColumnBuilder; + json(columnName: string): ColumnBuilder; + jsonb(columnName: string): ColumnBuilder; + uuid(columnName: string): ColumnBuilder; + comment(val: string): TableBuilder; + specificType(columnName: string, type: string): ColumnBuilder; + primary(columnNames: string[]): TableBuilder; + index(columnNames: string[], indexName?: string, indexType?: string): TableBuilder; + unique(columnNames: string[], indexName?: string): TableBuilder; + foreign(column: string): ForeignConstraintBuilder; + foreign(columns: string[]): MultikeyForeignConstraintBuilder; + dropForeign(columnNames: string[], foreignKeyName?: string): TableBuilder; + dropUnique(columnNames: string[], indexName?: string): TableBuilder; + dropPrimary(constraintName?: string): TableBuilder; } interface CreateTableBuilder extends TableBuilder { diff --git a/knex/knex-tests.ts b/knex/knex-tests.ts index eaab2ca8bd..353c382973 100644 --- a/knex/knex-tests.ts +++ b/knex/knex-tests.ts @@ -453,6 +453,10 @@ knex.schema.raw("SET sql_mode='TRADITIONAL'") table.dropColumn('name'); table.string('first_name'); table.string('last_name'); + table.dropUnique(["name1", "name2"], "index_name"); + table.dropUnique(["name1", "name2"]); + table.dropPrimary(); + table.dropPrimary("constraint_name"); }); knex('users') diff --git a/knockout/index.d.ts b/knockout/index.d.ts index e44f15814c..970a4e9a08 100644 --- a/knockout/index.d.ts +++ b/knockout/index.d.ts @@ -332,7 +332,7 @@ interface KnockoutUtils { } interface KnockoutArrayChange { - status: "added" | "deleted"; + status: "added" | "deleted" | "retained"; value: T; index: number; moved?: number; @@ -587,6 +587,12 @@ interface KnockoutStatic { ///////////////////////////////// tasks: KnockoutTasks; + + ///////////////////////////////// + // utils.js + ///////////////////////////////// + + onError?: (error: Error) => void; } interface KnockoutBindingProvider { diff --git a/koa-compress/koa-compress.d.ts b/koa-compress/index.d.ts similarity index 100% rename from koa-compress/koa-compress.d.ts rename to koa-compress/index.d.ts diff --git a/koa-compress/tsconfig.json b/koa-compress/tsconfig.json index 05c84b0a3a..3a922f661c 100644 --- a/koa-compress/tsconfig.json +++ b/koa-compress/tsconfig.json @@ -1,6 +1,6 @@ { "files": [ - "koa-compress.d.ts", + "index.d.ts", "koa-compress-tests.ts" ], "compilerOptions": { diff --git a/koa-hbs/koa-hbs.d.ts b/koa-hbs/index.d.ts similarity index 100% rename from koa-hbs/koa-hbs.d.ts rename to koa-hbs/index.d.ts diff --git a/koa-hbs/tsconfig.json b/koa-hbs/tsconfig.json index c20e3481c9..ba124e4c80 100644 --- a/koa-hbs/tsconfig.json +++ b/koa-hbs/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "koa-hbs.d.ts", + "index.d.ts", "koa-hbs-tests.ts" ] } \ No newline at end of file diff --git a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts b/leaflet-geocoder-mapzen/index.d.ts similarity index 100% rename from leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts rename to leaflet-geocoder-mapzen/index.d.ts diff --git a/leaflet-geocoder-mapzen/tsconfig.json b/leaflet-geocoder-mapzen/tsconfig.json index 75d2cf911a..6fb796302e 100644 --- a/leaflet-geocoder-mapzen/tsconfig.json +++ b/leaflet-geocoder-mapzen/tsconfig.json @@ -10,7 +10,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "leaflet-geocoder-mapzen.d.ts", + "index.d.ts", "leaflet-geocoder-mapzen-tests.ts" ] } \ No newline at end of file diff --git a/leaflet/index.d.ts b/leaflet/index.d.ts index d16be0bc1f..1adf9f0b0b 100644 --- a/leaflet/index.d.ts +++ b/leaflet/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Leaflet.js 1.0.0-rc3 +// Type definitions for Leaflet.js 1.0.0 // Project: https://github.com/Leaflet/Leaflet // Definitions by: Alejandro Sánchez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -1413,8 +1413,12 @@ declare namespace L { createShadow(oldIcon?: HTMLElement): HTMLElement; } + export interface IconDefault extends Icon { + imagePath: string; + } + export namespace Icon { - export const Default: Icon; + export const Default: IconDefault; } export function icon(options: IconOptions): Icon; @@ -1471,45 +1475,25 @@ declare namespace L { export const gecko: boolean; export const android: boolean; export const android23: boolean; - export const chrome: boolean; - export const safari: boolean; - export const win: boolean; - export const ie3d: boolean; - export const webkit3d: boolean; - export const gecko3d: boolean; - export const opera12: boolean; - export const any3d: boolean; - export const mobile: boolean; - export const mobileWebkit: boolean; - export const mobiWebkit3d: boolean; - export const mobileOpera: boolean; - export const mobileGecko: boolean; - export const touch: boolean; - export const msPointer: boolean; - export const pointer: boolean; - export const retina: boolean; - export const canvas: boolean; - export const vml: boolean; - export const svg: boolean; } } diff --git a/linqsharp/index.d.ts b/linqsharp/index.d.ts deleted file mode 100644 index 742698ed86..0000000000 --- a/linqsharp/index.d.ts +++ /dev/null @@ -1,498 +0,0 @@ -// Type definitions for linqsharp -// Project: https://www.npmjs.com/package/linqsharp -// Definitions by: Bruno Leonardo Michels -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// JSDoc: Extracted and adapted from .NET source code. - -/** - * LinqSharp module defines a helper class with - * .NET's Linq methods. - * - * @module linqsharp - */ - -export declare namespace LinqSharp { - /** - * Defines methods to support the comparison of objects for equality. - * - * {T} The type of objects to compare. - */ - export interface IEqualityComparer { - Equals(x: T, y: T): boolean; - GetHashCode(obj: T): number; - } - - /** - * Represents a collection of objects that have a common key. - * - * {TKey} The type of the key. - * {T} The type of the values. - */ - export interface IGrouping { - Key: TKey; - Elements: T[]; - } - - /** - * Gets the HashCode of the object. - * - * @param e Object to compute hash. - * @returns A computed HashCode for the object. - */ - export function GetHashCode(e: any): any; - - /** - * Transforms a object into a string replacing circular - * references by reference tokens. - * - * @param obj Object to convert to string. - * @returns String representation of the object. - */ - export function StringifyNonCircular(obj: any): string; -} - -/** - * Wrapper class for an array that provides Linq functionallity. - * - * @class Linq - */ -declare class Linq { - /** {T[]} Internal array reference. */ - private a: T[]; - - /** - * Creates a new instance holding an array of . - * @constructor - * - * @param {Array} a Array. - */ - constructor(a?: T[]); - - /** - * Applies an accumulator function over a sequence. - * - * @param func An accumulator function to be - * invoked on each element. - * @param {T} [initialValue] The initial accumulator value. - * - * @throws Error if array is empty. - * - * @returns {T} The final accumulator value. - */ - Aggregate(func: (previous: T, next: T) => TResult, initialValue?: T): T; - - /** - * Determines whether all elements of a sequence satisfy a condition. - * - * @param predicate A function to test each element for a condition. - * - * @returns true if every element of the source sequence passes the test in the specified - * predicate, or if the sequence is empty; otherwise, false. - */ - All(predicate: (value: T) => boolean): boolean; - - /** - * Determines whether a sequence contains any elements. - * - * @param [predicate] A function to test each element for a condition. - * - * @returns true if any elements in the source sequence pass the test in the specified predicate; - * otherwise, false. If no predicate is specified return true if the source sequence contains any elements; - * otherwise, false. - */ - Any(predicate?: (value: T) => boolean): boolean; - - /** - * Computes the average of a sequence of {number} values. - * - * @param [selector] A transform function to apply to each element. - * - * @returns The average of the sequence of values. - */ - Average(selector?: (value: T) => number): number; - - /** - * Concatenates two sequences. - * - * @param array The sequence to concatenate to the first sequence. - * - * @returns An array that contains the concatenated elements of the two input sequences. - */ - Concat(array: T[]): Linq; - - /** - * Determines whether a sequence contains a specified element by using a specified comparer. - * - * @param value The value to locate in the sequence. - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns true if the source sequence contains an element that has the specified value; - * otherwise, false. - */ - Contains(value: T, comparer?: LinqSharp.IEqualityComparer): boolean; - - /** - * Returns a number that represents how many elements in the specified sequence satisfy a condition. - * - * @param [selector] A function to test each element for a condition. - * - * @returns A number that represents how many elements in the sequence satisfy the condition - * in the predicate function. - */ - Count(selector?: (value: T) => boolean): number; - - /** - * Returns distinct elements from a sequence by using a specified IEqualityComparer - * to compare values. - * - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns An array that contains distinct elements from the source sequence. - */ - Distinct(comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Returns distinct elements from a sequence by using a specified IEqualityComparer - * to compare values. - * - * @param selector A function to test each element for a condition. - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns An array that contains distinct elements from the source sequence. - */ - DistinctBy(selector: (e: T) => U, comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Returns the element at a specified index in a sequence. - * - * @param index The zero-based index of the element to retrieve. - * - * @throws index is less than 0 or greater than or equal to the number of elements in source. - * - * @returns The element at the specified position in the source sequence. - */ - ElementAt(index: number): T; - - /** - * Returns the element at a specified index in a sequence or a default value if - * the index is out of range. - * - * @param index The zero-based index of the element to retrieve. - * @param defaultValue A default value if no element is found. - * - * @returns defaultValue if the index is outside the bounds of the source sequence; - * otherwise, the element at the specified position in the source sequence. - */ - ElementAtOrDefault(index: number, defaultValue: T): T; - - /** - * Produces the set difference of two sequences by using the specified IEqualityComparer - * to compare values. - * - * @param except An array whose elements that also occur in the first sequence will cause - * those elements to be removed from the returned sequence. - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns A sequence that contains the set difference of the elements of two sequences. - */ - Except(except: T[], comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Returns the first element in a sequence that satisfies a specified condition. - * - * @param [selector] A function to test each element for a condition. - * - * @throws No element satisfies the condition in predicate.-or-The source sequence is empty. - * - * @returns The first element in the sequence that passes the test in the specified predicate function. - */ - First(selector?: (e: T) => boolean): T; - - /** - * Returns the first element of the sequence that satisfies a condition or a default - * value if no such element is found. - * - * @param [selector] A function to test each element for a condition. - * @param [defaultValue] A default value to return if no element is found. - * - * @returns defaultValue if source is empty or if no element passes the test specified by predicate; - * otherwise, the first element in source that passes the test specified by predicate. - */ - FirstOrDefault(selector?: (e: T) => boolean, defaultValue?: T): T; - - /** - * Performs the specified action on each element of the array. - * - * @param callback The function delegate to perform on each element of the array. - */ - ForEach(callback: (e: T, index: number) => any): void; - - /** - * Groups the elements of a sequence according to a specified key selector function. - * - * @param keySelector A function to extract the key for each element. - * @param [elementSelector] A function to create a result value from each group. - * @param [comparer] An IEqualityComparer to compare keys with. - * - * @returns A collection of elements of type TResult where each element represents a projection - * over a group and its key. - */ - GroupBy(keySelector: (e: T) => TKey, elementSelector?: (e: T) => TElement, comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Searches for the specified object and returns the zero-based index of the first - * occurrence within the entire array. - * - * @param e The object to locate in the array. - * @param [comparer] An IEqualityComparer to compare elements with. - * - * @returns The zero-based index of the first occurrence of item within the entire array, if found; - * otherwise, –1. - */ - IndexOf(e: T, comparer?: LinqSharp.IEqualityComparer): number; - - /** - * Produces the set intersection of two sequences by using the specified IEqualityComparer - * to compare values. - * - * @param array An array whose distinct elements that also appear in the first sequence will be returned. - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns A sequence that contains the elements that form the set intersection of two sequences. - */ - Intersect(array: T[], comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Correlates the elements of two sequences based on matching keys. A specified IEqualityComparer is used to compare keys. - * - * @param array The sequence to join to the first sequence. - * @param outerKeySelector A function to extract the join key from each element of the first sequence. - * @param innerKeySelector A function to extract the join key from each element of the second sequence. - * @param resultSelector A function to create a result element from two matching elements. - * @param [comparer] An IEqualityComparer to hash and compare keys. - * - * @returns An array that has elements of type TResult that are obtained by performing an inner join on two sequences. - */ - Join(array: TInner[], outerKeySelector: (e: T) => TKey, innerKeySelector: (e: TInner) => TKey, resultSelector: (outer: T, inner: TInner) => TResult, comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Returns the last element of a sequence that satisfies a specified condition. - * - * @param [predicate] A function to test each element for a condition. - * - * @throws No element satisfies the condition in predicate.-or-The source sequence is empty. - * - * @returns The last element in the sequence that passes the test in the specified predicate function. - */ - Last(predicate?: (e: T) => boolean): T; - - /** - * Returns the last element of a sequence that satisfies a condition or a default - * value if no such element is found. - * - * @param [predicate] A function to test each element for a condition. - * @param [defaultValue] A default value to return if no element is found. - * - * @returns defaultValue if the sequence is empty or if no elements pass the test in - * the predicate function; otherwise, the last element that passes the test in the - * predicate function. - */ - LastOrDefault(predicate?: (e: T) => boolean, defaultValue?: T): T; - - /** - * Returns the maximum value in a sequence of System.Double values. - * - * @param [selector] A transform function to apply to each element. - * - * @returns The maximum value in the sequence. - */ - Max(): T; - Max(selector?: (e: T) => TResult): TResult; - - /** - * Returns the minimum value in a sequence of System.Int64 values. - * - * @param [selector] A transform function to apply to each element. - * - * @returns The minimum value in the sequence. - */ - Min(): T; - Min(selector?: (e: T) => TResult): TResult; - - /** - * Sorts the elements of a sequence in ascending order according to a key. - * - * @param keySelector A function to extract a key from an element. - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns An array whose elements are sorted according to a key. - */ - OrderBy(keySelector: (e: T) => TKey, comparer?: (a: TKey, b: TKey) => number): Linq; - - /** - * Sorts the elements of a sequence in descending order according to a key. - * - * @param keySelector A function to extract a key from an element. - * @param [comparer] An IEqualityComparer to compare values. - * - * @returns An array whose elements are sorted in descending order according to a key. - */ - OrderByDescending(keySelector: (e: T) => TKey, comparer?: (a: TKey, b: TKey) => number): Linq; - - /** - * Inverts the order of the elements in a sequence. - * - * @returns A sequence whose elements correspond to those of the input sequence in reverse order. - */ - Reverse(): Linq; - - /** - * Projects each element of a sequence into a new form. - * - * @param selector A transform function to apply to each element. - * - * @returns An array whose elements are the result of invoking the transform function on each element of source. - */ - Select(selector: (e: T, i?: number) => TResult): Linq; - - /** - * Projects each element of a sequence to an array flattens the resulting sequences into one sequence, - * and invokes a result selector function on each element therein. - * - * @param selector A transform function to apply to each element of the input sequence. - * @param [resultSelector] A transform function to apply to each element of the intermediate sequence. - * - * @returns An array whose elements are the result of invoking the one-to-many transform function - * selector on each element of source and then mapping each of those sequence elements and - * their corresponding source element to a result element. - */ - SelectMany(selector: (e: T) => T[], resultSelector?: (e: T) => TResult): Linq; - - /** - * Determines whether two sequences are equal by comparing their elements by using - * a specified IEqualityComparer. - * - * @param second An array to compare to the first sequence. - * @param [comparer] An equality comparer to compare values. - * - * @returns true if the two source sequences are of equal length and their corresponding - * elements compare equal according to comparer; otherwise, false. - */ - SequenceEqual(second: T[], comparer?: (a: T, b: T) => boolean): boolean; - - /** - * Returns the only element of a sequence that satisfies a specified condition, - * and throws an exception if more than one such element exists. - * - * @param [predicate] A function to test an element for a condition. - * - * @returns The single element of the input sequence that satisfies a condition. - */ - Single(predicate?: (e: T) => boolean): T; - - /** - * Returns the only element of a sequence that satisfies a specified condition or - * a default value if no such element exists; this method throws an exception if - * more than one element satisfies the condition. - * - * @param [predicate] A function to test an element for a condition. - * @param [defaultValue] A default value if no element is found. - * - * @returns The single element of the input sequence that satisfies the condition, - * or defaultValue if no such element is found. - */ - SingleOrDefault(predicate?: (e: T) => boolean, defaultValue?: T): T; - - /** - * Bypasses a specified number of elements in a sequence and then returns the remaining - * elements. - * - * @param count The number of elements to skip before returning the remaining elements. - * - * @returns An array that contains the elements that occur - * after the specified index in the input sequence. - */ - Skip(count: number): Linq; - - /** - * Bypasses elements in a sequence as long as a specified condition is true and - * then returns the remaining elements. - * - * @param predicate A function to test an element for a condition. - * - * @returns An array that contains the elements from the - * input sequence starting at the first element in the linear series that does not - * pass the test specified by predicate. - */ - SkipWhile(predicate: (e: T) => boolean): Linq; - - /** - * Computes the sum of a sequence values. - * - * @param [selector] A transform function to apply to each element. - * - * @returns The sum of the values in the sequence. - */ - Sum(selector?: (value: T) => number): number; - - /** - * Returns a specified number of contiguous elements from the start of a sequence. - * - * @param count The number of elements to skip before returning the remaining elements. - * - * @returns An array that contains the specified number of elements from the start - * of the input sequence. - */ - Take(count: number): Linq; - - /** - * Returns elements from a sequence as long as a specified condition is true. - * - * @param predicate A function to test an element for a condition. - * - * @returns An array that contains the elements from the - * input sequence that occur before the element at which the test no longer passes. - */ - TakeWhile(predicate: (e: T) => boolean): Linq; - - /** - * Produces the set union of two sequences by using a specified IEqualityComparer. - * - * @param second An array whose distinct elements form the second set for the union. - * @param [comparer] An equality comparer to compare values. - * - * @returns An array that contains the elements from both - * input sequences, excluding duplicates. - */ - Union(second: T[], comparer?: LinqSharp.IEqualityComparer): Linq; - - /** - * Filters a sequence of values based on a predicate. - * - * @param selector A transform function to apply to each element. - * - * @returns An array that contains elements from the input sequence - * that satisfy the condition. - */ - Where(selector: (value: T) => boolean): Linq; - - /** - * Applies a specified function to the corresponding elements of two sequences, - * producing a sequence of the results. - * - * @param array The second sequence to merge. - * @param resultSelector A function that specifies how to merge the elements from the two sequences. - * - * @returns An array that contains merged elements of two input sequences. - */ - Zip(array: TInner[], resultSelector: (o: T, i: TInner) => TResult): Linq; - - /** - * Retrieves the internal array. - * - * @returns Internal array. - */ - ToArray(): T[]; -} -export default Linq; diff --git a/linqsharp/linqsharp-tests.ts b/linqsharp/linqsharp-tests.ts deleted file mode 100644 index 1fda5716b8..0000000000 --- a/linqsharp/linqsharp-tests.ts +++ /dev/null @@ -1,91 +0,0 @@ - -import Linq, { LinqSharp } from "linqsharp"; - -var linq: Linq = new Linq([0, 1, 2, 3]); - -var linqResult: Linq; -var linqAny: Linq; -var arrayResult: number[]; - -var numberResult: number; -var boolResult: boolean; - -var comparer: LinqSharp.IEqualityComparer = { - Equals: (x: number, y: number): boolean => - { - return x === y; - }, - GetHashCode: (obj: number): number => - { - return obj.valueOf(); - } -}; -var comparer2: (o: number, i: number) => number; -var comparer3: (o: number, i: number) => boolean; - -numberResult = linq.Aggregate((prev: number, next: number) => { return prev + next; }); -boolResult = linq.All((value: number) => value == 0); -boolResult = linq.Any(); -boolResult = linq.Any((value: number) => value == 0); -numberResult = linq.Average(); -numberResult = linq.Average((value: number) => value); -linqResult = linq.Concat([4, 5, 6]); -boolResult = linq.Contains(0); -boolResult = linq.Contains(0, comparer); -numberResult = linq.Count(); -numberResult = linq.Count((value: number) => value == 0); -linqResult = linq.Distinct(); -linqResult = linq.Distinct(comparer); -linqResult = linq.DistinctBy((value: number) => value); -numberResult = linq.ElementAt(0); -numberResult = linq.ElementAtOrDefault(0, 1); -linqResult = linq.Except([2]); -linqResult = linq.Except([2], comparer); -numberResult = linq.First(); -numberResult = linq.First((value: number) => value == 0); -numberResult = linq.FirstOrDefault(); -numberResult = linq.FirstOrDefault((value: number) => value == 0); -linq.ForEach((value: number, index: number) => { }); -linqAny = linq.GroupBy((value: number) => value % 2); -linqAny = linq.GroupBy((value: number) => value % 2, (value: number) => value * 2); -linqAny = linq.GroupBy((value: number) => value % 2, (value: number) => value * 2, comparer); -numberResult = linq.IndexOf(0); -numberResult = linq.IndexOf(0, comparer); -linqResult = linq.Intersect([0]); -linqResult = linq.Intersect([0], comparer); -linqResult = linq.Join([0], (outer: number) => outer, (inner: number) => inner, (outer: number, inner: number) => outer + inner); -linqResult = linq.Join([0], (outer: number) => outer, (inner: number) => inner, (outer: number, inner: number) => outer + inner, comparer); -numberResult = linq.Last(); -numberResult = linq.Last((value: number) => value == 0); -numberResult = linq.LastOrDefault(); -numberResult = linq.LastOrDefault((value: number) => value == 0); -numberResult = linq.Max(); -numberResult = linq.Max((value: number) => value); -numberResult = linq.Min(); -numberResult = linq.Min((value: number) => value); -linqResult = linq.OrderBy((value: number) => value); -linqResult = linq.OrderBy((value: number) => value, comparer2); -linqResult = linq.OrderByDescending((value: number) => value); -linqResult = linq.OrderByDescending((value: number) => value, comparer2); -linqResult = linq.Reverse(); -linqResult = linq.Select((value: number) => value); -linqResult = linq.Select((value: number, index: number) => value + index); -linqResult = linq.SelectMany((value: number) => [ value ]); -linqResult = linq.SelectMany((value: number) => [ value ], (value: number) => value); -boolResult = linq.SequenceEqual([0]); -boolResult = linq.SequenceEqual([0], comparer3); -numberResult = linq.Single(); -numberResult = linq.Single((value: number) => value == 0); -numberResult = linq.SingleOrDefault(); -numberResult = linq.SingleOrDefault((value: number) => value == 0); -linqResult = linq.Skip(0); -linqResult = linq.SkipWhile((value: number) => value < 2); -numberResult = linq.Sum(); -numberResult = linq.Sum((value: number) => value * 2); -linqResult = linq.Take(2); -linqResult = linq.TakeWhile((value: number) => value < 2); -arrayResult = linq.ToArray(); -linqResult = linq.Union([0]); -linqResult = linq.Union([0], comparer); -linqResult = linq.Where((value: number) => value > 0); -linqResult = linq.Zip([0], (outer: number, inner: number) => outer + inner); \ No newline at end of file diff --git a/lodash-es/add/index.d.ts b/lodash-es/add/index.d.ts new file mode 100644 index 0000000000..a63439b906 --- /dev/null +++ b/lodash-es/add/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const add: typeof _.add; +export default add; diff --git a/lodash-es/after/index.d.ts b/lodash-es/after/index.d.ts new file mode 100644 index 0000000000..39a19b4f11 --- /dev/null +++ b/lodash-es/after/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const after: typeof _.after; +export default after; diff --git a/lodash-es/ary/index.d.ts b/lodash-es/ary/index.d.ts new file mode 100644 index 0000000000..683b4c2d16 --- /dev/null +++ b/lodash-es/ary/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const ary: typeof _.ary; +export default ary; diff --git a/lodash-es/assign/index.d.ts b/lodash-es/assign/index.d.ts new file mode 100644 index 0000000000..e07e8b3712 --- /dev/null +++ b/lodash-es/assign/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const assign: typeof _.assign; +export default assign; diff --git a/lodash-es/assignIn/index.d.ts b/lodash-es/assignIn/index.d.ts new file mode 100644 index 0000000000..ae37403f48 --- /dev/null +++ b/lodash-es/assignIn/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const assignIn: typeof _.assignIn; +export default assignIn; diff --git a/lodash-es/assignInWith/index.d.ts b/lodash-es/assignInWith/index.d.ts new file mode 100644 index 0000000000..1f99a630e1 --- /dev/null +++ b/lodash-es/assignInWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const assignInWith: typeof _.assignInWith; +export default assignInWith; diff --git a/lodash-es/assignWith/index.d.ts b/lodash-es/assignWith/index.d.ts new file mode 100644 index 0000000000..d7175fa8fd --- /dev/null +++ b/lodash-es/assignWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const assignWith: typeof _.assignWith; +export default assignWith; diff --git a/lodash-es/at/index.d.ts b/lodash-es/at/index.d.ts new file mode 100644 index 0000000000..98ab16eb60 --- /dev/null +++ b/lodash-es/at/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const at: typeof _.at; +export default at; diff --git a/lodash-es/attempt/index.d.ts b/lodash-es/attempt/index.d.ts new file mode 100644 index 0000000000..c4a32846c3 --- /dev/null +++ b/lodash-es/attempt/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const attempt: typeof _.attempt; +export default attempt; diff --git a/lodash-es/before/index.d.ts b/lodash-es/before/index.d.ts new file mode 100644 index 0000000000..1051dbf013 --- /dev/null +++ b/lodash-es/before/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const before: typeof _.before; +export default before; diff --git a/lodash-es/bind/index.d.ts b/lodash-es/bind/index.d.ts new file mode 100644 index 0000000000..b19c3c3f1f --- /dev/null +++ b/lodash-es/bind/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const bind: typeof _.bind; +export default bind; diff --git a/lodash-es/bindAll/index.d.ts b/lodash-es/bindAll/index.d.ts new file mode 100644 index 0000000000..4b7c95f654 --- /dev/null +++ b/lodash-es/bindAll/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const bindAll: typeof _.bindAll; +export default bindAll; diff --git a/lodash-es/bindKey/index.d.ts b/lodash-es/bindKey/index.d.ts new file mode 100644 index 0000000000..c302459d1b --- /dev/null +++ b/lodash-es/bindKey/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const bindKey: typeof _.bindKey; +export default bindKey; diff --git a/lodash-es/camelCase/index.d.ts b/lodash-es/camelCase/index.d.ts new file mode 100644 index 0000000000..db927ef779 --- /dev/null +++ b/lodash-es/camelCase/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const camelCase: typeof _.camelCase; +export default camelCase; diff --git a/lodash-es/capitalize/index.d.ts b/lodash-es/capitalize/index.d.ts new file mode 100644 index 0000000000..bebe71e9b2 --- /dev/null +++ b/lodash-es/capitalize/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const capitalize: typeof _.capitalize; +export default capitalize; diff --git a/lodash-es/castArray/index.d.ts b/lodash-es/castArray/index.d.ts new file mode 100644 index 0000000000..8474b4b3fc --- /dev/null +++ b/lodash-es/castArray/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const castArray: typeof _.castArray; +export default castArray; diff --git a/lodash-es/ceil/index.d.ts b/lodash-es/ceil/index.d.ts new file mode 100644 index 0000000000..eaaefd5a42 --- /dev/null +++ b/lodash-es/ceil/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const ceil: typeof _.ceil; +export default ceil; diff --git a/lodash-es/chain/index.d.ts b/lodash-es/chain/index.d.ts new file mode 100644 index 0000000000..2bbc3fcb3d --- /dev/null +++ b/lodash-es/chain/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const chain: typeof _.chain; +export default chain; diff --git a/lodash-es/chunk/index.d.ts b/lodash-es/chunk/index.d.ts new file mode 100644 index 0000000000..7ee13fad50 --- /dev/null +++ b/lodash-es/chunk/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const chunk: typeof _.chunk; +export default chunk; diff --git a/lodash-es/clamp/index.d.ts b/lodash-es/clamp/index.d.ts new file mode 100644 index 0000000000..8994eb52bc --- /dev/null +++ b/lodash-es/clamp/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const clamp: typeof _.clamp; +export default clamp; diff --git a/lodash-es/clone/index.d.ts b/lodash-es/clone/index.d.ts new file mode 100644 index 0000000000..8792f93fe5 --- /dev/null +++ b/lodash-es/clone/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const clone: typeof _.clone; +export default clone; diff --git a/lodash-es/cloneDeep/index.d.ts b/lodash-es/cloneDeep/index.d.ts new file mode 100644 index 0000000000..bb86cf7c56 --- /dev/null +++ b/lodash-es/cloneDeep/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const cloneDeep: typeof _.cloneDeep; +export default cloneDeep; diff --git a/lodash-es/cloneDeepWith/index.d.ts b/lodash-es/cloneDeepWith/index.d.ts new file mode 100644 index 0000000000..0ad1b449b8 --- /dev/null +++ b/lodash-es/cloneDeepWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const cloneDeepWith: typeof _.cloneDeepWith; +export default cloneDeepWith; diff --git a/lodash-es/cloneWith/index.d.ts b/lodash-es/cloneWith/index.d.ts new file mode 100644 index 0000000000..ba865f9eeb --- /dev/null +++ b/lodash-es/cloneWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const cloneWith: typeof _.cloneWith; +export default cloneWith; diff --git a/lodash-es/compact/index.d.ts b/lodash-es/compact/index.d.ts new file mode 100644 index 0000000000..b11a162f5b --- /dev/null +++ b/lodash-es/compact/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const compact: typeof _.compact; +export default compact; diff --git a/lodash-es/concat/index.d.ts b/lodash-es/concat/index.d.ts new file mode 100644 index 0000000000..258c9648e8 --- /dev/null +++ b/lodash-es/concat/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const concat: typeof _.concat; +export default concat; diff --git a/lodash-es/constant/index.d.ts b/lodash-es/constant/index.d.ts new file mode 100644 index 0000000000..ff3bbc5ead --- /dev/null +++ b/lodash-es/constant/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const constant: typeof _.constant; +export default constant; diff --git a/lodash-es/countBy/index.d.ts b/lodash-es/countBy/index.d.ts new file mode 100644 index 0000000000..b02617bdce --- /dev/null +++ b/lodash-es/countBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const countBy: typeof _.countBy; +export default countBy; diff --git a/lodash-es/create/index.d.ts b/lodash-es/create/index.d.ts new file mode 100644 index 0000000000..eacab36ac2 --- /dev/null +++ b/lodash-es/create/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const create: typeof _.create; +export default create; diff --git a/lodash-es/curry/index.d.ts b/lodash-es/curry/index.d.ts new file mode 100644 index 0000000000..c7a929f9fd --- /dev/null +++ b/lodash-es/curry/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const curry: typeof _.curry; +export default curry; diff --git a/lodash-es/curryRight/index.d.ts b/lodash-es/curryRight/index.d.ts new file mode 100644 index 0000000000..2a5bb1cfe2 --- /dev/null +++ b/lodash-es/curryRight/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const curryRight: typeof _.curryRight; +export default curryRight; diff --git a/lodash-es/debounce/index.d.ts b/lodash-es/debounce/index.d.ts new file mode 100644 index 0000000000..cdb629b926 --- /dev/null +++ b/lodash-es/debounce/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const debounce: typeof _.debounce; +export default debounce; diff --git a/lodash-es/deburr/index.d.ts b/lodash-es/deburr/index.d.ts new file mode 100644 index 0000000000..e0112e772e --- /dev/null +++ b/lodash-es/deburr/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const deburr: typeof _.deburr; +export default deburr; diff --git a/lodash-es/defaults/index.d.ts b/lodash-es/defaults/index.d.ts new file mode 100644 index 0000000000..9a3a9135d2 --- /dev/null +++ b/lodash-es/defaults/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const defaults: typeof _.defaults; +export default defaults; diff --git a/lodash-es/defaultsDeep/index.d.ts b/lodash-es/defaultsDeep/index.d.ts new file mode 100644 index 0000000000..01da70c706 --- /dev/null +++ b/lodash-es/defaultsDeep/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const defaultsDeep: typeof _.defaultsDeep; +export default defaultsDeep; diff --git a/lodash-es/defer/index.d.ts b/lodash-es/defer/index.d.ts new file mode 100644 index 0000000000..098cdde130 --- /dev/null +++ b/lodash-es/defer/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const defer: typeof _.defer; +export default defer; diff --git a/lodash-es/delay/index.d.ts b/lodash-es/delay/index.d.ts new file mode 100644 index 0000000000..ff4b25b339 --- /dev/null +++ b/lodash-es/delay/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const delay: typeof _.delay; +export default delay; diff --git a/lodash-es/difference/index.d.ts b/lodash-es/difference/index.d.ts new file mode 100644 index 0000000000..ab23246e99 --- /dev/null +++ b/lodash-es/difference/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const difference: typeof _.difference; +export default difference; diff --git a/lodash-es/differenceBy/index.d.ts b/lodash-es/differenceBy/index.d.ts new file mode 100644 index 0000000000..ecadabb5d6 --- /dev/null +++ b/lodash-es/differenceBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const differenceBy: typeof _.differenceBy; +export default differenceBy; diff --git a/lodash-es/differenceWith/index.d.ts b/lodash-es/differenceWith/index.d.ts new file mode 100644 index 0000000000..6b1d91760d --- /dev/null +++ b/lodash-es/differenceWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const differenceWith: typeof _.differenceWith; +export default differenceWith; diff --git a/lodash-es/drop/index.d.ts b/lodash-es/drop/index.d.ts new file mode 100644 index 0000000000..3acb7ffda5 --- /dev/null +++ b/lodash-es/drop/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const drop: typeof _.drop; +export default drop; diff --git a/lodash-es/dropRight/index.d.ts b/lodash-es/dropRight/index.d.ts new file mode 100644 index 0000000000..8cbf725bba --- /dev/null +++ b/lodash-es/dropRight/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const dropRight: typeof _.dropRight; +export default dropRight; diff --git a/lodash-es/dropRightWhile/index.d.ts b/lodash-es/dropRightWhile/index.d.ts new file mode 100644 index 0000000000..a9c18bdde1 --- /dev/null +++ b/lodash-es/dropRightWhile/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const dropRightWhile: typeof _.dropRightWhile; +export default dropRightWhile; diff --git a/lodash-es/dropWhile/index.d.ts b/lodash-es/dropWhile/index.d.ts new file mode 100644 index 0000000000..74ad0c260b --- /dev/null +++ b/lodash-es/dropWhile/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const dropWhile: typeof _.dropWhile; +export default dropWhile; diff --git a/lodash-es/each/index.d.ts b/lodash-es/each/index.d.ts new file mode 100644 index 0000000000..ce8fe9ee6b --- /dev/null +++ b/lodash-es/each/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const each: typeof _.each; +export default each; diff --git a/lodash-es/eachRight/index.d.ts b/lodash-es/eachRight/index.d.ts new file mode 100644 index 0000000000..12160067fb --- /dev/null +++ b/lodash-es/eachRight/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const eachRight: typeof _.eachRight; +export default eachRight; diff --git a/lodash-es/endsWith/index.d.ts b/lodash-es/endsWith/index.d.ts new file mode 100644 index 0000000000..d17582a9ca --- /dev/null +++ b/lodash-es/endsWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const endsWith: typeof _.endsWith; +export default endsWith; diff --git a/lodash-es/eq/index.d.ts b/lodash-es/eq/index.d.ts new file mode 100644 index 0000000000..96b4028265 --- /dev/null +++ b/lodash-es/eq/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const eq: typeof _.eq; +export default eq; diff --git a/lodash-es/escape/index.d.ts b/lodash-es/escape/index.d.ts new file mode 100644 index 0000000000..7dfe42a59d --- /dev/null +++ b/lodash-es/escape/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const escape: typeof _.escape; +export default escape; diff --git a/lodash-es/escapeRegExp/index.d.ts b/lodash-es/escapeRegExp/index.d.ts new file mode 100644 index 0000000000..03a6c3b212 --- /dev/null +++ b/lodash-es/escapeRegExp/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const escapeRegExp: typeof _.escapeRegExp; +export default escapeRegExp; diff --git a/lodash-es/every/index.d.ts b/lodash-es/every/index.d.ts new file mode 100644 index 0000000000..f101e06ef1 --- /dev/null +++ b/lodash-es/every/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const every: typeof _.every; +export default every; diff --git a/lodash-es/extend/index.d.ts b/lodash-es/extend/index.d.ts new file mode 100644 index 0000000000..0fefaee444 --- /dev/null +++ b/lodash-es/extend/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const extend: typeof _.extend; +export default extend; diff --git a/lodash-es/extendWith/index.d.ts b/lodash-es/extendWith/index.d.ts new file mode 100644 index 0000000000..43f7f30a90 --- /dev/null +++ b/lodash-es/extendWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const extendWith: typeof _.extendWith; +export default extendWith; diff --git a/lodash-es/fb/index.d.ts b/lodash-es/fb/index.d.ts new file mode 100644 index 0000000000..9c0c66123e --- /dev/null +++ b/lodash-es/fb/index.d.ts @@ -0,0 +1,2 @@ +import * as _ from "lodash"; +export default _; diff --git a/lodash-es/fill/index.d.ts b/lodash-es/fill/index.d.ts new file mode 100644 index 0000000000..6cc7fcdb08 --- /dev/null +++ b/lodash-es/fill/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const fill: typeof _.fill; +export default fill; diff --git a/lodash-es/filter/index.d.ts b/lodash-es/filter/index.d.ts new file mode 100644 index 0000000000..4ef8e09dca --- /dev/null +++ b/lodash-es/filter/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const filter: typeof _.filter; +export default filter; diff --git a/lodash-es/find/index.d.ts b/lodash-es/find/index.d.ts new file mode 100644 index 0000000000..6d7f0ccf51 --- /dev/null +++ b/lodash-es/find/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const find: typeof _.find; +export default find; diff --git a/lodash-es/findIndex/index.d.ts b/lodash-es/findIndex/index.d.ts new file mode 100644 index 0000000000..618ad93d7d --- /dev/null +++ b/lodash-es/findIndex/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const findIndex: typeof _.findIndex; +export default findIndex; diff --git a/lodash-es/findKey/index.d.ts b/lodash-es/findKey/index.d.ts new file mode 100644 index 0000000000..370d80614f --- /dev/null +++ b/lodash-es/findKey/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const findKey: typeof _.findKey; +export default findKey; diff --git a/lodash-es/findLast/index.d.ts b/lodash-es/findLast/index.d.ts new file mode 100644 index 0000000000..e9e08d93c2 --- /dev/null +++ b/lodash-es/findLast/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const findLast: typeof _.findLast; +export default findLast; diff --git a/lodash-es/findLastIndex/index.d.ts b/lodash-es/findLastIndex/index.d.ts new file mode 100644 index 0000000000..a1fbecd823 --- /dev/null +++ b/lodash-es/findLastIndex/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const findLastIndex: typeof _.findLastIndex; +export default findLastIndex; diff --git a/lodash-es/findLastKey/index.d.ts b/lodash-es/findLastKey/index.d.ts new file mode 100644 index 0000000000..0e6e62fc91 --- /dev/null +++ b/lodash-es/findLastKey/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const findLastKey: typeof _.findLastKey; +export default findLastKey; diff --git a/lodash-es/first/index.d.ts b/lodash-es/first/index.d.ts new file mode 100644 index 0000000000..96e9c74f0a --- /dev/null +++ b/lodash-es/first/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const first: typeof _.first; +export default first; diff --git a/lodash-es/flatMap/index.d.ts b/lodash-es/flatMap/index.d.ts new file mode 100644 index 0000000000..76f335a594 --- /dev/null +++ b/lodash-es/flatMap/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const flatMap: typeof _.flatMap; +export default flatMap; diff --git a/lodash-es/flatten/index.d.ts b/lodash-es/flatten/index.d.ts new file mode 100644 index 0000000000..ddb4912ba9 --- /dev/null +++ b/lodash-es/flatten/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const flatten: typeof _.flatten; +export default flatten; diff --git a/lodash-es/flattenDeep/index.d.ts b/lodash-es/flattenDeep/index.d.ts new file mode 100644 index 0000000000..803f501f1e --- /dev/null +++ b/lodash-es/flattenDeep/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const flattenDeep: typeof _.flattenDeep; +export default flattenDeep; diff --git a/lodash-es/flattenDepth/index.d.ts b/lodash-es/flattenDepth/index.d.ts new file mode 100644 index 0000000000..245279040f --- /dev/null +++ b/lodash-es/flattenDepth/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const flattenDepth: typeof _.flattenDepth; +export default flattenDepth; diff --git a/lodash-es/flip/index.d.ts b/lodash-es/flip/index.d.ts new file mode 100644 index 0000000000..6cc5ecce00 --- /dev/null +++ b/lodash-es/flip/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const flip: typeof _.flip; +export default flip; diff --git a/lodash-es/floor/index.d.ts b/lodash-es/floor/index.d.ts new file mode 100644 index 0000000000..50f7092478 --- /dev/null +++ b/lodash-es/floor/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const floor: typeof _.floor; +export default floor; diff --git a/lodash-es/flow/index.d.ts b/lodash-es/flow/index.d.ts new file mode 100644 index 0000000000..908ed2e2c4 --- /dev/null +++ b/lodash-es/flow/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const flow: typeof _.flow; +export default flow; diff --git a/lodash-es/flowRight/index.d.ts b/lodash-es/flowRight/index.d.ts new file mode 100644 index 0000000000..c5f4158c80 --- /dev/null +++ b/lodash-es/flowRight/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const flowRight: typeof _.flowRight; +export default flowRight; diff --git a/lodash-es/forEach/index.d.ts b/lodash-es/forEach/index.d.ts new file mode 100644 index 0000000000..991075c50c --- /dev/null +++ b/lodash-es/forEach/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const forEach: typeof _.forEach; +export default forEach; diff --git a/lodash-es/forEachRight/index.d.ts b/lodash-es/forEachRight/index.d.ts new file mode 100644 index 0000000000..98e60667c2 --- /dev/null +++ b/lodash-es/forEachRight/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const forEachRight: typeof _.forEachRight; +export default forEachRight; diff --git a/lodash-es/forIn/index.d.ts b/lodash-es/forIn/index.d.ts new file mode 100644 index 0000000000..b94adeb90b --- /dev/null +++ b/lodash-es/forIn/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const forIn: typeof _.forIn; +export default forIn; diff --git a/lodash-es/forInRight/index.d.ts b/lodash-es/forInRight/index.d.ts new file mode 100644 index 0000000000..ae7257e4b6 --- /dev/null +++ b/lodash-es/forInRight/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const forInRight: typeof _.forInRight; +export default forInRight; diff --git a/lodash-es/forOwn/index.d.ts b/lodash-es/forOwn/index.d.ts new file mode 100644 index 0000000000..9c206fd5a9 --- /dev/null +++ b/lodash-es/forOwn/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const forOwn: typeof _.forOwn; +export default forOwn; diff --git a/lodash-es/forOwnRight/index.d.ts b/lodash-es/forOwnRight/index.d.ts new file mode 100644 index 0000000000..5874b6c70e --- /dev/null +++ b/lodash-es/forOwnRight/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const forOwnRight: typeof _.forOwnRight; +export default forOwnRight; diff --git a/lodash-es/fromPairs/index.d.ts b/lodash-es/fromPairs/index.d.ts new file mode 100644 index 0000000000..a6446bff6f --- /dev/null +++ b/lodash-es/fromPairs/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const fromPairs: typeof _.fromPairs; +export default fromPairs; diff --git a/lodash-es/functions/index.d.ts b/lodash-es/functions/index.d.ts new file mode 100644 index 0000000000..18f6e34ce3 --- /dev/null +++ b/lodash-es/functions/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const functions: typeof _.functions; +export default functions; diff --git a/lodash-es/functionsIn/index.d.ts b/lodash-es/functionsIn/index.d.ts new file mode 100644 index 0000000000..b702c836ae --- /dev/null +++ b/lodash-es/functionsIn/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const functionsIn: typeof _.functionsIn; +export default functionsIn; diff --git a/lodash-es/get/index.d.ts b/lodash-es/get/index.d.ts new file mode 100644 index 0000000000..6a20d96558 --- /dev/null +++ b/lodash-es/get/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const get: typeof _.get; +export default get; diff --git a/lodash-es/groupBy/index.d.ts b/lodash-es/groupBy/index.d.ts new file mode 100644 index 0000000000..df50c25eeb --- /dev/null +++ b/lodash-es/groupBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const groupBy: typeof _.groupBy; +export default groupBy; diff --git a/lodash-es/gt/index.d.ts b/lodash-es/gt/index.d.ts new file mode 100644 index 0000000000..ae4e05da15 --- /dev/null +++ b/lodash-es/gt/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const gt: typeof _.gt; +export default gt; diff --git a/lodash-es/gte/index.d.ts b/lodash-es/gte/index.d.ts new file mode 100644 index 0000000000..49aeca418a --- /dev/null +++ b/lodash-es/gte/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const gte: typeof _.gte; +export default gte; diff --git a/lodash-es/has/index.d.ts b/lodash-es/has/index.d.ts new file mode 100644 index 0000000000..d8ef1a756c --- /dev/null +++ b/lodash-es/has/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const has: typeof _.has; +export default has; diff --git a/lodash-es/hasIn/index.d.ts b/lodash-es/hasIn/index.d.ts new file mode 100644 index 0000000000..5451c19bc9 --- /dev/null +++ b/lodash-es/hasIn/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const hasIn: typeof _.hasIn; +export default hasIn; diff --git a/lodash-es/head/index.d.ts b/lodash-es/head/index.d.ts new file mode 100644 index 0000000000..af8323559a --- /dev/null +++ b/lodash-es/head/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const head: typeof _.head; +export default head; diff --git a/lodash-es/identity/index.d.ts b/lodash-es/identity/index.d.ts new file mode 100644 index 0000000000..4933422107 --- /dev/null +++ b/lodash-es/identity/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const identity: typeof _.identity; +export default identity; diff --git a/lodash-es/inRange/index.d.ts b/lodash-es/inRange/index.d.ts new file mode 100644 index 0000000000..4c3e56ddf9 --- /dev/null +++ b/lodash-es/inRange/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const inRange: typeof _.inRange; +export default inRange; diff --git a/lodash-es/includes/index.d.ts b/lodash-es/includes/index.d.ts new file mode 100644 index 0000000000..09c694b13a --- /dev/null +++ b/lodash-es/includes/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const includes: typeof _.includes; +export default includes; diff --git a/lodash-es/index.d.ts b/lodash-es/index.d.ts new file mode 100644 index 0000000000..71f98587ff --- /dev/null +++ b/lodash-es/index.d.ts @@ -0,0 +1,4 @@ +// Type definitions for Lo-Dash-es 4.14 +// Project: http://lodash.com/ +// Definitions by: Stephen Lautier +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/lodash-es/indexOf/index.d.ts b/lodash-es/indexOf/index.d.ts new file mode 100644 index 0000000000..e10f425449 --- /dev/null +++ b/lodash-es/indexOf/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const indexOf: typeof _.indexOf; +export default indexOf; diff --git a/lodash-es/initial/index.d.ts b/lodash-es/initial/index.d.ts new file mode 100644 index 0000000000..e853918f3d --- /dev/null +++ b/lodash-es/initial/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const initial: typeof _.initial; +export default initial; diff --git a/lodash-es/intersection/index.d.ts b/lodash-es/intersection/index.d.ts new file mode 100644 index 0000000000..8c92aa0c98 --- /dev/null +++ b/lodash-es/intersection/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const intersection: typeof _.intersection; +export default intersection; diff --git a/lodash-es/intersectionBy/index.d.ts b/lodash-es/intersectionBy/index.d.ts new file mode 100644 index 0000000000..ec19a42859 --- /dev/null +++ b/lodash-es/intersectionBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const intersectionBy: typeof _.intersectionBy; +export default intersectionBy; diff --git a/lodash-es/intersectionWith/index.d.ts b/lodash-es/intersectionWith/index.d.ts new file mode 100644 index 0000000000..19bc6f5e3e --- /dev/null +++ b/lodash-es/intersectionWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const intersectionWith: typeof _.intersectionWith; +export default intersectionWith; diff --git a/lodash-es/invert/index.d.ts b/lodash-es/invert/index.d.ts new file mode 100644 index 0000000000..8cdab06a08 --- /dev/null +++ b/lodash-es/invert/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const invert: typeof _.invert; +export default invert; diff --git a/lodash-es/invertBy/index.d.ts b/lodash-es/invertBy/index.d.ts new file mode 100644 index 0000000000..c2e414940f --- /dev/null +++ b/lodash-es/invertBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const invertBy: typeof _.invertBy; +export default invertBy; diff --git a/lodash-es/invoke/index.d.ts b/lodash-es/invoke/index.d.ts new file mode 100644 index 0000000000..acd47aee19 --- /dev/null +++ b/lodash-es/invoke/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const invoke: typeof _.invoke; +export default invoke; diff --git a/lodash-es/invokeMap/index.d.ts b/lodash-es/invokeMap/index.d.ts new file mode 100644 index 0000000000..7f25853341 --- /dev/null +++ b/lodash-es/invokeMap/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const invokeMap: typeof _.invokeMap; +export default invokeMap; diff --git a/lodash-es/isArguments/index.d.ts b/lodash-es/isArguments/index.d.ts new file mode 100644 index 0000000000..ea8d55a68a --- /dev/null +++ b/lodash-es/isArguments/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isArguments: typeof _.isArguments; +export default isArguments; diff --git a/lodash-es/isArray/index.d.ts b/lodash-es/isArray/index.d.ts new file mode 100644 index 0000000000..e34b49878f --- /dev/null +++ b/lodash-es/isArray/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isArray: typeof _.isArray; +export default isArray; diff --git a/lodash-es/isArrayBuffer/index.d.ts b/lodash-es/isArrayBuffer/index.d.ts new file mode 100644 index 0000000000..ccd71b7775 --- /dev/null +++ b/lodash-es/isArrayBuffer/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isArrayBuffer: typeof _.isArrayBuffer; +export default isArrayBuffer; diff --git a/lodash-es/isArrayLike/index.d.ts b/lodash-es/isArrayLike/index.d.ts new file mode 100644 index 0000000000..3b42bbbc5c --- /dev/null +++ b/lodash-es/isArrayLike/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isArrayLike: typeof _.isArrayLike; +export default isArrayLike; diff --git a/lodash-es/isArrayLikeObject/index.d.ts b/lodash-es/isArrayLikeObject/index.d.ts new file mode 100644 index 0000000000..ea85e10017 --- /dev/null +++ b/lodash-es/isArrayLikeObject/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isArrayLikeObject: typeof _.isArrayLikeObject; +export default isArrayLikeObject; diff --git a/lodash-es/isBoolean/index.d.ts b/lodash-es/isBoolean/index.d.ts new file mode 100644 index 0000000000..65664f062b --- /dev/null +++ b/lodash-es/isBoolean/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isBoolean: typeof _.isBoolean; +export default isBoolean; diff --git a/lodash-es/isBuffer/index.d.ts b/lodash-es/isBuffer/index.d.ts new file mode 100644 index 0000000000..c3c32dea99 --- /dev/null +++ b/lodash-es/isBuffer/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isBuffer: typeof _.isBuffer; +export default isBuffer; diff --git a/lodash-es/isDate/index.d.ts b/lodash-es/isDate/index.d.ts new file mode 100644 index 0000000000..4f920c8c3f --- /dev/null +++ b/lodash-es/isDate/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isDate: typeof _.isDate; +export default isDate; diff --git a/lodash-es/isElement/index.d.ts b/lodash-es/isElement/index.d.ts new file mode 100644 index 0000000000..ea66ae6347 --- /dev/null +++ b/lodash-es/isElement/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isElement: typeof _.isElement; +export default isElement; diff --git a/lodash-es/isEmpty/index.d.ts b/lodash-es/isEmpty/index.d.ts new file mode 100644 index 0000000000..b8b4b87447 --- /dev/null +++ b/lodash-es/isEmpty/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isEmpty: typeof _.isEmpty; +export default isEmpty; diff --git a/lodash-es/isEqual/index.d.ts b/lodash-es/isEqual/index.d.ts new file mode 100644 index 0000000000..83e1f70e6f --- /dev/null +++ b/lodash-es/isEqual/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isEqual: typeof _.isEqual; +export default isEqual; diff --git a/lodash-es/isEqualWith/index.d.ts b/lodash-es/isEqualWith/index.d.ts new file mode 100644 index 0000000000..945a683116 --- /dev/null +++ b/lodash-es/isEqualWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isEqualWith: typeof _.isEqualWith; +export default isEqualWith; diff --git a/lodash-es/isError/index.d.ts b/lodash-es/isError/index.d.ts new file mode 100644 index 0000000000..46485d9e7c --- /dev/null +++ b/lodash-es/isError/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isError: typeof _.isError; +export default isError; diff --git a/lodash-es/isFinite/index.d.ts b/lodash-es/isFinite/index.d.ts new file mode 100644 index 0000000000..62507f7e1e --- /dev/null +++ b/lodash-es/isFinite/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isFinite: typeof _.isFinite; +export default isFinite; diff --git a/lodash-es/isFunction/index.d.ts b/lodash-es/isFunction/index.d.ts new file mode 100644 index 0000000000..3b66cce932 --- /dev/null +++ b/lodash-es/isFunction/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isFunction: typeof _.isFunction; +export default isFunction; diff --git a/lodash-es/isInteger/index.d.ts b/lodash-es/isInteger/index.d.ts new file mode 100644 index 0000000000..857fed396f --- /dev/null +++ b/lodash-es/isInteger/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isInteger: typeof _.isInteger; +export default isInteger; diff --git a/lodash-es/isLength/index.d.ts b/lodash-es/isLength/index.d.ts new file mode 100644 index 0000000000..3a7debd966 --- /dev/null +++ b/lodash-es/isLength/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isLength: typeof _.isLength; +export default isLength; diff --git a/lodash-es/isMap/index.d.ts b/lodash-es/isMap/index.d.ts new file mode 100644 index 0000000000..d17daa5740 --- /dev/null +++ b/lodash-es/isMap/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isMap: typeof _.isMap; +export default isMap; diff --git a/lodash-es/isMatch/index.d.ts b/lodash-es/isMatch/index.d.ts new file mode 100644 index 0000000000..90a940554d --- /dev/null +++ b/lodash-es/isMatch/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isMatch: typeof _.isMatch; +export default isMatch; diff --git a/lodash-es/isMatchWith/index.d.ts b/lodash-es/isMatchWith/index.d.ts new file mode 100644 index 0000000000..317ce04315 --- /dev/null +++ b/lodash-es/isMatchWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isMatchWith: typeof _.isMatchWith; +export default isMatchWith; diff --git a/lodash-es/isNaN/index.d.ts b/lodash-es/isNaN/index.d.ts new file mode 100644 index 0000000000..c1c5d06d51 --- /dev/null +++ b/lodash-es/isNaN/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isNaN: typeof _.isNaN; +export default isNaN; diff --git a/lodash-es/isNative/index.d.ts b/lodash-es/isNative/index.d.ts new file mode 100644 index 0000000000..08ee2fc1fd --- /dev/null +++ b/lodash-es/isNative/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isNative: typeof _.isNative; +export default isNative; diff --git a/lodash-es/isNil/index.d.ts b/lodash-es/isNil/index.d.ts new file mode 100644 index 0000000000..25bfaedac2 --- /dev/null +++ b/lodash-es/isNil/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isNil: typeof _.isNil; +export default isNil; diff --git a/lodash-es/isNull/index.d.ts b/lodash-es/isNull/index.d.ts new file mode 100644 index 0000000000..7e9c46de33 --- /dev/null +++ b/lodash-es/isNull/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isNull: typeof _.isNull; +export default isNull; diff --git a/lodash-es/isNumber/index.d.ts b/lodash-es/isNumber/index.d.ts new file mode 100644 index 0000000000..1079a60fef --- /dev/null +++ b/lodash-es/isNumber/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isNumber: typeof _.isNumber; +export default isNumber; diff --git a/lodash-es/isObject/index.d.ts b/lodash-es/isObject/index.d.ts new file mode 100644 index 0000000000..ea6ace66a8 --- /dev/null +++ b/lodash-es/isObject/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isObject: typeof _.isObject; +export default isObject; diff --git a/lodash-es/isObjectLike/index.d.ts b/lodash-es/isObjectLike/index.d.ts new file mode 100644 index 0000000000..3851d0959f --- /dev/null +++ b/lodash-es/isObjectLike/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isObjectLike: typeof _.isObjectLike; +export default isObjectLike; diff --git a/lodash-es/isPlainObject/index.d.ts b/lodash-es/isPlainObject/index.d.ts new file mode 100644 index 0000000000..0c855f6c47 --- /dev/null +++ b/lodash-es/isPlainObject/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isPlainObject: typeof _.isPlainObject; +export default isPlainObject; diff --git a/lodash-es/isRegExp/index.d.ts b/lodash-es/isRegExp/index.d.ts new file mode 100644 index 0000000000..7408b0ed3b --- /dev/null +++ b/lodash-es/isRegExp/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isRegExp: typeof _.isRegExp; +export default isRegExp; diff --git a/lodash-es/isSafeInteger/index.d.ts b/lodash-es/isSafeInteger/index.d.ts new file mode 100644 index 0000000000..4ed7f6416e --- /dev/null +++ b/lodash-es/isSafeInteger/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isSafeInteger: typeof _.isSafeInteger; +export default isSafeInteger; diff --git a/lodash-es/isSet/index.d.ts b/lodash-es/isSet/index.d.ts new file mode 100644 index 0000000000..40e4fc4ba5 --- /dev/null +++ b/lodash-es/isSet/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isSet: typeof _.isSet; +export default isSet; diff --git a/lodash-es/isString/index.d.ts b/lodash-es/isString/index.d.ts new file mode 100644 index 0000000000..d00c2c7f83 --- /dev/null +++ b/lodash-es/isString/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isString: typeof _.isString; +export default isString; diff --git a/lodash-es/isSymbol/index.d.ts b/lodash-es/isSymbol/index.d.ts new file mode 100644 index 0000000000..a3e43f8327 --- /dev/null +++ b/lodash-es/isSymbol/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isSymbol: typeof _.isSymbol; +export default isSymbol; diff --git a/lodash-es/isTypedArray/index.d.ts b/lodash-es/isTypedArray/index.d.ts new file mode 100644 index 0000000000..5b37a9ff0d --- /dev/null +++ b/lodash-es/isTypedArray/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isTypedArray: typeof _.isTypedArray; +export default isTypedArray; diff --git a/lodash-es/isUndefined/index.d.ts b/lodash-es/isUndefined/index.d.ts new file mode 100644 index 0000000000..a2ad3eab25 --- /dev/null +++ b/lodash-es/isUndefined/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isUndefined: typeof _.isUndefined; +export default isUndefined; diff --git a/lodash-es/isWeakMap/index.d.ts b/lodash-es/isWeakMap/index.d.ts new file mode 100644 index 0000000000..5115411a83 --- /dev/null +++ b/lodash-es/isWeakMap/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isWeakMap: typeof _.isWeakMap; +export default isWeakMap; diff --git a/lodash-es/isWeakSet/index.d.ts b/lodash-es/isWeakSet/index.d.ts new file mode 100644 index 0000000000..fffa232347 --- /dev/null +++ b/lodash-es/isWeakSet/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const isWeakSet: typeof _.isWeakSet; +export default isWeakSet; diff --git a/lodash-es/iteratee/index.d.ts b/lodash-es/iteratee/index.d.ts new file mode 100644 index 0000000000..bc3670a417 --- /dev/null +++ b/lodash-es/iteratee/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const iteratee: typeof _.iteratee; +export default iteratee; diff --git a/lodash-es/join/index.d.ts b/lodash-es/join/index.d.ts new file mode 100644 index 0000000000..5400a8a009 --- /dev/null +++ b/lodash-es/join/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const join: typeof _.join; +export default join; diff --git a/lodash-es/kebabCase/index.d.ts b/lodash-es/kebabCase/index.d.ts new file mode 100644 index 0000000000..f49f33dbf5 --- /dev/null +++ b/lodash-es/kebabCase/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const kebabCase: typeof _.kebabCase; +export default kebabCase; diff --git a/lodash-es/keyBy/index.d.ts b/lodash-es/keyBy/index.d.ts new file mode 100644 index 0000000000..676c034dcb --- /dev/null +++ b/lodash-es/keyBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const keyBy: typeof _.keyBy; +export default keyBy; diff --git a/lodash-es/keys/index.d.ts b/lodash-es/keys/index.d.ts new file mode 100644 index 0000000000..3a947b7243 --- /dev/null +++ b/lodash-es/keys/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const keys: typeof _.keys; +export default keys; diff --git a/lodash-es/keysIn/index.d.ts b/lodash-es/keysIn/index.d.ts new file mode 100644 index 0000000000..4fe392a6f7 --- /dev/null +++ b/lodash-es/keysIn/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const keysIn: typeof _.keysIn; +export default keysIn; diff --git a/lodash-es/last/index.d.ts b/lodash-es/last/index.d.ts new file mode 100644 index 0000000000..db4784da60 --- /dev/null +++ b/lodash-es/last/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const last: typeof _.last; +export default last; diff --git a/lodash-es/lastIndexOf/index.d.ts b/lodash-es/lastIndexOf/index.d.ts new file mode 100644 index 0000000000..43a17a6a21 --- /dev/null +++ b/lodash-es/lastIndexOf/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const lastIndexOf: typeof _.lastIndexOf; +export default lastIndexOf; diff --git a/lodash-es/lodash-es-tests.ts b/lodash-es/lodash-es-tests.ts new file mode 100644 index 0000000000..f849e811b6 --- /dev/null +++ b/lodash-es/lodash-es-tests.ts @@ -0,0 +1,3 @@ +import kebabCase from "lodash-es/kebabCase"; + +kebabCase("chickenWings"); diff --git a/lodash-es/lowerCase/index.d.ts b/lodash-es/lowerCase/index.d.ts new file mode 100644 index 0000000000..11f4bf8e90 --- /dev/null +++ b/lodash-es/lowerCase/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const lowerCase: typeof _.lowerCase; +export default lowerCase; diff --git a/lodash-es/lowerFirst/index.d.ts b/lodash-es/lowerFirst/index.d.ts new file mode 100644 index 0000000000..3b6950f527 --- /dev/null +++ b/lodash-es/lowerFirst/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const lowerFirst: typeof _.lowerFirst; +export default lowerFirst; diff --git a/lodash-es/lt/index.d.ts b/lodash-es/lt/index.d.ts new file mode 100644 index 0000000000..d16db45df9 --- /dev/null +++ b/lodash-es/lt/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const lt: typeof _.lt; +export default lt; diff --git a/lodash-es/lte/index.d.ts b/lodash-es/lte/index.d.ts new file mode 100644 index 0000000000..0f8c1b6eb8 --- /dev/null +++ b/lodash-es/lte/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const lte: typeof _.lte; +export default lte; diff --git a/lodash-es/map/index.d.ts b/lodash-es/map/index.d.ts new file mode 100644 index 0000000000..230189f901 --- /dev/null +++ b/lodash-es/map/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const map: typeof _.map; +export default map; diff --git a/lodash-es/mapKeys/index.d.ts b/lodash-es/mapKeys/index.d.ts new file mode 100644 index 0000000000..75c092904a --- /dev/null +++ b/lodash-es/mapKeys/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const mapKeys: typeof _.mapKeys; +export default mapKeys; diff --git a/lodash-es/mapValues/index.d.ts b/lodash-es/mapValues/index.d.ts new file mode 100644 index 0000000000..e94fe54ea4 --- /dev/null +++ b/lodash-es/mapValues/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const mapValues: typeof _.mapValues; +export default mapValues; diff --git a/lodash-es/matches/index.d.ts b/lodash-es/matches/index.d.ts new file mode 100644 index 0000000000..3649b1f816 --- /dev/null +++ b/lodash-es/matches/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const matches: typeof _.matches; +export default matches; diff --git a/lodash-es/matchesProperty/index.d.ts b/lodash-es/matchesProperty/index.d.ts new file mode 100644 index 0000000000..05c4214254 --- /dev/null +++ b/lodash-es/matchesProperty/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const matchesProperty: typeof _.matchesProperty; +export default matchesProperty; diff --git a/lodash-es/max/index.d.ts b/lodash-es/max/index.d.ts new file mode 100644 index 0000000000..5c3ecefa58 --- /dev/null +++ b/lodash-es/max/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const max: typeof _.max; +export default max; diff --git a/lodash-es/maxBy/index.d.ts b/lodash-es/maxBy/index.d.ts new file mode 100644 index 0000000000..891a6adc51 --- /dev/null +++ b/lodash-es/maxBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const maxBy: typeof _.maxBy; +export default maxBy; diff --git a/lodash-es/mean/index.d.ts b/lodash-es/mean/index.d.ts new file mode 100644 index 0000000000..4748a5b68c --- /dev/null +++ b/lodash-es/mean/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const mean: typeof _.mean; +export default mean; diff --git a/lodash-es/meanBy/index.d.ts b/lodash-es/meanBy/index.d.ts new file mode 100644 index 0000000000..98bb386726 --- /dev/null +++ b/lodash-es/meanBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const meanBy: typeof _.meanBy; +export default meanBy; diff --git a/lodash-es/memoize/index.d.ts b/lodash-es/memoize/index.d.ts new file mode 100644 index 0000000000..6f04797611 --- /dev/null +++ b/lodash-es/memoize/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const memoize: typeof _.memoize; +export default memoize; diff --git a/lodash-es/merge/index.d.ts b/lodash-es/merge/index.d.ts new file mode 100644 index 0000000000..857c5c3492 --- /dev/null +++ b/lodash-es/merge/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const merge: typeof _.merge; +export default merge; diff --git a/lodash-es/mergeWith/index.d.ts b/lodash-es/mergeWith/index.d.ts new file mode 100644 index 0000000000..6e80ad3a61 --- /dev/null +++ b/lodash-es/mergeWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const mergeWith: typeof _.mergeWith; +export default mergeWith; diff --git a/lodash-es/method/index.d.ts b/lodash-es/method/index.d.ts new file mode 100644 index 0000000000..258566af88 --- /dev/null +++ b/lodash-es/method/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const method: typeof _.method; +export default method; diff --git a/lodash-es/methodOf/index.d.ts b/lodash-es/methodOf/index.d.ts new file mode 100644 index 0000000000..3f106fa75a --- /dev/null +++ b/lodash-es/methodOf/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const methodOf: typeof _.methodOf; +export default methodOf; diff --git a/lodash-es/min/index.d.ts b/lodash-es/min/index.d.ts new file mode 100644 index 0000000000..bef0c59653 --- /dev/null +++ b/lodash-es/min/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const min: typeof _.min; +export default min; diff --git a/lodash-es/minBy/index.d.ts b/lodash-es/minBy/index.d.ts new file mode 100644 index 0000000000..61524b8636 --- /dev/null +++ b/lodash-es/minBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const minBy: typeof _.minBy; +export default minBy; diff --git a/lodash-es/mixin/index.d.ts b/lodash-es/mixin/index.d.ts new file mode 100644 index 0000000000..a4c1570442 --- /dev/null +++ b/lodash-es/mixin/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const mixin: typeof _.mixin; +export default mixin; diff --git a/lodash-es/negate/index.d.ts b/lodash-es/negate/index.d.ts new file mode 100644 index 0000000000..9062ca2344 --- /dev/null +++ b/lodash-es/negate/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const negate: typeof _.negate; +export default negate; diff --git a/lodash-es/noConflict/index.d.ts b/lodash-es/noConflict/index.d.ts new file mode 100644 index 0000000000..f3dc804e22 --- /dev/null +++ b/lodash-es/noConflict/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const noConflict: typeof _.noConflict; +export default noConflict; diff --git a/lodash-es/noop/index.d.ts b/lodash-es/noop/index.d.ts new file mode 100644 index 0000000000..54ddded976 --- /dev/null +++ b/lodash-es/noop/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const noop: typeof _.noop; +export default noop; diff --git a/lodash-es/now/index.d.ts b/lodash-es/now/index.d.ts new file mode 100644 index 0000000000..09b6facb97 --- /dev/null +++ b/lodash-es/now/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const now: typeof _.now; +export default now; diff --git a/lodash-es/nthArg/index.d.ts b/lodash-es/nthArg/index.d.ts new file mode 100644 index 0000000000..a4ece20ba0 --- /dev/null +++ b/lodash-es/nthArg/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const nthArg: typeof _.nthArg; +export default nthArg; diff --git a/lodash-es/omit/index.d.ts b/lodash-es/omit/index.d.ts new file mode 100644 index 0000000000..ff29ac332a --- /dev/null +++ b/lodash-es/omit/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const omit: typeof _.omit; +export default omit; diff --git a/lodash-es/omitBy/index.d.ts b/lodash-es/omitBy/index.d.ts new file mode 100644 index 0000000000..629fd47b0c --- /dev/null +++ b/lodash-es/omitBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const omitBy: typeof _.omitBy; +export default omitBy; diff --git a/lodash-es/once/index.d.ts b/lodash-es/once/index.d.ts new file mode 100644 index 0000000000..f6176c1577 --- /dev/null +++ b/lodash-es/once/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const once: typeof _.once; +export default once; diff --git a/lodash-es/orderBy/index.d.ts b/lodash-es/orderBy/index.d.ts new file mode 100644 index 0000000000..90928d3740 --- /dev/null +++ b/lodash-es/orderBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const orderBy: typeof _.orderBy; +export default orderBy; diff --git a/lodash-es/over/index.d.ts b/lodash-es/over/index.d.ts new file mode 100644 index 0000000000..97e8c56335 --- /dev/null +++ b/lodash-es/over/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const over: typeof _.over; +export default over; diff --git a/lodash-es/overArgs/index.d.ts b/lodash-es/overArgs/index.d.ts new file mode 100644 index 0000000000..c6bf86aaee --- /dev/null +++ b/lodash-es/overArgs/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const overArgs: typeof _.overArgs; +export default overArgs; diff --git a/lodash-es/overEvery/index.d.ts b/lodash-es/overEvery/index.d.ts new file mode 100644 index 0000000000..4d8bf3ac98 --- /dev/null +++ b/lodash-es/overEvery/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const overEvery: typeof _.overEvery; +export default overEvery; diff --git a/lodash-es/overSome/index.d.ts b/lodash-es/overSome/index.d.ts new file mode 100644 index 0000000000..6dcd9365a8 --- /dev/null +++ b/lodash-es/overSome/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const overSome: typeof _.overSome; +export default overSome; diff --git a/lodash-es/package.json b/lodash-es/package.json new file mode 100644 index 0000000000..27f0917342 --- /dev/null +++ b/lodash-es/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "lodash": ">=4.14.0" + } +} diff --git a/lodash-es/pad/index.d.ts b/lodash-es/pad/index.d.ts new file mode 100644 index 0000000000..cf433d4663 --- /dev/null +++ b/lodash-es/pad/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const pad: typeof _.pad; +export default pad; diff --git a/lodash-es/padEnd/index.d.ts b/lodash-es/padEnd/index.d.ts new file mode 100644 index 0000000000..701b09551d --- /dev/null +++ b/lodash-es/padEnd/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const padEnd: typeof _.padEnd; +export default padEnd; diff --git a/lodash-es/padStart/index.d.ts b/lodash-es/padStart/index.d.ts new file mode 100644 index 0000000000..be4d29907a --- /dev/null +++ b/lodash-es/padStart/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const padStart: typeof _.padStart; +export default padStart; diff --git a/lodash-es/parseInt/index.d.ts b/lodash-es/parseInt/index.d.ts new file mode 100644 index 0000000000..ea95ce55f4 --- /dev/null +++ b/lodash-es/parseInt/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const parseInt: typeof _.parseInt; +export default parseInt; diff --git a/lodash-es/partial/index.d.ts b/lodash-es/partial/index.d.ts new file mode 100644 index 0000000000..b87c82b07a --- /dev/null +++ b/lodash-es/partial/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const partial: typeof _.partial; +export default partial; diff --git a/lodash-es/partialRight/index.d.ts b/lodash-es/partialRight/index.d.ts new file mode 100644 index 0000000000..893f6541a6 --- /dev/null +++ b/lodash-es/partialRight/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const partialRight: typeof _.partialRight; +export default partialRight; diff --git a/lodash-es/partition/index.d.ts b/lodash-es/partition/index.d.ts new file mode 100644 index 0000000000..54c7aedd2f --- /dev/null +++ b/lodash-es/partition/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const partition: typeof _.partition; +export default partition; diff --git a/lodash-es/pick/index.d.ts b/lodash-es/pick/index.d.ts new file mode 100644 index 0000000000..7ed39cfd45 --- /dev/null +++ b/lodash-es/pick/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const pick: typeof _.pick; +export default pick; diff --git a/lodash-es/pickBy/index.d.ts b/lodash-es/pickBy/index.d.ts new file mode 100644 index 0000000000..c37adcc1e5 --- /dev/null +++ b/lodash-es/pickBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const pickBy: typeof _.pickBy; +export default pickBy; diff --git a/lodash-es/property/index.d.ts b/lodash-es/property/index.d.ts new file mode 100644 index 0000000000..fbb31e52b9 --- /dev/null +++ b/lodash-es/property/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const property: typeof _.property; +export default property; diff --git a/lodash-es/propertyOf/index.d.ts b/lodash-es/propertyOf/index.d.ts new file mode 100644 index 0000000000..27da14daad --- /dev/null +++ b/lodash-es/propertyOf/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const propertyOf: typeof _.propertyOf; +export default propertyOf; diff --git a/lodash-es/pull/index.d.ts b/lodash-es/pull/index.d.ts new file mode 100644 index 0000000000..6c959cf61e --- /dev/null +++ b/lodash-es/pull/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const pull: typeof _.pull; +export default pull; diff --git a/lodash-es/pullAll/index.d.ts b/lodash-es/pullAll/index.d.ts new file mode 100644 index 0000000000..c37b1d0f94 --- /dev/null +++ b/lodash-es/pullAll/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const pullAll: typeof _.pullAll; +export default pullAll; diff --git a/lodash-es/pullAllBy/index.d.ts b/lodash-es/pullAllBy/index.d.ts new file mode 100644 index 0000000000..c8fe2e16bf --- /dev/null +++ b/lodash-es/pullAllBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const pullAllBy: typeof _.pullAllBy; +export default pullAllBy; diff --git a/lodash-es/pullAt/index.d.ts b/lodash-es/pullAt/index.d.ts new file mode 100644 index 0000000000..15c3e2a377 --- /dev/null +++ b/lodash-es/pullAt/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const pullAt: typeof _.pullAt; +export default pullAt; diff --git a/lodash-es/random/index.d.ts b/lodash-es/random/index.d.ts new file mode 100644 index 0000000000..426f56ddef --- /dev/null +++ b/lodash-es/random/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const random: typeof _.random; +export default random; diff --git a/lodash-es/range/index.d.ts b/lodash-es/range/index.d.ts new file mode 100644 index 0000000000..cb18402b59 --- /dev/null +++ b/lodash-es/range/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const range: typeof _.range; +export default range; diff --git a/lodash-es/rangeRight/index.d.ts b/lodash-es/rangeRight/index.d.ts new file mode 100644 index 0000000000..e515dba52b --- /dev/null +++ b/lodash-es/rangeRight/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const rangeRight: typeof _.rangeRight; +export default rangeRight; diff --git a/lodash-es/rearg/index.d.ts b/lodash-es/rearg/index.d.ts new file mode 100644 index 0000000000..e446584d67 --- /dev/null +++ b/lodash-es/rearg/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const rearg: typeof _.rearg; +export default rearg; diff --git a/lodash-es/reduce/index.d.ts b/lodash-es/reduce/index.d.ts new file mode 100644 index 0000000000..4144ae4daa --- /dev/null +++ b/lodash-es/reduce/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const reduce: typeof _.reduce; +export default reduce; diff --git a/lodash-es/reduceRight/index.d.ts b/lodash-es/reduceRight/index.d.ts new file mode 100644 index 0000000000..50953f7228 --- /dev/null +++ b/lodash-es/reduceRight/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const reduceRight: typeof _.reduceRight; +export default reduceRight; diff --git a/lodash-es/reject/index.d.ts b/lodash-es/reject/index.d.ts new file mode 100644 index 0000000000..73812df5fe --- /dev/null +++ b/lodash-es/reject/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const reject: typeof _.reject; +export default reject; diff --git a/lodash-es/remove/index.d.ts b/lodash-es/remove/index.d.ts new file mode 100644 index 0000000000..41a78b2389 --- /dev/null +++ b/lodash-es/remove/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const remove: typeof _.remove; +export default remove; diff --git a/lodash-es/repeat/index.d.ts b/lodash-es/repeat/index.d.ts new file mode 100644 index 0000000000..64d2507d01 --- /dev/null +++ b/lodash-es/repeat/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const repeat: typeof _.repeat; +export default repeat; diff --git a/lodash-es/replace/index.d.ts b/lodash-es/replace/index.d.ts new file mode 100644 index 0000000000..cc35b2043b --- /dev/null +++ b/lodash-es/replace/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const replace: typeof _.replace; +export default replace; diff --git a/lodash-es/rest/index.d.ts b/lodash-es/rest/index.d.ts new file mode 100644 index 0000000000..4ff5ec1716 --- /dev/null +++ b/lodash-es/rest/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const rest: typeof _.rest; +export default rest; diff --git a/lodash-es/result/index.d.ts b/lodash-es/result/index.d.ts new file mode 100644 index 0000000000..36c1b43514 --- /dev/null +++ b/lodash-es/result/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const result: typeof _.result; +export default result; diff --git a/lodash-es/reverse/index.d.ts b/lodash-es/reverse/index.d.ts new file mode 100644 index 0000000000..baeaadeece --- /dev/null +++ b/lodash-es/reverse/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const reverse: typeof _.reverse; +export default reverse; diff --git a/lodash-es/round/index.d.ts b/lodash-es/round/index.d.ts new file mode 100644 index 0000000000..3e689aea24 --- /dev/null +++ b/lodash-es/round/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const round: typeof _.round; +export default round; diff --git a/lodash-es/runInContext/index.d.ts b/lodash-es/runInContext/index.d.ts new file mode 100644 index 0000000000..9062c43c9e --- /dev/null +++ b/lodash-es/runInContext/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const runInContext: typeof _.runInContext; +export default runInContext; diff --git a/lodash-es/sample/index.d.ts b/lodash-es/sample/index.d.ts new file mode 100644 index 0000000000..8b5ac9d960 --- /dev/null +++ b/lodash-es/sample/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const sample: typeof _.sample; +export default sample; diff --git a/lodash-es/sampleSize/index.d.ts b/lodash-es/sampleSize/index.d.ts new file mode 100644 index 0000000000..fd6714d967 --- /dev/null +++ b/lodash-es/sampleSize/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const sampleSize: typeof _.sampleSize; +export default sampleSize; diff --git a/lodash-es/set/index.d.ts b/lodash-es/set/index.d.ts new file mode 100644 index 0000000000..4472c88874 --- /dev/null +++ b/lodash-es/set/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const set: typeof _.set; +export default set; diff --git a/lodash-es/setWith/index.d.ts b/lodash-es/setWith/index.d.ts new file mode 100644 index 0000000000..bc9bfa2f23 --- /dev/null +++ b/lodash-es/setWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const setWith: typeof _.setWith; +export default setWith; diff --git a/lodash-es/shuffle/index.d.ts b/lodash-es/shuffle/index.d.ts new file mode 100644 index 0000000000..c1f10cb79f --- /dev/null +++ b/lodash-es/shuffle/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const shuffle: typeof _.shuffle; +export default shuffle; diff --git a/lodash-es/size/index.d.ts b/lodash-es/size/index.d.ts new file mode 100644 index 0000000000..0e47c325ea --- /dev/null +++ b/lodash-es/size/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const size: typeof _.size; +export default size; diff --git a/lodash-es/slice/index.d.ts b/lodash-es/slice/index.d.ts new file mode 100644 index 0000000000..9d8aaffc83 --- /dev/null +++ b/lodash-es/slice/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const slice: typeof _.slice; +export default slice; diff --git a/lodash-es/snakeCase/index.d.ts b/lodash-es/snakeCase/index.d.ts new file mode 100644 index 0000000000..4ed1129d8c --- /dev/null +++ b/lodash-es/snakeCase/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const snakeCase: typeof _.snakeCase; +export default snakeCase; diff --git a/lodash-es/some/index.d.ts b/lodash-es/some/index.d.ts new file mode 100644 index 0000000000..27dbceeddb --- /dev/null +++ b/lodash-es/some/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const some: typeof _.some; +export default some; diff --git a/lodash-es/sortBy/index.d.ts b/lodash-es/sortBy/index.d.ts new file mode 100644 index 0000000000..3974667db9 --- /dev/null +++ b/lodash-es/sortBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const sortBy: typeof _.sortBy; +export default sortBy; diff --git a/lodash-es/sortedIndex/index.d.ts b/lodash-es/sortedIndex/index.d.ts new file mode 100644 index 0000000000..47413f639e --- /dev/null +++ b/lodash-es/sortedIndex/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const sortedIndex: typeof _.sortedIndex; +export default sortedIndex; diff --git a/lodash-es/sortedIndexBy/index.d.ts b/lodash-es/sortedIndexBy/index.d.ts new file mode 100644 index 0000000000..319ed34d5a --- /dev/null +++ b/lodash-es/sortedIndexBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const sortedIndexBy: typeof _.sortedIndexBy; +export default sortedIndexBy; diff --git a/lodash-es/sortedIndexOf/index.d.ts b/lodash-es/sortedIndexOf/index.d.ts new file mode 100644 index 0000000000..24fba2ed53 --- /dev/null +++ b/lodash-es/sortedIndexOf/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const sortedIndexOf: typeof _.sortedIndexOf; +export default sortedIndexOf; diff --git a/lodash-es/sortedLastIndex/index.d.ts b/lodash-es/sortedLastIndex/index.d.ts new file mode 100644 index 0000000000..43f98b2a7e --- /dev/null +++ b/lodash-es/sortedLastIndex/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const sortedLastIndex: typeof _.sortedLastIndex; +export default sortedLastIndex; diff --git a/lodash-es/sortedLastIndexBy/index.d.ts b/lodash-es/sortedLastIndexBy/index.d.ts new file mode 100644 index 0000000000..9475209c54 --- /dev/null +++ b/lodash-es/sortedLastIndexBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const sortedLastIndexBy: typeof _.sortedLastIndexBy; +export default sortedLastIndexBy; diff --git a/lodash-es/sortedLastIndexOf/index.d.ts b/lodash-es/sortedLastIndexOf/index.d.ts new file mode 100644 index 0000000000..0616f1681c --- /dev/null +++ b/lodash-es/sortedLastIndexOf/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const sortedLastIndexOf: typeof _.sortedLastIndexOf; +export default sortedLastIndexOf; diff --git a/lodash-es/sortedUniq/index.d.ts b/lodash-es/sortedUniq/index.d.ts new file mode 100644 index 0000000000..d07b2cce2d --- /dev/null +++ b/lodash-es/sortedUniq/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const sortedUniq: typeof _.sortedUniq; +export default sortedUniq; diff --git a/lodash-es/sortedUniqBy/index.d.ts b/lodash-es/sortedUniqBy/index.d.ts new file mode 100644 index 0000000000..c8f6dd5af6 --- /dev/null +++ b/lodash-es/sortedUniqBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const sortedUniqBy: typeof _.sortedUniqBy; +export default sortedUniqBy; diff --git a/lodash-es/split/index.d.ts b/lodash-es/split/index.d.ts new file mode 100644 index 0000000000..324d02d47c --- /dev/null +++ b/lodash-es/split/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const split: typeof _.split; +export default split; diff --git a/lodash-es/spread/index.d.ts b/lodash-es/spread/index.d.ts new file mode 100644 index 0000000000..461cca54f8 --- /dev/null +++ b/lodash-es/spread/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const spread: typeof _.spread; +export default spread; diff --git a/lodash-es/startCase/index.d.ts b/lodash-es/startCase/index.d.ts new file mode 100644 index 0000000000..47adda4778 --- /dev/null +++ b/lodash-es/startCase/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const startCase: typeof _.startCase; +export default startCase; diff --git a/lodash-es/startsWith/index.d.ts b/lodash-es/startsWith/index.d.ts new file mode 100644 index 0000000000..6911075113 --- /dev/null +++ b/lodash-es/startsWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const startsWith: typeof _.startsWith; +export default startsWith; diff --git a/lodash-es/subtract/index.d.ts b/lodash-es/subtract/index.d.ts new file mode 100644 index 0000000000..0f95bf51bd --- /dev/null +++ b/lodash-es/subtract/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const subtract: typeof _.subtract; +export default subtract; diff --git a/lodash-es/sum/index.d.ts b/lodash-es/sum/index.d.ts new file mode 100644 index 0000000000..4c56b8d65e --- /dev/null +++ b/lodash-es/sum/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const sum: typeof _.sum; +export default sum; diff --git a/lodash-es/sumBy/index.d.ts b/lodash-es/sumBy/index.d.ts new file mode 100644 index 0000000000..f0eed13717 --- /dev/null +++ b/lodash-es/sumBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const sumBy: typeof _.sumBy; +export default sumBy; diff --git a/lodash-es/tail/index.d.ts b/lodash-es/tail/index.d.ts new file mode 100644 index 0000000000..0ac36fc944 --- /dev/null +++ b/lodash-es/tail/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const tail: typeof _.tail; +export default tail; diff --git a/lodash-es/take/index.d.ts b/lodash-es/take/index.d.ts new file mode 100644 index 0000000000..93178fa05f --- /dev/null +++ b/lodash-es/take/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const take: typeof _.take; +export default take; diff --git a/lodash-es/takeRight/index.d.ts b/lodash-es/takeRight/index.d.ts new file mode 100644 index 0000000000..198c35a364 --- /dev/null +++ b/lodash-es/takeRight/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const takeRight: typeof _.takeRight; +export default takeRight; diff --git a/lodash-es/takeRightWhile/index.d.ts b/lodash-es/takeRightWhile/index.d.ts new file mode 100644 index 0000000000..d530ad33d6 --- /dev/null +++ b/lodash-es/takeRightWhile/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const takeRightWhile: typeof _.takeRightWhile; +export default takeRightWhile; diff --git a/lodash-es/takeWhile/index.d.ts b/lodash-es/takeWhile/index.d.ts new file mode 100644 index 0000000000..526f3743b1 --- /dev/null +++ b/lodash-es/takeWhile/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const takeWhile: typeof _.takeWhile; +export default takeWhile; diff --git a/lodash-es/tap/index.d.ts b/lodash-es/tap/index.d.ts new file mode 100644 index 0000000000..33c2b8b111 --- /dev/null +++ b/lodash-es/tap/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const tap: typeof _.tap; +export default tap; diff --git a/lodash-es/template/index.d.ts b/lodash-es/template/index.d.ts new file mode 100644 index 0000000000..d034b9fa77 --- /dev/null +++ b/lodash-es/template/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const template: typeof _.template; +export default template; diff --git a/lodash-es/throttle/index.d.ts b/lodash-es/throttle/index.d.ts new file mode 100644 index 0000000000..513c7b5d5d --- /dev/null +++ b/lodash-es/throttle/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const throttle: typeof _.throttle; +export default throttle; diff --git a/lodash-es/thru/index.d.ts b/lodash-es/thru/index.d.ts new file mode 100644 index 0000000000..1726f23228 --- /dev/null +++ b/lodash-es/thru/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const thru: typeof _.thru; +export default thru; diff --git a/lodash-es/times/index.d.ts b/lodash-es/times/index.d.ts new file mode 100644 index 0000000000..a917d3c4b1 --- /dev/null +++ b/lodash-es/times/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const times: typeof _.times; +export default times; diff --git a/lodash-es/toArray/index.d.ts b/lodash-es/toArray/index.d.ts new file mode 100644 index 0000000000..3c0a17b73b --- /dev/null +++ b/lodash-es/toArray/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const toArray: typeof _.toArray; +export default toArray; diff --git a/lodash-es/toInteger/index.d.ts b/lodash-es/toInteger/index.d.ts new file mode 100644 index 0000000000..2cc3269564 --- /dev/null +++ b/lodash-es/toInteger/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const toInteger: typeof _.toInteger; +export default toInteger; diff --git a/lodash-es/toLength/index.d.ts b/lodash-es/toLength/index.d.ts new file mode 100644 index 0000000000..5a58a74444 --- /dev/null +++ b/lodash-es/toLength/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const toLength: typeof _.toLength; +export default toLength; diff --git a/lodash-es/toLower/index.d.ts b/lodash-es/toLower/index.d.ts new file mode 100644 index 0000000000..822e0a5398 --- /dev/null +++ b/lodash-es/toLower/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const toLower: typeof _.toLower; +export default toLower; diff --git a/lodash-es/toNumber/index.d.ts b/lodash-es/toNumber/index.d.ts new file mode 100644 index 0000000000..773b27b6ac --- /dev/null +++ b/lodash-es/toNumber/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const toNumber: typeof _.toNumber; +export default toNumber; diff --git a/lodash-es/toPairs/index.d.ts b/lodash-es/toPairs/index.d.ts new file mode 100644 index 0000000000..c8dd85752c --- /dev/null +++ b/lodash-es/toPairs/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const toPairs: typeof _.toPairs; +export default toPairs; diff --git a/lodash-es/toPairsIn/index.d.ts b/lodash-es/toPairsIn/index.d.ts new file mode 100644 index 0000000000..f25ebc6231 --- /dev/null +++ b/lodash-es/toPairsIn/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const toPairsIn: typeof _.toPairsIn; +export default toPairsIn; diff --git a/lodash-es/toPath/index.d.ts b/lodash-es/toPath/index.d.ts new file mode 100644 index 0000000000..14c24785e0 --- /dev/null +++ b/lodash-es/toPath/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const toPath: typeof _.toPath; +export default toPath; diff --git a/lodash-es/toPlainObject/index.d.ts b/lodash-es/toPlainObject/index.d.ts new file mode 100644 index 0000000000..daf78df646 --- /dev/null +++ b/lodash-es/toPlainObject/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const toPlainObject: typeof _.toPlainObject; +export default toPlainObject; diff --git a/lodash-es/toSafeInteger/index.d.ts b/lodash-es/toSafeInteger/index.d.ts new file mode 100644 index 0000000000..8a745612c7 --- /dev/null +++ b/lodash-es/toSafeInteger/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const toSafeInteger: typeof _.toSafeInteger; +export default toSafeInteger; diff --git a/lodash-es/toString/index.d.ts b/lodash-es/toString/index.d.ts new file mode 100644 index 0000000000..4368b5151e --- /dev/null +++ b/lodash-es/toString/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const toString: typeof _.toString; +export default toString; diff --git a/lodash-es/toUpper/index.d.ts b/lodash-es/toUpper/index.d.ts new file mode 100644 index 0000000000..1af2cf82ad --- /dev/null +++ b/lodash-es/toUpper/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const toUpper: typeof _.toUpper; +export default toUpper; diff --git a/lodash-es/transform/index.d.ts b/lodash-es/transform/index.d.ts new file mode 100644 index 0000000000..3cf81aaa34 --- /dev/null +++ b/lodash-es/transform/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const transform: typeof _.transform; +export default transform; diff --git a/lodash-es/trim/index.d.ts b/lodash-es/trim/index.d.ts new file mode 100644 index 0000000000..f4339c8ef4 --- /dev/null +++ b/lodash-es/trim/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const trim: typeof _.trim; +export default trim; diff --git a/lodash-es/trimEnd/index.d.ts b/lodash-es/trimEnd/index.d.ts new file mode 100644 index 0000000000..dd2e972c0e --- /dev/null +++ b/lodash-es/trimEnd/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const trimEnd: typeof _.trimEnd; +export default trimEnd; diff --git a/lodash-es/trimStart/index.d.ts b/lodash-es/trimStart/index.d.ts new file mode 100644 index 0000000000..8a097d0e41 --- /dev/null +++ b/lodash-es/trimStart/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const trimStart: typeof _.trimStart; +export default trimStart; diff --git a/lodash-es/truncate/index.d.ts b/lodash-es/truncate/index.d.ts new file mode 100644 index 0000000000..b460b03a77 --- /dev/null +++ b/lodash-es/truncate/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const truncate: typeof _.truncate; +export default truncate; diff --git a/lodash-es/tsconfig.json b/lodash-es/tsconfig.json new file mode 100644 index 0000000000..5cec53c53e --- /dev/null +++ b/lodash-es/tsconfig.json @@ -0,0 +1,304 @@ +{ + "files": [ + "index.d.ts", + "lodash-es-tests.ts", + "add/index.d.ts", + "after/index.d.ts", + "ary/index.d.ts", + "assign/index.d.ts", + "assignIn/index.d.ts", + "assignInWith/index.d.ts", + "assignWith/index.d.ts", + "at/index.d.ts", + "attempt/index.d.ts", + "before/index.d.ts", + "bind/index.d.ts", + "bindAll/index.d.ts", + "bindKey/index.d.ts", + "camelCase/index.d.ts", + "capitalize/index.d.ts", + "castArray/index.d.ts", + "ceil/index.d.ts", + "chain/index.d.ts", + "chunk/index.d.ts", + "clamp/index.d.ts", + "clone/index.d.ts", + "cloneDeep/index.d.ts", + "cloneDeepWith/index.d.ts", + "cloneWith/index.d.ts", + "compact/index.d.ts", + "concat/index.d.ts", + "constant/index.d.ts", + "countBy/index.d.ts", + "create/index.d.ts", + "curry/index.d.ts", + "curryRight/index.d.ts", + "debounce/index.d.ts", + "deburr/index.d.ts", + "defaults/index.d.ts", + "defaultsDeep/index.d.ts", + "defer/index.d.ts", + "delay/index.d.ts", + "difference/index.d.ts", + "differenceBy/index.d.ts", + "differenceWith/index.d.ts", + "drop/index.d.ts", + "dropRight/index.d.ts", + "dropRightWhile/index.d.ts", + "dropWhile/index.d.ts", + "each/index.d.ts", + "eachRight/index.d.ts", + "endsWith/index.d.ts", + "eq/index.d.ts", + "escape/index.d.ts", + "escapeRegExp/index.d.ts", + "every/index.d.ts", + "extend/index.d.ts", + "extendWith/index.d.ts", + "fb/index.d.ts", + "fill/index.d.ts", + "filter/index.d.ts", + "find/index.d.ts", + "findIndex/index.d.ts", + "findKey/index.d.ts", + "findLast/index.d.ts", + "findLastIndex/index.d.ts", + "findLastKey/index.d.ts", + "first/index.d.ts", + "flatMap/index.d.ts", + "flatten/index.d.ts", + "flattenDeep/index.d.ts", + "flattenDepth/index.d.ts", + "flip/index.d.ts", + "floor/index.d.ts", + "flow/index.d.ts", + "flowRight/index.d.ts", + "forEach/index.d.ts", + "forEachRight/index.d.ts", + "forIn/index.d.ts", + "forInRight/index.d.ts", + "forOwn/index.d.ts", + "forOwnRight/index.d.ts", + "fromPairs/index.d.ts", + "functions/index.d.ts", + "functionsIn/index.d.ts", + "get/index.d.ts", + "groupBy/index.d.ts", + "gt/index.d.ts", + "gte/index.d.ts", + "has/index.d.ts", + "hasIn/index.d.ts", + "head/index.d.ts", + "identity/index.d.ts", + "includes/index.d.ts", + "indexOf/index.d.ts", + "initial/index.d.ts", + "inRange/index.d.ts", + "intersection/index.d.ts", + "intersectionBy/index.d.ts", + "intersectionWith/index.d.ts", + "invert/index.d.ts", + "invertBy/index.d.ts", + "invoke/index.d.ts", + "invokeMap/index.d.ts", + "isArguments/index.d.ts", + "isArray/index.d.ts", + "isArrayBuffer/index.d.ts", + "isArrayLike/index.d.ts", + "isArrayLikeObject/index.d.ts", + "isBoolean/index.d.ts", + "isBuffer/index.d.ts", + "isDate/index.d.ts", + "isElement/index.d.ts", + "isEmpty/index.d.ts", + "isEqual/index.d.ts", + "isEqualWith/index.d.ts", + "isError/index.d.ts", + "isFinite/index.d.ts", + "isFunction/index.d.ts", + "isInteger/index.d.ts", + "isLength/index.d.ts", + "isMap/index.d.ts", + "isMatch/index.d.ts", + "isMatchWith/index.d.ts", + "isNaN/index.d.ts", + "isNative/index.d.ts", + "isNil/index.d.ts", + "isNull/index.d.ts", + "isNumber/index.d.ts", + "isObject/index.d.ts", + "isObjectLike/index.d.ts", + "isPlainObject/index.d.ts", + "isRegExp/index.d.ts", + "isSafeInteger/index.d.ts", + "isSet/index.d.ts", + "isString/index.d.ts", + "isSymbol/index.d.ts", + "isTypedArray/index.d.ts", + "isUndefined/index.d.ts", + "isWeakMap/index.d.ts", + "isWeakSet/index.d.ts", + "iteratee/index.d.ts", + "join/index.d.ts", + "kebabCase/index.d.ts", + "keyBy/index.d.ts", + "keys/index.d.ts", + "keysIn/index.d.ts", + "last/index.d.ts", + "lastIndexOf/index.d.ts", + "lowerCase/index.d.ts", + "lowerFirst/index.d.ts", + "lt/index.d.ts", + "lte/index.d.ts", + "map/index.d.ts", + "mapKeys/index.d.ts", + "mapValues/index.d.ts", + "matches/index.d.ts", + "matchesProperty/index.d.ts", + "max/index.d.ts", + "maxBy/index.d.ts", + "mean/index.d.ts", + "memoize/index.d.ts", + "merge/index.d.ts", + "mergeWith/index.d.ts", + "method/index.d.ts", + "methodOf/index.d.ts", + "min/index.d.ts", + "minBy/index.d.ts", + "mixin/index.d.ts", + "negate/index.d.ts", + "noConflict/index.d.ts", + "noop/index.d.ts", + "now/index.d.ts", + "nthArg/index.d.ts", + "omit/index.d.ts", + "omitBy/index.d.ts", + "once/index.d.ts", + "orderBy/index.d.ts", + "over/index.d.ts", + "overArgs/index.d.ts", + "overEvery/index.d.ts", + "overSome/index.d.ts", + "pad/index.d.ts", + "padEnd/index.d.ts", + "padStart/index.d.ts", + "parseInt/index.d.ts", + "partial/index.d.ts", + "partialRight/index.d.ts", + "partition/index.d.ts", + "pick/index.d.ts", + "pickBy/index.d.ts", + "property/index.d.ts", + "propertyOf/index.d.ts", + "pull/index.d.ts", + "pullAll/index.d.ts", + "pullAllBy/index.d.ts", + "pullAt/index.d.ts", + "random/index.d.ts", + "range/index.d.ts", + "rangeRight/index.d.ts", + "rearg/index.d.ts", + "reduce/index.d.ts", + "reduceRight/index.d.ts", + "reject/index.d.ts", + "remove/index.d.ts", + "repeat/index.d.ts", + "replace/index.d.ts", + "rest/index.d.ts", + "result/index.d.ts", + "reverse/index.d.ts", + "round/index.d.ts", + "runInContext/index.d.ts", + "sample/index.d.ts", + "sampleSize/index.d.ts", + "set/index.d.ts", + "setWith/index.d.ts", + "shuffle/index.d.ts", + "size/index.d.ts", + "slice/index.d.ts", + "snakeCase/index.d.ts", + "some/index.d.ts", + "sortBy/index.d.ts", + "sortedIndex/index.d.ts", + "sortedIndexBy/index.d.ts", + "sortedIndexOf/index.d.ts", + "sortedLastIndex/index.d.ts", + "sortedLastIndexBy/index.d.ts", + "sortedLastIndexOf/index.d.ts", + "sortedUniq/index.d.ts", + "sortedUniqBy/index.d.ts", + "split/index.d.ts", + "spread/index.d.ts", + "startCase/index.d.ts", + "startsWith/index.d.ts", + "subtract/index.d.ts", + "sum/index.d.ts", + "sumBy/index.d.ts", + "tail/index.d.ts", + "take/index.d.ts", + "takeRight/index.d.ts", + "takeRightWhile/index.d.ts", + "takeWhile/index.d.ts", + "tap/index.d.ts", + "template/index.d.ts", + "throttle/index.d.ts", + "thru/index.d.ts", + "times/index.d.ts", + "toArray/index.d.ts", + "toInteger/index.d.ts", + "toLength/index.d.ts", + "toLower/index.d.ts", + "toNumber/index.d.ts", + "toPairs/index.d.ts", + "toPairsIn/index.d.ts", + "toPath/index.d.ts", + "toPlainObject/index.d.ts", + "toSafeInteger/index.d.ts", + "toString/index.d.ts", + "toUpper/index.d.ts", + "transform/index.d.ts", + "trim/index.d.ts", + "trimEnd/index.d.ts", + "trimStart/index.d.ts", + "truncate/index.d.ts", + "unary/index.d.ts", + "unescape/index.d.ts", + "union/index.d.ts", + "unionBy/index.d.ts", + "unionWith/index.d.ts", + "uniq/index.d.ts", + "uniqBy/index.d.ts", + "uniqueId/index.d.ts", + "uniqWith/index.d.ts", + "unset/index.d.ts", + "unzip/index.d.ts", + "unzipWith/index.d.ts", + "update/index.d.ts", + "upperCase/index.d.ts", + "upperFirst/index.d.ts", + "values/index.d.ts", + "valuesIn/index.d.ts", + "without/index.d.ts", + "words/index.d.ts", + "wrap/index.d.ts", + "xor/index.d.ts", + "xorBy/index.d.ts", + "xorWith/index.d.ts", + "zip/index.d.ts", + "zipObject/index.d.ts", + "zipWith/index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/lodash-es/tslint.json b/lodash-es/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/lodash-es/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/lodash-es/unary/index.d.ts b/lodash-es/unary/index.d.ts new file mode 100644 index 0000000000..d8c0e57fb1 --- /dev/null +++ b/lodash-es/unary/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const unary: typeof _.unary; +export default unary; diff --git a/lodash-es/unescape/index.d.ts b/lodash-es/unescape/index.d.ts new file mode 100644 index 0000000000..3506888535 --- /dev/null +++ b/lodash-es/unescape/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const unescape: typeof _.unescape; +export default unescape; diff --git a/lodash-es/union/index.d.ts b/lodash-es/union/index.d.ts new file mode 100644 index 0000000000..b08034f25c --- /dev/null +++ b/lodash-es/union/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const union: typeof _.union; +export default union; diff --git a/lodash-es/unionBy/index.d.ts b/lodash-es/unionBy/index.d.ts new file mode 100644 index 0000000000..edadc46ba2 --- /dev/null +++ b/lodash-es/unionBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const unionBy: typeof _.unionBy; +export default unionBy; diff --git a/lodash-es/unionWith/index.d.ts b/lodash-es/unionWith/index.d.ts new file mode 100644 index 0000000000..d54e10d78c --- /dev/null +++ b/lodash-es/unionWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const unionWith: typeof _.unionWith; +export default unionWith; diff --git a/lodash-es/uniq/index.d.ts b/lodash-es/uniq/index.d.ts new file mode 100644 index 0000000000..4762079e3c --- /dev/null +++ b/lodash-es/uniq/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const uniq: typeof _.uniq; +export default uniq; diff --git a/lodash-es/uniqBy/index.d.ts b/lodash-es/uniqBy/index.d.ts new file mode 100644 index 0000000000..375c79ff00 --- /dev/null +++ b/lodash-es/uniqBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const uniqBy: typeof _.uniqBy; +export default uniqBy; diff --git a/lodash-es/uniqWith/index.d.ts b/lodash-es/uniqWith/index.d.ts new file mode 100644 index 0000000000..206dbd676f --- /dev/null +++ b/lodash-es/uniqWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const uniqWith: typeof _.uniqWith; +export default uniqWith; diff --git a/lodash-es/uniqueId/index.d.ts b/lodash-es/uniqueId/index.d.ts new file mode 100644 index 0000000000..19fc567963 --- /dev/null +++ b/lodash-es/uniqueId/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const uniqueId: typeof _.uniqueId; +export default uniqueId; diff --git a/lodash-es/unset/index.d.ts b/lodash-es/unset/index.d.ts new file mode 100644 index 0000000000..3ca4539505 --- /dev/null +++ b/lodash-es/unset/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const unset: typeof _.unset; +export default unset; diff --git a/lodash-es/unzip/index.d.ts b/lodash-es/unzip/index.d.ts new file mode 100644 index 0000000000..a7eead8dd4 --- /dev/null +++ b/lodash-es/unzip/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const unzip: typeof _.unzip; +export default unzip; diff --git a/lodash-es/unzipWith/index.d.ts b/lodash-es/unzipWith/index.d.ts new file mode 100644 index 0000000000..bd54fec609 --- /dev/null +++ b/lodash-es/unzipWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const unzipWith: typeof _.unzipWith; +export default unzipWith; diff --git a/lodash-es/update/index.d.ts b/lodash-es/update/index.d.ts new file mode 100644 index 0000000000..980239450a --- /dev/null +++ b/lodash-es/update/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const update: typeof _.update; +export default update; diff --git a/lodash-es/upperCase/index.d.ts b/lodash-es/upperCase/index.d.ts new file mode 100644 index 0000000000..ac41216f80 --- /dev/null +++ b/lodash-es/upperCase/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const upperCase: typeof _.upperCase; +export default upperCase; diff --git a/lodash-es/upperFirst/index.d.ts b/lodash-es/upperFirst/index.d.ts new file mode 100644 index 0000000000..aebaffb3d6 --- /dev/null +++ b/lodash-es/upperFirst/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const upperFirst: typeof _.upperFirst; +export default upperFirst; diff --git a/lodash-es/values/index.d.ts b/lodash-es/values/index.d.ts new file mode 100644 index 0000000000..8c2ec79150 --- /dev/null +++ b/lodash-es/values/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const values: typeof _.values; +export default values; diff --git a/lodash-es/valuesIn/index.d.ts b/lodash-es/valuesIn/index.d.ts new file mode 100644 index 0000000000..5a7a19d852 --- /dev/null +++ b/lodash-es/valuesIn/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const valuesIn: typeof _.valuesIn; +export default valuesIn; diff --git a/lodash-es/without/index.d.ts b/lodash-es/without/index.d.ts new file mode 100644 index 0000000000..88dba2ae33 --- /dev/null +++ b/lodash-es/without/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const without: typeof _.without; +export default without; diff --git a/lodash-es/words/index.d.ts b/lodash-es/words/index.d.ts new file mode 100644 index 0000000000..02fe6bcc57 --- /dev/null +++ b/lodash-es/words/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const words: typeof _.words; +export default words; diff --git a/lodash-es/wrap/index.d.ts b/lodash-es/wrap/index.d.ts new file mode 100644 index 0000000000..15a7ddbbc4 --- /dev/null +++ b/lodash-es/wrap/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const wrap: typeof _.wrap; +export default wrap; diff --git a/lodash-es/xor/index.d.ts b/lodash-es/xor/index.d.ts new file mode 100644 index 0000000000..bbbe130a7a --- /dev/null +++ b/lodash-es/xor/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const xor: typeof _.xor; +export default xor; diff --git a/lodash-es/xorBy/index.d.ts b/lodash-es/xorBy/index.d.ts new file mode 100644 index 0000000000..373baf8544 --- /dev/null +++ b/lodash-es/xorBy/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const xorBy: typeof _.xorBy; +export default xorBy; diff --git a/lodash-es/xorWith/index.d.ts b/lodash-es/xorWith/index.d.ts new file mode 100644 index 0000000000..0deeb4a07c --- /dev/null +++ b/lodash-es/xorWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const xorWith: typeof _.xorWith; +export default xorWith; diff --git a/lodash-es/zip/index.d.ts b/lodash-es/zip/index.d.ts new file mode 100644 index 0000000000..84bca1bbb8 --- /dev/null +++ b/lodash-es/zip/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const zip: typeof _.zip; +export default zip; diff --git a/lodash-es/zipObject/index.d.ts b/lodash-es/zipObject/index.d.ts new file mode 100644 index 0000000000..264c843317 --- /dev/null +++ b/lodash-es/zipObject/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const zipObject: typeof _.zipObject; +export default zipObject; diff --git a/lodash-es/zipWith/index.d.ts b/lodash-es/zipWith/index.d.ts new file mode 100644 index 0000000000..e67bc61a33 --- /dev/null +++ b/lodash-es/zipWith/index.d.ts @@ -0,0 +1,3 @@ +import * as _ from "lodash"; +declare const zipWith: typeof _.zipWith; +export default zipWith; diff --git a/lodash/index.d.ts b/lodash/index.d.ts index f8b14bb3af..507d8b3250 100644 --- a/lodash/index.d.ts +++ b/lodash/index.d.ts @@ -1594,12 +1594,13 @@ declare module _ { * * @param array The array to search. * @param predicate The function invoked per iteration. - * @param thisArg The this binding of predicate. + * @param fromIndex The index to search from. * @return Returns the index of the found element, else -1. */ findIndex( array: List, - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): number; /** @@ -1607,7 +1608,8 @@ declare module _ { */ findIndex( array: List, - predicate?: string + predicate?: string, + fromIndex?: number ): number; /** @@ -1615,7 +1617,8 @@ declare module _ { */ findIndex( array: List, - predicate?: W + predicate?: W, + fromIndex?: number ): number; } @@ -1624,21 +1627,24 @@ declare module _ { * @see _.findIndex */ findIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): number; /** * @see _.findIndex */ findIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): number; /** * @see _.findIndex */ findIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): number; } @@ -1647,21 +1653,24 @@ declare module _ { * @see _.findIndex */ findIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): number; /** * @see _.findIndex */ findIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): number; /** * @see _.findIndex */ findIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): number; } @@ -1670,21 +1679,24 @@ declare module _ { * @see _.findIndex */ findIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findIndex */ findIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findIndex */ findIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): LoDashExplicitWrapper; } @@ -1693,21 +1705,24 @@ declare module _ { * @see _.findIndex */ findIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findIndex */ findIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findIndex */ findIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): LoDashExplicitWrapper; } @@ -1727,12 +1742,13 @@ declare module _ { * * @param array The array to search. * @param predicate The function invoked per iteration. - * @param thisArg The function invoked per iteration. + * @param fromIndex The index to search from. * @return Returns the index of the found element, else -1. */ findLastIndex( array: List, - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): number; /** @@ -1740,7 +1756,8 @@ declare module _ { */ findLastIndex( array: List, - predicate?: string + predicate?: string, + fromIndex?: number ): number; /** @@ -1748,7 +1765,8 @@ declare module _ { */ findLastIndex( array: List, - predicate?: W + predicate?: W, + fromIndex?: number ): number; } @@ -1757,21 +1775,24 @@ declare module _ { * @see _.findLastIndex */ findLastIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): number; /** * @see _.findLastIndex */ findLastIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): number; /** * @see _.findLastIndex */ findLastIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): number; } @@ -1780,21 +1801,24 @@ declare module _ { * @see _.findLastIndex */ findLastIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): number; /** * @see _.findLastIndex */ findLastIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): number; /** * @see _.findLastIndex */ findLastIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): number; } @@ -1803,21 +1827,24 @@ declare module _ { * @see _.findLastIndex */ findLastIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findLastIndex */ findLastIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findLastIndex */ findLastIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): LoDashExplicitWrapper; } @@ -1826,21 +1853,24 @@ declare module _ { * @see _.findLastIndex */ findLastIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findLastIndex */ findLastIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findLastIndex */ findLastIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): LoDashExplicitWrapper; } @@ -6898,26 +6928,32 @@ declare module _ { * right to left. * @param collection Searches for a value in this list. * @param callback The function called per iteration. - * @param thisArg The this binding of callback. + * @param fromIndex The index to search from. * @return The found element, else undefined. **/ findLast( collection: Array, - callback: ListIterator): T; + callback: ListIterator, + fromIndex?: number + ): T; /** * @see _.find **/ findLast( collection: List, - callback: ListIterator): T; + callback: ListIterator, + fromIndex?: number + ): T; /** * @see _.find **/ findLast( collection: Dictionary, - callback: DictionaryIterator): T; + callback: DictionaryIterator, + fromIndex?: number + ): T; /** * @see _.find @@ -6925,7 +6961,9 @@ declare module _ { **/ findLast( collection: Array, - whereValue: W): T; + whereValue: W, + fromIndex?: number + ): T; /** * @see _.find @@ -6933,7 +6971,9 @@ declare module _ { **/ findLast( collection: List, - whereValue: W): T; + whereValue: W, + fromIndex?: number + ): T; /** * @see _.find @@ -6941,7 +6981,9 @@ declare module _ { **/ findLast( collection: Dictionary, - whereValue: W): T; + whereValue: W, + fromIndex?: number + ): T; /** * @see _.find @@ -6949,7 +6991,9 @@ declare module _ { **/ findLast( collection: Array, - pluckValue: string): T; + pluckValue: string, + fromIndex?: number + ): T; /** * @see _.find @@ -6957,7 +7001,9 @@ declare module _ { **/ findLast( collection: List, - pluckValue: string): T; + pluckValue: string, + fromIndex?: number + ): T; /** * @see _.find @@ -6965,7 +7011,9 @@ declare module _ { **/ findLast( collection: Dictionary, - pluckValue: string): T; + pluckValue: string, + fromIndex?: number + ): T; } interface LoDashImplicitArrayWrapper { @@ -6973,20 +7021,26 @@ declare module _ { * @see _.findLast */ findLast( - callback: ListIterator): T; + callback: ListIterator, + fromIndex?: number + ): T; /** * @see _.findLast * @param _.where style callback */ findLast( - whereValue: W): T; + whereValue: W, + fromIndex?: number + ): T; /** * @see _.findLast * @param _.where style callback */ findLast( - pluckValue: string): T; + pluckValue: string, + fromIndex?: number + ): T; } //_.flatMap @@ -18210,6 +18264,34 @@ declare module _ { constant(): LoDashExplicitObjectWrapper<() => TResult>; } + //_.defaultTo + interface LoDashStatic { + /** + * Checks `value` to determine whether a default value should be returned in + * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, + * or `undefined`. + * + * @param value The value to check. + * @param defaultValue The default value. + * @returns Returns the resolved value. + */ + defaultTo(value: T, defaultValue: T): T; + } + + interface LoDashImplicitWrapperBase { + /** + * @see _.defaultTo + */ + defaultTo(value: TResult): LoDashImplicitObjectWrapper; + } + + interface LoDashExplicitWrapperBase { + /** + * @see _.defaultTo + */ + defaultTo(value: TResult): LoDashExplicitObjectWrapper; + } + //_.identity interface LoDashStatic { /** diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 4f6ee5a921..cead404be0 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -681,6 +681,7 @@ namespace TestFindIndex { let array: TResult[]; let list: _.List; let predicateFn: (value: TResult, index?: number, collection?: _.List) => boolean; + let fromIndex: number; { let result: number; @@ -689,21 +690,25 @@ namespace TestFindIndex { result = _.findIndex(array, predicateFn); result = _.findIndex(array, ''); result = _.findIndex<{a: number}, TResult>(array, {a: 42}); + result = _.findIndex(array, predicateFn, fromIndex); result = _.findIndex(list); result = _.findIndex(list, predicateFn); result = _.findIndex(list, ''); result = _.findIndex<{a: number}, TResult>(list, {a: 42}); + result = _.findIndex(list, predicateFn, fromIndex); result = _(array).findIndex(); result = _(array).findIndex(predicateFn); result = _(array).findIndex(''); result = _(array).findIndex<{a: number}>({a: 42}); + result = _(array).findIndex(predicateFn, fromIndex); result = _(list).findIndex(); result = _(list).findIndex(predicateFn); result = _(list).findIndex(''); result = _(list).findIndex<{a: number}>({a: 42}); + result = _(list).findIndex(predicateFn, fromIndex); } { @@ -713,11 +718,13 @@ namespace TestFindIndex { result = _(array).chain().findIndex(predicateFn); result = _(array).chain().findIndex(''); result = _(array).chain().findIndex<{a: number}>({a: 42}); + result = _(array).chain().findIndex(predicateFn, fromIndex); result = _(list).chain().findIndex(); result = _(list).chain().findIndex(predicateFn); result = _(list).chain().findIndex(''); result = _(list).chain().findIndex<{a: number}>({a: 42}); + result = _(list).chain().findIndex(predicateFn, fromIndex); } } @@ -727,6 +734,7 @@ namespace TestFindLastIndex { let list: _.List; let predicateFn: (value: TResult, index?: number, collection?: _.List) => boolean; + let fromIndex: number; { let result: number; @@ -735,21 +743,25 @@ namespace TestFindLastIndex { result = _.findLastIndex(array, predicateFn); result = _.findLastIndex(array, ''); result = _.findLastIndex<{a: number}, TResult>(array, {a: 42}); + result = _.findLastIndex(array, predicateFn, fromIndex); result = _.findLastIndex(list); result = _.findLastIndex(list, predicateFn); result = _.findLastIndex(list, ''); result = _.findLastIndex<{a: number}, TResult>(list, {a: 42}); + result = _.findLastIndex(list, predicateFn, fromIndex); result = _(array).findLastIndex(); result = _(array).findLastIndex(predicateFn); result = _(array).findLastIndex(''); result = _(array).findLastIndex<{a: number}>({a: 42}); + result = _(array).findLastIndex(predicateFn, fromIndex); result = _(list).findLastIndex(); result = _(list).findLastIndex(predicateFn); result = _(list).findLastIndex(''); result = _(list).findLastIndex<{a: number}>({a: 42}); + result = _(list).findLastIndex(predicateFn, fromIndex); } { @@ -759,11 +771,13 @@ namespace TestFindLastIndex { result = _(array).chain().findLastIndex(predicateFn); result = _(array).chain().findLastIndex(''); result = _(array).chain().findLastIndex<{a: number}>({a: 42}); + result = _(array).chain().findLastIndex(predicateFn, fromIndex); result = _(list).chain().findLastIndex(); result = _(list).chain().findLastIndex(predicateFn); result = _(list).chain().findLastIndex(''); result = _(list).chain().findLastIndex<{a: number}>({a: 42}); + result = _(list).chain().findLastIndex(predicateFn, fromIndex); } } @@ -3735,12 +3749,16 @@ result = _.findLast([1, 2, 3, 4], function (num) { result = _.findLast(foodsCombined, { 'type': 'vegetable' }); result = _.findLast(foodsCombined, 'organic'); +result = _.findLast(foodsCombined, 'organic', 1); + result = _([1, 2, 3, 4]).findLast(function (num) { return num % 2 == 0; }); result = _(foodsCombined).findLast({ 'type': 'vegetable' }); result = _(foodsCombined).findLast('organic'); +result = _(foodsCombined).findLast('organic', 1); + // _.flatMap namespace TestFlatMap { let numArray: (number|number[])[] = [1, [2, 3]]; @@ -11111,6 +11129,125 @@ namespace TestConstant { } } +// _.defaultTo +namespace TestDefaultTo { + { + let result: number; + result = _.defaultTo(42, 42); + result = _.defaultTo(undefined, 42); + result = _.defaultTo(null, 42); + result = _.defaultTo(NaN, 42); + } + + { + let result: string; + result = _.defaultTo('a', 'default'); + result = _.defaultTo(undefined, 'default'); + result = _.defaultTo(null, 'default'); + } + + { + let result: boolean; + result = _.defaultTo(true, true); + result = _.defaultTo(undefined, true); + result = _.defaultTo(null, true); + } + + { + let result: string[]; + result = _.defaultTo(['a'], ['default']); + result = _.defaultTo(undefined, ['default']); + result = _.defaultTo(null, ['default']); + } + + { + let result: {a: string}; + result = _.defaultTo<{a: string}>({a: 'a'}, {a: 'a'}); + result = _.defaultTo<{a: string}>(undefined, {a: 'a'}); + result = _.defaultTo<{a: string}>(null, {a: 'a'}); + } + + { + let result: _.LoDashImplicitObjectWrapper; + result = _(42).defaultTo(42); + result = _(undefined).defaultTo(42); + result = _(null).defaultTo(42); + result = _(NaN).defaultTo(42); + } + + { + let result: _.LoDashImplicitObjectWrapper; + result = _('a').defaultTo('default'); + result = _(null).defaultTo('default'); + result = _(NaN).defaultTo('default'); + } + + { + let result: _.LoDashImplicitObjectWrapper; + result = _(true).defaultTo(true); + result = _(undefined).defaultTo(true); + result = _(null).defaultTo(true); + result = _(NaN).defaultTo(true); + } + + { + let result: _.LoDashImplicitObjectWrapper; + result = _(['a']).defaultTo(['default']); + result = _(undefined).defaultTo(['default']); + result = _(null).defaultTo(['default']); + result = _(NaN).defaultTo(['default']); + } + + { + let result: _.LoDashImplicitObjectWrapper<{ a: string }>; + result = _({ a: 'a' }).defaultTo({a : 'a'}); + result = _(undefined).defaultTo({a : 'a'}); + result = _(null).defaultTo({a : 'a'}); + result = _(NaN).defaultTo({a : 'a'}); + } + + { + let result: _.LoDashExplicitObjectWrapper; + result = _(42).chain().defaultTo(42); + result = _(undefined).chain().defaultTo(42); + result = _(null).chain().defaultTo(42); + result = _(NaN).chain().defaultTo(42); + } + + { + let result: _.LoDashExplicitObjectWrapper; + result = _('a').chain().defaultTo('default'); + result = _(undefined).chain().defaultTo('default'); + result = _(null).chain().defaultTo('default'); + result = _(NaN).chain().defaultTo('default'); + } + + { + let result: _.LoDashExplicitObjectWrapper; + result = _(true).chain().defaultTo(true); + result = _(undefined).chain().defaultTo(true); + result = _(null).chain().defaultTo(true); + result = _(NaN).chain().defaultTo(true); + } + + { + let result: _.LoDashExplicitObjectWrapper; + result = _(['a']).chain().defaultTo(['default']); + result = _(undefined).chain().defaultTo(['default']); + result = _(null).chain().defaultTo(['default']); + result = _(NaN).chain().defaultTo(['default']); + } + + { + let result: _.LoDashExplicitObjectWrapper<{ a: string }>; + result = _({ a: 'a' }).chain().defaultTo({a : 'a'}); + result = _(undefined).chain().defaultTo({a : 'a'}); + result = _(null).chain().defaultTo({a : 'a'}); + result = _(NaN).chain().defaultTo({a : 'a'}); + } + +} + // _.identity namespace TestIdentity { { diff --git a/lz-string/index.d.ts b/lz-string/index.d.ts index 19c97c419f..d61e39a6ba 100644 --- a/lz-string/index.d.ts +++ b/lz-string/index.d.ts @@ -4,6 +4,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var LZString: LZString.LZStringStatic; +export = LZString; +export as namespace LZString; declare namespace LZString { /** @@ -59,8 +61,8 @@ declare namespace LZString { decompressFromBase64(compressed: string): string; /** - * produces ASCII strings representing the original string encoded in Base64 with a few - * tweaks to make these URI safe. Hence, you can send them to the server without thinking + * produces ASCII strings representing the original string encoded in Base64 with a few + * tweaks to make these URI safe. Hence, you can send them to the server without thinking * about URL encoding them. This saves bandwidth and CPU * * @param uncompressed A string which should be compressed. diff --git a/lz-string/tslint.json b/lz-string/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/lz-string/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/maker.js/index.d.ts b/maker.js/index.d.ts index d23fe37c3f..7cf55d0448 100644 --- a/maker.js/index.d.ts +++ b/maker.js/index.d.ts @@ -5,7 +5,7 @@ /// /// -/// +/// /** * Root module for Maker.js. @@ -2173,6 +2173,6 @@ declare namespace MakerJs.models { declare namespace MakerJs.models { class Text implements IModel { models: IModelMap; - constructor(font: opentypejs.Font, text: string, fontSize: number, combine?: boolean); + constructor(font: opentype.Font, text: string, fontSize: number, combine?: boolean); } } diff --git a/maker.js/makerjs-tests.ts b/maker.js/makerjs-tests.ts index 534ef9eed7..cc7cc0804d 100644 --- a/maker.js/makerjs-tests.ts +++ b/maker.js/makerjs-tests.ts @@ -1,7 +1,7 @@ function test() { - + var makerjs: typeof MakerJs; var p1: MakerJs.IPoint = [0, 0]; @@ -9,7 +9,7 @@ function test() { var paths = testPaths(); var models = testModels(); var model: MakerJs.IModel = models[0]; - + function testRoot() { makerjs.cloneObject({}); makerjs.createRouteKey([]); @@ -29,7 +29,7 @@ function test() { makerjs.unitType.Millimeter; new makerjs.Collector(); } - + function testAngle() { makerjs.angle.mirror(45, true, false); makerjs.angle.noRevolutions(90); @@ -49,22 +49,22 @@ function test() { makerjs.exporter.toOpenJsCad(model); makerjs.exporter.toPDF({} as PDFKit.PDFDocument, model); makerjs.exporter.toSTL(model); - makerjs.exporter.toSVG(model, - { - annotate: true, - fontSize: '', - origin: [], - scale: 9.9, - stroke: '', - strokeWidth: '', - svgAttrs: {}, - units: '', + makerjs.exporter.toSVG(model, + { + annotate: true, + fontSize: '', + origin: [], + scale: 9.9, + stroke: '', + strokeWidth: '', + svgAttrs: {}, + units: '', useSvgPathOnly: false, viewBox: false }); makerjs.exporter.tryGetModelUnits(model); } - + function testImporter() { makerjs.importer.fromSVGPathData(''); makerjs.importer.parseNumericList(''); @@ -77,7 +77,7 @@ function test() { ({}).metaParameters; ({}).notes; } - + function testMeasure() { makerjs.measure.increase(mp, mm); makerjs.measure.isPointEqual(p1, p2); @@ -102,7 +102,7 @@ function test() { makerjs.measure.isPointOnSlope([], s); makerjs.measure.isSlopeEqual(s, s); } - + function testModel(){ makerjs.model.breakPathsAtIntersections(model, { paths:{ } }); var opts: MakerJs.ICombineOptions = { trimDeadEnds: true, pointMatchingDistance: 2 }; @@ -153,10 +153,10 @@ function test() { new makerjs.models.Slot([0, 0], [1, 1], 7), new makerjs.models.Square(8), new makerjs.models.Star(5, 10, 5), - new makerjs.models.Text({} as opentypejs.Font, 'z', 12) + new makerjs.models.Text({} as opentype.Font, 'z', 12) ]; } - + function testPath() { makerjs.path.breakAtPoint(paths.arc, [0,0]).type; makerjs.path.clone(paths.line); @@ -174,9 +174,9 @@ function test() { makerjs.path.scale(paths.arc, 8); makerjs.path.straighten(paths.arc); } - + function testPaths() { - var paths = { + var paths = { arc: new makerjs.paths.Arc([0,0], 7, 0, 180), circle: new MakerJs.paths.Circle([0,0], 5), line: new makerjs.paths.Line([0,0], [1,1]) @@ -184,20 +184,20 @@ function test() { new makerjs.paths.Chord(paths.arc); new makerjs.paths.Parallel(paths.line, 4, [1,1]); - + //paths.line.layer = "0"; - - var x: MakerJs.IPathLine = { - type: "line", - origin: [9,9], - end: [8,8], + + var x: MakerJs.IPathLine = { + type: "line", + origin: [9,9], + end: [8,8], layer: "4" }; - + return paths; } - - function testPoint() { + + function testPoint() { makerjs.point.add(p1, p2); makerjs.point.average(p1, p2); makerjs.point.clone(p1); @@ -216,14 +216,14 @@ function test() { makerjs.point.subtract(p2, p1); makerjs.point.zero(); } - - function testSolvers() { + + function testSolvers() { makerjs.solvers.solveTriangleASA(4, 4, 4); makerjs.solvers.solveTriangleSSS(9, 9, 9); } - - function testUnits() { + + function testUnits() { makerjs.units.conversionScale(makerjs.unitType.Centimeter, makerjs.unitType.Foot); } - + } \ No newline at end of file diff --git a/mapbox-gl/index.d.ts b/mapbox-gl/index.d.ts index f8fb9d9b60..a0ba241d99 100644 --- a/mapbox-gl/index.d.ts +++ b/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.26.0 +// Type definitions for Mapbox GL JS v0.27.0 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -16,7 +16,9 @@ declare namespace mapboxgl { export class Map extends Evented { constructor(options?: MapboxOptions); - addControl(control: Control): this; + addControl(control: Control, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; + + removeControl(control: Control): this; addClass(klass: string, options?: mapboxgl.StyleOptions): this; @@ -36,8 +38,12 @@ declare namespace mapboxgl { setMinZoom(minZoom?: number): this; + getMinZoom(): number; + setMaxZoom(maxZoom?: number): this; + getMaxZoom(): number; + project(lnglat: mapboxgl.LngLat | number[]): mapboxgl.Point; unproject(point: mapboxgl.Point | number[]): mapboxgl.LngLat; @@ -328,44 +334,34 @@ declare namespace mapboxgl { * Control */ export class Control extends Evented { - addTo(map: mapboxgl.Map): this; - - remove(): this; - } - - /** - * ControlOptions - */ - export interface ControlOptions { - position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'; } /** * Navigation */ export class NavigationControl extends Control { - constructor(options?: mapboxgl.ControlOptions); + constructor(); } /** * Geolocate */ export class GeolocateControl extends Control { - constructor(options?: mapboxgl.ControlOptions); + constructor(); } /** * Attribution */ export class AttributionControl extends Control { - constructor(options?: mapboxgl.ControlOptions); + constructor(); } /** * Scale */ export class ScaleControl extends Control { - constructor(options?: {position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left', maxWidth?: number, unit?: string}) + constructor(options?: {maxWidth?: number, unit?: string}) } /** @@ -409,6 +405,7 @@ declare namespace mapboxgl { metadata?: any; name?: string; pitch?: number; + light?: Light; sources?: any; sprite?: string; transition?: Transition; @@ -421,6 +418,13 @@ declare namespace mapboxgl { duration?: number; } + export interface Light { + "anchor"?: "map" | "viewport"; + "position"?: number[]; + "color"?: string; + "intensity"?: number; + } + export interface Source { type: "vector" | "raster" | "geojson" | "image" | "video"; } @@ -799,8 +803,8 @@ declare namespace mapboxgl { interactive?: boolean; filter?: any[]; - layout?: BackgroundLayout | FillLayout | LineLayout | SymbolLayout | RasterLayout | CircleLayout; - paint?: BackgroundPaint | FillPaint | LinePaint | SymbolPaint | RasterPaint | CirclePaint; + layout?: BackgroundLayout | FillLayout | FillExtrusionLayout | LineLayout | SymbolLayout | RasterLayout | CircleLayout; + paint?: BackgroundPaint | FillPaint | FillExtrusionPaint | LinePaint | SymbolPaint | RasterPaint | CirclePaint; } export interface StyleFunction { @@ -831,8 +835,18 @@ declare namespace mapboxgl { "fill-translate"?: number[]; "fill-translate-anchor"?: "map" | "viewport"; "fill-pattern"?: "string"; - "fill-extrude-height"?: number; - "fill-extrude-base"?: number; + } + + export interface FillExtrusionLayout { + visibility?: "visible" | "none"; + } + export interface FillExtrusionPaint { + "fill-extrusion-opacity"?: number; + "fill-extrusion-color"?: string | StyleFunction; + "fill-extrusion-translate"?: number[]; + "fill-extrusion-translate-anchor"?: "map" | "viewport"; + "fill-extrusion-height"?: number | StyleFunction; + "fill-extrusion-base"?: number; } export interface LineLayout { diff --git a/mapbox-gl/mapbox-gl-0.26.0.d.ts b/mapbox-gl/mapbox-gl-0.26.0.d.ts new file mode 100644 index 0000000000..ddb6344cbd --- /dev/null +++ b/mapbox-gl/mapbox-gl-0.26.0.d.ts @@ -0,0 +1,948 @@ +// Type definitions for Mapbox GL JS v0.26.0 +// Project: https://github.com/mapbox/mapbox-gl-js +// Definitions by: Dominik Bruderer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace mapboxgl { + let accessToken: string; + let version: string; + export function supported(options?: {failIfMajorPerformanceCaveat?: boolean}): boolean; + + /** + * Map + */ + export class Map extends Evented { + constructor(options?: MapboxOptions); + + addControl(control: Control): 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; + + getBounds(): mapboxgl.LngLatBounds; + + setMaxBounds(lnglatbounds?: mapboxgl.LngLatBounds | number[][]): this; + + setMinZoom(minZoom?: number): this; + + setMaxZoom(maxZoom?: number): this; + + project(lnglat: mapboxgl.LngLat | number[]): mapboxgl.Point; + + unproject(point: mapboxgl.Point | number[]): mapboxgl.LngLat; + + queryRenderedFeatures(pointOrBox?: mapboxgl.Point|number[]|mapboxgl.Point[]|number[][], parameters?: {layers?: string[], filter?: any[]}): GeoJSON.Feature[]; + + querySourceFeatures(sourceID: string, parameters: {sourceLayer?: string, filter?: any[]}): GeoJSON.Feature[]; + + setStyle(style: mapboxgl.Style | string): this; + + getStyle(): mapboxgl.Style; + + addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; + + removeSource(id: string): this; + + getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; + + addLayer(layer: mapboxgl.Layer, before?: string): this; + + removeLayer(id: string): this; + + getLayer(id: string): mapboxgl.Layer; + + setFilter(layer: string, filter: any[]): this; + + setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this; + + getFilter(layer: string): any[]; + + setPaintProperty(layer: string, name: string, value: any, klass?: string): this; + + getPaintProperty(layer: string, name: string, klass?: string): any; + + setLayoutProperty(layer: string, name: string, value: any): this; + + getLayoutProperty(layer: string, name: string, klass?: string): any; + + getContainer(): HTMLElement; + + getCanvasContainer(): HTMLElement; + + getCanvas(): HTMLCanvasElement; + + loaded(): boolean; + + remove(): void; + + onError(): void; + + showTileBoundaries: boolean; + + showCollisionBoxes: boolean; + + repaint: boolean; + + getCenter(): mapboxgl.LngLat; + + setCenter(center: LngLat|number[], eventData?: mapboxgl.EventData): this; + + panBy(offset: number[], options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + panTo(lnglat: mapboxgl.LngLat, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; + + getZoom(): number; + + setZoom(zoom: number, eventData?: mapboxgl.EventData): this; + + zoomTo(zoom: number, options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + zoomIn(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + zoomOut(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + getBearing(): number; + + setBearing(bearing: number, eventData?: mapboxgl.EventData): this; + + rotateTo(bearing: number, options?: mapboxgl.AnimationOptions, eventData?: EventData): this; + + resetNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + snapToNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + getPitch(): number; + + setPitch(pitch: number, eventData?: EventData): this; + + fitBounds(bounds: mapboxgl.LngLatBounds | number[][], options?: { linear?: boolean, easing?: Function, padding?: number, offset?: Point|number[],maxZoom?: number }): this; + + jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; + + easeTo(options: mapboxgl.CameraOptions | mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + flyTo(options: mapboxgl.FlyToOptions, eventData?: mapboxgl.EventData): this; + + stop(): this; + + scrollZoom: ScrollZoomHandler; + + boxZoom: BoxZoomHandler; + + dragRotate: DragRotateHandler; + + dragPan: DragPanHandler; + + keyboard: KeyboardHandler; + + doublClickZoom: DoubleClickZoomHandler; + + touchZoomRotate: TouchZoomRotateHandler; + } + + export interface MapboxOptions { + /** If true, an attribution control will be added to the map. */ + attributionControl?: boolean; + + bearing?: number; + + /** Snap to north threshold in degrees. */ + bearingSnap?: number; + + /** If true, enable the "box zoom" interaction (see BoxZoomHandler) */ + boxZoom?: boolean; + + /** initial map center */ + center?: mapboxgl.LngLat | number[]; + + /** Style class names with which to initialize the map */ + classes?: string[]; + + /** ID of the container element */ + container?: string | Element; + + /** If true, enable the "drag to pan" interaction (see DragPanHandler). */ + dragPan?: boolean; + + /** If true, enable the "drag to rotate" interaction (see DragRotateHandler). */ + dragRotate?: boolean; + + /** If true, enable the "double click to zoom" interaction (see DoubleClickZoomHandler). */ + doubleClickZoom?: boolean; + + /** If true, the map will track and update the page URL according to map position */ + hash?: boolean; + + /** If true, map creation will fail if the implementation determines that the performance of the created WebGL context would be dramatically lower than expected. */ + failIfMayorPerformanceCaveat?: boolean; + + /** If false, no mouse, touch, or keyboard listeners are attached to the map, so it will not respond to input */ + interactive?: boolean; + + /** If true, enable keyboard shortcuts (see KeyboardHandler). */ + keyboard?: boolean; + + /** If set, the map is constrained to the given bounds. */ + maxBounds?: mapboxgl.LngLatBounds | number[][]; + + /** Maximum zoom of the map */ + maxZoom?: number; + + /** Minimum zoom of the map */ + minZoom?: number; + + /** If true, The maps canvas can be exported to a PNG using map.getCanvas().toDataURL();. This is false by default as a performance optimization. */ + preserveDrawingBuffer?: boolean; + + pitch?: number; + + /** If true, enable the "scroll to zoom" interaction */ + scrollZoom?: boolean; + + /** stylesheet location */ + style?: mapboxgl.Style | string; + + /** If true, the map will automatically resize when the browser window resizes */ + trackResize?: boolean; + + /** If true, enable the "pinch to rotate and zoom" interaction (see TouchZoomRotateHandler). */ + touchZoomRotate?: boolean; + + /** Initial zoom level */ + zoom?: number; + } + + /** + * BoxZoomHandler + */ + export class BoxZoomHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + isActive(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * ScrollZoomHandler + */ + export class ScrollZoomHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * DragPenHandler + */ + export class DragPanHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + isActive(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * DragRotateHandler + */ + export class DragRotateHandler { + constructor(map: mapboxgl.Map, options?: {bearingSnap?: number, pitchWithRotate?: boolean}); + + isEnabled(): boolean; + + isActive(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * KeyboardHandler + */ + export class KeyboardHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * DoubleClickZoomHandler + */ + export class DoubleClickZoomHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * TouchZoomRotateHandler + */ + export class TouchZoomRotateHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + + disableRotation(): void; + + enableRotation(): void; + } + + /** + * Control + */ + export class Control extends Evented { + addTo(map: mapboxgl.Map): this; + + remove(): this; + } + + /** + * ControlOptions + */ + export interface ControlOptions { + position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'; + } + + /** + * Navigation + */ + export class NavigationControl extends Control { + constructor(options?: mapboxgl.ControlOptions); + } + + /** + * Geolocate + */ + export class GeolocateControl extends Control { + constructor(options?: mapboxgl.ControlOptions); + } + + /** + * Attribution + */ + export class AttributionControl extends Control { + constructor(options?: mapboxgl.ControlOptions); + } + + /** + * Scale + */ + export class ScaleControl extends Control { + constructor(options?: {position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left', maxWidth?: number, unit?: string}) + } + + /** + * Popup + */ + export class Popup extends Evented { + constructor(options?: mapboxgl.PopupOptions); + + addTo(map: mapboxgl.Map): this; + + isOpen(): boolean; + + remove(): this; + + getLngLat(): mapboxgl.LngLat; + + setLngLat(lnglat: mapboxgl.LngLat | number[]): this; + + setText(text: string): this; + + setHTML(html: string): this; + + setDOMContent(htmlNode: Node): this; + } + + export interface PopupOptions { + closeButton?: boolean; + + closeOnClick?: boolean; + + anchor?: 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; + + offset?: number | Point | number[] | { [key:string]: Point | number[];}; + } + + export interface Style { + bearing?: number; + center?: number[]; + glyphs?: string; + layers?: Layer[]; + metadata?: any; + name?: string; + pitch?: number; + sources?: any; + sprite?: string; + transition?: Transition; + version: number; + zoom?: number; + } + + export interface Transition { + delay?: number; + duration?: number; + } + + export interface Source { + type: "vector" | "raster" | "geojson" | "image" | "video"; + } + + /** + * GeoJSONSource + */ + + export interface GeoJSONSourceRaw extends Source, GeoJSONSourceOptions { + type: "geojson"; + } + + export class GeoJSONSource implements GeoJSONSourceRaw { + type: "geojson"; + + constructor(options?: mapboxgl.GeoJSONSourceOptions); + + setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; + } + + export interface GeoJSONSourceOptions { + data?: GeoJSON.Feature | GeoJSON.FeatureCollection | string; + + maxzoom?: number; + + buffer?: number; + + tolerance?: number; + + cluster?: number | boolean; + + clusterRadius?: number; + + clusterMaxZoom?: number; + } + + /** + * VideoSource + */ + export class VideoSource implements Source, VideoSourceOptions { + type: "video"; + + constructor(options?: mapboxgl.VideoSourceOptions); + + getVideo(): HTMLVideoElement; + + setCoordinates(coordinates: number[][]): this; + } + + export interface VideoSourceOptions { + urls?: string[]; + + coordinates?: number[][]; + } + + /** + * ImageSource + */ + export class ImageSource implements Source, ImageSourceOptions { + type: "image"; + + constructor(options?: mapboxgl.ImageSourceOptions); + + setCoordinates(coordinates: number[][]): this; + } + + export interface ImageSourceOptions { + url?: string; + + coordinates?: number[][]; + } + + interface VectorSource extends Source { + type: "vector"; + url?: string; + tiles?: string[]; + minzoom?: number; + maxzoom?: number; + } + + interface RasterSource extends Source { + type: "raster"; + url: string; + tiles?: string[]; + minzoom?: number; + maxzoom?: number; + tileSize?: number; + } + + /** + * LngLat + */ + export class LngLat { + lng: number; + lat: number; + + constructor(lng: number, lat: number); + + /** Return a new LngLat object whose longitude is wrapped to the range (-180, 180). */ + wrap(): mapboxgl.LngLat; + + /** Return a LngLat as an array */ + toArray(): number[]; + + /** Return a LngLat as a string */ + toString(): string; + + static convert(input: number[]|mapboxgl.LngLat): mapboxgl.LngLat; + } + + /** + * LngLatBounds + */ + export class LngLatBounds { + sw: LngLat | number[]; + ne: LngLat | number[]; + constructor(sw?: LngLat, ne?: LngLat); + + /** Extend the bounds to include a given LngLat or LngLatBounds. */ + extend(obj: mapboxgl.LngLat | mapboxgl.LngLatBounds): this; + + /** Get the point equidistant from this box's corners */ + getCenter(): mapboxgl.LngLat; + + /** Get southwest corner */ + getSouthWest(): mapboxgl.LngLat; + + /** Get northeast corner */ + getNorthEast(): mapboxgl.LngLat; + + /** Get northwest corner */ + getNorthWest(): mapboxgl.LngLat; + + /** Get southeast corner */ + getSouthEast(): mapboxgl.LngLat; + + /** Get west edge longitude */ + getWest(): number; + + /** Get south edge latitude */ + getSouth(): number; + + /** Get east edge longitude */ + getEast(): number; + + /** Get north edge latitude */ + getNorth(): number; + + /** Returns a LngLatBounds as an array */ + toArray(): number[][]; + + /** Return a LngLatBounds as a string */ + toString(): string; + + /** Convert an array to a LngLatBounds object, or return an existing LngLatBounds object unchanged. */ + static convert(input: mapboxgl.LngLatBounds | number[] | number[][]): mapboxgl.LngLatBounds; + } + + /** + * Point + */ + // Todo: Pull out class to seperate definition for Module "point-geometry" + export class Point { + constructor(options?: Object); + + clone(): Point; + + add(p: number): Point; + + sub(p: number): Point; + + mult(k: number): Point; + + div(k: number): Point; + + rotate(a: number): Point; + + matMult(m: number): Point; + + unit(): Point; + + perp(): Point; + + round(): Point; + + mag(): number; + + equals(): boolean; + + dist(): number; + + distSqr(): number; + + angle(): number; + + angleTo(): number; + + angleWidth(): number; + + angleWidthSep(): number; + } + + export class Marker { + constructor(element?: HTMLElement, options?: { offset?: Point | number[] }); + + addTo(map: Map): this; + + remove(): this; + + getLngLat(): LngLat; + + setLngLat(lngLat: LngLat | number[]): this; + + setPopup(popup?: Popup): this; + + getPopup(): Popup; + + togglePopup(): this; + } + + /** + * Evented + */ + export class Evented { + on(type: string, listener: Function): this; + + off(type?: string | any, listener?: Function): this; + + once(type: string, listener: Function): this; + + fire(type: string, data?: mapboxgl.EventData | Object): this; + + listens(type: string): boolean; + } + + /** + * StyleOptions + */ + export interface StyleOptions { + transition?: boolean; + } + + /** + * EventData + */ + export class EventData { + type: string; + target: Map; + originalEvent: Event; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + } + + export class MapMouseEvent { + type: string; + target: Map; + originalEvent: MouseEvent; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + } + + export class MapTouchEvent { + type: string; + target: Map; + originalEvent: TouchEvent; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + points: Point[]; + lngLats: LngLat[]; + } + + export class MapBoxZoomEvent { + originalEvent: MouseEvent; + boxZoomBounds: LngLatBounds; + } + + export class MapDataEvent { + type: string; + dataType: "source" | "style" | "tile"; + } + + /** + * AnimationOptions + */ + export interface AnimationOptions { + /** Number in milliseconds */ + duration?: number; + easing?: Function; + /** point, origin of movement relative to map center */ + offset?: Point | number[]; + /** When set to false, no animation happens */ + animate?: boolean; + } + + /** + * CameraOptions + */ + export interface CameraOptions { + /** Map center */ + center?: mapboxgl.LngLat | number[]; + /** Map zoom level */ + zoom?: number; + /** Map rotation bearing in degrees counter-clockwise from north */ + bearing?: number; + /** Map angle in degrees at which the camera is looking at the ground */ + pitch?: number; + /** If zooming, the zoom center (defaults to map center) */ + around?: mapboxgl.LngLat | number[]; + } + + /** + * FlyToOptions + */ + export interface FlyToOptions extends AnimationOptions, CameraOptions { + curve?: number; + minZoom?: number; + speed?: number; + screenSpeed?: number; + easing?: Function; + } + + /** + * MapEvent + */ + export interface MapEvent { + resize?: void; + webglcontextlost?: {originalEvent: WebGLContextEvent}; + webglcontextrestored?: {originalEvent: WebGLContextEvent}; + remove?: void; + dataloading?: {data: mapboxgl.MapDataEvent}; + data?: {data: mapboxgl.MapDataEvent}; + render?: void; + contextmenu?: {data: mapboxgl.MapMouseEvent}; + dblclick?: {data: mapboxgl.MapMouseEvent}; + click?: {data: mapboxgl.MapMouseEvent}; + touchcancel?: {data: mapboxgl.MapTouchEvent}; + touchmove?: {data: mapboxgl.MapTouchEvent}; + touchend?: {data: mapboxgl.MapTouchEvent}; + touchstart?: {data: mapboxgl.MapTouchEvent}; + mousemove?: {data: mapboxgl.MapMouseEvent}; + mouseup?: {data: mapboxgl.MapMouseEvent}; + mousedown?: {data: mapboxgl.MapMouseEvent}; + moveend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + move?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + movestart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + mouseout?:{data: mapboxgl.MapMouseEvent}; + load?: void; + zoomend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + zoom?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + zoomstart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + boxzoomcancel?: {data: mapboxgl.MapBoxZoomEvent}; + boxzoomstart?: {data: mapboxgl.MapBoxZoomEvent}; + boxzoomend?: {data: mapboxgl.MapBoxZoomEvent}; + rotate?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + rotatestart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + rotateend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + drag?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + dragend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + pitch?: {data: mapboxgl.EventData}; + } + + export interface Layer { + id: string; + type?: "fill" | "line" | "symbol" | "circle" | "raster" | "background" | string; //TODO: Ideally we wouldn't accept string here, just these specific strings + + metadata?: any; + ref?: string; + + source?: string; + + "source-layer"?: string; + + minzoom?: number; + maxzoom?: number; + + interactive?: boolean; + + filter?: any[]; + layout?: BackgroundLayout | FillLayout | LineLayout | SymbolLayout | RasterLayout | CircleLayout; + paint?: BackgroundPaint | FillPaint | LinePaint | SymbolPaint | RasterPaint | CirclePaint; + } + + export interface StyleFunction { + stops: any[][]; + property?: string; + base?: number; + type?: "identity" | "exponential" | "interval" | "categorical"; + "colorSpace"?: "rgb" | "lab" | "interval"; + } + + export interface BackgroundLayout { + visibility?: "visible" | "none"; + } + export interface BackgroundPaint { + "background-color"?: string; + "background-pattern"?: string; + "background-opacity"?: number; + } + + export interface FillLayout { + visibility?: "visible" | "none"; + } + export interface FillPaint { + "fill-antialias"?: boolean; + "fill-opacity"?: number | StyleFunction; + "fill-color"?: string | StyleFunction; + "fill-outline-color": string | StyleFunction; + "fill-translate"?: number[]; + "fill-translate-anchor"?: "map" | "viewport"; + "fill-pattern"?: "string"; + "fill-extrude-height"?: number; + "fill-extrude-base"?: number; + } + + export interface LineLayout { + visibility?: "visible" | "none"; + + "line-cap"?: "butt" | "round" | "square"; + "line-join"?: "bevel" | "round" | "miter"; + "line-miter-limit"?: number; + "line-round-limit"?: number; + } + export interface LinePaint { + "line-opacity"?: number; + "line-color"?: string| StyleFunction; + "line-translate"?: number[]; + "line-translate-anchor"?: "map" | "viewport"; + "line-width"?: number; + "line-gap-width"?: number; + "line-offset"?: number; + "line-blur"?: number; + "line-dasharray"?: number[]; + "line-dasharray-transition"?: Transition; + "line-pattern"?: string; + } + + export interface SymbolLayout { + visibility?: "visible" | "none"; + + "symbol-placement"?: "point" | "line"; + "symbol-spacing"?: number; + "symbol-avoid-edges"?: boolean; + "icon-allow-overlap"?: boolean; + "icon-ignore-placement"?: boolean; + "icon-optional"?: boolean; + "icon-rotation-alignment"?: "map" | "viewport" | "auto"; + "icon-size"?: number; + "icon-text-fit"?: "none" | "both" | "width" | "height"; + "icon-text-fit-padding"?: number[]; + "icon-image"?: string; + "icon-rotate"?: number | StyleFunction; + "icon-padding"?: number; + "icon-keep-upright"?: boolean; + "icon-offset"?: number[]; + "text-pitch-alignment"?: "map" | "viewport" | "auto"; + "text-rotation-alignment"?: "map" | "viewport" | "auto"; + "text-field"?: string; + "text-font"?: string | string[]; + "text-size"?: number; + "text-max-width"?: number; + "text-line-height"?: number; + "text-letter-spacing"?: number; + "text-justify"?: "left" | "center" | "right"; + "text-anchor"?: "center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right"; + "text-max-angle"?: number; + "text-rotate"?: number; + "text-padding"?: number; + "text-keep-upright"?: boolean; + "text-transform"?: "none" | "uppercase" | "lowercase"; + "text-offset"?: number[]; + "text-allow-overlap"?: boolean; + "text-ignore-placement"?: boolean; + "text-optional"?: boolean; + + } + export interface SymbolPaint { + "icon-opacity"?: number; + "icon-color"?: string; + "icon-halo-color"?: string; + "icon-halo-width"?: number; + "icon-halo-blur"?: number; + "icon-translate"?: number[]; + "icon-translate-anchor"?: "map" | "viewport"; + "text-opacity"?: number; + "text-color"?: "string"; + "text-halo-color"?: "string"; + "text-halo-width"?: number; + "text-halo-blur"?: number; + "text-translate"?: number[]; + "text-translate-anchor"?: "map" | "viewport"; + } + + export interface RasterLayout { + visibility?: "visible" | "none"; + } + + export interface RasterPaint { + "raster-opacity"?: number; + "raster-hue-rotate"?: number; + "raster-brightness-min"?: number; + "raster-brightness-max"?: number; + "raster-saturation"?: number; + "raster-contrast"?: number; + "raster-fade-duration"?: number; + } + + export interface CircleLayout { + visibility?: "visible" | "none"; + } + + export interface CirclePaint { + "circle-radius"?: number | StyleFunction; + "circle-radius-transition"?: Transition; + "circle-color"?: number | StyleFunction; + "circle-blur"?: number | StyleFunction; + "circle-opacity"?: number | StyleFunction; + "circle-translate"?: number[]; + "circle-translate-anchor"?: "map" | "viewport"; + "circle-pitch-scale"?: "map" | "viewport"; + } +} + +declare module 'mapbox-gl' { + export = mapboxgl; +} diff --git a/marker-animate-unobtrusive/marker-animate-unobtrusive.d.ts b/marker-animate-unobtrusive/index.d.ts similarity index 100% rename from marker-animate-unobtrusive/marker-animate-unobtrusive.d.ts rename to marker-animate-unobtrusive/index.d.ts diff --git a/marker-animate-unobtrusive/tsconfig.json b/marker-animate-unobtrusive/tsconfig.json index 3961120707..9398f7b73e 100644 --- a/marker-animate-unobtrusive/tsconfig.json +++ b/marker-animate-unobtrusive/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "marker-animate-unobtrusive.d.ts", + "index.d.ts", "marker-animate-unobtrusive-tests.ts", "marker-animate-unobtrusive-amd-tests.ts" ] diff --git a/masonry-layout/masonry-layout.d.ts b/masonry-layout/index.d.ts similarity index 100% rename from masonry-layout/masonry-layout.d.ts rename to masonry-layout/index.d.ts diff --git a/masonry-layout/tsconfig.json b/masonry-layout/tsconfig.json index 0638ecd09d..125331bcd8 100644 --- a/masonry-layout/tsconfig.json +++ b/masonry-layout/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "masonry-layout.d.ts", + "index.d.ts", "masonry-layout-tests.ts" ] } \ No newline at end of file diff --git a/material-ui/index.d.ts b/material-ui/index.d.ts index a75fa9a369..c98250fc0b 100644 --- a/material-ui/index.d.ts +++ b/material-ui/index.d.ts @@ -1116,6 +1116,7 @@ declare namespace __MaterialUI { secondaryText?: React.ReactNode; style?: React.CSSProperties; value?: any; + containerElement?: React.ReactNode | string; } export class MenuItem extends React.Component { } diff --git a/math3d/index.d.ts b/math3d/index.d.ts new file mode 100644 index 0000000000..8981aaf1a9 --- /dev/null +++ b/math3d/index.d.ts @@ -0,0 +1,168 @@ +// Type definitions for math3.d.ts +// Project: https://github.com/adragonite/math3d +// Definitions by: Laszlo Jakab +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export class Vector3 { + constructor(x?: number, y?: number, z?: number); + + static back: Vector3; + static down: Vector3; + static forward: Vector3; + static left: Vector3; + static one: Vector3; + static right: Vector3; + static up: Vector3; + static zero: Vector3; + static dimension: number; + static FromVector4: (vector4: Vector4) => Vector3; + + homogeneous: Vector4; + magnitude: number; + values: number[]; + vector4: Vector4; + x: number; + y: number; + z: number; + + add(vector3: Vector3): Vector3; + average(vector3: Vector3): Vector3; + cross(vector3: Vector3): Vector3; + distanceTo(vector3: Vector3): number; + dot(vector3: Vector3): number; + equals(vector3: Vector3): boolean; + mulScalar(scalar: number): Vector3; + negate(): Vector3; + normalize(): Vector3; + scale(vector3: Vector3): Vector3; + sub(vector3: Vector3): Vector3; + toString(): string; +} + +export class Vector4 { + constructor(x?: number, y?: number, z?: number, w?: number); + + static one: Vector4; + static zero: Vector4; + static dimension: number; + + magnitude: number; + values: number[]; + x: number; + y: number; + z: number; + w: number; + + add(vector4: Vector4): Vector4; + distanceTo(vector4: Vector4): number; + dot(vector4: Vector4): number; + equals(vector4: Vector4): boolean; + mulScalar(scalar: number): Vector4; + negate(): Vector4; + normalize(): Vector3; + sub(vector4: Vector4): Vector3; + toString(): string; +} + +export class Quaternion { + constructor(x?: number, y?: number, z?: number, w?: number); + static Euler(x?: number, y?: number, z?: number): Quaternion; + static AngleAxis(axis: Vector3, angle: number): Quaternion; + + static identity: Quaternion; + static zero: Quaternion; + + angleAxis: { axis: Vector3, angle: number }; + eulerAngles: { x: number, y: number, z: number }; + x: number; + y: number; + z: number; + w: number; + + angleTo(quaternion: Quaternion): number; + conjugate(): Quaternion; + distanceTo(quaternion: Quaternion): number; + dot(quaternion: Quaternion): number; + equals(quaternion: Quaternion): boolean; + inverse(): Quaternion; + mul(quaternion: Quaternion): Quaternion; + mulVector3(vector3: Vector3): Vector3; + toString(): string; +} + +export class Matrix4x4 { + constructor(data: number[]); + + static FlipMatrix(flipX: boolean, flipY: boolean, flipZ: boolean): Matrix4x4; + static ScaleMatrix(scale: number | Vector3): Matrix4x4; + static RotationMatrix(quaternion: Quaternion): Matrix4x4; + static TranslationMatrix(translation: Vector3): Matrix4x4; + static TRS(translation: Vector3, rotation: Quaternion, scale: number | Vector3): Matrix4x4; + static LocalToWorldMatrix(position: Vector3, rotation: Quaternion, scale: number | Vector3): Matrix4x4; + static WorldToLocalMatrix(position: Vector3, rotation: Quaternion, scale: number | Vector3): Matrix4x4; + + static identity: Matrix4x4; + static zero: Matrix4x4; + + columns: number[][]; + m11: number; + m12: number; + m13: number; + m14: number; + m21: number; + m22: number; + m23: number; + m24: number; + m31: number; + m32: number; + m33: number; + m34: number; + m41: number; + m42: number; + m43: number; + m44: number; + rows: number[][]; + size: { rows: number, columns: number }; + values: number[]; + + determinant(): number + inverse(): Matrix4x4; + negate(): Matrix4x4; + transpose(): Matrix4x4; + add(matrix4x4: Matrix4x4): Matrix4x4; + sub(matrix4x4: Matrix4x4): Matrix4x4; + mul(matrix4x4: Matrix4x4): Matrix4x4; + mulScalar(scalar: number): Matrix4x4; + mulVector3(vector3: Vector3): Vector3; +} + +export class Transform { + constructor(position?: Vector3, rotation?: Quaternion); + + forward: Vector3; + localPosition: Vector3; + localRotation: Quaternion; + localToWorldMatrix: Matrix4x4; + name: string; + parent: Transform; + position: Vector3; + right: Vector3; + root: Transform; + rotation: Vector3; + up: Vector3; + worldToLocalMatrix: Matrix4x4; + + addChild(child: Transform): void; + inverseTransformPosition(position: Vector3): Vector3; + removeChild(child: Transform): void; + transformPosition(position: Vector3): Vector3; + translate(translation: Vector3, relativeTo?: Transform.Space): Transform; + rotate(x: number, y: number, z: number, relativeTo?: Transform.Space): Transform; +} + +export namespace Transform { + export enum Space { + Self, + World + } +} diff --git a/math3d/math3d-tests.ts b/math3d/math3d-tests.ts new file mode 100644 index 0000000000..d04ddbefb9 --- /dev/null +++ b/math3d/math3d-tests.ts @@ -0,0 +1,7 @@ +import * as math3d from 'math3d'; +const v = new math3d.Vector3(1, 2, 3); +v.add(new math3d.Vector3(0, 0, 1)); +new math3d.Matrix4x4([1,1,1,1, + 2,2,2,2, + 3,3,3,3, + 4,4,4,4]); diff --git a/math3d/tsconfig.json b/math3d/tsconfig.json new file mode 100644 index 0000000000..2f4e358aaf --- /dev/null +++ b/math3d/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "math3d-tests.ts" + ] +} diff --git a/math3d/tslint.json b/math3d/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/math3d/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/matter-js/index.d.ts b/matter-js/index.d.ts index 7d63ad6195..2ecf70d680 100644 --- a/matter-js/index.d.ts +++ b/matter-js/index.d.ts @@ -487,7 +487,7 @@ declare namespace Matter { * @type boolean * @default true */ - visible: boolean; + visible?: boolean; /** * An `Object` that defines the sprite properties to use when rendering, if any. @@ -495,31 +495,31 @@ declare namespace Matter { * @property render.sprite * @type object */ - sprite: IBodyRenderOptionsSprite; + sprite?: IBodyRenderOptionsSprite; /** * A String that defines the fill style to use when rendering the body (if a sprite is not defined). It is the same as when using a canvas, so it accepts CSS style property values. Default: a random colour */ - fillStyle: string; + fillStyle?: string; /** * A Number that defines the line width to use when rendering the body outline (if a sprite is not defined). A value of 0 means no outline will be rendered. Default: 1.5 */ - lineWidth: number; + lineWidth?: number; /** * A String that defines the stroke style to use when rendering the body outline (if a sprite is not defined). It is the same as when using a canvas, so it accepts CSS style property values. Default: a random colour */ - strokeStyle: string; + strokeStyle?: string; /* * Sets the opacity. 1.0 is fully opaque. 0.0 is fully translucent */ - opacity: number; + opacity?: number; } export interface IBodyRenderOptionsSprite { @@ -1969,6 +1969,11 @@ declare namespace Matter { */ enableSleeping: boolean; + /** + * Collision pair set for this `Engine`. + */ + pairs: any; + /** * An integer `Number` that specifies the number of position iterations to perform each update. * The higher the value, the higher quality the simulation will be at the expense of performance. @@ -2124,7 +2129,7 @@ declare namespace Matter { * @param {} options * @return {MouseConstraint} A new MouseConstraint */ - create(engine: Engine, options: IMouseConstraintDefinition): MouseConstraint; + static create(engine: Engine, options?: IMouseConstraintDefinition): MouseConstraint; /** * The `Constraint` object that is used to move the body during interaction. @@ -2173,6 +2178,21 @@ declare namespace Matter { type: string; } + /** + * The `Matter.Pairs` module contains methods for creating and manipulating collision pair sets. + * + * @class Pairs + */ + export class Pairs { + /** + * Clears the given pairs structure. + * @method clear + * @param {pairs} pairs + * @return {pairs} pairs + */ + static clear(pairs: any): any; + } + export interface IPair { id: number; bodyA: Body; @@ -2328,9 +2348,12 @@ declare namespace Matter { */ hasBounds?: boolean; - - - + /** + * Render wireframes only + * @type boolean + * @default true + */ + wireframes?: boolean; } /** @@ -2923,7 +2946,7 @@ declare namespace Matter { * @param body * @returns world */ - static add(world: World, body: Body | Array | Composite | Array | Constraint | Array): World; + static add(world: World, body: Body | Array | Composite | Array | Constraint | Array | MouseConstraint): World; /** * An alias for Composite.addBody since World is also a Composite @@ -3285,7 +3308,7 @@ declare namespace Matter { * @param eventNames * @param event */ - static trigger(object: any, eventNames: string, event: (e: any) => void): void; + static trigger(object: any, eventNames: string, event?: (e: any) => void): void; } } diff --git a/mitm/mitm.d.ts b/mitm/index.d.ts similarity index 100% rename from mitm/mitm.d.ts rename to mitm/index.d.ts diff --git a/mitm/tsconfig.json b/mitm/tsconfig.json index e14e440597..d37bc6fddb 100644 --- a/mitm/tsconfig.json +++ b/mitm/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "mitm.d.ts", + "index.d.ts", "mitm-tests.ts" ] } \ No newline at end of file diff --git a/moment-range/index.d.ts b/moment-range/index.d.ts index bf8ff18350..7ff7feb9b8 100644 --- a/moment-range/index.d.ts +++ b/moment-range/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Moment.js 2.0.3 +// Type definitions for Moment.js 2.0.4 // Project: https://github.com/gf3/moment-range // Definitions by: Bart van den Burg , Wilgert Velinga // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -34,6 +34,8 @@ declare module 'moment' { toString (): string; + toArray (by: Range|String, exclusive?: boolean): Moment[]; + valueOf (): number; center (): number; diff --git a/moment-range/moment-range-tests.ts b/moment-range/moment-range-tests.ts index 21949aac1c..16bcf7c808 100644 --- a/moment-range/moment-range-tests.ts +++ b/moment-range/moment-range-tests.ts @@ -42,3 +42,6 @@ var res17: moment.Range = range.clone(); var res18: moment.Moment = range.start; var res19: moment.Moment = range.end; + +var res20: moment.Moment[] = range.toArray('days'); +var res22: moment.Moment[] = range.toArray('days', true); diff --git a/mongodb/index.d.ts b/mongodb/index.d.ts index 49f092a0f1..82f8f0dcce 100644 --- a/mongodb/index.d.ts +++ b/mongodb/index.d.ts @@ -8,6 +8,7 @@ /// import {EventEmitter} from 'events'; +import { Readable, Writable } from "stream"; // Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html export class MongoClient { @@ -982,8 +983,10 @@ export interface FindOperatorsOrdered { upsert(): FindOperatorsOrdered; } -//http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html + //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html export interface UnorderedBulkOperation { + //http://mongodb.github.io/node-mongodb-native/2.1/api/lib_bulk_unordered.js.html line 339 + length: number; //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#execute execute(callback: MongoCallback): void; execute(options?: FSyncOptions): Promise; @@ -1112,26 +1115,11 @@ export interface WriteOpResult { result: any; } -//http://mongodb.github.io/node-mongodb-native/2.1/api/external-Readable.html -export interface Readable { - pause(): void; - pipe(destination: Writable, options?: Object): void; - read(size: number): string | Buffer | void; - resume(): void; - setEncoding(encoding: string): void; - unpipe(destination?: Writable): void; - unshift(stream: Buffer | string): void; - wrap(stream: Stream): void; -} - -export interface Writable { } -export interface Stream { } - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~resultCallback export type CursorResult = any | void | boolean; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html -export interface Cursor extends Readable, NodeJS.EventEmitter { +export interface Cursor extends Readable { sortValue: string; timeout: boolean; @@ -1170,7 +1158,7 @@ export interface Cursor extends Readable, NodeJS.EventEmitter { // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#limit limit(value: number): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#map - map(transform: Function): void; + map(transform: Function): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#max max(max: number): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#maxAwaitTimeMS @@ -1184,16 +1172,12 @@ export interface Cursor extends Readable, NodeJS.EventEmitter { // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#next next(): Promise; next(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#pause - pause(): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#pipe pipe(destination: Writable, options?: Object): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#project project(value: Object): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#read read(size: number): string | Buffer | void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#resume - resume(): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#next returnKey(returnKey: Object): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#rewind @@ -1221,8 +1205,6 @@ export interface Cursor extends Readable, NodeJS.EventEmitter { unpipe(destination?: Writable): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#unshift unshift(stream: Buffer | string): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#wrap - wrap(stream: Stream): void; } //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#count @@ -1248,7 +1230,7 @@ export interface EndCallback { export type AggregationCursorResult = any | void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html -export interface AggregationCursor extends Readable, NodeJS.EventEmitter { +export interface AggregationCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#batchSize batchSize(value: number): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#clone @@ -1278,8 +1260,6 @@ export interface AggregationCursor extends Readable, NodeJS.EventEmitter { next(callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#out out(destination: string): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#pause - pause(): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#pipe pipe(destination: Writable, options?: Object): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#project @@ -1288,8 +1268,6 @@ export interface AggregationCursor extends Readable, NodeJS.EventEmitter { read(size: number): string | Buffer | void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#redact redact(document: Object): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#resume - resume(): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#rewind rewind(): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#setEncoding @@ -1307,12 +1285,10 @@ export interface AggregationCursor extends Readable, NodeJS.EventEmitter { unshift(stream: Buffer | string): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#unwind unwind(field: string): AggregationCursor; - //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#wrap - wrap(stream: Stream): void; } //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html -export interface CommandCursor extends Readable, NodeJS.EventEmitter { +export interface CommandCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#batchSize batchSize(value: number): CommandCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#clone @@ -1329,14 +1305,10 @@ export interface CommandCursor extends Readable, NodeJS.EventEmitter { // http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#next next(): Promise; next(callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#pause - pause(): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#pipe pipe(destination: Writable, options?: Object): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#read read(size: number): string | Buffer | void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#resume - resume(): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#rewind rewind(): CommandCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#setEncoding @@ -1350,6 +1322,83 @@ export interface CommandCursor extends Readable, NodeJS.EventEmitter { unpipe(destination?: Writable): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#unshift unshift(stream: Buffer | string): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/CommandCursor.html#wrap - wrap(stream: Stream): void; +} + +// http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html +export class GridFSBucket { + constructor(db: Db, options?: GridFSBucketOptions); + // http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#delete + delete(id: ObjectID, callback?: GridFSBucketErrorCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#drop + drop(callback?: GridFSBucketErrorCallback): void; + // http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#find + find(filter?: Object, options?: GridFSBucketFindOptions): Cursor; + // http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#openDownloadStream + openDownloadStream(id: ObjectID, options?: { start: number, end: number }): GridFSBucketReadStream; + // http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#openDownloadStreamByName + openDownloadStreamByName(filename: string, options?: { revision: number, start: number, end: number }): GridFSBucketReadStream; + // http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#openUploadStream + openUploadStream(filename: string, options?: GridFSBucketOpenUploadStreamOptions): GridFSBucketWriteStream; + // http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#openUploadStreamWithId + openUploadStreamWithId(id: string | number | Object, filename: string, options?: GridFSBucketOpenUploadStreamOptions): GridFSBucketWriteStream; + // http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#rename + rename(id: ObjectID, filename: string, callback?: GridFSBucketErrorCallback): void; +} + +// http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html +export interface GridFSBucketOptions { + bucketName?: string; + chunkSizeBytes?: number; + writeConcern?: Object; + ReadPreference?: Object; +} + +// http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#~errorCallback +export interface GridFSBucketErrorCallback { + (err?: MongoError): void; +} + +// http://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#find +export interface GridFSBucketFindOptions { + batchSize?: number; + limit?: number; + maxTimeMS?: number; + noCursorTimeout?: boolean; + skip?: number; + sort?: Object; +} + +// https://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucket.html#openUploadStream +export interface GridFSBucketOpenUploadStreamOptions { + chunkSizeBytes?: number, + metadata?: Object, + contentType?: string, + aliases?: Array +} + +// https://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucketReadStream.html +export class GridFSBucketReadStream extends Readable { + constructor(chunks: Collection, files: Collection, readPreference: Object, filter: Object, options?: GridFSBucketReadStreamOptions); +} + +// https://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucketReadStream.html +export interface GridFSBucketReadStreamOptions { + sort?: number, + skip?: number, + start?: number, + end?: number +} + +// https://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucketWriteStream.html +export class GridFSBucketWriteStream extends Writable{ + constructor(bucket: GridFSBucket, filename:string, options?: GridFSBucketWriteStreamOptions); +} + +// https://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucketWriteStream.html +export interface GridFSBucketWriteStreamOptions { + id?: string | number | Object, + chunkSizeBytes?: number, + w?: number, + wtimeout?: number, + j?: number } diff --git a/mongoose-paginate/mongoose-paginate.d.ts b/mongoose-paginate/index.d.ts similarity index 100% rename from mongoose-paginate/mongoose-paginate.d.ts rename to mongoose-paginate/index.d.ts diff --git a/mongoose-paginate/tsconfig.json b/mongoose-paginate/tsconfig.json index 6cd106d699..a580a52c42 100644 --- a/mongoose-paginate/tsconfig.json +++ b/mongoose-paginate/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "mongoose-paginate.d.ts", + "index.d.ts", "mongoose-paginate-tests.ts" ] } \ No newline at end of file diff --git a/mongoose/index.d.ts b/mongoose/index.d.ts index 150d94b2df..f862d3b3d1 100644 --- a/mongoose/index.d.ts +++ b/mongoose/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mongoose 4.5.4 +// Type definitions for Mongoose 4.6.8 // Project: http://mongoosejs.com/ // Definitions by: simonxca , horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -285,6 +285,9 @@ declare module "mongoose" { open(connection_string: string, database?: string, port?: number, options?: ConnectionOpenOptions, callback?: (err: any) => void): any; + /** Helper for dropDatabase() */ + dropDatabase(callback?: (err: any) => void): Promise; + /** * Opens the connection to a replica set. * @param uris comma-separated mongodb:// URIs @@ -659,6 +662,8 @@ declare module "mongoose" { methods: any; /** Object of currently defined statics on this schema. */ statics: any; + /** The original object passed to the schema constructor */ + obj: any; } interface SchemaOptions { @@ -808,7 +813,7 @@ declare module "mongoose" { */ populate(callback: (err: any, res: this) => void): this; populate(path: string, callback?: (err: any, res: this) => void): this; - populate(options: ModelPopulateOptions, callback?: (err: any, res: this) => void): this; + populate(options: ModelPopulateOptions | ModelPopulateOptions[], callback?: (err: any, res: this) => void): this; /** Gets _id(s) used during population of the given path. If the path was not populated, undefined is returned. */ populated(path: string): any; @@ -1449,7 +1454,7 @@ declare module "mongoose" { */ populate(path: string | Object, select?: string | Object, model?: any, match?: Object, options?: Object): this; - populate(options: ModelPopulateOptions): this; + populate(options: ModelPopulateOptions | ModelPopulateOptions[]): this; /** * Determines the MongoDB nodes from which to read. @@ -2423,6 +2428,8 @@ declare module "mongoose" { model?: string; /** optional query options like sort, limit, etc */ options?: Object; + /** deep populate */ + populate?: ModelPopulateOptions | ModelPopulateOptions[] } interface ModelUpdateOptions { diff --git a/multer-s3/multer-s3.d.ts b/multer-s3/index.d.ts similarity index 100% rename from multer-s3/multer-s3.d.ts rename to multer-s3/index.d.ts diff --git a/multer-s3/tsconfig.json b/multer-s3/tsconfig.json index 04e16429ee..e05b4498c8 100644 --- a/multer-s3/tsconfig.json +++ b/multer-s3/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "multer-s3.d.ts", + "index.d.ts", "multer-s3-tests.ts" ] } \ No newline at end of file diff --git a/multiparty/index.d.ts b/multiparty/index.d.ts index 601d888956..ca968fefcf 100644 --- a/multiparty/index.d.ts +++ b/multiparty/index.d.ts @@ -19,7 +19,7 @@ export declare class Form extends events.EventEmitter { * @param callback */ parse(request: http.IncomingMessage, callback?: (error: Error, fields: any, files: any) => any): void; - } +} export interface File { /** diff --git a/multiplexjs/multiplexjs-tests.ts b/multiplexjs/multiplexjs-tests.ts index 94f212b533..606b63fa13 100644 --- a/multiplexjs/multiplexjs-tests.ts +++ b/multiplexjs/multiplexjs-tests.ts @@ -1,4 +1,3 @@ - /// diff --git a/musicmetadata/musicmetadata.d.ts b/musicmetadata/index.d.ts similarity index 100% rename from musicmetadata/musicmetadata.d.ts rename to musicmetadata/index.d.ts diff --git a/musicmetadata/tsconfig.json b/musicmetadata/tsconfig.json index d403132a8d..aaecf53410 100644 --- a/musicmetadata/tsconfig.json +++ b/musicmetadata/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "musicmetadata.d.ts", + "index.d.ts", "musicmetadata-tests.ts" ] } \ No newline at end of file diff --git a/needle/index.d.ts b/needle/index.d.ts index 63270e3ff8..7607fdfc78 100644 --- a/needle/index.d.ts +++ b/needle/index.d.ts @@ -5,93 +5,88 @@ /// -declare var needle: Needle.NeedleStatic; -export = needle; +declare module "needle" { + import * as http from 'http'; + import * as Buffer from 'buffer'; + module Needle { + interface NeedleResponse extends http.IncomingMessage { + body: any; + raw: Buffer; + bytes: number; + } -declare namespace Needle { - interface ReadableStream extends NodeJS.ReadableStream { - } + interface ReadableStream extends NodeJS.ReadableStream { + } - interface Callback { - (error: Error, response: any, body: any): void; + interface Callback { + (error: Error, response: NeedleResponse, body: any): void; + } + + interface RequestOptions { + timeout?: number; + follow?: number; + follow_max?: number; + multipart?: boolean; + proxy?: string; + agent?: string; + headers?: Object; + auth?: string; // auto | digest | basic (default) + json?: boolean; + + // These properties are overwritten by those in the 'headers' field + compressed?: boolean; + cookies?: { [name: string]: any; }; + // Overwritten if present in the URI + username?: string; + password?: string; + } + + interface ResponseOptions { + decode?: boolean; + parse?: boolean; + output?: any; + } + + interface TLSOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: any; + rejectUnauthorized?: boolean; + secureProtocol?: any; + } + + interface NeedleStatic { + defaults(options?: any): void; + + head(url: string): ReadableStream; + head(url: string, callback?: Callback): ReadableStream; + head(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + + get(url: string): ReadableStream; + get(url: string, callback?: Callback): ReadableStream; + get(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; + + post(url: string, data: any): ReadableStream; + post(url: string, data: any, callback?: Callback): ReadableStream; + post(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + + put(url: string, data: any): ReadableStream; + put(url: string, data: any, callback?: Callback): ReadableStream; + put(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + + delete(url: string, data: any): ReadableStream; + delete(url: string, data: any, callback?: Callback): ReadableStream; + delete(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + + request(method: string, url: string, data: any): ReadableStream; + request(method: string, url: string, data: any, callback?: Callback): ReadableStream; + request(method: string, url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; + } } - interface RequestOptions { - timeout?: number; - follow?: number; - follow_max?: number; - multipart?: boolean; - proxy?: string; - agent?: string; - headers?: HttpHeaderOptions; - auth?: string; // auto | digest | basic (default) - json?: boolean; - - // These properties are overwritten by those in the 'headers' field - compressed?: boolean; - cookies?: { [name: string]: any; }; - // Overwritten if present in the URI - username?: string; - password?: string; - } - - interface ResponseOptions { - decode?: boolean; - parse?: boolean; - output?: any; - } - - interface HttpHeaderOptions { - cookies?: { [name: string]: any; }; - compressed?: boolean; - accept?: string; - connection?: string; - user_agent?: string; - - // Overwritten if present in the URI - username?: string; - password?: string; - } - - interface TLSOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: any; - rejectUnauthorized?: boolean; - secureProtocol?: any; - } - - interface NeedleOptions extends RequestOptions, ResponseOptions, HttpHeaderOptions, TLSOptions { - } - - interface NeedleStatic { - defaults(options?: any): void; - - head(url: string): ReadableStream; - head(url: string, callback?: Callback): ReadableStream; - head(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; - - get(url: string): ReadableStream; - get(url: string, callback?: Callback): ReadableStream; - get(url: string, options?: RequestOptions, callback?: Callback): ReadableStream; - - post(url: string, data: any): ReadableStream; - post(url: string, data: any, callback?: Callback): ReadableStream; - post(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; - - put(url: string, data: any): ReadableStream; - put(url: string, data: any, callback?: Callback): ReadableStream; - put(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; - - delete(url: string, data: any): ReadableStream; - delete(url: string, data: any, callback?: Callback): ReadableStream; - delete(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; - - request(method: string, url: string, data: any): ReadableStream; - request(method: string, url: string, data: any, callback?: Callback): ReadableStream; - request(method: string, url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream; - } -} + var needle: Needle.NeedleStatic; + export = needle; +} \ No newline at end of file diff --git a/needle/needle-tests.ts b/needle/needle-tests.ts index 4db70f008c..3df14952c3 100644 --- a/needle/needle-tests.ts +++ b/needle/needle-tests.ts @@ -1,5 +1,3 @@ - - import needle = require("needle"); function Usage() { diff --git a/nes/nes.d.ts b/nes/index.d.ts similarity index 100% rename from nes/nes.d.ts rename to nes/index.d.ts diff --git a/nes/tsconfig.json b/nes/tsconfig.json index c0b45f689b..283844577b 100644 --- a/nes/tsconfig.json +++ b/nes/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "nes.d.ts", + "index.d.ts", "nes-tests.ts" ] } \ No newline at end of file diff --git a/ng-dialog/index.d.ts b/ng-dialog/index.d.ts index 1c24461057..f38757afbf 100644 --- a/ng-dialog/index.d.ts +++ b/ng-dialog/index.d.ts @@ -237,7 +237,7 @@ declare module 'angular' { template: string; controller?: string| any[] | any; controllerAs?: string; - bindToController?: boolean; + bindToController?: boolean; /** * Scope object that will be passed to dialog. If you use controller with separate $scope service this object will be passed to $scope.$parent param. diff --git a/ng-file-upload/index.d.ts b/ng-file-upload/index.d.ts index 03976de7e8..17f454c5a9 100644 --- a/ng-file-upload/index.d.ts +++ b/ng-file-upload/index.d.ts @@ -91,6 +91,20 @@ declare module 'angular' { */ ngfValidateForce?: boolean; } + + interface ResizeIfFunction { + (width: number, height: number): boolean; + } + + interface FileResizeOptions { + centerCrop?: boolean; + height?: number; + ratio?: number; + resizeIf?: ResizeIfFunction; + restoreExif?: boolean; + quality?: number; + width?: number; + } interface ResizeIfFunction { (width: number, height: number): boolean; diff --git a/ng-file-upload/ng-file-upload-tests.ts b/ng-file-upload/ng-file-upload-tests.ts index 0bca49ea91..3f3f264c2b 100644 --- a/ng-file-upload/ng-file-upload-tests.ts +++ b/ng-file-upload/ng-file-upload-tests.ts @@ -85,7 +85,7 @@ class UploadController { ratio: 0.9, centerCrop: true, restoreExif: true, - resizeIf: (width, height) => { + resizeIf: (width: number, height: number) => { return true; } }) diff --git a/ngmap/ngmap.d.ts b/ngmap/index.d.ts similarity index 100% rename from ngmap/ngmap.d.ts rename to ngmap/index.d.ts diff --git a/ngmap/tsconfig.json b/ngmap/tsconfig.json index d86f53d20a..132e6d6842 100644 --- a/ngmap/tsconfig.json +++ b/ngmap/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "ngmap.d.ts", + "index.d.ts", "ngmap-tests.ts" ] } \ No newline at end of file diff --git a/ngreact/ngreact.d.ts b/ngreact/index.d.ts similarity index 100% rename from ngreact/ngreact.d.ts rename to ngreact/index.d.ts diff --git a/ngreact/tsconfig.json b/ngreact/tsconfig.json index 1b80eaf055..194de86d87 100644 --- a/ngreact/tsconfig.json +++ b/ngreact/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "ngreact.d.ts", + "index.d.ts", "ngreact-tests.tsx" ] } \ No newline at end of file diff --git a/node-sass/index.d.ts b/node-sass/index.d.ts index c75469595f..a91d56e370 100644 --- a/node-sass/index.d.ts +++ b/node-sass/index.d.ts @@ -22,13 +22,13 @@ interface Options { linefeed?: string; omitSourceMapUrl?: boolean; outFile?: string; - outputStyle?: "compact" | "compressed" | "expanded" | "nested"; + outputStyle?: "compact" | "compressed" | "expanded" | "nested"; precision?: number; sourceComments?: boolean; sourceMap?: boolean | string; sourceMapContents?: boolean; sourceMapEmbed?: boolean; - sourceMapRoot?: string; + sourceMapRoot?: string; } interface SassError extends Error { diff --git a/node-sass/node-sass-tests.ts b/node-sass/node-sass-tests.ts index 623e7ae4d6..33ce90ec67 100644 --- a/node-sass/node-sass-tests.ts +++ b/node-sass/node-sass-tests.ts @@ -1,4 +1,3 @@ - import * as sass from 'node-sass'; sass.render({ file: '/path/to/myFile.scss', diff --git a/node-usb/node-usb.d.ts b/node-usb/node-usb.d.ts deleted file mode 100644 index 78b93bbfd9..0000000000 --- a/node-usb/node-usb.d.ts +++ /dev/null @@ -1,233 +0,0 @@ -// Type definitions for node-usb 1.1.2 -// Project: https://github.com/nonolith/node-usb -// Definitions by: Eric Brody -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module "usb" { - - class Device { - public timeout: number; - public busNumber: number; - public deviceAddress: number; - public portNumbers: Array; - public deviceDescriptor: DeviceDescriptor; - public configDescriptor: ConfigDescriptor; - public interfaces: Array; - - __open(): void; - __claimInterface(addr: number): void; - - open(defaultConfig?: boolean): void; - close(): void; - interface(addr: number): Interface; - controlTransfer(bmRequestType: number, bRequest: number, wValue: number, wIndex: number, data_or_length: any, callback: (error?: string, buf?: Buffer) => void): Device; - getStringDescriptor(desc_index: number, callback: (error?: string, buf?: Buffer) => void): void; - setConfiguration(desired: number, cb: (err?: string) => void): void; - reset(callback: (err?: string) => void): void; - } - - class DeviceDescriptor { - public bLength: number; - public bDescriptorType: number; - public bcdUSB: number; - public bDeviceClass: number; - public bDeviceSubClass: number; - public bDeviceProtocol: number; - public bMaxPacketSize: number; - public idVendor: number; - public idProduct: number; - public bcdDevice: number; - public iManufacturer: number; - public iProduct: number; - public iSerialNumber: number; - public bNumConfigurations: number; - } - - class ConfigDescriptor { - public bLength: number; - public bDescriptorType: number; - public wTotalLength: number; - public bNumInterfaces: number; - public bConfigurationValue: number; - public iConfiguration: number; - public bmAttributes: number; - public bMaxPower: number; - public extra: Buffer; - } - - class Interface { - public descriptor: InterfaceDescriptor; - public endpoints: Array; - constructor(device: Device, id: number); - claim(): void; - release(closeEndpoints?: (err?: string) => void, cb?: (err?: string) => void): void; - isKernelDriverActive(): boolean; - detachKernelDriver(): number; - attachKernelDriver(): number; - setAltSetting(altSetting: number, cb: (err?: string) => void): void; - endpoint(addr: number): IEndpoint; - } - - class InterfaceDescriptor { - public bLength: number; - public bDescriptorType: number; - public bInterfaceNumber: number; - public bAlternateSetting: number; - public bNumEndpoints: number; - public bInterfaceClass: number; - public bInterfaceSubClass: number; - public bInterfaceProtocol: number; - public iInterface: number; - public extra: Buffer; - } - - interface IEndpoint { - direction: string; - transferType: number; - timeout: number; - descriptor: EndpointDescriptor; - } - - class InEndpoint implements IEndpoint { - public direction: string; - public transferType: number; - public timeout: number; - public descriptor: EndpointDescriptor; - constructor(device: Device, descriptor: EndpointDescriptor); - transfer(length: number, callback: (error: string, data: Buffer) => void): InEndpoint; - startPoll(nTransfers: number, transferSize: number): void; - stopPoll(cb: () => void): void; - } - - class OutEndpoint implements IEndpoint { - public direction: string; - public transferType: number; - public timeout: number; - public descriptor: EndpointDescriptor; - constructor(device: Device, descriptor: EndpointDescriptor); - transfer(buffer: Buffer, cb: (err?: string) => void): OutEndpoint; - transferWithZLP(buf: Buffer, cb: (err?: string) => void): void; - } - - class EndpointDescriptor { - public bLength: number; - public bDescriptorType: number; - public bEndpointAddress: number; - public bmAttributes: number; - public wMaxPacketSize: number; - public bInterval: number; - public bRefresh: number; - public bSynchAddress: number; - } - - function findByIds(vid: number, pid: number): Device; - function on(event: string, callback: (device: Device) => void): void; - function getDeviceList(): Array; - function setDebugLevel(level: number): void; - - const LIBUSB_CLASS_PER_INTERFACE: number; - const LIBUSB_CLASS_AUDIO: number; - const LIBUSB_CLASS_COMM: number; - const LIBUSB_CLASS_HID: number; - const LIBUSB_CLASS_PRINTER: number; - const LIBUSB_CLASS_PTP: number; - const LIBUSB_CLASS_MASS_STORAGE: number; - const LIBUSB_CLASS_HUB: number; - const LIBUSB_CLASS_DATA: number; - const LIBUSB_CLASS_WIRELESS: number; - const LIBUSB_CLASS_APPLICATION: number; - const LIBUSB_CLASS_VENDOR_SPEC: number; - // libusb_standard_request - const LIBUSB_REQUEST_GET_STATUS: number; - const LIBUSB_REQUEST_CLEAR_FEATURE: number; - const LIBUSB_REQUEST_SET_FEATURE: number; - const LIBUSB_REQUEST_SET_ADDRESS: number; - const LIBUSB_REQUEST_GET_DESCRIPTOR: number; - const LIBUSB_REQUEST_SET_DESCRIPTOR: number; - const LIBUSB_REQUEST_GET_CONFIGURATION: number; - const LIBUSB_REQUEST_SET_CONFIGURATION: number; - const LIBUSB_REQUEST_GET_INTERFACE: number; - const LIBUSB_REQUEST_SET_INTERFACE: number; - const LIBUSB_REQUEST_SYNCH_FRAME: number; - // libusb_descriptor_type - const LIBUSB_DT_DEVICE: number; - const LIBUSB_DT_CONFIG: number; - const LIBUSB_DT_STRING: number; - const LIBUSB_DT_INTERFACE: number; - const LIBUSB_DT_ENDPOINT: number; - const LIBUSB_DT_HID: number; - const LIBUSB_DT_REPORT: number; - const LIBUSB_DT_PHYSICAL: number; - const LIBUSB_DT_HUB: number; - // libusb_endpoint_direction - const LIBUSB_ENDPOINT_IN: number; - const LIBUSB_ENDPOINT_OUT: number; - // libusb_transfer_type - const LIBUSB_TRANSFER_TYPE_CONTROL: number; - const LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: number; - const LIBUSB_TRANSFER_TYPE_BULK: number; - const LIBUSB_TRANSFER_TYPE_INTERRUPT: number; - // libusb_iso_sync_type - const LIBUSB_ISO_SYNC_TYPE_NONE: number; - const LIBUSB_ISO_SYNC_TYPE_ASYNC: number; - const LIBUSB_ISO_SYNC_TYPE_ADAPTIVE: number; - const LIBUSB_ISO_SYNC_TYPE_SYNC: number; - // libusb_iso_usage_type - const LIBUSB_ISO_USAGE_TYPE_DATA: number; - const LIBUSB_ISO_USAGE_TYPE_FEEDBACK: number; - const LIBUSB_ISO_USAGE_TYPE_IMPLICIT: number; - // libusb_transfer_status - const LIBUSB_TRANSFER_COMPLETED: number; - const LIBUSB_TRANSFER_ERROR: number; - const LIBUSB_TRANSFER_TIMED_OUT: number; - const LIBUSB_TRANSFER_CANCELLED: number; - const LIBUSB_TRANSFER_STALL: number; - const LIBUSB_TRANSFER_NO_DEVICE: number; - const LIBUSB_TRANSFER_OVERFLOW: number; - // libusb_transfer_flags - const LIBUSB_TRANSFER_SHORT_NOT_OK: number; - const LIBUSB_TRANSFER_FREE_BUFFER: number; - const LIBUSB_TRANSFER_FREE_TRANSFER: number; - // libusb_request_type - const LIBUSB_REQUEST_TYPE_STANDARD: number; - const LIBUSB_REQUEST_TYPE_CLASS: number; - const LIBUSB_REQUEST_TYPE_VENDOR: number; - const LIBUSB_REQUEST_TYPE_RESERVED: number; - // libusb_request_recipient - const LIBUSB_RECIPIENT_DEVICE: number; - const LIBUSB_RECIPIENT_INTERFACE: number; - const LIBUSB_RECIPIENT_ENDPOINT: number; - const LIBUSB_RECIPIENT_OTHER: number; - - const LIBUSB_CONTROL_SETUP_SIZE: number; - - // libusb_error - // Input/output error - const LIBUSB_ERROR_IO: number; - // Invalid parameter - const LIBUSB_ERROR_INVALID_PARAM: number; - // Access denied (insufficient permissions) - const LIBUSB_ERROR_ACCESS: number; - // No such device (it may have been disconnected) - const LIBUSB_ERROR_NO_DEVICE: number; - // Entity not found - const LIBUSB_ERROR_NOT_FOUND: number; - // Resource busy - const LIBUSB_ERROR_BUSY: number; - // Operation timed out - const LIBUSB_ERROR_TIMEOUT: number; - // Overflow - const LIBUSB_ERROR_OVERFLOW: number; - // Pipe error - const LIBUSB_ERROR_PIPE: number; - // System call interrupted (perhaps due to signal) - const LIBUSB_ERROR_INTERRUPTED: number; - // Insufficient memory - const LIBUSB_ERROR_NO_MEM: number; - // Operation not supported or unimplemented on this platform - const LIBUSB_ERROR_NOT_SUPPORTED: number; - // Other error - const LIBUSB_ERROR_OTHER: number; -} diff --git a/node-usb/tsconfig.json b/node-usb/tsconfig.json deleted file mode 100644 index 8b33ce72d6..0000000000 --- a/node-usb/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "node-usb.d.ts", - "node-usb-tests.ts" - ] -} \ No newline at end of file diff --git a/node/index.d.ts b/node/index.d.ts index ea81e61147..bfa0e8b159 100644 --- a/node/index.d.ts +++ b/node/index.d.ts @@ -1046,20 +1046,20 @@ declare module "zlib" { export function createInflateRaw(options?: ZlibOptions): InflateRaw; export function createUnzip(options?: ZlibOptions): Unzip; - export function deflate(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function deflateSync(buf: Buffer, options?: ZlibOptions): any; - export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function gzip(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function gzipSync(buf: Buffer, options?: ZlibOptions): any; - export function gunzip(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; - export function inflate(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function inflateSync(buf: Buffer, options?: ZlibOptions): any; - export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function unzip(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function unzipSync(buf: Buffer, options?: ZlibOptions): any; + export function deflate(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; + export function deflateSync(buf: Buffer | string, options?: ZlibOptions): Buffer; + export function deflateRaw(buf: Buffer | string, callback: (error: Error, result: Buffer) => void): void; + export function deflateRawSync(buf: Buffer | string, options?: ZlibOptions): Buffer; + export function gzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function gzipSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function gunzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function gunzipSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function inflate(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function inflateSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function inflateRawSync(buf: Buffer, options?: ZlibOptions): Buffer; + export function unzip(buf: Buffer, callback: (error: Error, result: Buffer) => void): void; + export function unzipSync(buf: Buffer, options?: ZlibOptions): Buffer; // Constants export var Z_NO_FLUSH: number; @@ -1539,7 +1539,7 @@ declare module "child_process" { disconnect(): void; unref(): void; ref(): void; - + /** * events.EventEmitter * 1. close @@ -1851,6 +1851,7 @@ declare module "net" { localPort: number; bytesRead: number; bytesWritten: number; + destroyed: boolean; // Extended base methods end(): void; @@ -3051,7 +3052,7 @@ declare module "tls" { } export interface Server extends net.Server { - close(): Server; + close(callback?: Function): Server; address(): { port: number; family: string; address: string; }; addContext(hostName: string, credentials: { key: string; diff --git a/node/node-tests.ts b/node/node-tests.ts index 9873b19e72..41e1887c56 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -1,3 +1,4 @@ +/// import * as assert from "assert"; import * as fs from "fs"; import * as events from "events"; @@ -47,33 +48,33 @@ namespace global_tests { namespace assert_tests { { assert(1 + 1 - 2 === 0, "The universe isn't how it should."); - + assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); - + assert.doesNotThrow(() => { const b = false; if (b) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); - + assert.equal(3, "3", "uses == comparator"); assert.fail(1, 2, undefined, '>'); - + assert.ifError(0); - + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - + assert.notEqual(1, 2, "uses != comparator"); - + assert.notStrictEqual(2, "2", "uses === comparator"); - + assert.ok(true); assert.ok(1); - + assert.strictEqual(1, 1, "uses === comparator"); - + assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); } } @@ -153,21 +154,21 @@ namespace fs_tests { fs.writeFile("thebible.txt", "Do unto others as you would have them do unto you.", assert.ifError); - + fs.write(1234, "test"); - + fs.writeFile("Harry Potter", "\"You be wizzing, Harry,\" jived Dumbledore.", { encoding: "ascii" }, - assert.ifError); + assert.ifError); } { var content: string; var buffer: Buffer; - + content = fs.readFileSync('testfile', 'utf8'); content = fs.readFileSync('testfile', { encoding: 'utf8' }); buffer = fs.readFileSync('testfile'); @@ -177,7 +178,7 @@ namespace fs_tests { fs.readFile('testfile', (err, data) => buffer = data); fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); } - + { var errno: number; fs.readFile('testfile', (err, data) => { @@ -186,28 +187,28 @@ namespace fs_tests { } }); } - + { fs.mkdtemp('/tmp/foo-', (err, folder) => { console.log(folder); // Prints: /tmp/foo-itXde2 }); } - + { var tempDir: string; tempDir = fs.mkdtempSync('/tmp/foo-'); } - + { fs.watch('/tmp/foo-', (event, filename) => { console.log(event, filename); }); - + fs.watch('/tmp/foo-', 'utf8', (event, filename) => { console.log(event, filename); }); - + fs.watch('/tmp/foo-', { recursive: true, persistent: true, @@ -216,22 +217,22 @@ namespace fs_tests { console.log(event, filename); }); } - + { fs.access('/path/to/folder', (err) => { }); - + fs.access(Buffer.from(''), (err) => { }); - + fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - + fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { }); - + fs.accessSync('/path/to/folder'); - + fs.accessSync(Buffer.from('')); - + fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK); - + fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); } } @@ -400,14 +401,14 @@ function bufferTests() { namespace url_tests { { url.format(url.parse('http://www.example.com/xyz')); - + // https://google.com/search?q=you're%20a%20lizard%2C%20gary url.format({ protocol: 'https', host: "google.com", pathname: 'search', query: { q: "you're a lizard, gary" } - }); + }); } { @@ -424,7 +425,7 @@ namespace util_tests { { // Old and new util.inspect APIs util.inspect(["This is nice"], false, 5); - util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); + util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); } } @@ -449,6 +450,26 @@ function stream_readable_pipe_test() { rs.close(); } +// helpers +const compressMe = new Buffer("some data"); +const compressMeString = "compress me!"; + +zlib.deflate(compressMe, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); +zlib.deflate(compressMeString, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); +const inflated = zlib.inflateSync(zlib.deflateSync(compressMe)); +const inflatedString = zlib.inflateSync(zlib.deflateSync(compressMeString)); + +zlib.deflateRaw(compressMe, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); +zlib.deflateRaw(compressMeString, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); +const inflatedRaw: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMe)); +const inflatedRawString: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMeString)); + +zlib.gzip(compressMe, (err: Error, result: Buffer) => zlib.gunzip(result, (err: Error, result: Buffer) => result)); +const gunzipped: Buffer = zlib.gunzipSync(zlib.gzipSync(compressMe)); + +zlib.unzip(compressMe, (err: Error, result: Buffer) => result); +const unzipped: Buffer = zlib.unzipSync(compressMe); + // Simplified constructors function simplified_stream_ctor_test() { new stream.Readable({ @@ -731,6 +752,14 @@ namespace tls_tests { _server = _server.prependOnceListener("secureConnection", (tlsSocket) => { let _tlsSocket: tls.TLSSocket = tlsSocket; }) + + // close callback parameter is optional + _server = _server.close(); + + // close callback parameter doesn't specify any arguments, so any + // function is acceptable + _server = _server.close(() => {}); + _server = _server.close((...args:any[]) => {}); } { @@ -772,7 +801,7 @@ namespace tls_tests { let _response: Buffer = response; }) _TLSSocket = _TLSSocket.prependOnceListener("secureConnect", () => { }); - } + } } //////////////////////////////////////////////////// @@ -1315,9 +1344,9 @@ namespace string_decoder_tests { namespace child_process_tests { { childProcess.exec("echo test"); - childProcess.spawnSync("echo test"); + childProcess.spawnSync("echo test"); } - + { let _cp: childProcess.ChildProcess; let _boolean: boolean; @@ -1574,7 +1603,7 @@ namespace process_tests { { var eventEmitter: events.EventEmitter; eventEmitter = process; // Test that process implements EventEmitter... - + var _p: NodeJS.Process = process; _p = p; } @@ -1605,8 +1634,22 @@ namespace console_tests { namespace net_tests { { - // Make sure .listen() and .close() retuern a Server instance - net.createServer().listen(0).close().address(); + let server = net.createServer(); + // Check methods which return server instances by chaining calls + server = server.listen(0) + .close() + .ref() + .unref(); + + // close has an optional callback function. No callback parameters are + // specified, so any callback function is permissible. + 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"; } { @@ -1770,6 +1813,9 @@ namespace net_tests { str = host; }) _socket = _socket.prependOnceListener("timeout", () => { }) + + bool = _socket.destroyed; + _socket.destroy(); } { diff --git a/nodemailer-ses-transport/nodemailer-ses-transport.d.ts b/nodemailer-ses-transport/index.d.ts similarity index 100% rename from nodemailer-ses-transport/nodemailer-ses-transport.d.ts rename to nodemailer-ses-transport/index.d.ts diff --git a/nodemailer-ses-transport/tsconfig.json b/nodemailer-ses-transport/tsconfig.json index 8aa631bf9a..6e77bfb4f1 100644 --- a/nodemailer-ses-transport/tsconfig.json +++ b/nodemailer-ses-transport/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "nodemailer-ses-transport.d.ts", + "index.d.ts", "nodemailer-ses-transport-tests.ts" ] } \ No newline at end of file diff --git a/notNeededPackages.json b/notNeededPackages.json index 59686d86eb..7c049c86fa 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -40,6 +40,37 @@ "typingsPackageName": "dexie", "sourceRepoURL": "https://github.com/dfahlander/Dexie.js", "asOfVersion": "1.3.1" + }, + { + "libraryName": "LinqSharp", + "typingsPackageName": "linqsharp", + "sourceRepoURL": "https://github.com/brunolm/LinqSharp", + "asOfVersion": "1.0.0" + }, + { + "libraryName": "TypeScript", + "typingsPackageName": "typescript", + "sourceRepoURL": "https://github.com/Microsoft/TypeScript", + "asOfVersion": "2.0.0" + }, + { + "libraryName": "TypeScript", + "typingsPackageName": "typescript-services", + "sourceRepoURL": "https://github.com/Microsoft/TypeScript", + "asOfVersion": "2.0.0" + }, + { + "libraryName": "Prando", + "typingsPackageName": "prando", + "sourceRepoURL": "https://github.com/zeh/prando", + "asOfVersion": "1.0.0" + }, + { + "libraryName": "SimpleSignal", + "typingsPackageName": "simplesignal", + "sourceRepoURL": "https://github.com/zeh/simplesignal", + "asOfVersion": "1.0.0" +>>>>>>> types-2.0 } ] } diff --git a/notify.js/notify.js.d.ts b/notify.js/index.d.ts similarity index 100% rename from notify.js/notify.js.d.ts rename to notify.js/index.d.ts diff --git a/notify.js/tsconfig.json b/notify.js/tsconfig.json index 1c62932129..520d32ba10 100644 --- a/notify.js/tsconfig.json +++ b/notify.js/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "notify.js.d.ts", + "index.d.ts", "notify.js.tests.ts" ] } \ No newline at end of file diff --git a/npm-debug.log.3539137130 b/npm-debug.log.3539137130 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/nw.js/nw.js.d.ts b/nw.js/index.d.ts similarity index 100% rename from nw.js/nw.js.d.ts rename to nw.js/index.d.ts diff --git a/nw.js/tsconfig.json b/nw.js/tsconfig.json index 63803a69d9..61fc71fe70 100644 --- a/nw.js/tsconfig.json +++ b/nw.js/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "nw.js.d.ts", + "index.d.ts", "nw.js-tests.ts" ] } \ No newline at end of file diff --git a/o.js/o.js.d.ts b/o.js/index.d.ts similarity index 100% rename from o.js/o.js.d.ts rename to o.js/index.d.ts diff --git a/o.js/tsconfig.json b/o.js/tsconfig.json index a630e4dee7..9902659eec 100644 --- a/o.js/tsconfig.json +++ b/o.js/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "o.js.d.ts", + "index.d.ts", "o.js-tests.ts" ] } \ No newline at end of file diff --git a/oauth2orize/index.d.ts b/oauth2orize/index.d.ts new file mode 100644 index 0000000000..b36272dee6 --- /dev/null +++ b/oauth2orize/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for oauth2orize v1.5.1 +// Project: https://github.com/jaredhanson/oauth2orize/ +// Definitions by: Wonshik Kim , Kei Son +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +import * as http from "http"; + +interface ServerOptions { + store: any; + loadTransaction: boolean; +} +export function createServer(options?: ServerOptions): OAuth2Server; + +export interface AuthorizeOptions { + idLength?: number; + sessionKey?: string; +} + +export interface ErrorHandlerOptions { + mode?: string; +} + +type MiddlewareFunction = (req: http.IncomingMessage, res: http.ServerResponse, next: Function) => void; +type ValidatedFunction = (err: Error | null, client?: any, redirectURI?: string) => void; +type IssuedFunction = (err: Error | null, accessToken?: string | boolean, refreshToken?: string, params?: any) => void; + +export class OAuth2Server { + exchange(fn: MiddlewareFunction): OAuth2Server; + exchange(type: string, fn: MiddlewareFunction): OAuth2Server; + // Parses requests to obtain authorization + authorize (options: AuthorizeOptions, validate: (clientId: string, redirectURI: string, validated: ValidatedFunction) => void): MiddlewareFunction; + authorization(options: AuthorizeOptions, validate: (clientId: string, redirectURI: string, validated: ValidatedFunction) => void): MiddlewareFunction; + authorize (validate: (clientId: string, redirectURI: string, validated: ValidatedFunction) => void): MiddlewareFunction; + authorization(validate: (clientId: string, redirectURI: string, validated: ValidatedFunction) => void): MiddlewareFunction; + + token(options?: any): MiddlewareFunction; + errorHandler(options?: any): (err: Error, req: http.IncomingMessage, res: http.ServerResponse, next: any) => void; + serializeClient(fn: (client: any, done: (err: Error | null, id: string) => void) => void): void; + serializeClient(client: any, done: (err: Error | null, id: string) => void): void; + deserializeClient(fn: (id: string, done: (err: Error | null, client?: any | boolean) => void) => void): void; + deserializeClient(obj: any, done: (err: Error | null, client?: any | boolean) => void): void; +} + +export namespace exchange { + interface Options { + // The 'user' property of `req` holds the authenticated user. In the case + // of the token endpoint, the property will contain the OAuth 2.0 client. + userProperty?: string; + + // For maximum flexibility, multiple scope spearators can optionally be + // allowed. This allows the server to accept clients that separate scope + // with either space or comma (' ', ','). This violates the specification, + // but achieves compatibility with existing client libraries that are already + // deployed. + scopeSeparator?: string; + } + + function authorizationCode(options: Options, issue: (client: any, code: string, redirectURI: string, issued: IssuedFunction) => void): MiddlewareFunction; + function authorizationCode(issue: (client: any, code: string, redirectURI: string, issued: IssuedFunction) => void): MiddlewareFunction; + function code(options: Options, issue: (client: any, code: string, redirectURI: string, issued: IssuedFunction) => void): MiddlewareFunction; + function code(issue: (client: any, code: string, redirectURI: string, issued: IssuedFunction) => void): MiddlewareFunction; + + function clientCredentials(options: Options, issue: (client: any, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; + function clientCredentials(options: Options, issue: (client: any, issued: IssuedFunction) => void): MiddlewareFunction; + function clientCredentials(issue: (client: any, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; + function clientCredentials(issue: (client: any, issued: IssuedFunction) => void): MiddlewareFunction; + + function password(options: Options, issue: (client: any, username: string, password: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; + function password(options: Options, issue: (client: any, username: string, password: string, issued: IssuedFunction) => void): MiddlewareFunction; + function password(issue: (client: any, username: string, password: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; + function password(issue: (client: any, username: string, password: string, issued: IssuedFunction) => void): MiddlewareFunction; + + function refreshToken(options: Options, issue: (client: any, refreshToken: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; + function refreshToken(options: Options, issue: (client: any, refreshToken: string, issued: IssuedFunction) => void): MiddlewareFunction; + function refreshToken(issue: (client: any, refreshToken: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; + function refreshToken(issue: (client: any, refreshToken: string, issued: IssuedFunction) => void): MiddlewareFunction; +} diff --git a/oauth2orize/oauth2orize-tests.ts b/oauth2orize/oauth2orize-tests.ts new file mode 100644 index 0000000000..9795b3e89e --- /dev/null +++ b/oauth2orize/oauth2orize-tests.ts @@ -0,0 +1,84 @@ +import * as oauth2orize from 'oauth2orize'; +import * as http from 'http'; + +// from https://github.com/jaredhanson/oauth2orize/ + +// Create an OAuth Server +const server = oauth2orize.createServer(); + +// Register Grants +// server.grant(oauth2orize.grant.code(function(client, redirectURI, user, ares, done) { +// var code = utils.uid(16); + +// var ac = new AuthorizationCode(code, client.id, redirectURI, user.id, ares.scope); +// ac.save(function(err) { +// if (err) { return done(err); } +// return done(null, code); +// }); +// })); + + +// Register Exchanges +class AuthorizationCode { + static findOne(code: string, callback: (err: Error, code: { + clientId: string, userId: string, redirectURI: string, scope: string + }) => void): void {} +} + +server.exchange(oauth2orize.exchange.code(function(client, code, redirectURI, done) { + AuthorizationCode.findOne(code, function(err, code) { + if (err) { return done(err); } + if (client.id !== code.clientId) { return done(null, false); } + if (redirectURI !== code.redirectURI) { return done(null, false); } + + // var token = utils.uid(256); + // var at = new AccessToken(token, code.userId, code.clientId, code.scope); + // at.save(function(err) { + // if (err) { return done(err); } + // return done(null, token); + // }); + }); +})); + +// Implement Authorization Endpoint +class Clients { + static findOne(id: string, callback: (err: Error, client?: Clients) => void): void { + callback(new Error(), {} as Clients); + } + redirectURI: string; +} + +// app.get('/dialog/authorize', + // login.ensureLoggedIn(), + server.authorize(function(clientID, redirectURI, done) { + Clients.findOne(clientID, function(err, client) { + if (err) { return done(err); } + if (!client) { return done(null, false); } + if (client.redirectURI != redirectURI) { return done(null, false); } + return done(null, client, client.redirectURI); + }); + }), + function(req: http.IncomingMessage, res: http.ServerResponse) { + // res.render('dialog', { transactionID: req.oauth2.transactionID, + // user: req.user, client: req.oauth2.client }); + } +// ); + +// Session Serialization +server.serializeClient(function(client, done) { + return done(null, client.id); +}); + +server.deserializeClient(function(id, done) { + Clients.findOne(id, function(err, client) { + if (err) { return done(err); } + return done(null, client); + }); +}); + +// Implement Token Endpoint +// app.post('/token', + // passport.authenticate(['basic', 'oauth2-client-password'], { session: false }), + server.token(), + server.errorHandler() +// ); diff --git a/algoliasearch-client-js/tsconfig.json b/oauth2orize/tsconfig.json similarity index 76% rename from algoliasearch-client-js/tsconfig.json rename to oauth2orize/tsconfig.json index d8c5e4f8f1..d188681ac4 100644 --- a/algoliasearch-client-js/tsconfig.json +++ b/oauth2orize/tsconfig.json @@ -1,9 +1,10 @@ { "compilerOptions": { "module": "commonjs", + "moduleResolution": "node", "target": "es6", "noImplicitAny": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -14,6 +15,6 @@ }, "files": [ "index.d.ts", - "algoliasearch-client-js-tests.ts" + "oauth2orize-tests.ts" ] -} \ No newline at end of file +} diff --git a/object-assign/object-assign-tests.ts b/object-assign/object-assign-tests.ts index d3a5197a7e..e7c58cf5fb 100644 --- a/object-assign/object-assign-tests.ts +++ b/object-assign/object-assign-tests.ts @@ -9,7 +9,7 @@ interface Source1 { } interface Result extends Target, Source1 { - + } interface Source2 { @@ -17,7 +17,7 @@ interface Source2 { } interface Result2 extends Result, Source2 { - + } interface Source3 { @@ -25,7 +25,7 @@ interface Source3 { } interface Result3 extends Result2, Source3 { - + } interface Source4 { @@ -33,7 +33,7 @@ interface Source4 { } interface Result4 extends Result3, Source4 { - + } interface Source5 { @@ -41,7 +41,7 @@ interface Source5 { } interface Result5 extends Result4, Source5 { - + } function assign1(): Result { diff --git a/office-js/index.d.ts b/office-js/index.d.ts index 59510c6ffa..cae1dedcae 100644 --- a/office-js/index.d.ts +++ b/office-js/index.d.ts @@ -63,8 +63,24 @@ declare namespace Office { isSetSupported(name: string, minVersion?: number): boolean; } } + /** + * Provides specific information about an error that occurred during an asynchronous data operation. + */ export interface Error { + /** + * Gets the numeric code of the error. + * @since 1.0 + */ + code: number; + /** + * Gets the name of the error. + * @since 1.0 + */ message: string; + /** + * Gets a detailed description of the error. + * @since 1.0 + */ name: string; } export interface UI { @@ -112,284 +128,6 @@ declare namespace Office { } } -declare module OfficeExtension { - /** An abstract proxy object that represents an object in an Office document. You create proxy objects from the context (or from other proxy objects), add commands to a queue to act on the object, and then synchronize the proxy object state with the document by calling "context.sync()". */ - class ClientObject { - /** The request context associated with the object */ - context: ClientRequestContext; - /** Returns a boolean value for whether the corresponding object is null. You must call "context.sync()" before reading the isNull property. [Api set: ExcelApi 1.3 (Preview), WordApi 1.3] */ - isNull: boolean; - } -} -declare module OfficeExtension { - interface LoadOption { - select?: string | string[]; - expand?: string | string[]; - top?: number; - skip?: number; - } - /** An abstract RequestContext object that facilitates requests to the host Office application. The "Excel.run" and "Word.run" methods provide a request context. */ - class ClientRequestContext { - constructor(url?: string); - /** Collection of objects that are tracked for automatic adjustments based on surrounding changes in the document. */ - trackedObjects: TrackedObjects; - /** Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ - load(object: ClientObject, option?: string | string[] | LoadOption): void; - /** Adds a trace message to the queue. If the promise returned by "context.sync()" is rejected due to an error, this adds a ".traceMessages" array to the OfficeExtension.Error object, containing all trace messages that were executed. These messages can help you monitor the program execution sequence and detect the cause of the error. */ - trace(message: string): void; - /** Synchronizes the state between JavaScript proxy objects and the Office document, by executing instructions queued on the request context and retrieving properties of loaded Office objects for use in your code. This method returns a promise, which is resolved when the synchronization is complete. */ - sync(passThroughValue?: T): IPromise; - } -} -declare module OfficeExtension { - /** Contains the result for methods that return primitive types. The object's value property is retrieved from the document after "context.sync()" is invoked. */ - class ClientResult { - /** The value of the result that is retrieved from the document after "context.sync()" is invoked. */ - value: T; - } -} -declare module OfficeExtension { - /** The error object returned by "context.sync()", if a promise is rejected due to an error while processing the request. */ - class Error { - /** Error name: "OfficeExtension.Error".*/ - name: string; - /** The error message passed through from the host Office application. */ - message: string; - /** Stack trace, if applicable. */ - stack: string; - /** Error code string, such as "InvalidArgument". */ - code: string; - /** Trace messages (if any) that were added via a "context.trace()" invocation before calling "context.sync()". If there was an error, this contains all trace messages that were executed before the error occurred. These messages can help you monitor the program execution sequence and detect the case of the error. */ - traceMessages: Array; - /** Debug info, if applicable. The ".errorLocation" property can describe the object and method or property that caused the error. */ - debugInfo: { - /** If applicable, will return the object type and the name of the method or property that caused the error. */ - errorLocation?: string; - }; - } -} -declare module OfficeExtension { - class ErrorCodes { - static accessDenied: string; - static generalException: string; - static activityLimitReached: string; - static invalidObjectPath: string; - static propertyNotLoaded: string; - static valueNotLoaded: string; - static invalidRequestContext: string; - static invalidArgument: string; - static runMustReturnPromise: string; - static cannotRegisterEvent: string; - } -} -declare module OfficeExtension { - /** An IPromise object that represents a deferred interaction with the host Office application. */ - interface IPromise { - /** - * This method will be called once the previous promise has been resolved. - * Both the onFulfilled on onRejected callbacks are optional. - * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. - - * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. - */ - then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => IPromise): IPromise; - - /** - * This method will be called once the previous promise has been resolved. - * Both the onFulfilled on onRejected callbacks are optional. - * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. - - * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. - */ - then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => U): IPromise; - - /** - * This method will be called once the previous promise has been resolved. - * Both the onFulfilled on onRejected callbacks are optional. - * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. - - * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. - */ - then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => void): IPromise; - - /** - * This method will be called once the previous promise has been resolved. - * Both the onFulfilled on onRejected callbacks are optional. - * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. - - * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. - */ - then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => IPromise): IPromise; - - /** - * This method will be called once the previous promise has been resolved. - * Both the onFulfilled on onRejected callbacks are optional. - * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. - - * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. - */ - then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): IPromise; - - /** - * This method will be called once the previous promise has been resolved. - * Both the onFulfilled on onRejected callbacks are optional. - * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. - - * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. - */ - then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => void): IPromise; - - - /** - * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. - * @param onRejected function to be called if or when the promise rejects. - */ - catch(onRejected?: (error: any) => IPromise): IPromise; - - /** - * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. - * @param onRejected function to be called if or when the promise rejects. - */ - catch(onRejected?: (error: any) => U): IPromise; - - /** - * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. - * @param onRejected function to be called if or when the promise rejects. - */ - catch(onRejected?: (error: any) => void): IPromise; - } - - /** An Promise object that represents a deferred interaction with the host Office application. The publically-consumable OfficeExtension.Promise is available starting in ExcelApi 1.2 and WordApi 1.2. Promises can be chained via ".then", and errors can be caught via ".catch". Remember to always use a ".catch" on the outer promise, and to return intermediary promises so as not to break the promise chain. When a "native" Promise implementation is available, OfficeExtension.Promise will switch to use the native Promise instead. */ - export class Promise implements IPromise - { - /** - * Creates a new promise based on a function that accepts resolve and reject handlers. - */ - constructor(func: (resolve: (value?: R | IPromise) => void, reject: (error?: any) => void) => void); - - /** - * Creates a promise that resolves when all of the child promises resolve. - */ - static all(promises: OfficeExtension.IPromise[]): IPromise; - - /** - * Creates a promise that is resolved. - */ - static resolve(value: U): IPromise; - - /** - * Creates a promise that is rejected. - */ - static reject(error: any): IPromise; - - /* This method will be called once the previous promise has been resolved. - * Both the onFulfilled on onRejected callbacks are optional. - * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. - - * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. - */ - then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => IPromise): IPromise; - - /** - * This method will be called once the previous promise has been resolved. - * Both the onFulfilled on onRejected callbacks are optional. - * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. - - * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. - */ - then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => U): IPromise; - - /** - * This method will be called once the previous promise has been resolved. - * Both the onFulfilled on onRejected callbacks are optional. - * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. - - * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. - */ - then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => void): IPromise; - - /** - * This method will be called once the previous promise has been resolved. - * Both the onFulfilled on onRejected callbacks are optional. - * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. - - * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. - */ - then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => IPromise): IPromise; - - /** - * This method will be called once the previous promise has been resolved. - * Both the onFulfilled on onRejected callbacks are optional. - * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. - - * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. - */ - then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): IPromise; - - /** - * This method will be called once the previous promise has been resolved. - * Both the onFulfilled on onRejected callbacks are optional. - * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. - - * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. - */ - then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => void): IPromise; - - - /** - * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. - * @param onRejected function to be called if or when the promise rejects. - */ - catch(onRejected?: (error: any) => IPromise): IPromise; - - /** - * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. - * @param onRejected function to be called if or when the promise rejects. - */ - catch(onRejected?: (error: any) => U): IPromise; - - /** - * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. - * @param onRejected function to be called if or when the promise rejects. - */ - catch(onRejected?: (error: any) => void): IPromise; - } -} - -declare module OfficeExtension { - /** Collection of tracked objects, contained within a request context. See "context.trackedObjects" for more information. */ - class TrackedObjects { - /** Track a new object for automatic adjustment based on surrounding changes in the document. Only some object types require this. If you are using an object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ - add(object: ClientObject): void; - /** Track a new object for automatic adjustment based on surrounding changes in the document. Only some object types require this. If you are using an object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ - add(objects: ClientObject[]): void; - /** Release the memory associated with an object that was previously added to this collection. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ - remove(object: ClientObject): void; - /** Release the memory associated with an object that was previously added to this collection. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ - remove(objects: ClientObject[]): void; - } -} - -declare module OfficeExtension { - export class EventHandlers { - constructor(context: ClientRequestContext, parentObject: ClientObject, name: string, eventInfo: EventInfo); - add(handler: (args: T) => IPromise): EventHandlerResult; - remove(handler: (args: T) => IPromise): void; - removeAll(): void; - } - - export class EventHandlerResult { - constructor(context: ClientRequestContext, handlers: EventHandlers, handler: (args: T) => IPromise); - remove(): void; - } - - export interface EventInfo { - registerFunc: (callback: (args: any) => void) => IPromise; - unregisterFunc: (callback: (args: any) => void) => IPromise; - eventArgsTransformFunc: (args: any) => IPromise; - } -} - declare namespace Office { /** * Returns a promise of an object described in the expression. Callback is invoked only if method fails. @@ -920,6 +658,19 @@ declare namespace Office { */ setSelectedDataAsync(data: string | TableData | any[][], options?: any, callback?: (result: AsyncResult) => void): void; } + /** + * Provides information about the document that raised the SelectionChanged event. + */ + export interface DocumentSelectionChangedEventArgs { + /** + * Gets a Document object that represents the document that raised the SelectionChanged event. + */ + document: Document; + /** + * Get an EventType enumeration value that identifies the kind of event that was raised. + */ + type: EventType; + } export interface File { size: number; sliceCount: number; @@ -1660,6 +1411,958 @@ declare namespace Office { getWSSUrlAsync(options?: any, callback?: (result: AsyncResult) => void): void; } } + + + + +//////////////////////////////////////////////////////////////// +////////////////////// Begin Exchange APIs ///////////////////// +//////////////////////////////////////////////////////////////// + + +declare namespace Office.MailboxEnums { + export enum BodyType { + /** + * The body is in HTML format + */ + Html, + /** + * The body is in text format + */ + text + } + export enum EntityType { + /** + * Specifies that the entity is a meeting suggestion + */ + MeetingSuggestion, + /** + * Specifies that the entity is a task suggestion + */ + TaskSuggestion, + /** + * Specifies that the entity is a postal address + */ + Address, + /** + * Specifies that the entity is SMTP email address + */ + EmailAddress, + /** + * Specifies that the entity is an Internet URL + */ + Url, + /** + * Specifies that the entity is US phone number + */ + PhoneNumber, + /** + * Specifies that the entity is a contact + */ + Contact + } + export enum ItemType { + /** + * A meeting request, response, or cancellation + */ + Message, + /** + * Specifies an appointment item + */ + Appointment + } + export enum ResponseType { + /** + * There has been no response from the attendee + */ + None, + /** + * The attendee is the meeting organizer + */ + Organizer, + /** + * The meeting request was tentatively accepted by the attendee + */ + Tentative, + /** + * The meeting request was accepted by the attendee + */ + Accepted, + /** + * The meeting request was declined by the attendee + */ + Declined + } + export enum RecipientType { + /** + * Specifies that the recipient is not one of the other recipient types + */ + Other, + /** + * Specifies that the recipient is a distribution list containing a list of email addresses + */ + DistributionList, + /** + * Specifies that the recipient is an SMTP email address that is on the Exchange server + */ + User, + /** + * Specifies that the recipient is an SMTP email address that is not on the Exchange server + */ + ExternalUser + } + export enum AttachmentType { + /** + * The attachment is a file + */ + File, + /** + * The attachment is an Exchange item + */ + Item + } +} +declare namespace Office { + export module Types { + export interface ItemRead extends Office.Item { + subject: any; + /** + * Displays a reply form that includes the sender and all the recipients of the selected message + * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + */ + displayReplyAllForm(htmlBody: string): void; + /** + * Displays a reply form that includes only the sender of the selected message + * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + */ + displayReplyForm(htmlBody: string): void; + /** + * Gets an array of entities found in an message + */ + getEntities(): Office.Entities; + /** + * Gets an array of entities of the specified entity type found in an message + * @param entityType One of the EntityType enumeration values + */ + getEntitiesByType(entityType: Office.MailboxEnums.EntityType): Office.Entities; + /** + * Returns well-known entities that pass the named filter defined in the manifest XML file + * @param name A TableData object with the headers and rows + */ + getFilteredEntitiesByName(name: string): Office.Entities; + /** + * Returns string values in the currently selected message object that match the regular expressions defined in the manifest XML file + */ + getRegExMatches(): string[]; + /** + * Returns string values that match the named regular expression defined in the manifest XML file + */ + getRegExMatchesByName(name: string): string[]; + } + export interface ItemCompose extends Office.Item { + body: Office.Body; + subject: any; + /** + * Adds a file to a message as an attachment + * @param uri The URI that provides the location of the file to attach to the message. The maximum length is 2048 characters + * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + addFileAttachmentAsync(uri: string, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; + /** + * Adds an Exchange item, such as a message, as an attachment to the message + * @param itemId The Exchange identifier of the item to attach. The maximum length is 100 characters + * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + addItemAttachmentAsync(itemId: any, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; + /** + * Removes an attachment from a message + * @param attachmentIndex The index of the attachment to remove. The maximum length of the string is 100 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + removeAttachmentAsync(attachmentIndex: string, option?: any, callback?: (result: AsyncResult) => void): void; + } + export interface MessageCompose extends Office.Message { + attachments: Office.AttachmentDetails[]; + body: Office.Body; + bcc: Office.Recipients; + cc: Office.Recipients; + subject: Office.Subject; + to: Office.Recipients; + /** + * Adds a file to a message as an attachment + * @param uri The URI that provides the location of the file to attach to the message. The maximum length is 2048 characters + * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + addFileAttachmentAsync(uri: string, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; + /** + * Adds an Exchange item, such as a message, as an attachment to the message + * @param itemId The Exchange identifier of the item to attach. The maximum length is 100 characters + * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + addItemAttachmentAsync(itemId: any, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; + /** + * Removes an attachment from a message + * @param attachmentIndex The index of the attachment to remove. The maximum length of the string is 100 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + removeAttachmentAsync(attachmentIndex: string, option?: any, callback?: (result: AsyncResult) => void): void; + } + export interface MessageRead extends Office.Message { + cc: Office.EmailAddressDetails[]; + from: Office.EmailAddressDetails; + internetMessageId: string; + normalizedSubject: string; + sender: Office.EmailAddressDetails; + subject: string; + to: Office.EmailAddressDetails; + /** + * Displays a reply form that includes the sender and all the recipients of the selected message + * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + */ + displayReplyAllForm(htmlBody: string): void; + /** + * Displays a reply form that includes only the sender of the selected message + * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + */ + displayReplyForm(htmlBody: string): void; + /** + * Gets an array of entities found in an message + */ + getEntities(): Office.Entities; + /** + * Gets an array of entities of the specified entity type found in an message + * @param entityType One of the EntityType enumeration values + */ + getEntitiesByType(entityType: Office.MailboxEnums.EntityType): Office.Entities; + /** + * Returns well-known entities that pass the named filter defined in the manifest XML file + * @param name A TableData object with the headers and rows + */ + getFilteredEntitiesByName(name: string): Office.Entities; + /** + * Returns string values in the currently selected message object that match the regular expressions defined in the manifest XML file + */ + getRegExMatches(): string[]; + /** + * Returns string values that match the named regular expression defined in the manifest XML file + */ + getRegExMatchesByName(name: string): string[]; + } + export interface AppointmentCompose extends Office.Appointment { + body: Office.Body; + end: Office.Time; + location: Office.Location; + optionalAttendees: Office.Recipients; + requiredAttendees: Office.Recipients; + start: Office.Time; + subject: Office.Subject; + /** + * Adds a file to an appointment as an attachment + * @param uri The URI that provides the location of the file to attach to the appointment. The maximum length is 2048 characters + * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + addFileAttachmentAsync(uri: string, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; + /** + * Adds an Exchange item, such as a message, as an attachment to the appointment + * @param itemId The Exchange identifier of the item to attach. The maximum length is 100 characters + * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + addItemAttachmentAsync(itemId: any, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; + /** + * Removes an attachment from a appointment + * @param attachmentIndex The index of the attachment to remove. The maximum length of the string is 100 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional callback method + */ + removeAttachmentAsync(attachmentIndex: string, option?: any, callback?: (result: AsyncResult) => void): void; + } + export interface AppointmentRead extends Office.Appointment { + attachments: Office.AttachmentDetails[]; + end: Date; + location: string; + normalizedSubject: string; + optionalAttendees: Office.EmailAddressDetails; + organizer: Office.EmailAddressDetails; + requiredAttendees: Office.EmailAddressDetails; + resources: string[]; + start: Date; + subject: string; + /** + * Displays a reply form that includes the organizer and all the attendees of the selected appointment item + * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + */ + displayReplyAllForm(htmlBody: string): void; + /** + * Displays a reply form that includes only the organizer of the selected appointment item + * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB + */ + displayReplyForm(htmlBody: string): void; + /** + * Gets an array of entities found in an appointment + */ + getEntities(): Office.Entities; + /** + * Gets an array of entities of the specified entity type found in an appointment + * @param entityType One of the EntityType enumeration values + */ + getEntitiesByType(entityType: Office.MailboxEnums.EntityType): Office.Entities; + /** + * Returns well-known entities that pass the named filter defined in the manifest XML file + * @param name A TableData object with the headers and rows + */ + getFilteredEntitiesByName(name: string): Office.Entities; + /** + * Returns string values in the currently selected appointment object that match the regular expressions defined in the manifest XML file + */ + getRegExMatches(): string[]; + /** + * Returns string values that match the named regular expression defined in the manifest XML file + */ + getRegExMatchesByName(name: string): string[]; + } + } + export module cast { + export module item { + function toAppointmentCompose(item: Office.Item): Office.Types.AppointmentCompose; + function toAppointmentRead(item: Office.Item): Office.Types.AppointmentRead; + function toAppointment(item: Office.Item): Office.Appointment; + function toMessageCompose(item: Office.Item): Office.Types.MessageCompose; + function toMessageRead(item: Office.Item): Office.Types.MessageRead; + function toMessage(item: Office.Item): Office.Message; + function toItemCompose(item: Office.Item): Office.Types.ItemCompose; + function toItemRead(item: Office.Item): Office.Types.ItemRead; + } + } + export interface AttachmentDetails { + attachmentType: Office.MailboxEnums.AttachmentType; + contentType: string; + id: string; + isInline: boolean; + name: string; + size: number; + } + export interface Contact { + personName: string; + businessName: string; + phoneNumbers: PhoneNumber[]; + emailAddresses: string[]; + urls: string[]; + addresses: string[]; + contactString: string; + } + + export interface Context { + mailbox: Mailbox; + roamingSettings: RoamingSettings; + } + export interface CustomProperties { + /** + * Returns the value of the specified custom property + * @param name The name of the property to be returned + */ + get(name: string): any; + /** + * Sets the specified property to the specified value + * @param name The name of the property to be set + * @param value The value of the property to be set + */ + set(name: string, value: string): void; + /** + * Removes the specified property from the custom property collection. + * @param name The name of the property to be removed + */ + remove(name: string): void; + /** + * Saves the custom property collection to the server + * @param callback The optional callback method + * @param userContext Optional variable for any state data that is passed to the saveAsync method + */ + saveAsync(callback?: (result: AsyncResult) => void, userContext?: any): void; + } + export interface EmailAddressDetails { + emailAddress: string; + displayName: string; + appointmentResponse: Office.MailboxEnums.ResponseType; + recipientType: Office.MailboxEnums.RecipientType; + } + export interface EmailUser { + name: string; + userId: string; + } + export interface Entities { + addresses: string[]; + taskSuggestions: string[]; + meetingSuggestions: MeetingSuggestion[]; + emailAddresses: string[]; + urls: string[]; + phoneNumbers: PhoneNumber[]; + contacts: Contact[]; + } + export interface Item { + dateTimeCreated: Date; + dateTimeModified: Date; + itemClass: string; + itemId: string; + itemType: Office.MailboxEnums.ItemType; + /** + * Asynchronously loads custom properties that are specific to the item and a app for Office + * @param callback The optional callback method + * @param userContext Optional variable for any state data that is passed to the asynchronous method + */ + loadCustomPropertiesAsync(callback?: (result: AsyncResult) => void, userContext?: any): void; + } + export interface Appointment extends Item { + } + export interface Body { + /** + * Gets a value that indicates whether the content is in HTML or text format + * @param tableData A TableData object with the headers and rows + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the getTypeAsync method returns + */ + getTypeAsync(options?: any, callback?: (result: AsyncResult) => void): void; + /** + * Adds the specified content to the beginning of the item body + * @param data The string to be inserted at the beginning of the body. The string is limited to 1,000,000 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the string is inserted + */ + prependAsync(data: string, options?: any, callback?: (result: AsyncResult) => void): void; + /** + * Replaces the selection in the body with the specified text + * @param data The string to be inserted at the beginning of the body. The string is limited to 1,000,000 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the string is inserted + */ + setSelectedDataAsync(data: string, options?: any, callback?: (result: AsyncResult) => void): void; + } + export interface Location { + /** + * Begins an asynchronous request for the location of an appointment + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the string is inserted + */ + getAsync(options?: any, callback?: (result: AsyncResult) => void): void; + /** + * Begins an asynchronous request to set the location of an appointment + * @param data The location of the appointment. The string is limited to 255 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the location is set + */ + setAsync(location: string, options?: any, callback?: (result: AsyncResult) => void): void; + } + export interface Mailbox { + item: Item; + userProfile: UserProfile; + /** + * Gets a Date object from a dictionary containing time information + * @param timeValue A Date object + */ + convertToLocalClientTime(timeValue: Date): any; + /** + * Gets a dictionary containing time information in local client time + * @param input A dictionary containing a date. The dictionary should contain the following fields: year, month, date, hours, minutes, seconds, time zone, time zone offset + */ + convertToUtcClientTime(input: any): Date; + /** + * Displays an existing calendar appointment + * @param itemId The Exchange Web Services (EWS) identifier for an existing calendar appointment + */ + displayAppointmentForm(itemId: any): void; + /** + * Displays an existing message + * @param itemId The Exchange Web Services (EWS) identifier for an existing message + */ + displayMessageForm(itemId: any): void; + /** + * Displays a form for creating a new calendar appointment + * @param requiredAttendees An array of strings containing the email addresses or an array containing an EmailAddressDetails object for each of the required attendees for the appointment. The array is limited to a maximum of 100 entries + * @param optionalAttendees An array of strings containing the email addresses or an array containing an EmailAddressDetails object for each of the optional attendees for the appointment. The array is limited to a maximum of 100 entries + * @param start A Date object specifying the start date and time of the appointment + * @param end A Date object specifying the end date and time of the appointment + * @param location A string containing the location of the appointment. The string is limited to a maximum of 255 characters + * @param resources An array of strings containing the resources required for the appointment. The array is limited to a maximum of 100 entries + * @param subject A string containing the subject of the appointment. The string is limited to a maximum of 255 characters + * @param body The body of the appointment message. The body content is limited to a maximum size of 32 KB + */ + displayNewAppointmentForm(requiredAttendees: any, optionalAttendees: any, start: Date, end: Date, location: string, resources: string[], subject: string, body: string): void; + /** + * Gets a string that contains a token used to get an attachment or item from an Exchange Server + * @param callback The optional method to call when the string is inserted + * @param userContext Optional variable for any state data that is passed to the asynchronous method + */ + getCallbackTokenAsync(callback?: (result: AsyncResult) => void, userContext?: any): void; + /** + * Gets a token identifying the user and the app for Office + * @param callback The optional method to call when the string is inserted + * @param userContext Optional variable for any state data that is passed to the asynchronous method + */ + getUserIdentityTokenAsync(callback?: (result: AsyncResult) => void, userContext?: any): void; + /** + * Makes an asynchronous request to an Exchange Web Services (EWS) service on the Exchange server that hosts the user’s mailbox + * @param data The EWS request + * @param callback The optional method to call when the string is inserted + * @param userContext Optional variable for any state data that is passed to the asynchronous method + */ + makeEwsRequestAsync(data: any, callback?: (result: AsyncResult) => void, userContext?: any): void; + } + export interface Message extends Item { + conversationId: string; + } + export interface MeetingRequest extends Message { + start: Date; + end: Date; + location: string; + optionalAttendees: EmailAddressDetails[]; + requiredAttendees: EmailAddressDetails[]; + } + export interface MeetingSuggestion { + meetingString: string; + attendees: EmailAddressDetails[]; + location: string; + subject: string; + start: Date; + end: Date; + } + export interface PhoneNumber { + phoneString: string; + originalPhoneString: string; + type: string; + } + export interface Recipients { + /** + * Begins an asynchronous request to add a recipient list to an appointment or message + * @param recipients The recipients to add to the recipients list + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the string is inserted + */ + addAsync(recipients: any, options?: any, callback?: (result: AsyncResult) => void): void; + /** + * Begins an asynchronous request to get the recipient list for an appointment or message + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the string is inserted + */ + getAsync(options?: any, callback?: (result: AsyncResult) => void): void; + /** + * Begins an asynchronous request to set the recipient list for an appointment or message + * @param recipients The recipients to add to the recipients list + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the string is inserted + */ + setAsync(recipients: any, options?: any, callback?: (result: AsyncResult) => void): void; + } + export interface RoamingSettings { + /** + * Retrieves the specified setting + * @param name The case-sensitive name of the setting to retrieve + */ + get(name: string): any; + /** + * Removes the specified setting + * @param name The case-sensitive name of the setting to remove + */ + remove(name: string): void; + /** + * Saves the settings + * @param callback A function that is invoked when the callback returns, whose only parameter is of type AsyncResult + */ + saveAsync(callback?: (result: AsyncResult) => void): void; + /** + * Sets or creates the specified setting + * @param name The case-sensitive name of the setting to set or create + * @param value Specifies the value to be stored + */ + set(name: string, value: any): void; + } + export interface Subject { + /** + * Begins an asynchronous request to get the subject of an appointment or message + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the string is inserted + */ + getAsync(options?: any, callback?: (result: AsyncResult) => void): void; + /** + * Begins an asynchronous call to set the subject of an appointment or message + * @param data The subject of the appointment. The string is limited to 255 characters + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the string is inserted + */ + setAsync(data: string, options?: any, callback?: (result: AsyncResult) => void): void; + } + export interface TaskSuggestion { + assignees: EmailUser[]; + taskString: string; + } + export interface Time { + /** + * Begins an asynchronous request to get the start or end time + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the string is inserted + */ + getAsync(options?: any, callback?: (result: AsyncResult) => void): void; + /** + * Begins an asynchronous request to set the start or end time + * @param dateTime A date-time object in Coordinated Universal Time (UTC) + * @param options Any optional parameters or state data passed to the method + * @param callback The optional method to call when the string is inserted + */ + setAsync(dateTime: Date, options?: any, callback?: (result: AsyncResult) => void): void; + } + export interface UserProfile { + displayName: string; + emailAddress: string; + timeZone: string; + } +} + + +//////////////////////////////////////////////////////////////// +/////////////////////// End Exchange APIs ////////////////////// +//////////////////////////////////////////////////////////////// + + + +/////////////////////////////////////////////////////////////// + + + +//////////////////////////////////////////////////////////////// +///////////////// Begin OfficeExtension runtime //////////////// +//////////////////////////////////////////////////////////////// + + +declare module OfficeExtension { + /** An abstract proxy object that represents an object in an Office document. You create proxy objects from the context (or from other proxy objects), add commands to a queue to act on the object, and then synchronize the proxy object state with the document by calling "context.sync()". */ + class ClientObject { + /** The request context associated with the object */ + context: ClientRequestContext; + /** Returns a boolean value for whether the corresponding object is a null object. You must call "context.sync()" before reading the isNullObject property. */ + isNullObject: boolean; + } +} +declare module OfficeExtension { + interface LoadOption { + select?: string | string[]; + expand?: string | string[]; + top?: number; + skip?: number; + } + /** An abstract RequestContext object that facilitates requests to the host Office application. The "Excel.run" and "Word.run" methods provide a request context. */ + class ClientRequestContext { + constructor(url?: string); + + /** Collection of objects that are tracked for automatic adjustments based on surrounding changes in the document. */ + trackedObjects: TrackedObjects; + + /** Request headers */ + requestHeaders: { [name: string]: string }; + + /** Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ + load(object: ClientObject, option?: string | string[]| LoadOption): void; + + /** + * Queues up a command to recursively load the specified properties of the object and its navigation properties. + * You must call "context.sync()" before reading the properties. + * + * @param object The object to be loaded. + * @param options The key-value pairing of load options for the types, such as { "Workbook": "worksheets,tables", "Worksheet": "tables", "Tables": "name" } + * @param maxDepth The maximum recursive depth. + */ + loadRecursive(object: ClientObject, options: { [typeName: string]: string | string[] | LoadOption }, maxDepth?: number): void; + + /** Adds a trace message to the queue. If the promise returned by "context.sync()" is rejected due to an error, this adds a ".traceMessages" array to the OfficeExtension.Error object, containing all trace messages that were executed. These messages can help you monitor the program execution sequence and detect the cause of the error. */ + trace(message: string): void; + + /** Synchronizes the state between JavaScript proxy objects and the Office document, by executing instructions queued on the request context and retrieving properties of loaded Office objects for use in your code. This method returns a promise, which is resolved when the synchronization is complete. */ + sync(passThroughValue?: T): IPromise; + } +} +declare module OfficeExtension { + /** Contains the result for methods that return primitive types. The object's value property is retrieved from the document after "context.sync()" is invoked. */ + class ClientResult { + /** The value of the result that is retrieved from the document after "context.sync()" is invoked. */ + value: T; + } +} +declare module OfficeExtension { + /** The error object returned by "context.sync()", if a promise is rejected due to an error while processing the request. */ + class Error { + /** Error name: "OfficeExtension.Error".*/ + name: string; + /** The error message passed through from the host Office application. */ + message: string; + /** Stack trace, if applicable. */ + stack: string; + /** Error code string, such as "InvalidArgument". */ + code: string; + /** Trace messages (if any) that were added via a "context.trace()" invocation before calling "context.sync()". If there was an error, this contains all trace messages that were executed before the error occurred. These messages can help you monitor the program execution sequence and detect the case of the error. */ + traceMessages: Array; + /** Debug info, if applicable. The ".errorLocation" property can describe the object and method or property that caused the error. */ + debugInfo: { + /** If applicable, will return the object type and the name of the method or property that caused the error. */ + errorLocation?: string; + }; + } +} +declare module OfficeExtension { + class ErrorCodes { + static accessDenied: string; + static generalException: string; + static activityLimitReached: string; + } +} +declare module OfficeExtension { + /** An IPromise object that represents a deferred interaction with the host Office application. */ + interface IPromise { + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => IPromise): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => U): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => void): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => IPromise): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => void): IPromise; + + + /** + * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. + * @param onRejected function to be called if or when the promise rejects. + */ + catch(onRejected?: (error: any) => IPromise): IPromise; + + /** + * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. + * @param onRejected function to be called if or when the promise rejects. + */ + catch(onRejected?: (error: any) => U): IPromise; + + /** + * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. + * @param onRejected function to be called if or when the promise rejects. + */ + catch(onRejected?: (error: any) => void): IPromise; + } + + /** An Promise object that represents a deferred interaction with the host Office application. The publically-consumable OfficeExtension.Promise is available starting in ExcelApi 1.2 and WordApi 1.2. Promises can be chained via ".then", and errors can be caught via ".catch". Remember to always use a ".catch" on the outer promise, and to return intermediary promises so as not to break the promise chain. When a "native" Promise implementation is available, OfficeExtension.Promise will switch to use the native Promise instead. */ + export class Promise implements IPromise + { + /** + * Creates a new promise based on a function that accepts resolve and reject handlers. + */ + constructor(func: (resolve: (value?: R | IPromise) => void, reject: (error?: any) => void) => void); + + /** + * Creates a promise that resolves when all of the child promises resolve. + */ + static all(promises: OfficeExtension.IPromise[]): IPromise; + + /** + * Creates a promise that is resolved. + */ + static resolve(value: U): IPromise; + + /** + * Creates a promise that is rejected. + */ + static reject(error: any): IPromise; + + /* This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => IPromise): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => U): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => IPromise, onRejected?: (error: any) => void): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => IPromise): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): IPromise; + + /** + * This method will be called once the previous promise has been resolved. + * Both the onFulfilled on onRejected callbacks are optional. + * If either or both are omitted, the next onFulfilled/onRejected in the chain will be called called. + + * @returns A new promise for the value or error that was returned from onFulfilled/onRejected. + */ + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => void): IPromise; + + + /** + * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. + * @param onRejected function to be called if or when the promise rejects. + */ + catch(onRejected?: (error: any) => IPromise): IPromise; + + /** + * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. + * @param onRejected function to be called if or when the promise rejects. + */ + catch(onRejected?: (error: any) => U): IPromise; + + /** + * Catches failures or exceptions from actions within the promise, or from an unhandled exception earlier in the call stack. + * @param onRejected function to be called if or when the promise rejects. + */ + catch(onRejected?: (error: any) => void): IPromise; + } +} + +declare module OfficeExtension { + /** Collection of tracked objects, contained within a request context. See "context.trackedObjects" for more information. */ + class TrackedObjects { + /** Track a new object for automatic adjustment based on surrounding changes in the document. Only some object types require this. If you are using an object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ + add(object: ClientObject): void; + /** Track a new object for automatic adjustment based on surrounding changes in the document. Only some object types require this. If you are using an object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. */ + add(objects: ClientObject[]): void; + /** Release the memory associated with an object that was previously added to this collection. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ + remove(object: ClientObject): void; + /** Release the memory associated with an object that was previously added to this collection. Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ + remove(objects: ClientObject[]): void; + } +} + +declare module OfficeExtension { + export class EventHandlers { + constructor(context: ClientRequestContext, parentObject: ClientObject, name: string, eventInfo: EventInfo); + add(handler: (args: T) => IPromise): EventHandlerResult; + remove(handler: (args: T) => IPromise): void; + removeAll(): void; + } + + export class EventHandlerResult { + constructor(context: ClientRequestContext, handlers: EventHandlers, handler: (args: T) => IPromise); + remove(): void; + } + + export interface EventInfo { + registerFunc: (callback: (args: any) => void) => IPromise; + unregisterFunc: (callback: (args: any) => void) => IPromise; + eventArgsTransformFunc: (args: any) => IPromise; + } +} +declare module OfficeExtension { + /** + * Request URL and headers + */ + interface RequestUrlAndHeaderInfo { + /** Request URL */ + url: string; + /** Request headers */ + headers?: { + [name: string]: string; + }; + } +} + + + +//////////////////////////////////////////////////////////////// +////////////////// End OfficeExtension runtime ///////////////// +//////////////////////////////////////////////////////////////// + + + +//////////////////////////////////////////////////////////////// + + + +//////////////////////////////////////////////////////////////// +//////////////// Begin Excel APIs (latest = 1.3) /////////////// +//////////////////////////////////////////////////////////////// + + declare module Excel { interface ThreeArrowsSet { [index: number]: Icon; @@ -1899,7 +2602,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class Application extends OfficeExtension.ClientObject { - private m_calculationMode; /** * * Returns the calculation mode used in the workbook. See Excel.CalculationMode for details. Read-only. @@ -1920,6 +2622,9 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.Application; + toJSON(): { + "calculationMode": string; + }; } /** * @@ -1928,14 +2633,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class Workbook extends OfficeExtension.ClientObject { - private m_application; - private m_bindings; - private m_functions; - private m_names; - private m_pivotTables; - private m_tables; - private m_worksheets; - private m_selectionChanged; /** * * Represents Excel application instance that contains this workbook. Read-only. @@ -1968,7 +2665,7 @@ declare module Excel { * * Represents a collection of PivotTables associated with the workbook. Read-only. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ pivotTables: Excel.PivotTableCollection; /** @@ -2003,6 +2700,7 @@ declare module Excel { * [Api set: ExcelApi 1.2] */ onSelectionChanged: OfficeExtension.EventHandlers; + toJSON(): {}; } /** * @@ -2011,14 +2709,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class Worksheet extends OfficeExtension.ClientObject { - private m_charts; - private m_id; - private m_name; - private m_pivotTables; - private m_position; - private m_protection; - private m_tables; - private m_visibility; /** * * Returns collection of charts that are part of the worksheet. Read-only. @@ -2030,7 +2720,7 @@ declare module Excel { * * Collection of PivotTables that are part of the worksheet. Read-only. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ pivotTables: Excel.PivotTableCollection; /** @@ -2121,6 +2811,13 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.Worksheet; + toJSON(): { + "id": string; + "name": string; + "position": number; + "protection": WorksheetProtection; + "visibility": string; + }; } /** * @@ -2129,7 +2826,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class WorksheetCollection extends OfficeExtension.ClientObject { - private m__items; /** Gets the loaded child items in this collection. */ items: Array; /** @@ -2157,19 +2853,11 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ getItem(key: string): Excel.Worksheet; - /** - * - * Gets a worksheet object using its Name or ID. If the worksheet does not exist, the returned object's isNull property will be true. - * - * @param key The Name or ID of the worksheet. - * - * [Api set: ExcelApi 1.3 (Preview)] - */ - getItemOrNull(key: string): Excel.Worksheet; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.WorksheetCollection; + toJSON(): {}; } /** * @@ -2178,11 +2866,9 @@ declare module Excel { * [Api set: ExcelApi 1.2] */ class WorksheetProtection extends OfficeExtension.ClientObject { - private m_options; - private m_protected; /** * - * Sheet protection options. + * Sheet protection options. Read-Only. * * [Api set: ExcelApi 1.2] */ @@ -2214,6 +2900,10 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.WorksheetProtection; + toJSON(): { + "options": WorksheetProtectionOptions; + "protected": boolean; + }; } /** * @@ -2307,29 +2997,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class Range extends OfficeExtension.ClientObject { - private m_address; - private m_addressLocal; - private m_cellCount; - private m_columnCount; - private m_columnHidden; - private m_columnIndex; - private m_format; - private m_formulas; - private m_formulasLocal; - private m_formulasR1C1; - private m_hidden; - private m_numberFormat; - private m_rowCount; - private m_rowHidden; - private m_rowIndex; - private m_sort; - private m_text; - private m_valueTypes; - private m_values; - private m_worksheet; - private m__ReferenceId; - private _ensureInteger(num, methodName); - private _getAdjacentRange(functionName, count, referenceRange, rowDirection, columnDirection); /** * * Returns a format object, encapsulating the range's font, fill, borders, alignment, and other properties. Read-only. @@ -2367,7 +3034,7 @@ declare module Excel { addressLocal: string; /** * - * Number of cells in the range. Read-only. + * Number of cells in the range. This API will return -1 if the cell count exceeds 2^31-1 (2,147,483,647). Read-only. * * [Api set: ExcelApi 1.1] */ @@ -2557,15 +3224,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ getIntersection(anotherRange: Excel.Range | string): Excel.Range; - /** - * - * Gets the range object that represents the rectangular intersection of the given ranges. If no intersection is found, will return a null object. - * - * @param anotherRange The range object or range address that will be used to determine the intersection of ranges. - * - * [Api set: ExcelApi 1.3 (Preview)] - */ - getIntersectionOrNull(anotherRange: Excel.Range | string): Excel.Range; /** * * Gets the last cell within the range. For example, the last cell of "B2:D5" is "D5". @@ -2647,7 +3305,7 @@ declare module Excel { * * Represents the visible rows of the current range. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ getVisibleView(): Excel.RangeView; /** @@ -2686,6 +3344,34 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.Range; + /** + * Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across ".sync" calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you needed to have added the object to the tracked object collection when the object was first created. + */ + track(): Excel.Range; + /** + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + */ + untrack(): Excel.Range; + toJSON(): { + "address": string; + "addressLocal": string; + "cellCount": number; + "columnCount": number; + "columnHidden": boolean; + "columnIndex": number; + "format": RangeFormat; + "formulas": any[][]; + "formulasLocal": any[][]; + "formulasR1C1": any[][]; + "hidden": boolean; + "numberFormat": any[][]; + "rowCount": number; + "rowHidden": boolean; + "rowIndex": number; + "text": any[][]; + "values": any[][]; + "valueTypes": string[][]; + }; } /** * @@ -2700,109 +3386,125 @@ declare module Excel { * * RangeView represents a set of visible cells of the parent range. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ class RangeView extends OfficeExtension.ClientObject { - private m_columnCount; - private m_formulas; - private m_formulasLocal; - private m_formulasR1C1; - private m_numberFormat; - private m_rowCount; - private m_rows; - private m_text; - private m_valueTypes; - private m_values; /** * * Represents a collection of range views associated with the range. Read-only. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ rows: Excel.RangeViewCollection; + /** + * + * Represents the cell addresses of the RangeView. + * + * [Api set: ExcelApi 1.3] + */ + cellAddresses: Array>; /** * * Returns the number of visible columns. Read-only. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ columnCount: number; /** * * Represents the formula in A1-style notation. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ formulas: Array>; /** * * Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become "=SUMME(A1; 1,5)" in German. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ formulasLocal: Array>; /** * * Represents the formula in R1C1-style notation. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ formulasR1C1: Array>; /** * - * Represents Excel's number format code for the given cell. Read-only. + * Returns a value that represents the index of the RangeView. Read-only. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] + */ + index: number; + /** + * + * Represents Excel's number format code for the given cell. + * + * [Api set: ExcelApi 1.3] */ numberFormat: Array>; /** * * Returns the number of visible rows. Read-only. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ rowCount: number; /** * * Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API. Read-only. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ text: Array>; /** * * Represents the type of data of each cell. Read-only. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ valueTypes: Array>; /** * * Represents the raw values of the specified range view. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ values: Array>; /** * * Gets the parent range associated with the current RangeView. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ getRange(): Excel.Range; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.RangeView; + toJSON(): { + "cellAddresses": any[][]; + "columnCount": number; + "formulas": any[][]; + "formulasLocal": any[][]; + "formulasR1C1": any[][]; + "index": number; + "numberFormat": any[][]; + "rowCount": number; + "text": any[][]; + "values": any[][]; + "valueTypes": string[][]; + }; } /** * * Represents a collection of worksheet objects that are part of the workbook. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ class RangeViewCollection extends OfficeExtension.ClientObject { - private m__items; /** Gets the loaded child items in this collection. */ items: Array; /** @@ -2811,22 +3513,58 @@ declare module Excel { * * @param index Index of the visible row. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ - getItem(index: number): Excel.RangeView; + getItemAt(index: number): Excel.RangeView; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.RangeViewCollection; + toJSON(): {}; } /** * - * A collection of all the nameditem objects that are part of the workbook. + * Setting represents a key-value pair of a setting persisted to the document. + * + * [Api set: ExcelApi 1.3] + */ + class Setting extends OfficeExtension.ClientObject { + /** + * + * Represents the value stored for this setting. + * + * [Api set: ExcelApi 1.3] + */ + value: any; + /** + * + * Returns the key that represents the id of the Setting. Read-only. + * + * [Api set: ExcelApi 1.3] + */ + key: string; + /** + * + * Deletes the setting. + * + * [Api set: ExcelApi 1.3] + */ + delete(): void; + /** + * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. + */ + load(option?: string | string[] | OfficeExtension.LoadOption): Excel.Setting; + toJSON(): { + "key": string; + }; + } + /** + * + * A collection of all the nameditem objects that are part of the workbook or worksheet, depending on how it was reached. * * [Api set: ExcelApi 1.1] */ class NamedItemCollection extends OfficeExtension.ClientObject { - private m__items; /** Gets the loaded child items in this collection. */ items: Array; /** @@ -2838,19 +3576,11 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ getItem(name: string): Excel.NamedItem; - /** - * - * Gets a nameditem object using its name. If the nameditem object does not exist, the returned object's isNull property will be true. - * - * @param name nameditem name. - * - * [Api set: ExcelApi 1.3 (Preview)] - */ - getItemOrNull(name: string): Excel.NamedItem; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.NamedItemCollection; + toJSON(): {}; } /** * @@ -2859,11 +3589,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class NamedItem extends OfficeExtension.ClientObject { - private m_name; - private m_type; - private m_value; - private m_visible; - private m__Id; /** * * The name of the object. Read-only. @@ -2873,14 +3598,14 @@ declare module Excel { name: string; /** * - * Indicates what type of reference is associated with the name. See Excel.NamedItemType for details. Read-only. + * Indicates the type of the value returned by the name's formula. See Excel.NamedItemType for details. Read-only. * * [Api set: ExcelApi 1.1] */ type: string; /** * - * Represents the formula that the name is defined to refer to. E.g. =Sheet14!$B$2:$H$12, =4.75, etc. Read-only. + * Represents the value computed by the name's formula. Read-only. * * [Api set: ExcelApi 1.1] */ @@ -2899,10 +3624,23 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ getRange(): Excel.Range; + /** + * + * Returns the range object that is associated with the name. Returns a null object if the named item's type is not a range + * + * [Api set: ExcelApi 1.1] + */ + getRangeOrNullObject(): Excel.Range; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.NamedItem; + toJSON(): { + "name": string; + "type": string; + "value": any; + "visible": boolean; + }; } /** * @@ -2911,10 +3649,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class Binding extends OfficeExtension.ClientObject { - private m_id; - private m_type; - private m_dataChanged; - private m_selectionChanged; /** * * Represents binding identifier. Read-only. @@ -2929,6 +3663,13 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ type: string; + /** + * + * Deletes the binding. + * + * [Api set: ExcelApi 1.3] + */ + delete(): void; /** * * Returns the range represented by the binding. Will throw an error if binding is not of the correct type. @@ -2956,7 +3697,7 @@ declare module Excel { load(option?: string | string[] | OfficeExtension.LoadOption): Excel.Binding; /** * - * Occurs when data within the binding is changed. + * Occurs when data or formatting within the binding is changed. * * [Api set: ExcelApi 1.2] */ @@ -2968,6 +3709,10 @@ declare module Excel { * [Api set: ExcelApi 1.2] */ onSelectionChanged: OfficeExtension.EventHandlers; + toJSON(): { + "id": string; + "type": string; + }; } /** * @@ -2976,8 +3721,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class BindingCollection extends OfficeExtension.ClientObject { - private m_count; - private m__items; /** Gets the loaded child items in this collection. */ items: Array; /** @@ -2995,7 +3738,7 @@ declare module Excel { * @param bindingType Type of binding. See Excel.BindingType. * @param id Name of binding. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ add(range: Excel.Range | string, bindingType: string, id: string): Excel.Binding; /** @@ -3006,7 +3749,7 @@ declare module Excel { * @param bindingType Type of binding. See Excel.BindingType. * @param id Name of binding. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ addFromNamedItem(name: string, bindingType: string, id: string): Excel.Binding; /** @@ -3016,7 +3759,7 @@ declare module Excel { * @param bindingType Type of binding. See Excel.BindingType. * @param id Name of binding. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ addFromSelection(bindingType: string, id: string): Excel.Binding; /** @@ -3037,29 +3780,21 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ getItemAt(index: number): Excel.Binding; - /** - * - * Gets a binding object by ID. If the binding object does not exist, the return object's isNull property will be true. - * - * @param id Id of the binding object to be retrieved. - * - * [Api set: ExcelApi 1.3 (Preview)] - */ - getItemOrNull(id: string): Excel.Binding; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.BindingCollection; + toJSON(): { + "count": number; + }; } /** * - * Represents a collection of all the tables that are part of the workbook. + * Represents a collection of all the tables that are part of the workbook or worksheet, depending on how it was reached. * * [Api set: ExcelApi 1.1] */ class TableCollection extends OfficeExtension.ClientObject { - private m_count; - private m__items; /** Gets the loaded child items in this collection. */ items: Array; /** @@ -3071,14 +3806,14 @@ declare module Excel { count: number; /** * - * Create a new table. The range source address determines the worksheet under which the table will be added. If the table cannot be added (e.g., because the address is invalid, or the table would overlap with another table), an error will be thrown. + * Create a new table. The range object or source address determines the worksheet under which the table will be added. If the table cannot be added (e.g., because the address is invalid, or the table would overlap with another table), an error will be thrown. * - * @param address Address or name of the range object representing the data source. If the address does not contain a sheet name, the currently-active sheet is used. + * @param address A Range object, or a string address or name of the range representing the data source. If the address does not contain a sheet name, the currently-active sheet is used. [Api set: ExcelApi 1.1 for string parameter; 1.3 for accepting a Range object as well] * @param hasHeaders Boolean value that indicates whether the data being imported has column labels. If the source does not contain headers (i.e,. when this property set to false), Excel will automatically generate header shifting the data down by one row. * * [Api set: ExcelApi 1.1] */ - add(address: string, hasHeaders: boolean): Excel.Table; + add(address: Excel.Range | string, hasHeaders: boolean): Excel.Table; /** * * Gets a table by Name or ID. @@ -3097,19 +3832,13 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ getItemAt(index: number): Excel.Table; - /** - * - * Gets a table by Name or ID. If the table does not exist, the return object's isNull property will be true. - * - * @param key Name or ID of the table to be retrieved. - * - * [Api set: ExcelApi 1.3 (Preview)] - */ - getItemOrNull(key: number | string): Excel.Table; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.TableCollection; + toJSON(): { + "count": number; + }; } /** * @@ -3118,20 +3847,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class Table extends OfficeExtension.ClientObject { - private m_columns; - private m_highlightFirstColumn; - private m_highlightLastColumn; - private m_id; - private m_name; - private m_rows; - private m_showBandedColumns; - private m_showBandedRows; - private m_showFilterButton; - private m_showHeaders; - private m_showTotals; - private m_sort; - private m_style; - private m_worksheet; /** * * Represents a collection of all the columns in the table. Read-only. @@ -3164,14 +3879,14 @@ declare module Excel { * * Indicates whether the first column contains special formatting. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ highlightFirstColumn: boolean; /** * * Indicates whether the last column contains special formatting. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ highlightLastColumn: boolean; /** @@ -3192,21 +3907,21 @@ declare module Excel { * * Indicates whether the columns show banded formatting in which odd columns are highlighted differently from even ones to make reading the table easier. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ showBandedColumns: boolean; /** * * Indicates whether the rows show banded formatting in which odd rows are highlighted differently from even ones to make reading the table easier. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ showBandedRows: boolean; /** * * Indicates whether the filter buttons are visible at the top of each column header. Setting this is only allowed if the table contains a header row. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ showFilterButton: boolean; /** @@ -3290,6 +4005,18 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.Table; + toJSON(): { + "highlightFirstColumn": boolean; + "highlightLastColumn": boolean; + "id": number; + "name": string; + "showBandedColumns": boolean; + "showBandedRows": boolean; + "showFilterButton": boolean; + "showHeaders": boolean; + "showTotals": boolean; + "style": string; + }; } /** * @@ -3298,8 +4025,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class TableColumnCollection extends OfficeExtension.ClientObject { - private m_count; - private m__items; /** Gets the loaded child items in this collection. */ items: Array; /** @@ -3313,12 +4038,13 @@ declare module Excel { * * Adds a new column to the table. * - * @param index Specifies the relative position of the new column. The previous column at this position is shifted to the right. The index value should be equal to or less than the last column's index value, so it cannot be used to append a column at the end of the table. Zero-indexed. + * @param index Specifies the relative position of the new column. If null or -1, the addition happens at the end. Columns with a higher index will be shifted to the side. Zero-indexed. * @param values A 2-dimensional array of unformatted values of the table column. + * @param name Specifies the name of the new column. If null, the default name will be used. * - * [Api set: ExcelApi 1.1] + * [Api set: ExcelApi 1.1 requires an index smaller than the total column count; 1.4 allows index to be optional (null or -1) and will append a column at the end; 1.4 allows name parameter at creation time.] */ - add(index: number, values?: Array> | boolean | string | number): Excel.TableColumn; + add(index?: number, values?: Array> | boolean | string | number, name?: string): Excel.TableColumn; /** * * Gets a column object by Name or ID. @@ -3337,19 +4063,13 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ getItemAt(index: number): Excel.TableColumn; - /** - * - * Gets a column object by Name or ID. If the column does not exist, the returned object's isNull property will be true. - * - * @param key Column Name or ID. - * - * [Api set: ExcelApi 1.3 (Preview)] - */ - getItemOrNull(key: number | string): Excel.TableColumn; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.TableColumnCollection; + toJSON(): { + "count": number; + }; } /** * @@ -3358,11 +4078,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class TableColumn extends OfficeExtension.ClientObject { - private m_filter; - private m_id; - private m_index; - private m_name; - private m_values; /** * * Retrieve the filter applied to the column. @@ -3386,9 +4101,9 @@ declare module Excel { index: number; /** * - * Returns the name of the table column. Read-only. + * Represents the name of the table column. * - * [Api set: ExcelApi 1.1] + * [Api set: ExcelApi 1.1 for getting the name; 1.4 for setting it.] */ name: string; /** @@ -3437,6 +4152,12 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.TableColumn; + toJSON(): { + "id": number; + "index": number; + "name": string; + "values": any[][]; + }; } /** * @@ -3445,8 +4166,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class TableRowCollection extends OfficeExtension.ClientObject { - private m_count; - private m__items; /** Gets the loaded child items in this collection. */ items: Array; /** @@ -3458,12 +4177,12 @@ declare module Excel { count: number; /** * - * Adds a new row to the table. + * Adds one or more rows to the table. The return object will be the top of the newly added row(s). * - * @param index Specifies the relative position of the new row. If null, the addition happens at the end. Any rows below the inserted row are shifted downwards. Zero-indexed. + * @param index Specifies the relative position of the new row. If null or -1, the addition happens at the end. Any rows below the inserted row are shifted downwards. Zero-indexed. * @param values A 2-dimensional array of unformatted values of the table row. * - * [Api set: ExcelApi 1.1] + * [Api set: ExcelApi 1.1 for adding a single row; 1.4 allows adding of multiple rows.] */ add(index?: number, values?: Array> | boolean | string | number): Excel.TableRow; /** @@ -3479,6 +4198,9 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.TableRowCollection; + toJSON(): { + "count": number; + }; } /** * @@ -3487,8 +4209,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class TableRow extends OfficeExtension.ClientObject { - private m_index; - private m_values; /** * * Returns the index number of the row within the rows collection of the table. Zero-indexed. Read-only. @@ -3498,7 +4218,14 @@ declare module Excel { index: number; /** * +<<<<<<< HEAD * Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string. +======= + * The first criterion used to filter data. Used as an operator in the case of "custom" filtering. + For example ">50" for number greater than 50 or "=*s" for values ending in "s". + + Used as a number in the case of top/bottom items/percents. E.g. "5" for the top 5 items if filterOn is set to "topItems" +>>>>>>> types-2.0 * * [Api set: ExcelApi 1.1] */ @@ -3521,6 +4248,10 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.TableRow; + toJSON(): { + "index": number; + "values": any[][]; + }; } /** * @@ -3529,18 +4260,9 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class RangeFormat extends OfficeExtension.ClientObject { - private m_borders; - private m_columnWidth; - private m_fill; - private m_font; - private m_horizontalAlignment; - private m_protection; - private m_rowHeight; - private m_verticalAlignment; - private m_wrapText; /** * - * Collection of border objects that apply to the overall range selected Read-only. + * Collection of border objects that apply to the overall range. Read-only. * * [Api set: ExcelApi 1.1] */ @@ -3554,7 +4276,7 @@ declare module Excel { fill: Excel.RangeFill; /** * - * Returns the font object defined on the overall range selected Read-only. + * Returns the font object defined on the overall range. Read-only. * * [Api set: ExcelApi 1.1] */ @@ -3619,6 +4341,16 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.RangeFormat; + toJSON(): { + "columnWidth": number; + "fill": RangeFill; + "font": RangeFont; + "horizontalAlignment": string; + "protection": FormatProtection; + "rowHeight": number; + "verticalAlignment": string; + "wrapText": boolean; + }; } /** * @@ -3627,8 +4359,6 @@ declare module Excel { * [Api set: ExcelApi 1.2] */ class FormatProtection extends OfficeExtension.ClientObject { - private m_formulaHidden; - private m_locked; /** * * Indicates if Excel hides the formula for the cells in the range. A null value indicates that the entire range doesn't have uniform formula hidden setting. @@ -3647,6 +4377,10 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.FormatProtection; + toJSON(): { + "formulaHidden": boolean; + "locked": boolean; + }; } /** * @@ -3655,7 +4389,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class RangeFill extends OfficeExtension.ClientObject { - private m_color; /** * * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange") @@ -3674,6 +4407,9 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.RangeFill; + toJSON(): { + "color": string; + }; } /** * @@ -3682,10 +4418,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class RangeBorder extends OfficeExtension.ClientObject { - private m_color; - private m_sideIndex; - private m_style; - private m_weight; /** * * HTML color code representing the color of the border line, of the form #RRGGBB (e.g. "FFA500") or as a named HTML color (e.g. "orange"). @@ -3718,6 +4450,12 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.RangeBorder; + toJSON(): { + "color": string; + "sideIndex": string; + "style": string; + "weight": string; + }; } /** * @@ -3726,8 +4464,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class RangeBorderCollection extends OfficeExtension.ClientObject { - private m_count; - private m__items; /** Gets the loaded child items in this collection. */ items: Array; /** @@ -3759,6 +4495,9 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.RangeBorderCollection; + toJSON(): { + "count": number; + }; } /** * @@ -3767,12 +4506,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class RangeFont extends OfficeExtension.ClientObject { - private m_bold; - private m_color; - private m_italic; - private m_name; - private m_size; - private m_underline; /** * * Represents the bold status of font. @@ -3819,6 +4552,14 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.RangeFont; + toJSON(): { + "bold": boolean; + "color": string; + "italic": boolean; + "name": string; + "size": number; + "underline": string; + }; } /** * @@ -3827,8 +4568,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartCollection extends OfficeExtension.ClientObject { - private m_count; - private m__items; /** Gets the loaded child items in this collection. */ items: Array; /** @@ -3867,20 +4606,13 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ getItemAt(index: number): Excel.Chart; - /** - * - * Gets a chart using its name. If there are multiple charts with the same name, the first one will be returned. - If the chart does not exist, the returned object's isNull property will be true. - * - * @param name Name of the chart to be retrieved. - * - * [Api set: ExcelApi 1.3 (Preview)] - */ - getItemOrNull(name: string): Excel.Chart; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartCollection; + toJSON(): { + "count": number; + }; } /** * @@ -3889,18 +4621,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class Chart extends OfficeExtension.ClientObject { - private m_axes; - private m_dataLabels; - private m_format; - private m_height; - private m_left; - private m_legend; - private m_name; - private m_series; - private m_title; - private m_top; - private m_width; - private m_worksheet; /** * * Represents chart axes. Read-only. @@ -4028,6 +4748,18 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.Chart; + toJSON(): { + "axes": ChartAxes; + "dataLabels": ChartDataLabels; + "format": ChartAreaFormat; + "height": number; + "left": number; + "legend": ChartLegend; + "name": string; + "title": ChartTitle; + "top": number; + "width": number; + }; } /** * @@ -4036,8 +4768,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartAreaFormat extends OfficeExtension.ClientObject { - private m_fill; - private m_font; /** * * Represents the fill format of an object, which includes background formatting information. Read-only. @@ -4056,6 +4786,10 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartAreaFormat; + toJSON(): { + "fill": ChartFill; + "font": ChartFont; + }; } /** * @@ -4064,8 +4798,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartSeriesCollection extends OfficeExtension.ClientObject { - private m_count; - private m__items; /** Gets the loaded child items in this collection. */ items: Array; /** @@ -4088,6 +4820,9 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartSeriesCollection; + toJSON(): { + "count": number; + }; } /** * @@ -4096,9 +4831,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartSeries extends OfficeExtension.ClientObject { - private m_format; - private m_name; - private m_points; /** * * Represents the formatting of a chart series, which includes fill and line formatting. Read-only. @@ -4124,6 +4856,10 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartSeries; + toJSON(): { + "format": ChartSeriesFormat; + "name": string; + }; } /** * @@ -4132,8 +4868,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartSeriesFormat extends OfficeExtension.ClientObject { - private m_fill; - private m_line; /** * * Represents the fill format of a chart series, which includes background formating information. Read-only. @@ -4152,6 +4886,10 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartSeriesFormat; + toJSON(): { + "fill": ChartFill; + "line": ChartLineFormat; + }; } /** * @@ -4160,8 +4898,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartPointsCollection extends OfficeExtension.ClientObject { - private m_count; - private m__items; /** Gets the loaded child items in this collection. */ items: Array; /** @@ -4184,6 +4920,9 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartPointsCollection; + toJSON(): { + "count": number; + }; } /** * @@ -4192,8 +4931,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartPoint extends OfficeExtension.ClientObject { - private m_format; - private m_value; /** * * Encapsulates the format properties chart point. Read-only. @@ -4212,6 +4949,10 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartPoint; + toJSON(): { + "format": ChartPointFormat; + "value": any; + }; } /** * @@ -4220,7 +4961,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartPointFormat extends OfficeExtension.ClientObject { - private m_fill; /** * * Represents the fill format of a chart, which includes background formating information. Read-only. @@ -4232,6 +4972,9 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartPointFormat; + toJSON(): { + "fill": ChartFill; + }; } /** * @@ -4240,9 +4983,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartAxes extends OfficeExtension.ClientObject { - private m_categoryAxis; - private m_seriesAxis; - private m_valueAxis; /** * * Represents the category axis in a chart. Read-only. @@ -4268,6 +5008,11 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartAxes; + toJSON(): { + "categoryAxis": ChartAxis; + "seriesAxis": ChartAxis; + "valueAxis": ChartAxis; + }; } /** * @@ -4276,14 +5021,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartAxis extends OfficeExtension.ClientObject { - private m_format; - private m_majorGridlines; - private m_majorUnit; - private m_maximum; - private m_minimum; - private m_minorGridlines; - private m_minorUnit; - private m_title; /** * * Represents the formatting of a chart object, which includes line and font formatting. Read-only. @@ -4344,6 +5081,16 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartAxis; + toJSON(): { + "format": ChartAxisFormat; + "majorGridlines": ChartGridlines; + "majorUnit": any; + "maximum": any; + "minimum": any; + "minorGridlines": ChartGridlines; + "minorUnit": any; + "title": ChartAxisTitle; + }; } /** * @@ -4352,8 +5099,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartAxisFormat extends OfficeExtension.ClientObject { - private m_font; - private m_line; /** * * Represents the font attributes (font name, font size, color, etc.) for a chart axis element. Read-only. @@ -4372,6 +5117,10 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartAxisFormat; + toJSON(): { + "font": ChartFont; + "line": ChartLineFormat; + }; } /** * @@ -4380,9 +5129,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartAxisTitle extends OfficeExtension.ClientObject { - private m_format; - private m_text; - private m_visible; /** * * Represents the formatting of chart axis title. Read-only. @@ -4408,6 +5154,11 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartAxisTitle; + toJSON(): { + "format": ChartAxisTitleFormat; + "text": string; + "visible": boolean; + }; } /** * @@ -4416,7 +5167,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartAxisTitleFormat extends OfficeExtension.ClientObject { - private m_font; /** * * Represents the font attributes, such as font name, font size, color, etc. of chart axis title object. Read-only. @@ -4428,6 +5178,9 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartAxisTitleFormat; + toJSON(): { + "font": ChartFont; + }; } /** * @@ -4436,15 +5189,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartDataLabels extends OfficeExtension.ClientObject { - private m_format; - private m_position; - private m_separator; - private m_showBubbleSize; - private m_showCategoryName; - private m_showLegendKey; - private m_showPercentage; - private m_showSeriesName; - private m_showValue; /** * * Represents the format of chart data labels, which includes fill and font formatting. Read-only. @@ -4512,6 +5256,17 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartDataLabels; + toJSON(): { + "format": ChartDataLabelFormat; + "position": string; + "separator": string; + "showBubbleSize": boolean; + "showCategoryName": boolean; + "showLegendKey": boolean; + "showPercentage": boolean; + "showSeriesName": boolean; + "showValue": boolean; + }; } /** * @@ -4520,8 +5275,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartDataLabelFormat extends OfficeExtension.ClientObject { - private m_fill; - private m_font; /** * * Represents the fill format of the current chart data label. Read-only. @@ -4540,6 +5293,10 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartDataLabelFormat; + toJSON(): { + "fill": ChartFill; + "font": ChartFont; + }; } /** * @@ -4548,8 +5305,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartGridlines extends OfficeExtension.ClientObject { - private m_format; - private m_visible; /** * * Represents the formatting of chart gridlines. Read-only. @@ -4568,6 +5323,10 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartGridlines; + toJSON(): { + "format": ChartGridlinesFormat; + "visible": boolean; + }; } /** * @@ -4576,7 +5335,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartGridlinesFormat extends OfficeExtension.ClientObject { - private m_line; /** * * Represents chart line formatting. Read-only. @@ -4588,6 +5346,9 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartGridlinesFormat; + toJSON(): { + "line": ChartLineFormat; + }; } /** * @@ -4596,10 +5357,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartLegend extends OfficeExtension.ClientObject { - private m_format; - private m_overlay; - private m_position; - private m_visible; /** * * Represents the formatting of a chart legend, which includes fill and font formatting. Read-only. @@ -4632,6 +5389,12 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartLegend; + toJSON(): { + "format": ChartLegendFormat; + "overlay": boolean; + "position": string; + "visible": boolean; + }; } /** * @@ -4640,8 +5403,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartLegendFormat extends OfficeExtension.ClientObject { - private m_fill; - private m_font; /** * * Represents the fill format of an object, which includes background formating information. Read-only. @@ -4660,6 +5421,10 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartLegendFormat; + toJSON(): { + "fill": ChartFill; + "font": ChartFont; + }; } /** * @@ -4668,10 +5433,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartTitle extends OfficeExtension.ClientObject { - private m_format; - private m_overlay; - private m_text; - private m_visible; /** * * Represents the formatting of a chart title, which includes fill and font formatting. Read-only. @@ -4704,6 +5465,12 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartTitle; + toJSON(): { + "format": ChartTitleFormat; + "overlay": boolean; + "text": string; + "visible": boolean; + }; } /** * @@ -4712,8 +5479,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartTitleFormat extends OfficeExtension.ClientObject { - private m_fill; - private m_font; /** * * Represents the fill format of an object, which includes background formating information. Read-only. @@ -4732,6 +5497,10 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartTitleFormat; + toJSON(): { + "fill": ChartFill; + "font": ChartFont; + }; } /** * @@ -4760,6 +5529,7 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ setSolidColor(color: string): void; + toJSON(): {}; } /** * @@ -4768,7 +5538,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartLineFormat extends OfficeExtension.ClientObject { - private m_color; /** * * HTML color code representing the color of lines in the chart. @@ -4787,6 +5556,9 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartLineFormat; + toJSON(): { + "color": string; + }; } /** * @@ -4795,12 +5567,6 @@ declare module Excel { * [Api set: ExcelApi 1.1] */ class ChartFont extends OfficeExtension.ClientObject { - private m_bold; - private m_color; - private m_italic; - private m_name; - private m_size; - private m_underline; /** * * Represents the bold status of font. @@ -4847,6 +5613,14 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.ChartFont; + toJSON(): { + "bold": boolean; + "color": string; + "italic": boolean; + "name": string; + "size": number; + "underline": string; + }; } /** * @@ -4868,6 +5642,7 @@ declare module Excel { * [Api set: ExcelApi 1.2] */ apply(fields: Array, matchCase?: boolean, hasHeaders?: boolean, orientation?: string, method?: string): void; + toJSON(): {}; } /** * @@ -4876,9 +5651,6 @@ declare module Excel { * [Api set: ExcelApi 1.2] */ class TableSort extends OfficeExtension.ClientObject { - private m_fields; - private m_matchCase; - private m_method; /** * * Represents the current conditions used to last sort the table. @@ -4929,6 +5701,11 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.TableSort; + toJSON(): { + "fields": SortField[]; + "matchCase": boolean; + "method": string; + }; } /** * @@ -4987,7 +5764,6 @@ declare module Excel { * [Api set: ExcelApi 1.2] */ class Filter extends OfficeExtension.ClientObject { - private m_criteria; /** * * The currently applied filter on the given column. @@ -5107,6 +5883,9 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.Filter; + toJSON(): { + "criteria": FilterCriteria; + }; } /** * @@ -5223,10 +6002,9 @@ declare module Excel { * * Represents a collection of all the PivotTables that are part of the workbook or worksheet. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ class PivotTableCollection extends OfficeExtension.ClientObject { - private m__items; /** Gets the loaded child items in this collection. */ items: Array; /** @@ -5235,64 +6013,57 @@ declare module Excel { * * @param name Name of the PivotTable to be retrieved. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ getItem(name: string): Excel.PivotTable; - /** - * - * Gets a PivotTable by name. If the PivotTable does not exist, the return object's isNull property will be true. - * - * @param name Name of the PivotTable to be retrieved. - * - * [Api set: ExcelApi 1.3 (Preview)] - */ - getItemOrNull(name: string): Excel.PivotTable; /** * * Refreshes all the PivotTables in the collection. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ refreshAll(): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.PivotTableCollection; + toJSON(): {}; } /** * * Represents an Excel PivotTable. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ class PivotTable extends OfficeExtension.ClientObject { - private m_name; - private m_worksheet; /** * * The worksheet containing the current PivotTable. Read-only. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ worksheet: Excel.Worksheet; /** * * Name of the PivotTable. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ name: string; /** * * Refreshes the PivotTable. * - * [Api set: ExcelApi 1.3 (Preview)] + * [Api set: ExcelApi 1.3] */ refresh(): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): Excel.PivotTable; + toJSON(): { + "name": string; + }; } /** * [Api set: ExcelApi 1.1] @@ -5635,6 +6406,7 @@ declare module Excel { var double: string; var boolean: string; var range: string; + var error: string; } /** * [Api set: ExcelApi 1.1] @@ -5713,8 +6485,6 @@ declare module Excel { * [Api set: ExcelApi 1.2] */ class FunctionResult extends OfficeExtension.ClientObject { - private m_error; - private m_value; /** * * Error value (such as "#DIV/0") representing the error. If the error string is not set, then the function succeeded, and its result is written to the Value field. The error is always in the English locale. @@ -5724,7 +6494,7 @@ declare module Excel { error: string; /** * - * The value of function evaluation. The value field will be populated only if no error has occured (i.e., the Error property is not set). + * The value of function evaluation. The value field will be populated only if no error has occurred (i.e., the Error property is not set). * * [Api set: ExcelApi 1.2] */ @@ -5733,6 +6503,10 @@ declare module Excel { * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ load(option?: string | string[] | OfficeExtension.LoadOption): FunctionResult; + toJSON(): { + "error": string; + "value": T; + }; } /** * @@ -9477,9 +10251,11 @@ declare module Excel { * [Api set: ExcelApi 1.2] */ z_Test(array: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, x: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult, sigma?: number | Excel.Range | Excel.RangeReference | Excel.FunctionResult): FunctionResult; + toJSON(): {}; } module ErrorCodes { var accessDenied: string; + var apiNotFound: string; var generalException: string; var insertDeleteConflict: string; var invalidArgument: string; @@ -9498,17 +10274,67 @@ declare module Excel { * The RequestContext object facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the request context is required to get access to the Excel object model from the add-in. */ class RequestContext extends OfficeExtension.ClientRequestContext { - private m_workbook; constructor(url?: string); workbook: Workbook; } /** - * Executes a batch script that performs actions on the Excel object model. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. - * @param batch - A function that takes in an Excel.RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the request context is required to get access to the Excel object model from the add-in. + * Executes a batch script that performs actions on the Excel object model, using a new RequestContext. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. */ function run(batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; + /** + * Executes a batch script that performs actions on the Excel object model, using a new remote RequestContext. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + * @param requestInfo - The URL of the remote workbook and the request headers to be sent. + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. + */ + function run(requestInfo: OfficeExtension.RequestUrlAndHeaderInfo, batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; + /** + * Executes a batch script that performs actions on the Excel object model, using the RequestContext of a previously-created API object. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + * @param object - A previously-created API object. The batch will use the same RequestContext as the passed-in object, which means that any changes applied to the object will be picked up by "context.sync()". + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. + */ + function run(object: OfficeExtension.ClientObject, batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; + /** + * Executes a batch script that performs actions on the Excel object model, using the remote RequestContext of a previously-created API object. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. + * @param requestInfo - The URL of the remote workbook and the request headers to be sent. + * @param object - A previously-created API object. The batch will use the same RequestContext as the passed-in object, which means that any changes applied to the object will be picked up by "context.sync()". + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. + */ + function run(requestInfo: OfficeExtension.RequestUrlAndHeaderInfo, object: OfficeExtension.ClientObject, batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; + /** + * Executes a batch script that performs actions on the Excel object model, using the RequestContext of previously-created API objects. + * @param objects - An array of previously-created API objects. The array will be validated to make sure that all of the objects share the same context. The batch will use this shared RequestContext, which means that any changes applied to these objects will be picked up by "context.sync()". + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. + */ + function run(objects: OfficeExtension.ClientObject[], batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; + /** + * Executes a batch script that performs actions on the Excel object model, using the remote RequestContext of previously-created API objects. + * @param requestInfo - The URL of the remote workbook and the request headers to be sent. + * @param objects - An array of previously-created API objects. The array will be validated to make sure that all of the objects share the same context. The batch will use this shared RequestContext, which means that any changes applied to these objects will be picked up by "context.sync()". + * @param batch - A function that takes in a RequestContext and returns a promise (typically, just the result of "context.sync()"). The context parameter facilitates requests to the Excel application. Since the Office add-in and the Excel application run in two different processes, the RequestContext is required to get access to the Excel object model from the add-in. + */ + function run(requestInfo: OfficeExtension.RequestUrlAndHeaderInfo, objects: OfficeExtension.ClientObject[], batch: (context: Excel.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; } + + +//////////////////////////////////////////////////////////////// +//////////////////////// End Excel APIs //////////////////////// +//////////////////////////////////////////////////////////////// + + + + +//////////////////////////////////////////////////////////////// + + + + +//////////////////////////////////////////////////////////////// +//////////////////////// Begin Word APIs /////////////////////// +//////////////////////////////////////////////////////////////// + + declare namespace Word { /** * @@ -12914,614 +13740,26 @@ declare namespace Word { function run(batch: (context: Word.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; } -declare namespace Office.MailboxEnums { - export enum BodyType { - /** - * The body is in HTML format - */ - Html, - /** - * The body is in text format - */ - text - } - export enum EntityType { - /** - * Specifies that the entity is a meeting suggestion - */ - MeetingSuggestion, - /** - * Specifies that the entity is a task suggestion - */ - TaskSuggestion, - /** - * Specifies that the entity is a postal address - */ - Address, - /** - * Specifies that the entity is SMTP email address - */ - EmailAddress, - /** - * Specifies that the entity is an Internet URL - */ - Url, - /** - * Specifies that the entity is US phone number - */ - PhoneNumber, - /** - * Specifies that the entity is a contact - */ - Contact - } - export enum ItemType { - /** - * A meeting request, response, or cancellation - */ - Message, - /** - * Specifies an appointment item - */ - Appointment - } - export enum ResponseType { - /** - * There has been no response from the attendee - */ - None, - /** - * The attendee is the meeting organizer - */ - Organizer, - /** - * The meeting request was tentatively accepted by the attendee - */ - Tentative, - /** - * The meeting request was accepted by the attendee - */ - Accepted, - /** - * The meeting request was declined by the attendee - */ - Declined - } - export enum RecipientType { - /** - * Specifies that the recipient is not one of the other recipient types - */ - Other, - /** - * Specifies that the recipient is a distribution list containing a list of email addresses - */ - DistributionList, - /** - * Specifies that the recipient is an SMTP email address that is on the Exchange server - */ - User, - /** - * Specifies that the recipient is an SMTP email address that is not on the Exchange server - */ - ExternalUser - } - export enum AttachmentType { - /** - * The attachment is a file - */ - File, - /** - * The attachment is an Exchange item - */ - Item - } -} -declare namespace Office { - export module Types { - export interface ItemRead extends Office.Item { - subject: any; - /** - * Displays a reply form that includes the sender and all the recipients of the selected message - * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB - */ - displayReplyAllForm(htmlBody: string): void; - /** - * Displays a reply form that includes only the sender of the selected message - * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB - */ - displayReplyForm(htmlBody: string): void; - /** - * Gets an array of entities found in an message - */ - getEntities(): Office.Entities; - /** - * Gets an array of entities of the specified entity type found in an message - * @param entityType One of the EntityType enumeration values - */ - getEntitiesByType(entityType: Office.MailboxEnums.EntityType): Office.Entities; - /** - * Returns well-known entities that pass the named filter defined in the manifest XML file - * @param name A TableData object with the headers and rows - */ - getFilteredEntitiesByName(name: string): Office.Entities; - /** - * Returns string values in the currently selected message object that match the regular expressions defined in the manifest XML file - */ - getRegExMatches(): string[]; - /** - * Returns string values that match the named regular expression defined in the manifest XML file - */ - getRegExMatchesByName(name: string): string[]; - } - export interface ItemCompose extends Office.Item { - body: Office.Body; - subject: any; - /** - * Adds a file to a message as an attachment - * @param uri The URI that provides the location of the file to attach to the message. The maximum length is 2048 characters - * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method - */ - addFileAttachmentAsync(uri: string, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; - /** - * Adds an Exchange item, such as a message, as an attachment to the message - * @param itemId The Exchange identifier of the item to attach. The maximum length is 100 characters - * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method - */ - addItemAttachmentAsync(itemId: any, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; - /** - * Removes an attachment from a message - * @param attachmentIndex The index of the attachment to remove. The maximum length of the string is 100 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method - */ - removeAttachmentAsync(attachmentIndex: string, option?: any, callback?: (result: AsyncResult) => void): void; - } - export interface MessageCompose extends Office.Message { - attachments: Office.AttachmentDetails[]; - body: Office.Body; - bcc: Office.Recipients; - cc: Office.Recipients; - subject: Office.Subject; - to: Office.Recipients; - /** - * Adds a file to a message as an attachment - * @param uri The URI that provides the location of the file to attach to the message. The maximum length is 2048 characters - * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method - */ - addFileAttachmentAsync(uri: string, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; - /** - * Adds an Exchange item, such as a message, as an attachment to the message - * @param itemId The Exchange identifier of the item to attach. The maximum length is 100 characters - * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method - */ - addItemAttachmentAsync(itemId: any, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; - /** - * Removes an attachment from a message - * @param attachmentIndex The index of the attachment to remove. The maximum length of the string is 100 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method - */ - removeAttachmentAsync(attachmentIndex: string, option?: any, callback?: (result: AsyncResult) => void): void; - } - export interface MessageRead extends Office.Message { - cc: Office.EmailAddressDetails[]; - from: Office.EmailAddressDetails; - internetMessageId: string; - normalizedSubject: string; - sender: Office.EmailAddressDetails; - subject: string; - to: Office.EmailAddressDetails; - /** - * Displays a reply form that includes the sender and all the recipients of the selected message - * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB - */ - displayReplyAllForm(htmlBody: string): void; - /** - * Displays a reply form that includes only the sender of the selected message - * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB - */ - displayReplyForm(htmlBody: string): void; - /** - * Gets an array of entities found in an message - */ - getEntities(): Office.Entities; - /** - * Gets an array of entities of the specified entity type found in an message - * @param entityType One of the EntityType enumeration values - */ - getEntitiesByType(entityType: Office.MailboxEnums.EntityType): Office.Entities; - /** - * Returns well-known entities that pass the named filter defined in the manifest XML file - * @param name A TableData object with the headers and rows - */ - getFilteredEntitiesByName(name: string): Office.Entities; - /** - * Returns string values in the currently selected message object that match the regular expressions defined in the manifest XML file - */ - getRegExMatches(): string[]; - /** - * Returns string values that match the named regular expression defined in the manifest XML file - */ - getRegExMatchesByName(name: string): string[]; - } - export interface AppointmentCompose extends Office.Appointment { - body: Office.Body; - end: Office.Time; - location: Office.Location; - optionalAttendees: Office.Recipients; - requiredAttendees: Office.Recipients; - start: Office.Time; - subject: Office.Subject; - /** - * Adds a file to an appointment as an attachment - * @param uri The URI that provides the location of the file to attach to the appointment. The maximum length is 2048 characters - * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method - */ - addFileAttachmentAsync(uri: string, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; - /** - * Adds an Exchange item, such as a message, as an attachment to the appointment - * @param itemId The Exchange identifier of the item to attach. The maximum length is 100 characters - * @param attachmentName The name of the attachment that is shown while the attachment is uploading. The maximum length is 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method - */ - addItemAttachmentAsync(itemId: any, attachmentName: string, options?: any, callback?: (result: AsyncResult) => void): void; - /** - * Removes an attachment from a appointment - * @param attachmentIndex The index of the attachment to remove. The maximum length of the string is 100 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional callback method - */ - removeAttachmentAsync(attachmentIndex: string, option?: any, callback?: (result: AsyncResult) => void): void; - } - export interface AppointmentRead extends Office.Appointment { - attachments: Office.AttachmentDetails[]; - end: Date; - location: string; - normalizedSubject: string; - optionalAttendees: Office.EmailAddressDetails; - organizer: Office.EmailAddressDetails; - requiredAttendees: Office.EmailAddressDetails; - resources: string[]; - start: Date; - subject: string; - /** - * Displays a reply form that includes the organizer and all the attendees of the selected appointment item - * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB - */ - displayReplyAllForm(htmlBody: string): void; - /** - * Displays a reply form that includes only the organizer of the selected appointment item - * @param htmlBody A string that contains text and HTML and that represents the body of the reply form. The string is limited to 32 KB - */ - displayReplyForm(htmlBody: string): void; - /** - * Gets an array of entities found in an appointment - */ - getEntities(): Office.Entities; - /** - * Gets an array of entities of the specified entity type found in an appointment - * @param entityType One of the EntityType enumeration values - */ - getEntitiesByType(entityType: Office.MailboxEnums.EntityType): Office.Entities; - /** - * Returns well-known entities that pass the named filter defined in the manifest XML file - * @param name A TableData object with the headers and rows - */ - getFilteredEntitiesByName(name: string): Office.Entities; - /** - * Returns string values in the currently selected appointment object that match the regular expressions defined in the manifest XML file - */ - getRegExMatches(): string[]; - /** - * Returns string values that match the named regular expression defined in the manifest XML file - */ - getRegExMatchesByName(name: string): string[]; - } - } - export module cast { - export module item { - function toAppointmentCompose(item: Office.Item): Office.Types.AppointmentCompose; - function toAppointmentRead(item: Office.Item): Office.Types.AppointmentRead; - function toAppointment(item: Office.Item): Office.Appointment; - function toMessageCompose(item: Office.Item): Office.Types.MessageCompose; - function toMessageRead(item: Office.Item): Office.Types.MessageRead; - function toMessage(item: Office.Item): Office.Message; - function toItemCompose(item: Office.Item): Office.Types.ItemCompose; - function toItemRead(item: Office.Item): Office.Types.ItemRead; - } - } - export interface AttachmentDetails { - attachmentType: Office.MailboxEnums.AttachmentType; - contentType: string; - id: string; - isInline: boolean; - name: string; - size: number; - } - export interface Contact { - personName: string; - businessName: string; - phoneNumbers: PhoneNumber[]; - emailAddresses: string[]; - urls: string[]; - addresses: string[]; - contactString: string; - } - export interface Context { - mailbox: Mailbox; - roamingSettings: RoamingSettings; - } - export interface CustomProperties { - /** - * Returns the value of the specified custom property - * @param name The name of the property to be returned - */ - get(name: string): any; - /** - * Sets the specified property to the specified value - * @param name The name of the property to be set - * @param value The value of the property to be set - */ - set(name: string, value: string): void; - /** - * Removes the specified property from the custom property collection. - * @param name The name of the property to be removed - */ - remove(name: string): void; - /** - * Saves the custom property collection to the server - * @param callback The optional callback method - * @param userContext Optional variable for any state data that is passed to the saveAsync method - */ - saveAsync(callback?: (result: AsyncResult) => void, userContext?: any): void; - } - export interface EmailAddressDetails { - emailAddress: string; - displayName: string; - appointmentResponse: Office.MailboxEnums.ResponseType; - recipientType: Office.MailboxEnums.RecipientType; - } - export interface EmailUser { - name: string; - userId: string; - } - export interface Entities { - addresses: string[]; - taskSuggestions: string[]; - meetingSuggestions: MeetingSuggestion[]; - emailAddresses: string[]; - urls: string[]; - phoneNumbers: PhoneNumber[]; - contacts: Contact[]; - } - export interface Item { - dateTimeCreated: Date; - dateTimeModified: Date; - itemClass: string; - itemId: string; - itemType: Office.MailboxEnums.ItemType; - /** - * Asynchronously loads custom properties that are specific to the item and a app for Office - * @param callback The optional callback method - * @param userContext Optional variable for any state data that is passed to the asynchronous method - */ - loadCustomPropertiesAsync(callback?: (result: AsyncResult) => void, userContext?: any): void; - } - export interface Appointment extends Item { - } - export interface Body { - /** - * Gets a value that indicates whether the content is in HTML or text format - * @param tableData A TableData object with the headers and rows - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the getTypeAsync method returns - */ - getTypeAsync(options?: any, callback?: (result: AsyncResult) => void): void; - /** - * Adds the specified content to the beginning of the item body - * @param data The string to be inserted at the beginning of the body. The string is limited to 1,000,000 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the string is inserted - */ - prependAsync(data: string, options?: any, callback?: (result: AsyncResult) => void): void; - /** - * Replaces the selection in the body with the specified text - * @param data The string to be inserted at the beginning of the body. The string is limited to 1,000,000 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the string is inserted - */ - setSelectedDataAsync(data: string, options?: any, callback?: (result: AsyncResult) => void): void; - } - export interface Location { - /** - * Begins an asynchronous request for the location of an appointment - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the string is inserted - */ - getAsync(options?: any, callback?: (result: AsyncResult) => void): void; - /** - * Begins an asynchronous request to set the location of an appointment - * @param data The location of the appointment. The string is limited to 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the location is set - */ - setAsync(location: string, options?: any, callback?: (result: AsyncResult) => void): void; - } - export interface Mailbox { - item: Item; - userProfile: UserProfile; - /** - * Gets a Date object from a dictionary containing time information - * @param timeValue A Date object - */ - convertToLocalClientTime(timeValue: Date): any; - /** - * Gets a dictionary containing time information in local client time - * @param input A dictionary containing a date. The dictionary should contain the following fields: year, month, date, hours, minutes, seconds, time zone, time zone offset - */ - convertToUtcClientTime(input: any): Date; - /** - * Displays an existing calendar appointment - * @param itemId The Exchange Web Services (EWS) identifier for an existing calendar appointment - */ - displayAppointmentForm(itemId: any): void; - /** - * Displays an existing message - * @param itemId The Exchange Web Services (EWS) identifier for an existing message - */ - displayMessageForm(itemId: any): void; - /** - * Displays a form for creating a new calendar appointment - * @param requiredAttendees An array of strings containing the email addresses or an array containing an EmailAddressDetails object for each of the required attendees for the appointment. The array is limited to a maximum of 100 entries - * @param optionalAttendees An array of strings containing the email addresses or an array containing an EmailAddressDetails object for each of the optional attendees for the appointment. The array is limited to a maximum of 100 entries - * @param start A Date object specifying the start date and time of the appointment - * @param end A Date object specifying the end date and time of the appointment - * @param location A string containing the location of the appointment. The string is limited to a maximum of 255 characters - * @param resources An array of strings containing the resources required for the appointment. The array is limited to a maximum of 100 entries - * @param subject A string containing the subject of the appointment. The string is limited to a maximum of 255 characters - * @param body The body of the appointment message. The body content is limited to a maximum size of 32 KB - */ - displayNewAppointmentForm(requiredAttendees: any, optionalAttendees: any, start: Date, end: Date, location: string, resources: string[], subject: string, body: string): void; - /** - * Gets a string that contains a token used to get an attachment or item from an Exchange Server - * @param callback The optional method to call when the string is inserted - * @param userContext Optional variable for any state data that is passed to the asynchronous method - */ - getCallbackTokenAsync(callback?: (result: AsyncResult) => void, userContext?: any): void; - /** - * Gets a token identifying the user and the app for Office - * @param callback The optional method to call when the string is inserted - * @param userContext Optional variable for any state data that is passed to the asynchronous method - */ - getUserIdentityTokenAsync(callback?: (result: AsyncResult) => void, userContext?: any): void; - /** - * Makes an asynchronous request to an Exchange Web Services (EWS) service on the Exchange server that hosts the user’s mailbox - * @param data The EWS request - * @param callback The optional method to call when the string is inserted - * @param userContext Optional variable for any state data that is passed to the asynchronous method - */ - makeEwsRequestAsync(data: any, callback?: (result: AsyncResult) => void, userContext?: any): void; - } - export interface Message extends Item { - conversationId: string; - } - export interface MeetingRequest extends Message { - start: Date; - end: Date; - location: string; - optionalAttendees: EmailAddressDetails[]; - requiredAttendees: EmailAddressDetails[]; - } - export interface MeetingSuggestion { - meetingString: string; - attendees: EmailAddressDetails[]; - location: string; - subject: string; - start: Date; - end: Date; - } - export interface PhoneNumber { - phoneString: string; - originalPhoneString: string; - type: string; - } - export interface Recipients { - /** - * Begins an asynchronous request to add a recipient list to an appointment or message - * @param recipients The recipients to add to the recipients list - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the string is inserted - */ - addAsync(recipients: any, options?: any, callback?: (result: AsyncResult) => void): void; - /** - * Begins an asynchronous request to get the recipient list for an appointment or message - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the string is inserted - */ - getAsync(options?: any, callback?: (result: AsyncResult) => void): void; - /** - * Begins an asynchronous request to set the recipient list for an appointment or message - * @param recipients The recipients to add to the recipients list - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the string is inserted - */ - setAsync(recipients: any, options?: any, callback?: (result: AsyncResult) => void): void; - } - export interface RoamingSettings { - /** - * Retrieves the specified setting - * @param name The case-sensitive name of the setting to retrieve - */ - get(name: string): any; - /** - * Removes the specified setting - * @param name The case-sensitive name of the setting to remove - */ - remove(name: string): void; - /** - * Saves the settings - * @param callback A function that is invoked when the callback returns, whose only parameter is of type AsyncResult - */ - saveAsync(callback?: (result: AsyncResult) => void): void; - /** - * Sets or creates the specified setting - * @param name The case-sensitive name of the setting to set or create - * @param value Specifies the value to be stored - */ - set(name: string, value: any): void; - } - export interface Subject { - /** - * Begins an asynchronous request to get the subject of an appointment or message - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the string is inserted - */ - getAsync(options?: any, callback?: (result: AsyncResult) => void): void; - /** - * Begins an asynchronous call to set the subject of an appointment or message - * @param data The subject of the appointment. The string is limited to 255 characters - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the string is inserted - */ - setAsync(data: string, options?: any, callback?: (result: AsyncResult) => void): void; - } - export interface TaskSuggestion { - assignees: EmailUser[]; - taskString: string; - } - export interface Time { - /** - * Begins an asynchronous request to get the start or end time - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the string is inserted - */ - getAsync(options?: any, callback?: (result: AsyncResult) => void): void; - /** - * Begins an asynchronous request to set the start or end time - * @param dateTime A date-time object in Coordinated Universal Time (UTC) - * @param options Any optional parameters or state data passed to the method - * @param callback The optional method to call when the string is inserted - */ - setAsync(dateTime: Date, options?: any, callback?: (result: AsyncResult) => void): void; - } - export interface UserProfile { - displayName: string; - emailAddress: string; - timeZone: string; - } -} + + + +//////////////////////////////////////////////////////////////// +///////////////////////// End Word APIs //////////////////////// +//////////////////////////////////////////////////////////////// + + + + +//////////////////////////////////////////////////////////////// + + + + +//////////////////////////////////////////////////////////////// +////////////////////// Begin OneNote APIs ////////////////////// +//////////////////////////////////////////////////////////////// + declare namespace OneNote { /** @@ -15696,3 +15934,8 @@ declare namespace OneNote { */ function run(batch: (context: OneNote.RequestContext) => OfficeExtension.IPromise): OfficeExtension.IPromise; } + + +//////////////////////////////////////////////////////////////// +/////////////////////// End OneNote APIs /////////////////////// +//////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/openlayers/index.d.ts b/openlayers/index.d.ts index 25fabc2107..a48e26071b 100644 --- a/openlayers/index.d.ts +++ b/openlayers/index.d.ts @@ -59,7 +59,7 @@ declare module ol { } - /** + /** * Error object thrown when an assertion failed. This is an ECMA-262 Error, * extended with a `code` property. * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} @@ -67,7 +67,7 @@ declare module ol { * @extends {Error} * @implements {oli.AssertionError} * @param {number} code Error code. - */ + */ class AssertionError extends Error { /** * Error object thrown when an assertion failed. This is an ECMA-262 Error, @@ -146,21 +146,21 @@ declare module ol { } - /** + /** * @classdesc * An expanded version of standard JS Array, adding convenience methods for * manipulation. Add and remove changes to the Collection trigger a Collection * event. Note that this does not cover changes to the objects _within_ the * Collection; they trigger events on the appropriate object, not on the * Collection as a whole. - * + * * @constructor * @extends {ol.Object} * @fires ol.Collection.Event * @param {!Array.=} opt_array Array. * @template T * @api stable - */ + */ class Collection extends ol.Object { /** * @classdesc @@ -318,7 +318,7 @@ declare module ol { */ element: any; - } + } } /** @@ -330,21 +330,21 @@ declare module ol { * @namespace ol.color */ module color { - /** + /** * Return the color as an array. This function maintains a cache of calculated * arrays which means the result should not be modified. * @param {ol.Color|string} color Color. * @return {ol.Color} Color. * @api - */ + */ function asArray(color: (ol.Color | string)): ol.Color; - /** + /** * Return the color as an rgba string. * @param {ol.Color|string} color Color. * @return {string} Rgba string. * @api - */ + */ function asString(color: (ol.Color | string)): string; } @@ -364,9 +364,9 @@ declare module ol { } - /** + /** * @namespace ol.control - */ + */ module control { /** * @classdesc @@ -381,7 +381,7 @@ declare module ol { * @api stable */ class Attribution extends ol.control.Control { - /** + /** * @classdesc * Control to show all the attributions associated with the layer sources * in the map. This control is one of the default controls included in maps. @@ -392,46 +392,46 @@ declare module ol { * @extends {ol.control.Control} * @param {olx.control.AttributionOptions=} opt_options Attribution options. * @api stable - */ + */ constructor(opt_options?: olx.control.AttributionOptions); - /** + /** * Update the attribution element. * @param {ol.MapEvent} mapEvent Map event. * @this {ol.control.Attribution} * @api - */ + */ static render(mapEvent: ol.MapEvent): void; - /** + /** * Return `true` if the attribution is collapsible, `false` otherwise. * @return {boolean} True if the widget is collapsible. * @api stable - */ + */ getCollapsible(): boolean; - /** + /** * Set whether the attribution should be collapsible. * @param {boolean} collapsible True if the widget is collapsible. * @api stable - */ + */ setCollapsible(collapsible: boolean): void; - /** + /** * Collapse or expand the attribution according to the passed parameter. Will * not do anything if the attribution isn't collapsible or if the current * collapsed state is already the one requested. * @param {boolean} collapsed True if the widget is collapsed. * @api stable - */ + */ setCollapsed(collapsed: boolean): void; - /** + /** * Return `true` when the attribution is currently collapsed or `false` * otherwise. * @return {boolean} True if the widget is collapsed. * @api stable - */ + */ getCollapsed(): boolean; } @@ -494,14 +494,14 @@ declare module ol { * @implements {oli.control.Control} * @param {olx.control.ControlOptions} options Control options. * @api stable - */ + */ constructor(options: olx.control.ControlOptions); - /** + /** * Get the map associated with this control. * @return {ol.Map} Map. * @api stable - */ + */ getMap(): ol.Map; /** @@ -524,7 +524,7 @@ declare module ol { */ setTarget(target: (Element | string)): void; - } + } /** * @classdesc @@ -544,7 +544,7 @@ declare module ol { * @api stable */ class FullScreen extends ol.control.Control { - /** + /** * @classdesc * Provides a button that when clicked fills up the full screen with the map. * The full screen source element is by default the element containing the map viewport unless @@ -554,13 +554,13 @@ declare module ol { * When in full screen mode, a close button is shown to exit full screen mode. * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to * toggle the map in full screen mode. - * + * * * @constructor * @extends {ol.control.Control} * @param {olx.control.FullScreenOptions=} opt_options Options. * @api stable - */ + */ constructor(opt_options?: olx.control.FullScreenOptions); } @@ -605,52 +605,52 @@ declare module ol { * @param {olx.control.MousePositionOptions=} opt_options Mouse position * options. * @api stable - */ + */ constructor(opt_options?: olx.control.MousePositionOptions); - /** + /** * Update the mouseposition element. * @param {ol.MapEvent} mapEvent Map event. * @this {ol.control.MousePosition} * @api - */ + */ static render(mapEvent: ol.MapEvent): void; - /** + /** * Return the coordinate format type used to render the current position or * undefined. * @return {ol.CoordinateFormatType|undefined} The format to render the current * position in. * @observable * @api stable - */ + */ getCoordinateFormat(): (ol.CoordinateFormatType); - /** + /** * Return the projection that is used to report the mouse position. * @return {ol.proj.Projection|undefined} The projection to report mouse * position in. * @observable * @api stable - */ + */ getProjection(): (ol.proj.Projection); - /** + /** * Set the coordinate format type used to render the current position. * @param {ol.CoordinateFormatType} format The format to render the current * position in. * @observable * @api stable - */ + */ setCoordinateFormat(format: ol.CoordinateFormatType): void; - /** + /** * Set the projection that is used to report the mouse position. * @param {ol.proj.Projection} projection The projection to report mouse * position in. * @observable * @api stable - */ + */ setProjection(projection: ol.proj.Projection): void; } @@ -662,16 +662,16 @@ declare module ol { * @extends {ol.control.Control} * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. * @api - */ + */ class OverviewMap extends ol.control.Control { - /** + /** * Create a new control with a map acting as an overview map for an other * defined map. * @constructor * @extends {ol.control.Control} * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. * @api - */ + */ constructor(opt_options?: olx.control.OverviewMapOptions); /** @@ -721,7 +721,7 @@ declare module ol { } - /** + /** * @classdesc * A button control to reset rotation to 0. * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css @@ -731,7 +731,7 @@ declare module ol { * @extends {ol.control.Control} * @param {olx.control.RotateOptions=} opt_options Rotate options. * @api stable - */ + */ class Rotate extends ol.control.Control { /** * @classdesc @@ -756,7 +756,7 @@ declare module ol { } - /** + /** * @classdesc * A control displaying rough y-axis distances, calculated for the center of the * viewport. For conformal projections (e.g. EPSG:3857, the default view @@ -826,11 +826,11 @@ declare module ol { * Units for the scale line. Supported values are `'degrees'`, `'imperial'`, * `'nautical'`, `'metric'`, `'us'`. * @enum {string} - */ + */ type Units = string; } - /** + /** * @classdesc * A control with 2 buttons, one for zoom in and one for zoom out. * This control is one of the default controls of a map. To style this control @@ -840,7 +840,7 @@ declare module ol { * @extends {ol.control.Control} * @param {olx.control.ZoomOptions=} opt_options Zoom options. * @api stable - */ + */ class Zoom extends ol.control.Control { /** * @classdesc @@ -857,7 +857,7 @@ declare module ol { } - /** + /** * @classdesc * A slider type of control for zooming. * @@ -869,7 +869,7 @@ declare module ol { * @extends {ol.control.Control} * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. * @api stable - */ + */ class ZoomSlider extends ol.control.Control { /** * @classdesc @@ -896,7 +896,7 @@ declare module ol { } - /** + /** * @classdesc * A button control which, when pressed, changes the map view to a specific * extent. To style this control use the css selector `.ol-zoom-extent`. @@ -905,7 +905,7 @@ declare module ol { * @extends {ol.control.Control} * @param {olx.control.ZoomToExtentOptions=} opt_options Options. * @api stable - */ + */ class ZoomToExtent extends ol.control.Control { /** * @classdesc @@ -921,13 +921,13 @@ declare module ol { } - } + } - /** + /** * @namespace ol.coordinate - */ + */ module coordinate { - /** + /** * Add `delta` to `coordinate`. `coordinate` is modified in place and returned * by the function. * @@ -941,10 +941,10 @@ declare module ol { * @param {ol.Coordinate} delta Delta. * @return {ol.Coordinate} The input coordinate adjusted by the given delta. * @api stable - */ + */ function add(coordinate: ol.Coordinate, delta: ol.Coordinate): ol.Coordinate; - /** + /** * Returns a {@link ol.CoordinateFormatType} function that can be used to format * a {ol.Coordinate} to a string. * @@ -966,10 +966,10 @@ declare module ol { * after the decimal point. Default is `0`. * @return {ol.CoordinateFormatType} Coordinate format. * @api stable - */ + */ function createStringXY(opt_fractionDigits?: number): ol.CoordinateFormatType; - /** + /** * Transforms the given {@link ol.Coordinate} to a string using the given string * template. The strings `{x}` and `{y}` in the template will be replaced with * the first and second coordinate values respectively. @@ -995,10 +995,10 @@ declare module ol { * after the decimal point. Default is `0`. * @return {string} Formatted coordinate. * @api stable - */ + */ function format(coordinate: (ol.Coordinate), template: string, opt_fractionDigits?: number): string; - /** + /** * Rotate `coordinate` by `angle`. `coordinate` is modified in place and * returned by the function. * @@ -1013,10 +1013,10 @@ declare module ol { * @param {number} angle Angle in radian. * @return {ol.Coordinate} Coordinate. * @api stable - */ + */ function rotate(coordinate: ol.Coordinate, angle: number): ol.Coordinate; - /** + /** * Format a geographic coordinate with the hemisphere, degrees, minutes, and * seconds. * @@ -1037,10 +1037,10 @@ declare module ol { * after the decimal point. Default is `0`. * @return {string} Hemisphere, degrees, minutes and seconds. * @api stable - */ + */ function toStringHDMS(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; - /** + /** * Format a coordinate as a comma delimited string. * * Example without specifying fractional digits: @@ -1060,12 +1060,12 @@ declare module ol { * after the decimal point. Default is `0`. * @return {string} XY. * @api stable - */ + */ function toStringXY(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; } - /** + /** * @classdesc * The ol.DeviceOrientation class provides access to information from * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification]( @@ -1119,9 +1119,9 @@ declare module ol { * @extends {ol.Object} * @param {olx.DeviceOrientationOptions=} opt_options Options. * @api - */ + */ class DeviceOrientation extends ol.Object { - /** + /** * @classdesc * The ol.DeviceOrientation class provides access to information from * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification]( @@ -1175,127 +1175,127 @@ declare module ol { * @extends {ol.Object} * @param {olx.DeviceOrientationOptions=} opt_options Options. * @api - */ + */ constructor(opt_options?: olx.DeviceOrientationOptions); - /** + /** * Rotation around the device z-axis (in radians). * @return {number|undefined} The euler angle in radians of the device from the * standard Z axis. * @observable * @api - */ + */ getAlpha(): (number); - /** + /** * Rotation around the device x-axis (in radians). * @return {number|undefined} The euler angle in radians of the device from the * planar X axis. * @observable * @api - */ + */ getBeta(): (number); - /** + /** * Rotation around the device y-axis (in radians). * @return {number|undefined} The euler angle in radians of the device from the * planar Y axis. * @observable * @api - */ + */ getGamma(): (number); - /** + /** * The heading of the device relative to north (in radians). * @return {number|undefined} The heading of the device relative to north, in * radians, normalizing for different browser behavior. * @observable * @api - */ + */ getHeading(): (number); - /** + /** * Determine if orientation is being tracked. * @return {boolean} Changes in device orientation are being tracked. * @observable * @api - */ + */ getTracking(): boolean; - /** + /** * Enable or disable tracking of device orientation events. * @param {boolean} tracking The status of tracking changes to alpha, beta and * gamma. If true, changes are tracked and reported immediately. * @observable * @api - */ + */ setTracking(tracking: boolean): void; } - /** + /** * Objects that need to clean up after themselves. * @constructor - */ + */ class Disposable { - /** + /** * Objects that need to clean up after themselves. * @constructor - */ + */ constructor(); - } + } - /** + /** * Easing functions for {@link ol.animation}. * @namespace ol.easing - */ + */ module easing { - /** + /** * Start slow and speed up. * @param {number} t Input between 0 and 1. * @return {number} Output between 0 and 1. * @api - */ + */ function easeIn(t: number): number; - /** + /** * Start fast and slow down. * @param {number} t Input between 0 and 1. * @return {number} Output between 0 and 1. * @api - */ + */ function easeOut(t: number): number; - /** + /** * Start slow, speed up, and then slow down again. * @param {number} t Input between 0 and 1. * @return {number} Output between 0 and 1. * @api - */ + */ function inAndOut(t: number): number; - /** + /** * Maintain a constant speed over time. * @param {number} t Input between 0 and 1. * @return {number} Output between 0 and 1. * @api - */ + */ function linear(t: number): number; - /** + /** * Start slow, speed up, and at the very end slow down again. This has the * same general behavior as {@link ol.easing.inAndOut}, but the final slowdown * is delayed. * @param {number} t Input between 0 and 1. * @return {number} Output between 0 and 1. * @api - */ + */ function upAndDown(t: number): number; - } + } - /** + /** * Applications do not normally create event instances. They register (and * unregister) event listener functions, which, when called by the library as * the result of an event being dispatched, are passed event instances as their @@ -1308,11 +1308,11 @@ declare module ol { * properties; see the specific event class page for details. * * @namespace ol.events - */ + */ module events { - /** + /** * @namespace ol.events.condition - */ + */ module condition { /** * Return `true` if only the alt-key is pressed, `false` otherwise (e.g. when @@ -1454,7 +1454,7 @@ declare module ol { } - /** + /** * @classdesc * Stripped down implementation of the W3C DOM Level 2 Event interface. * @see {@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface} @@ -1467,7 +1467,7 @@ declare module ol { * @constructor * @implements {oli.events.Event} * @param {string} type Type. - */ + */ class Event { /** * @classdesc @@ -1515,7 +1515,7 @@ declare module ol { } - /** + /** * @classdesc * A simplified implementation of the W3C DOM Level 2 EventTarget interface. * @see {@link https://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-EventTarget} @@ -1532,7 +1532,7 @@ declare module ol { * * @constructor * @extends {ol.Disposable} - */ + */ class EventTarget extends ol.Disposable { /** * @classdesc @@ -1558,40 +1558,40 @@ declare module ol { } - /** + /** * @namespace ol.extent - */ + */ module extent { - /** + /** * Build an extent that includes all given coordinates. * * @param {Array.} coordinates Coordinates. * @return {ol.Extent} Bounding extent. * @api stable - */ + */ function boundingExtent(coordinates: ol.Coordinate[]): ol.Extent; - /** + /** * Return extent increased by the provided value. * @param {ol.Extent} extent Extent. * @param {number} value The amount by which the extent should be buffered. * @param {ol.Extent=} opt_extent Extent. * @return {ol.Extent} Extent. * @api stable - */ + */ function buffer(extent: ol.Extent, value: number, opt_extent?: ol.Extent): ol.Extent; - /** + /** * Check if the passed coordinate is contained or on the edge of the extent. * * @param {ol.Extent} extent Extent. * @param {ol.Coordinate} coordinate Coordinate. * @return {boolean} The coordinate is contained in the extent. * @api stable - */ + */ function containsCoordinate(extent: ol.Extent, coordinate: ol.Coordinate): boolean; - /** + /** * Check if one extent contains another. * * An extent is deemed contained if it lies completely within the other extent, @@ -1602,10 +1602,10 @@ declare module ol { * @return {boolean} The second extent is contained by or on the edge of the * first. * @api stable - */ + */ function containsExtent(extent1: ol.Extent, extent2: ol.Extent): boolean; - /** + /** * Check if the passed coordinate is contained or on the edge of the extent. * * @param {ol.Extent} extent Extent. @@ -1613,126 +1613,126 @@ declare module ol { * @param {number} y Y coordinate. * @return {boolean} The x, y values are contained in the extent. * @api stable - */ + */ function containsXY(extent: ol.Extent, x: number, y: number): boolean; - /** + /** * Create an empty extent. * @return {ol.Extent} Empty extent. * @api stable - */ + */ function createEmpty(): ol.Extent; - /** + /** * Determine if two extents are equivalent. * @param {ol.Extent} extent1 Extent 1. * @param {ol.Extent} extent2 Extent 2. * @return {boolean} The two extents are equivalent. * @api stable - */ + */ function equals(extent1: ol.Extent, extent2: ol.Extent): boolean; - /** + /** * Modify an extent to include another extent. * @param {ol.Extent} extent1 The extent to be modified. * @param {ol.Extent} extent2 The extent that will be included in the first. * @return {ol.Extent} A reference to the first (extended) extent. * @api stable - */ + */ function extend(extent1: ol.Extent, extent2: ol.Extent): ol.Extent; - /** + /** * Get the bottom left coordinate of an extent. * @param {ol.Extent} extent Extent. * @return {ol.Coordinate} Bottom left coordinate. * @api stable - */ + */ function getBottomLeft(extent: ol.Extent): ol.Coordinate; - /** + /** * Get the bottom right coordinate of an extent. * @param {ol.Extent} extent Extent. * @return {ol.Coordinate} Bottom right coordinate. * @api stable - */ + */ function getBottomRight(extent: ol.Extent): ol.Coordinate; - /** + /** * Get the center coordinate of an extent. * @param {ol.Extent} extent Extent. * @return {ol.Coordinate} Center. * @api stable - */ + */ function getCenter(extent: ol.Extent): ol.Coordinate; - /** + /** * Get the height of an extent. * @param {ol.Extent} extent Extent. * @return {number} Height. * @api stable - */ + */ function getHeight(extent: ol.Extent): number; - /** + /** * Get the intersection of two extents. * @param {ol.Extent} extent1 Extent 1. * @param {ol.Extent} extent2 Extent 2. * @param {ol.Extent=} opt_extent Optional extent to populate with intersection. * @return {ol.Extent} Intersecting extent. * @api stable - */ + */ function getIntersection(extent1: ol.Extent, extent2: ol.Extent, opt_extent?: ol.Extent): ol.Extent; - /** + /** * Get the size (width, height) of an extent. * @param {ol.Extent} extent The extent. * @return {ol.Size} The extent size. * @api stable - */ + */ function getSize(extent: ol.Extent): ol.Size; - /** + /** * Get the top left coordinate of an extent. * @param {ol.Extent} extent Extent. * @return {ol.Coordinate} Top left coordinate. * @api stable - */ + */ function getTopLeft(extent: ol.Extent): ol.Coordinate; - /** + /** * Get the top right coordinate of an extent. * @param {ol.Extent} extent Extent. * @return {ol.Coordinate} Top right coordinate. * @api stable - */ + */ function getTopRight(extent: ol.Extent): ol.Coordinate; - /** + /** * Get the width of an extent. * @param {ol.Extent} extent Extent. * @return {number} Width. * @api stable - */ + */ function getWidth(extent: ol.Extent): number; - /** + /** * Determine if one extent intersects another. * @param {ol.Extent} extent1 Extent 1. * @param {ol.Extent} extent2 Extent. * @return {boolean} The two extents intersect. * @api stable - */ + */ function intersects(extent1: ol.Extent, extent2: ol.Extent): boolean; - /** + /** * Determine if an extent is empty. * @param {ol.Extent} extent Extent. * @return {boolean} Is empty. * @api stable - */ + */ function isEmpty(extent: ol.Extent): boolean; - /** + /** * Apply a transform function to the extent. * @param {ol.Extent} extent Extent. * @param {ol.TransformFunction} transformFn Transform function. Called with @@ -1740,12 +1740,12 @@ declare module ol { * @param {ol.Extent=} opt_extent Destination extent. * @return {ol.Extent} Extent. * @api stable - */ + */ function applyTransform(extent: ol.Extent, transformFn: ol.TransformFunction, opt_extent?: ol.Extent): ol.Extent; } - /** + /** * @classdesc * A vector object for geographic features with a geometry and other * attribute properties, similar to the features in vector file formats like @@ -1789,9 +1789,9 @@ declare module ol { * containing properties. If you pass an object literal, you may * include a Geometry associated with a `geometry` key. * @api stable - */ + */ class Feature extends ol.Object { - /** + /** * @classdesc * A vector object for geographic features with a geometry and other * attribute properties, similar to the features in vector file formats like @@ -1835,74 +1835,74 @@ declare module ol { * containing properties. If you pass an object literal, you may * include a Geometry associated with a `geometry` key. * @api stable - */ + */ constructor(opt_geometryOrProperties?: (ol.geom.Geometry | { [k: string]: any })); - /** + /** * Clone this feature. If the original feature has a geometry it * is also cloned. The feature id is not set in the clone. * @return {ol.Feature} The clone. * @api stable - */ + */ clone(): ol.Feature; - /** + /** * Get the feature's default geometry. A feature may have any number of named * geometries. The "default" geometry (the one that is rendered by default) is * set when calling {@link ol.Feature#setGeometry}. * @return {ol.geom.Geometry|undefined} The default geometry for the feature. * @api stable * @observable - */ + */ getGeometry(): (ol.geom.Geometry); - /** + /** * Get the feature identifier. This is a stable identifier for the feature and * is either set when reading data from a remote source or set explicitly by * calling {@link ol.Feature#setId}. * @return {number|string|undefined} Id. * @api stable * @observable - */ + */ getId(): (number | string); - /** + /** * Get the name of the feature's default geometry. By default, the default * geometry is named `geometry`. * @return {string} Get the property name associated with the default geometry * for this feature. * @api stable - */ + */ getGeometryName(): string; - /** + /** * Get the feature's style. This return for this method depends on what was * provided to the {@link ol.Feature#setStyle} method. * @return {ol.style.Style|Array.| * ol.FeatureStyleFunction} The feature style. * @api stable * @observable - */ + */ getStyle(): (ol.style.Style | ol.style.Style[] | ol.FeatureStyleFunction); - /** + /** * Get the feature's style function. * @return {ol.FeatureStyleFunction|undefined} Return a function * representing the current style of this feature. * @api stable - */ + */ getStyleFunction(): (ol.FeatureStyleFunction); - /** + /** * Set the default geometry for the feature. This will update the property * with the name returned by {@link ol.Feature#getGeometryName}. * @param {ol.geom.Geometry|undefined} geometry The new geometry. * @api stable * @observable - */ + */ setGeometry(geometry: (ol.geom.Geometry)): void; - /** + /** * Set the style for the feature. This can be a single style object, an array * of styles, or a function that takes a resolution and returns an array of * styles. If it is `null` the feature has no style (a `null` style). @@ -1910,10 +1910,10 @@ declare module ol { * ol.FeatureStyleFunction} style Style for this feature. * @api stable * @observable - */ + */ setStyle(style: (ol.style.Style | ol.style.Style[] | ol.FeatureStyleFunction)): void; - /** + /** * Set the feature id. The feature id is considered stable and may be used when * requesting features or comparing identifiers returned from a remote source. * The feature id can be used with the {@link ol.source.Vector#getFeatureById} @@ -1921,24 +1921,24 @@ declare module ol { * @param {number|string|undefined} id The feature id. * @api stable * @observable - */ + */ setId(id: (number | string)): void; - /** + /** * Set the property name to be used when getting the feature's default geometry. * When calling {@link ol.Feature#getGeometry}, the value of the property with * this name will be returned. * @param {string} name The property name of the default geometry. * @api stable - */ + */ setGeometryName(name: string): void; } - /** + /** * Loading mechanisms for vector data. * @namespace ol.featureloader - */ + */ module featureloader { /** * Create an XHR feature loader for a `url` and `format`. The feature loader @@ -1951,7 +1951,7 @@ declare module ol { */ function tile(url: (string | ol.FeatureUrlFunction), format: ol.format.Feature): ol.FeatureLoader; - /** + /** * Create an XHR feature loader for a `url` and `format`. The feature loader * loads features (with XHR), parses the features, and adds them to the * vector source. @@ -1959,17 +1959,17 @@ declare module ol { * @param {ol.format.Feature} format Feature format. * @return {ol.FeatureLoader} The feature loader. * @api - */ + */ function xhr(url: (string | ol.FeatureUrlFunction), format: ol.format.Feature): ol.FeatureLoader; } - /** + /** * @namespace ol.format - */ + */ module format { - /** + /** * @classdesc * Feature format for reading and writing data in the EsriJSON format. * @@ -1977,7 +1977,7 @@ declare module ol { * @extends {ol.format.JSONFeature} * @param {olx.format.EsriJSONOptions=} opt_options Options. * @api - */ + */ class EsriJSON extends ol.format.JSONFeature { /** * @classdesc @@ -2098,7 +2098,7 @@ declare module ol { */ writeFeaturesObject(features: ol.Feature[], opt_options?: olx.format.WriteOptions): GlobalObject; - } + } type EsriJSONGeometry = JSON; @@ -2129,14 +2129,14 @@ declare module ol { */ constructor(); - } + } type GeoJSONFeature = JSON; type GeoJSONFeatureCollection = JSON; type GeoJSONGeometry = JSON; type GeoJSONGeometryCollection = JSON; - /** + /** * @classdesc * Feature format for reading and writing data in the GeoJSON format. * @@ -2144,7 +2144,7 @@ declare module ol { * @extends {ol.format.JSONFeature} * @param {olx.format.GeoJSONOptions=} opt_options Options. * @api stable - */ + */ class GeoJSON extends ol.format.JSONFeature { /** * @classdesc @@ -2267,7 +2267,7 @@ declare module ol { } - /** + /** * @classdesc * Feature format for reading and writing data in the GML format * version 3.1.1. @@ -2278,7 +2278,7 @@ declare module ol { * Optional configuration object. * @extends {ol.format.GMLBase} * @api stable - */ + */ class GML extends ol.format.GMLBase { /** * @classdesc @@ -2318,7 +2318,7 @@ declare module ol { } - /** + /** * @classdesc * Feature format for reading and writing data in the GML format, * version 2.1.2. @@ -2327,7 +2327,7 @@ declare module ol { * @param {olx.format.GMLOptions=} opt_options Optional configuration object. * @extends {ol.format.GMLBase} * @api - */ + */ class GML2 extends ol.format.GMLBase { /** * @classdesc @@ -2343,7 +2343,7 @@ declare module ol { } - /** + /** * @classdesc * Feature format for reading and writing data in the GML format * version 3.1.1. @@ -2354,7 +2354,7 @@ declare module ol { * Optional configuration object. * @extends {ol.format.GMLBase} * @api - */ + */ class GML3 extends ol.format.GMLBase { /** * @classdesc @@ -2403,7 +2403,7 @@ declare module ol { } - /** + /** * @classdesc * Abstract base class; normally only used for creating subclasses and not * instantiated in apps. @@ -2416,7 +2416,7 @@ declare module ol { * @param {olx.format.GMLOptions=} opt_options * Optional configuration object. * @extends {ol.format.XMLFeature} - */ + */ class GMLBase extends ol.format.XMLFeature { /** * @classdesc @@ -2447,7 +2447,7 @@ declare module ol { } - /** + /** * @classdesc * Feature format for reading and writing data in the GPX format. * @@ -2455,7 +2455,7 @@ declare module ol { * @extends {ol.format.XMLFeature} * @param {olx.format.GPXOptions=} opt_options Options. * @api stable - */ + */ class GPX extends ol.format.XMLFeature { /** * @classdesc @@ -2529,15 +2529,15 @@ declare module ol { */ writeFeaturesNode(features: ol.Feature[], opt_options?: olx.format.WriteOptions): Node; - } + } - /** + /** * IGC altitude/z. One of 'barometric', 'gps', 'none'. * @enum {string} - */ + */ type IGCZ = string; - /** + /** * @classdesc * Feature format for `*.igc` flight recording files. * @@ -2545,7 +2545,7 @@ declare module ol { * @extends {ol.format.TextFeature} * @param {olx.format.IGCOptions=} opt_options Options. * @api - */ + */ class IGC extends ol.format.TextFeature { /** * @classdesc @@ -2566,7 +2566,7 @@ declare module ol { * @param {olx.format.ReadOptions=} opt_options Read options. * @return {ol.Feature} Feature. * @api - */ + */ readFeature(source: (Document | Node | GlobalObject | string), opt_options?: olx.format.ReadOptions): ol.Feature; /** @@ -2593,7 +2593,7 @@ declare module ol { } - /** + /** * @classdesc * Abstract base class; normally only used for creating subclasses and not * instantiated in apps. @@ -2601,22 +2601,22 @@ declare module ol { * * @constructor * @extends {ol.format.Feature} - */ + */ class JSONFeature extends ol.format.Feature { - /** + /** * @classdesc * Abstract base class; normally only used for creating subclasses and not * instantiated in apps. * Base class for JSON feature formats. * - * @constructor + * @constructor * @extends {ol.format.Feature} - */ + */ constructor(); - } + } - /** + /** * @classdesc * Feature format for reading and writing data in the KML format. * @@ -2627,23 +2627,23 @@ declare module ol { * @extends {ol.format.XMLFeature} * @param {olx.format.KMLOptions=} opt_options Options. * @api stable - */ + */ class KML extends ol.format.XMLFeature { - /** + /** * @classdesc * Feature format for reading and writing data in the KML format. * * Note that the KML format uses the URL() constructor. Older browsers such as IE * which do not support this will need a URL polyfill to be loaded before use. * - * @constructor + * @constructor * @extends {ol.format.XMLFeature} * @param {olx.format.KMLOptions=} opt_options Options. * @api stable - */ + */ constructor(opt_options?: olx.format.KMLOptions); - /** + /** * Read the first feature from a KML source. MultiGeometries are converted into * GeometryCollections if they are a mix of geometry types, and into MultiPoint/ * MultiLineString/MultiPolygon if they are all of the same type. @@ -2653,10 +2653,10 @@ declare module ol { * @param {olx.format.ReadOptions=} opt_options Read options. * @return {ol.Feature} Feature. * @api stable - */ + */ readFeature(source: (Document | Node | GlobalObject | string), opt_options?: olx.format.ReadOptions): ol.Feature; - /** + /** * Read all features from a KML source. MultiGeometries are converted into * GeometryCollections if they are a mix of geometry types, and into MultiPoint/ * MultiLineString/MultiPolygon if they are all of the same type. @@ -2666,38 +2666,38 @@ declare module ol { * @param {olx.format.ReadOptions=} opt_options Read options. * @return {Array.} Features. * @api stable - */ + */ readFeatures(source: (Document | Node | GlobalObject | string), opt_options?: olx.format.ReadOptions): ol.Feature[]; - /** + /** * Read the name of the KML. * * @param {Document|Node|string} source Souce. * @return {string|undefined} Name. * @api stable - */ + */ readName(source: (Document | Node | string)): (string); - /** + /** * Read the network links of the KML. * * @param {Document|Node|string} source Source. * @return {Array.} Network links. * @api - */ + */ readNetworkLinks(source: (Document | Node | string)): GlobalObject[]; - /** + /** * Read the projection from a KML source. * * @function * @param {Document|Node|Object|string} source Source. * @return {ol.proj.Projection} Projection. * @api stable - */ + */ readProjection(source: (Document | Node | GlobalObject | string)): ol.proj.Projection; - /** + /** * Encode an array of features in the KML format. GeometryCollections, MultiPoints, * MultiLineStrings, and MultiPolygons are output as MultiGeometries. * @@ -2706,10 +2706,10 @@ declare module ol { * @param {olx.format.WriteOptions=} opt_options Options. * @return {string} Result. * @api stable - */ + */ writeFeatures(features: ol.Feature[], opt_options?: olx.format.WriteOptions): string; - /** + /** * Encode an array of features in the KML format as an XML node. GeometryCollections, * MultiPoints, MultiLineStrings, and MultiPolygons are output as MultiGeometries. * @@ -2717,7 +2717,7 @@ declare module ol { * @param {olx.format.WriteOptions=} opt_options Options. * @return {Node} Node. * @api - */ + */ writeFeaturesNode(features: ol.Feature[], opt_options?: olx.format.WriteOptions): Node; } @@ -2732,7 +2732,7 @@ declare module ol { * @api */ class MVT extends ol.format.Feature { - /** + /** * @classdesc * Feature format for reading data in the Mapbox MVT format. * @@ -2740,26 +2740,26 @@ declare module ol { * @extends {ol.format.Feature} * @param {olx.format.MVTOptions=} opt_options Options. * @api - */ + */ constructor(opt_options?: olx.format.MVTOptions); - /** + /** * @inheritDoc * @api - */ + */ readFeatures(source: (Document | Node | ArrayBuffer | GlobalObject | string), opt_options?: olx.format.ReadOptions): ol.Feature[]; - /** + /** * @inheritDoc * @api - */ + */ readProjection(source: (Document | Node | GlobalObject | string)): ol.proj.Projection; - /** + /** * Sets the layers that features will be read from. * @param {Array.} layers Layers. * @api - */ + */ setLayers(layers: string[]): void; } @@ -2768,9 +2768,9 @@ declare module ol { module filter { interface Filter { } } - } + } - /** + /** * @classdesc * Feature format for reading data in the * [OSMXML format](http://wiki.openstreetmap.org/wiki/OSM_XML). @@ -2788,10 +2788,10 @@ declare module ol { * @constructor * @extends {ol.format.XMLFeature} * @api stable - */ + */ constructor(); - /** + /** * Read all features from an OSM source. * * @function @@ -2799,17 +2799,17 @@ declare module ol { * @param {olx.format.ReadOptions=} opt_options Read options. * @return {Array.} Features. * @api stable - */ + */ readFeatures(source: (Document | Node | GlobalObject | string), opt_options?: olx.format.ReadOptions): ol.Feature[]; - /** + /** * Read the projection from an OSM source. * * @function * @param {Document|Node|Object|string} source Source. * @return {ol.proj.Projection} Projection. * @api stable - */ + */ readProjection(source: (Document | Node | GlobalObject | string)): ol.proj.Projection; } @@ -2826,20 +2826,20 @@ declare module ol { * @api stable */ class Polyline extends ol.format.TextFeature { - /** + /** * @classdesc * Feature format for reading and writing data in the Encoded * Polyline Algorithm Format. * - * @constructor + * @constructor * @extends {ol.format.TextFeature} * @param {olx.format.PolylineOptions=} opt_options * Optional configuration object. * @api stable - */ + */ constructor(opt_options?: olx.format.PolylineOptions); - /** + /** * Encode a list of n-dimensional points and return an encoded string * * Attention: This function will modify the passed array! @@ -2851,10 +2851,10 @@ declare module ol { * Default is `1e5`. * @return {string} The encoded string. * @api - */ + */ static encodeDeltas(numbers: number[], stride: number, opt_factor?: number): string; - /** + /** * Decode a list of n-dimensional points from an encoded string * * @param {string} encoded An encoded string. @@ -2864,10 +2864,10 @@ declare module ol { * be divided. Default is `1e5`. * @return {Array.} A list of n-dimensional points. * @api - */ + */ static decodeDeltas(encoded: string, stride: number, opt_factor?: number): number[]; - /** + /** * Encode a list of floating point numbers and return an encoded string * * Attention: This function will modify the passed array! @@ -2878,10 +2878,10 @@ declare module ol { * Default is `1e5`. * @return {string} The encoded string. * @api - */ + */ static encodeFloats(numbers: number[], opt_factor?: number): string; - /** + /** * Decode a list of floating point numbers from an encoded string * * @param {string} encoded An encoded string. @@ -2889,10 +2889,10 @@ declare module ol { * Default is `1e5`. * @return {Array.} A list of floating point numbers. * @api - */ + */ static decodeFloats(encoded: string, opt_factor?: number): number[]; - /** + /** * Read the feature from the Polyline source. The coordinates are assumed to be * in two dimensions and in latitude, longitude order. * @@ -2901,10 +2901,10 @@ declare module ol { * @param {olx.format.ReadOptions=} opt_options Read options. * @return {ol.Feature} Feature. * @api stable - */ + */ readFeature(source: (Document | Node | GlobalObject | string), opt_options?: olx.format.ReadOptions): ol.Feature; - /** + /** * Read the feature from the source. As Polyline sources contain a single * feature, this will return the feature in an array. * @@ -2913,10 +2913,10 @@ declare module ol { * @param {olx.format.ReadOptions=} opt_options Read options. * @return {Array.} Features. * @api stable - */ + */ readFeatures(source: (Document | Node | GlobalObject | string), opt_options?: olx.format.ReadOptions): ol.Feature[]; - /** + /** * Read the geometry from the source. * * @function @@ -2924,20 +2924,20 @@ declare module ol { * @param {olx.format.ReadOptions=} opt_options Read options. * @return {ol.geom.Geometry} Geometry. * @api stable - */ + */ readGeometry(source: (Document | Node | GlobalObject | string), opt_options?: olx.format.ReadOptions): ol.geom.Geometry; - /** + /** * Read the projection from a Polyline source. * * @function * @param {Document|Node|Object|string} source Source. * @return {ol.proj.Projection} Projection. * @api stable - */ + */ readProjection(source: (Document | Node | GlobalObject | string)): ol.proj.Projection; - /** + /** * Write a single geometry in Polyline format. * * @function @@ -2945,7 +2945,7 @@ declare module ol { * @param {olx.format.WriteOptions=} opt_options Write options. * @return {string} Geometry. * @api stable - */ + */ writeGeometry(geometry: ol.geom.Geometry, opt_options?: olx.format.WriteOptions): string; } @@ -2960,15 +2960,15 @@ declare module ol { * @extends {ol.format.Feature} */ class TextFeature extends ol.format.Feature { - /** + /** * @classdesc * Abstract base class; normally only used for creating subclasses and not * instantiated in apps. * Base class for text feature formats. * - * @constructor + * @constructor * @extends {ol.format.Feature} - */ + */ constructor(); } @@ -2991,27 +2991,27 @@ declare module ol { * @extends {ol.format.JSONFeature} * @param {olx.format.TopoJSONOptions=} opt_options Options. * @api stable - */ + */ constructor(opt_options?: olx.format.TopoJSONOptions); - /** + /** * Read all features from a TopoJSON source. * * @function * @param {Document|Node|Object|string} source Source. * @return {Array.} Features. * @api stable - */ + */ readFeatures(source: (Document | Node | GlobalObject | string)): ol.Feature[]; - /** + /** * Read the projection from a TopoJSON source. * * @function * @param {Document|Node|Object|string} object Source. * @return {ol.proj.Projection} Projection. * @api stable - */ + */ readProjection(object: (Document | Node | GlobalObject | string)): ol.proj.Projection; } @@ -3042,10 +3042,10 @@ declare module ol { * Optional configuration object. * @extends {ol.format.XMLFeature} * @api stable - */ + */ constructor(opt_options?: olx.format.WFSOptions); - /** + /** * Read all features from a WFS FeatureCollection. * * @function @@ -3053,38 +3053,38 @@ declare module ol { * @param {olx.format.ReadOptions=} opt_options Read options. * @return {Array.} Features. * @api stable - */ + */ readFeatures(source: (Document | Node | GlobalObject | string), opt_options?: olx.format.ReadOptions): ol.Feature[]; - /** + /** * Read transaction response of the source. * * @param {Document|Node|Object|string} source Source. * @return {ol.WFSTransactionResponse|undefined} Transaction response. * @api stable - */ + */ readTransactionResponse(source: (Document | Node | GlobalObject | string)): (ol.WFSTransactionResponse); - /** + /** * Read feature collection metadata of the source. * * @param {Document|Node|Object|string} source Source. * @return {ol.WFSFeatureCollectionMetadata|undefined} * FeatureCollection metadata. * @api stable - */ + */ readFeatureCollectionMetadata(source: (Document | Node | GlobalObject | string)): (ol.WFSFeatureCollectionMetadata); - /** + /** * Encode format as WFS `GetFeature` and return the Node. * * @param {olx.format.WFSWriteGetFeatureOptions} options Options. * @return {Node} Result. * @api stable - */ + */ writeGetFeature(options: olx.format.WFSWriteGetFeatureOptions): Node; - /** + /** * Encode format as WFS `Transaction` and return the Node. * * @param {Array.} inserts The features to insert. @@ -3093,17 +3093,17 @@ declare module ol { * @param {olx.format.WFSWriteTransactionOptions} options Write options. * @return {Node} Result. * @api stable - */ + */ writeTransaction(inserts: ol.Feature[], updates: ol.Feature[], deletes: ol.Feature[], options: olx.format.WFSWriteTransactionOptions): Node; - /** + /** * Read the projection from a WFS source. * * @function * @param {Document|Node|Object|string} source Source. * @return {?ol.proj.Projection} Projection. * @api stable - */ + */ readProjection(source: (Document | Node | GlobalObject | string)): ol.proj.Projection; } @@ -3128,10 +3128,10 @@ declare module ol { * @extends {ol.format.TextFeature} * @param {olx.format.WKTOptions=} opt_options Options. * @api stable - */ + */ constructor(opt_options?: olx.format.WKTOptions); - /** + /** * Read a feature from a WKT source. * * @function @@ -3139,10 +3139,10 @@ declare module ol { * @param {olx.format.ReadOptions=} opt_options Read options. * @return {ol.Feature} Feature. * @api stable - */ + */ readFeature(source: (Document | Node | GlobalObject | string), opt_options?: olx.format.ReadOptions): ol.Feature; - /** + /** * Read all features from a WKT source. * * @function @@ -3150,10 +3150,10 @@ declare module ol { * @param {olx.format.ReadOptions=} opt_options Read options. * @return {Array.} Features. * @api stable - */ + */ readFeatures(source: (Document | Node | GlobalObject | string), opt_options?: olx.format.ReadOptions): ol.Feature[]; - /** + /** * Read a single geometry from a WKT source. * * @function @@ -3161,10 +3161,10 @@ declare module ol { * @param {olx.format.ReadOptions=} opt_options Read options. * @return {ol.geom.Geometry} Geometry. * @api stable - */ + */ readGeometry(source: (Document | Node | GlobalObject | string), opt_options?: olx.format.ReadOptions): ol.geom.Geometry; - /** + /** * Encode a feature as a WKT string. * * @function @@ -3172,10 +3172,10 @@ declare module ol { * @param {olx.format.WriteOptions=} opt_options Write options. * @return {string} WKT string. * @api stable - */ + */ writeFeature(feature: ol.Feature, opt_options?: olx.format.WriteOptions): string; - /** + /** * Encode an array of features as a WKT string. * * @function @@ -3183,17 +3183,17 @@ declare module ol { * @param {olx.format.WriteOptions=} opt_options Write options. * @return {string} WKT string. * @api stable - */ + */ writeFeatures(features: ol.Feature[], opt_options?: olx.format.WriteOptions): string; - /** + /** * Write a single geometry as a WKT string. * * @function * @param {ol.geom.Geometry} geometry Geometry. * @return {string} WKT string. * @api stable - */ + */ writeGeometry(geometry: ol.geom.Geometry): string; } @@ -3214,17 +3214,17 @@ declare module ol { * @constructor * @extends {ol.format.XML} * @api - */ + */ constructor(); - /** + /** * Read a WMS capabilities document. * * @function * @param {Document|Node|string} source The XML source. * @return {Object} An object representing the WMS capabilities. * @api - */ + */ read(source: (Document | Node | string)): GlobalObject; } @@ -3252,7 +3252,7 @@ declare module ol { */ constructor(opt_options?: olx.format.WMSGetFeatureInfoOptions); - /** + /** * Read all features from a WMSGetFeatureInfo response. * * @function @@ -3260,7 +3260,7 @@ declare module ol { * @param {olx.format.ReadOptions=} opt_options Options. * @return {Array.} Features. * @api stable - */ + */ readFeatures(source: (Document | Node | GlobalObject | string), opt_options?: olx.format.ReadOptions): ol.Feature[]; } @@ -3284,14 +3284,14 @@ declare module ol { */ constructor(); - /** + /** * Read a WMTS capabilities document. * * @function * @param {Document|Node|string} source The XML source. * @return {Object} An object representing the WMTS capabilities. * @api - */ + */ read(source: (Document | Node | string)): GlobalObject; } @@ -3310,7 +3310,7 @@ declare module ol { * * @constructor * @struct - */ + */ constructor(); } @@ -3325,7 +3325,7 @@ declare module ol { * @extends {ol.format.Feature} */ class XMLFeature extends ol.format.Feature { - /** + /** * @classdesc * Abstract base class; normally only used for creating subclasses and not * instantiated in apps. @@ -3333,7 +3333,7 @@ declare module ol { * * @constructor * @extends {ol.format.Feature} - */ + */ constructor(); } @@ -3530,7 +3530,7 @@ declare module ol { * @api */ class Circle extends ol.geom.SimpleGeometry { - /** + /** * @classdesc * Circle geometry. * @@ -3540,74 +3540,74 @@ declare module ol { * @param {number=} opt_radius Radius. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api - */ + */ constructor(center: ol.Coordinate, opt_radius?: number, opt_layout?: ol.geom.GeometryLayout); - /** + /** * Make a complete copy of the geometry. * @return {!ol.geom.Circle} Clone. * @api - */ + */ clone(): ol.geom.Circle; - /** + /** * Return the center of the circle as {@link ol.Coordinate coordinate}. * @return {ol.Coordinate} Center. * @api - */ + */ getCenter(): ol.Coordinate; - /** + /** * Return the radius of the circle. * @return {number} Radius. * @api - */ + */ getRadius(): number; - /** + /** * @inheritDoc * @api - */ + */ getType(): ol.geom.GeometryType; - /** + /** * @inheritDoc * @api stable - */ + */ intersectsExtent(extent: ol.Extent): boolean; - /** + /** * Set the center of the circle as {@link ol.Coordinate coordinate}. * @param {ol.Coordinate} center Center. * @api - */ + */ setCenter(center: ol.Coordinate): void; - /** + /** * Set the center (as {@link ol.Coordinate coordinate}) and the radius (as * number) of the circle. * @param {ol.Coordinate} center Center. * @param {number} radius Radius. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api - */ + */ setCenterAndRadius(center: ol.Coordinate, radius: number, opt_layout?: ol.geom.GeometryLayout): void; - /** + /** * Set the radius of the circle. The radius is in the units of the projection. * @param {number} radius Radius. * @api - */ + */ setRadius(radius: number): void; - } + } - /** + /** * The geometry type. One of `'Point'`, `'LineString'`, `'LinearRing'`, * `'Polygon'`, `'MultiPoint'`, `'MultiLineString'`, `'MultiPolygon'`, * `'GeometryCollection'`, `'Circle'`. * @enum {string} - */ + */ type GeometryType = string; /** @@ -3632,7 +3632,7 @@ declare module ol { * @api stable */ class Geometry extends ol.Object { - /** + /** * @classdesc * Abstract base class; normally only used for creating subclasses and not * instantiated in apps. @@ -3644,47 +3644,47 @@ declare module ol { * @constructor * @extends {ol.Object} * @api stable - */ + */ constructor(); - /** + /** * Return the closest point of the geometry to the passed point as * {@link ol.Coordinate coordinate}. * @param {ol.Coordinate} point Point. * @param {ol.Coordinate=} opt_closestPoint Closest point. * @return {ol.Coordinate} Closest point. * @api stable - */ + */ getClosestPoint(point: ol.Coordinate, opt_closestPoint?: ol.Coordinate): ol.Coordinate; - /** + /** * Returns true if this geometry includes the specified coordinate. If the * coordinate is on the boundary of the geometry, returns false. * @param {ol.Coordinate} coordinate Coordinate. * @return {boolean} Contains coordinate. * @api - */ + */ intersectsCoordinate(coordinate: ol.Coordinate): boolean; - /** + /** * Get the extent of the geometry. * @param {ol.Extent=} opt_extent Extent. * @return {ol.Extent} extent Extent. * @api stable - */ + */ getExtent(opt_extent?: ol.Extent): ol.Extent; - /** + /** * Rotate the geometry around a given coordinate. This modifies the geometry * coordinates in place. * @abstract * @param {number} angle Rotation angle in radians. * @param {ol.Coordinate} anchor The rotation center. * @api - */ + */ rotate(angle: number, anchor: ol.Coordinate): void; - /** + /** * Scale the geometry (with an optional origin). This modifies the geometry * coordinates in place. * @abstract @@ -3694,10 +3694,10 @@ declare module ol { * @param {ol.Coordinate=} opt_anchor The scale origin (defaults to the center * of the geometry extent). * @api - */ + */ scale(sx: number, opt_sy?: number, opt_anchor?: ol.Coordinate): void; - /** + /** * Create a simplified version of this geometry. For linestrings, this uses * the the {@link * https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm @@ -3708,10 +3708,10 @@ declare module ol { * @return {ol.geom.Geometry} A new, simplified version of the original * geometry. * @api - */ + */ simplify(tolerance: number): ol.geom.Geometry; - /** + /** * Transform each coordinate of the geometry from one coordinate reference * system to another. The geometry is modified in place. * For example, a line will be transformed to a line and a circle to a circle. @@ -3725,9 +3725,15 @@ declare module ol { * @return {ol.geom.Geometry} This geometry. Note that original geometry is * modified in place. * @api stable - */ + */ transform(source: ol.ProjectionLike, destination: ol.ProjectionLike): ol.geom.Geometry; + /** + * Get the type of this geometry. + * @abstract + * @return {ol.geom.GeometryType} Geometry type. + */ + getType(): ol.geom.GeometryType; } /** @@ -3740,7 +3746,7 @@ declare module ol { * @api stable */ class GeometryCollection extends ol.geom.Geometry { - /** + /** * @classdesc * An array of {@link ol.geom.Geometry} objects. * @@ -3748,54 +3754,54 @@ declare module ol { * @extends {ol.geom.Geometry} * @param {Array.=} opt_geometries Geometries. * @api stable - */ + */ constructor(opt_geometries?: ol.geom.Geometry[]); - /** + /** * Make a complete copy of the geometry. * @return {!ol.geom.GeometryCollection} Clone. * @api stable - */ + */ clone(): ol.geom.GeometryCollection; - /** + /** * Return the geometries that make up this geometry collection. * @return {Array.} Geometries. * @api stable - */ + */ getGeometries(): ol.geom.Geometry[]; - /** + /** * @inheritDoc * @api stable - */ + */ getType(): ol.geom.GeometryType; - /** + /** * @inheritDoc * @api stable - */ + */ intersectsExtent(extent: ol.Extent): boolean; - /** + /** * Set the geometries that make up this geometry collection. * @param {Array.} geometries Geometries. * @api stable - */ + */ setGeometries(geometries: ol.geom.Geometry[]): void; - /** + /** * @inheritDoc * @api stable - */ + */ applyTransform(transformFn: ol.TransformFunction): void; - /** + /** * Translate the geometry. * @param {number} deltaX Delta X. * @param {number} deltaY Delta Y. * @api - */ + */ translate(deltaX: number, deltaY: number): void; } @@ -3812,7 +3818,7 @@ declare module ol { * @api stable */ class LinearRing extends ol.geom.SimpleGeometry { - /** + /** * @classdesc * Linear ring geometry. Only used as part of polygon; cannot be rendered * on its own. @@ -3822,42 +3828,42 @@ declare module ol { * @param {Array.} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ constructor(coordinates: ol.Coordinate[], opt_layout?: ol.geom.GeometryLayout); - /** + /** * Make a complete copy of the geometry. * @return {!ol.geom.LinearRing} Clone. * @api stable - */ + */ clone(): ol.geom.LinearRing; - /** + /** * Return the area of the linear ring on projected plane. * @return {number} Area (on projected plane). * @api stable - */ + */ getArea(): number; - /** + /** * Return the coordinates of the linear ring. * @return {Array.} Coordinates. * @api stable - */ + */ getCoordinates(): ol.Coordinate[]; - /** + /** * @inheritDoc * @api stable - */ + */ getType(): ol.geom.GeometryType; - /** + /** * Set the coordinates of the linear ring. * @param {Array.} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ setCoordinates(coordinates: ol.Coordinate[], opt_layout?: ol.geom.GeometryLayout): void; } @@ -3873,7 +3879,7 @@ declare module ol { * @api stable */ class LineString extends ol.geom.SimpleGeometry { - /** + /** * @classdesc * Linestring geometry. * @@ -3882,24 +3888,24 @@ declare module ol { * @param {Array.} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ constructor(coordinates: ol.Coordinate[], opt_layout?: ol.geom.GeometryLayout); - /** + /** * Append the passed coordinate to the coordinates of the linestring. * @param {ol.Coordinate} coordinate Coordinate. * @api stable - */ + */ appendCoordinate(coordinate: ol.Coordinate): void; - /** + /** * Make a complete copy of the geometry. * @return {!ol.geom.LineString} Clone. * @api stable - */ + */ clone(): ol.geom.LineString; - /** + /** * Iterate over each segment, calling the provided callback. * If the callback returns a truthy value the function returns that * value immediately. Otherwise the function returns `false`. @@ -3911,10 +3917,10 @@ declare module ol { * @return {T|boolean} Value. * @template T,S * @api - */ + */ forEachSegment(callback: (() => T), opt_this?: S): (T | boolean); - /** + /** * Returns the coordinate at `m` using linear interpolation, or `null` if no * such coordinate exists. * @@ -3927,17 +3933,17 @@ declare module ol { * @param {boolean=} opt_extrapolate Extrapolate. Default is `false`. * @return {ol.Coordinate} Coordinate. * @api stable - */ + */ getCoordinateAtM(m: number, opt_extrapolate?: boolean): ol.Coordinate; - /** + /** * Return the coordinates of the linestring. * @return {Array.} Coordinates. * @api stable - */ + */ getCoordinates(): ol.Coordinate[]; - /** + /** * Return the coordinate at the provided fraction along the linestring. * The `fraction` is a number between 0 and 1, where 0 is the start of the * linestring and 1 is the end. @@ -3946,39 +3952,39 @@ declare module ol { * be modified. If not provided, a new coordinate will be returned. * @return {ol.Coordinate} Coordinate of the interpolated point. * @api - */ + */ getCoordinateAt(fraction: number, opt_dest?: ol.Coordinate): ol.Coordinate; - /** + /** * Return the length of the linestring on projected plane. * @return {number} Length (on projected plane). * @api stable - */ + */ getLength(): number; - /** + /** * @inheritDoc * @api stable - */ + */ getType(): ol.geom.GeometryType; - /** + /** * @inheritDoc * @api stable - */ + */ intersectsExtent(extent: ol.Extent): boolean; - /** + /** * Set the coordinates of the linestring. * @param {Array.} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ setCoordinates(coordinates: ol.Coordinate[], opt_layout?: ol.geom.GeometryLayout): void; - } + } - /** + /** * @classdesc * Multi-linestring geometry. * @@ -3987,9 +3993,9 @@ declare module ol { * @param {Array.>} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ class MultiLineString extends ol.geom.SimpleGeometry { - /** + /** * @classdesc * Multi-linestring geometry. * @@ -3998,24 +4004,24 @@ declare module ol { * @param {Array.>} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ constructor(coordinates: ol.Coordinate[][], opt_layout?: ol.geom.GeometryLayout); - /** + /** * Append the passed linestring to the multilinestring. * @param {ol.geom.LineString} lineString LineString. * @api stable - */ + */ appendLineString(lineString: ol.geom.LineString): void; - /** + /** * Make a complete copy of the geometry. * @return {!ol.geom.MultiLineString} Clone. * @api stable - */ + */ clone(): ol.geom.MultiLineString; - /** + /** * Returns the coordinate at `m` using linear interpolation, or `null` if no * such coordinate exists. * @@ -4036,54 +4042,54 @@ declare module ol { * @param {boolean=} opt_interpolate Interpolate. Default is `false`. * @return {ol.Coordinate} Coordinate. * @api stable - */ + */ getCoordinateAtM(m: number, opt_extrapolate?: boolean, opt_interpolate?: boolean): ol.Coordinate; - /** + /** * Return the coordinates of the multilinestring. * @return {Array.>} Coordinates. * @api stable - */ + */ getCoordinates(): ol.Coordinate[][]; - /** + /** * Return the linestring at the specified index. * @param {number} index Index. * @return {ol.geom.LineString} LineString. * @api stable - */ + */ getLineString(index: number): ol.geom.LineString; - /** + /** * Return the linestrings of this multilinestring. * @return {Array.} LineStrings. * @api stable - */ + */ getLineStrings(): ol.geom.LineString[]; - /** + /** * @inheritDoc * @api stable - */ + */ getType(): ol.geom.GeometryType; - /** + /** * @inheritDoc * @api stable - */ + */ intersectsExtent(extent: ol.Extent): boolean; - /** + /** * Set the coordinates of the multilinestring. * @param {Array.>} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ setCoordinates(coordinates: ol.Coordinate[][], opt_layout?: ol.geom.GeometryLayout): void; - } + } - /** + /** * @classdesc * Multi-point geometry. * @@ -4092,74 +4098,74 @@ declare module ol { * @param {Array.} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ class MultiPoint extends ol.geom.SimpleGeometry { - /** + /** * @classdesc * Multi-point geometry. * - * @constructor + * @constructor * @extends {ol.geom.SimpleGeometry} * @param {Array.} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ constructor(coordinates: ol.Coordinate[], opt_layout?: ol.geom.GeometryLayout); - /** + /** * Append the passed point to this multipoint. * @param {ol.geom.Point} point Point. * @api stable - */ + */ appendPoint(point: ol.geom.Point): void; - /** + /** * Make a complete copy of the geometry. * @return {!ol.geom.MultiPoint} Clone. * @api stable - */ + */ clone(): ol.geom.MultiPoint; - /** + /** * Return the coordinates of the multipoint. * @return {Array.} Coordinates. * @api stable - */ + */ getCoordinates(): ol.Coordinate[]; - /** + /** * Return the point at the specified index. * @param {number} index Index. * @return {ol.geom.Point} Point. * @api stable - */ + */ getPoint(index: number): ol.geom.Point; - /** + /** * Return the points of this multipoint. * @return {Array.} Points. * @api stable - */ + */ getPoints(): ol.geom.Point[]; - /** + /** * @inheritDoc * @api stable - */ + */ getType(): ol.geom.GeometryType; - /** + /** * @inheritDoc * @api stable - */ + */ intersectsExtent(extent: ol.Extent): boolean; - /** + /** * Set the coordinates of the multipoint. * @param {Array.} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ setCoordinates(coordinates: ol.Coordinate[], opt_layout?: ol.geom.GeometryLayout): void; } @@ -4175,7 +4181,7 @@ declare module ol { * @api stable */ class MultiPolygon extends ol.geom.SimpleGeometry { - /** + /** * @classdesc * Multi-polygon geometry. * @@ -4184,31 +4190,31 @@ declare module ol { * @param {Array.>>} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ constructor(coordinates: ol.Coordinate[][][], opt_layout?: ol.geom.GeometryLayout); - /** + /** * Append the passed polygon to this multipolygon. * @param {ol.geom.Polygon} polygon Polygon. * @api stable - */ + */ appendPolygon(polygon: ol.geom.Polygon): void; - /** + /** * Make a complete copy of the geometry. * @return {!ol.geom.MultiPolygon} Clone. * @api stable - */ + */ clone(): ol.geom.MultiPolygon; - /** + /** * Return the area of the multipolygon on projected plane. * @return {number} Area (on projected plane). * @api stable - */ + */ getArea(): number; - /** + /** * Get the coordinate array for this geometry. This array has the structure * of a GeoJSON coordinate array for multi-polygons. * @@ -4220,54 +4226,54 @@ declare module ol { * constructed. * @return {Array.>>} Coordinates. * @api stable - */ + */ getCoordinates(opt_right?: boolean): ol.Coordinate[][][]; - /** + /** * Return the interior points as {@link ol.geom.MultiPoint multipoint}. * @return {ol.geom.MultiPoint} Interior points. * @api stable - */ + */ getInteriorPoints(): ol.geom.MultiPoint; - /** + /** * Return the polygon at the specified index. * @param {number} index Index. * @return {ol.geom.Polygon} Polygon. * @api stable - */ + */ getPolygon(index: number): ol.geom.Polygon; - /** + /** * Return the polygons of this multipolygon. * @return {Array.} Polygons. * @api stable - */ + */ getPolygons(): ol.geom.Polygon[]; - /** + /** * @inheritDoc * @api stable - */ + */ getType(): ol.geom.GeometryType; - /** + /** * @inheritDoc * @api stable - */ + */ intersectsExtent(extent: ol.Extent): boolean; - /** + /** * Set the coordinates of the multipolygon. * @param {Array.>>} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ setCoordinates(coordinates: ol.Coordinate[][][], opt_layout?: ol.geom.GeometryLayout): void; - } + } - /** + /** * @classdesc * Point geometry. * @@ -4276,52 +4282,52 @@ declare module ol { * @param {ol.Coordinate} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ class Point extends ol.geom.SimpleGeometry { - /** + /** * @classdesc * Point geometry. * - * @constructor + * @constructor * @extends {ol.geom.SimpleGeometry} * @param {ol.Coordinate} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ constructor(coordinates: ol.Coordinate, opt_layout?: ol.geom.GeometryLayout); - /** + /** * Make a complete copy of the geometry. * @return {!ol.geom.Point} Clone. * @api stable - */ + */ clone(): ol.geom.Point; - /** + /** * Return the coordinate of the point. * @return {ol.Coordinate} Coordinates. * @api stable - */ + */ getCoordinates(): ol.Coordinate; - /** + /** * @inheritDoc * @api stable - */ + */ getType(): ol.geom.GeometryType; - /** + /** * @inheritDoc * @api stable - */ + */ intersectsExtent(extent: ol.Extent): boolean; - /** + /** * Set the coordinate of the point. * @param {ol.Coordinate} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ setCoordinates(coordinates: ol.Coordinate, opt_layout?: ol.geom.GeometryLayout): void; } @@ -4337,7 +4343,7 @@ declare module ol { * @api stable */ class Polygon extends ol.geom.SimpleGeometry { - /** + /** * @classdesc * Polygon geometry. * @@ -4346,31 +4352,31 @@ declare module ol { * @param {Array.>} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ constructor(coordinates: ol.Coordinate[][], opt_layout?: ol.geom.GeometryLayout); - /** + /** * Append the passed linear ring to this polygon. * @param {ol.geom.LinearRing} linearRing Linear ring. * @api stable - */ + */ appendLinearRing(linearRing: ol.geom.LinearRing): void; - /** + /** * Make a complete copy of the geometry. * @return {!ol.geom.Polygon} Clone. * @api stable - */ + */ clone(): ol.geom.Polygon; - /** + /** * Return the area of the polygon on projected plane. * @return {number} Area (on projected plane). * @api stable - */ + */ getArea(): number; - /** + /** * Get the coordinate array for this geometry. This array has the structure * of a GeoJSON coordinate array for polygons. * @@ -4382,26 +4388,26 @@ declare module ol { * constructed. * @return {Array.>} Coordinates. * @api stable - */ + */ getCoordinates(opt_right?: boolean): ol.Coordinate[][]; - /** + /** * Return an interior point of the polygon. * @return {ol.geom.Point} Interior point. * @api stable - */ + */ getInteriorPoint(): ol.geom.Point; - /** + /** * Return the number of rings of the polygon, this includes the exterior * ring and any interior rings. * * @return {number} Number of rings. * @api - */ + */ getLinearRingCount(): number; - /** + /** * Return the Nth linear ring of the polygon geometry. Return `null` if the * given index is out of range. * The exterior linear ring is available at index `0` and the interior rings @@ -4410,37 +4416,37 @@ declare module ol { * @param {number} index Index. * @return {ol.geom.LinearRing} Linear ring. * @api stable - */ + */ getLinearRing(index: number): ol.geom.LinearRing; - /** + /** * Return the linear rings of the polygon. * @return {Array.} Linear rings. * @api stable - */ + */ getLinearRings(): ol.geom.LinearRing[]; - /** + /** * @inheritDoc * @api stable - */ + */ getType(): ol.geom.GeometryType; - /** + /** * @inheritDoc * @api stable - */ + */ intersectsExtent(extent: ol.Extent): boolean; - /** + /** * Set the coordinates of the polygon. * @param {Array.>} coordinates Coordinates. * @param {ol.geom.GeometryLayout=} opt_layout Layout. * @api stable - */ + */ setCoordinates(coordinates: ol.Coordinate[][], opt_layout?: ol.geom.GeometryLayout): void; - /** + /** * Create an approximation of a circle on the surface of a sphere. * @param {ol.Sphere} sphere The sphere. * @param {ol.Coordinate} center Center (`[lon, lat]` in degrees). @@ -4450,18 +4456,18 @@ declare module ol { * polygon. Default is `32`. * @return {ol.geom.Polygon} The "circular" polygon. * @api stable - */ + */ static circular(sphere: ol.Sphere, center: ol.Coordinate, radius: number, opt_n?: number): ol.geom.Polygon; - /** + /** * Create a polygon from an extent. The layout used is `XY`. * @param {ol.Extent} extent The extent. * @return {ol.geom.Polygon} The polygon. * @api - */ + */ static fromExtent(extent: ol.Extent): ol.geom.Polygon; - /** + /** * Create a regular polygon from a circle. * @param {ol.geom.Circle} circle Circle geometry. * @param {number=} opt_sides Number of sides of the polygon. Default is 32. @@ -4469,7 +4475,7 @@ declare module ol { * radians. Default is 0. * @return {ol.geom.Polygon} Polygon geometry. * @api - */ + */ static fromCircle(circle: ol.geom.Circle, opt_sides?: number, opt_angle?: number): ol.geom.Polygon; } @@ -4484,7 +4490,7 @@ declare module ol { * @api stable */ class SimpleGeometry extends ol.geom.Geometry { - /** + /** * @classdesc * Abstract base class; only used for creating subclasses; do not instantiate * in apps, as cannot be rendered. @@ -4492,52 +4498,52 @@ declare module ol { * @constructor * @extends {ol.geom.Geometry} * @api stable - */ + */ constructor(); - /** + /** * Return the first coordinate of the geometry. * @return {ol.Coordinate} First coordinate. * @api stable - */ + */ getFirstCoordinate(): ol.Coordinate; - /** + /** * Return the last coordinate of the geometry. * @return {ol.Coordinate} Last point. * @api stable - */ + */ getLastCoordinate(): ol.Coordinate; - /** + /** * Return the {@link ol.geom.GeometryLayout layout} of the geometry. * @return {ol.geom.GeometryLayout} Layout. * @api stable - */ + */ getLayout(): ol.geom.GeometryLayout; - /** + /** * @inheritDoc * @api stable - */ + */ applyTransform(transformFn: ol.TransformFunction): void; - /** + /** * @inheritDoc * @api stable - */ + */ translate(deltaX: number, deltaY: number): void; } } - /** + /** * Render a grid for a coordinate system on a map. * @constructor * @param {olx.GraticuleOptions=} opt_options Options. * @api - */ + */ class Graticule { /** * Render a grid for a coordinate system on a map. @@ -4578,9 +4584,9 @@ declare module ol { } - /** + /** * @namespace ol.has - */ + */ module has { /** * The ratio between physical pixels and device-independent pixels @@ -4591,13 +4597,13 @@ declare module ol { */ const DEVICE_PIXEL_RATIO: number; - /** + /** * True if both the library and browser support Canvas. Always `false` * if `ol.ENABLE_CANVAS` is set to `false` at compile time. * @const * @type {boolean} * @api stable - */ + */ const CANVAS: boolean; /** @@ -4678,7 +4684,7 @@ declare module ol { } - /** + /** * @constructor * @extends {ol.events.EventTarget} * @param {ol.Extent} extent Extent. @@ -4686,9 +4692,9 @@ declare module ol { * @param {number} pixelRatio Pixel ratio. * @param {ol.ImageState} state State. * @param {Array.} attributions Attributions. - */ + */ class ImageBase extends ol.events.EventTarget { - /** + /** * @constructor * @extends {ol.events.EventTarget} * @param {ol.Extent} extent Extent. @@ -4696,14 +4702,14 @@ declare module ol { * @param {number} pixelRatio Pixel ratio. * @param {ol.ImageState} state State. * @param {Array.} attributions Attributions. - */ + */ constructor(extent: ol.Extent, resolution: (number), pixelRatio: number, state: ol.ImageState, attributions: ol.Attribution[]); - } + } type ImageState = number; - /** + /** * @constructor * @extends {ol.Tile} * @param {ol.TileCoord} tileCoord Tile coordinate. @@ -4711,9 +4717,9 @@ declare module ol { * @param {string} src Image source URI. * @param {?string} crossOrigin Cross origin. * @param {ol.TileLoadFunctionType} tileLoadFunction Tile load function. - */ + */ class ImageTile extends ol.Tile { - /** + /** * @constructor * @extends {ol.Tile} * @param {ol.TileCoord} tileCoord Tile coordinate. @@ -4721,19 +4727,19 @@ declare module ol { * @param {string} src Image source URI. * @param {?string} crossOrigin Cross origin. * @param {ol.TileLoadFunctionType} tileLoadFunction Tile load function. - */ + */ constructor(tileCoord: ol.TileCoord, state: ol.Tile.State, src: string, crossOrigin?: string, tileLoadFunction?: ol.TileLoadFunctionType); - /** + /** * Get the image element for this tile. * @inheritDoc * @api - */ + */ getImage(opt_context?: GlobalObject): (HTMLCanvasElement | HTMLImageElement | HTMLVideoElement); - } + } - /** + /** * Inherit the prototype methods from one constructor into another. * * Usage: @@ -4754,10 +4760,10 @@ declare module ol { * @param {!Function} parentCtor Parent constructor. * @function * @api - */ + */ function inherits(childCtor: (() => any), parentCtor: (() => any)): void; - /** + /** * @classdesc * Events emitted by {@link ol.interaction.DragBox} instances are instances of * this type. @@ -4768,9 +4774,9 @@ declare module ol { * @extends {ol.events.Event} * @constructor * @implements {oli.DragBoxEvent} - */ + */ class DragBoxEvent extends ol.events.Event { - /** + /** * @classdesc * Events emitted by {@link ol.interaction.DragBox} instances are instances of * this type. @@ -4781,31 +4787,31 @@ declare module ol { * @extends {ol.events.Event} * @constructor * @implements {oli.DragBoxEvent} - */ + */ constructor(type: string, coordinate: ol.Coordinate, mapBrowserEvent: ol.MapBrowserEvent); - /** + /** * The coordinate of the drag event. * @const * @type {ol.Coordinate} * @api stable - */ + */ coordinate: ol.Coordinate; - /** + /** * @const * @type {ol.MapBrowserEvent} * @api - */ + */ mapBrowserEvent: ol.MapBrowserEvent; - } + } - /** + /** * @namespace ol.interaction - */ + */ module interaction { - /** + /** * @classdesc * Allows the user to zoom by double-clicking on the map. * @@ -4813,7 +4819,7 @@ declare module ol { * @extends {ol.interaction.Interaction} * @param {olx.interaction.DoubleClickZoomOptions=} opt_options Options. * @api stable - */ + */ class DoubleClickZoom extends ol.interaction.Interaction { /** * @classdesc @@ -4838,7 +4844,7 @@ declare module ol { } - /** + /** * @classdesc * Handles input of vector data by drag and drop. * @@ -4847,7 +4853,7 @@ declare module ol { * @fires ol.interaction.DragAndDropEvent * @param {olx.interaction.DragAndDropOptions=} opt_options Options. * @api stable - */ + */ class DragAndDrop extends ol.interaction.Interaction { /** * @classdesc @@ -4871,7 +4877,7 @@ declare module ol { */ static handleEvent: any; - } + } /** * @classdesc @@ -4887,7 +4893,7 @@ declare module ol { * @param {ol.proj.Projection=} opt_projection Projection. */ class DragAndDropEvent extends ol.events.Event { - /** + /** * @classdesc * Events emitted by {@link ol.interaction.DragAndDrop} instances are instances * of this type. @@ -4899,35 +4905,35 @@ declare module ol { * @param {File} file File. * @param {Array.=} opt_features Features. * @param {ol.proj.Projection=} opt_projection Projection. - */ + */ constructor(type: ol.interaction.DragAndDropEventType, file: File, opt_features?: ol.Feature[], opt_projection?: ol.proj.Projection); - /** + /** * The features parsed from dropped data. * @type {Array.|undefined} * @api stable - */ + */ features: ol.Feature[]; - /** + /** * The dropped file. * @type {File} * @api stable - */ + */ file: File; - /** + /** * The feature projection. * @type {ol.proj.Projection|undefined} * @api - */ + */ projection: ol.proj.Projection; - } + } type DragAndDropEventType = string; - /** + /** * @classdesc * Allows the user to draw a vector box by clicking and dragging on the map, * normally combined with an {@link ol.events.condition} that limits @@ -4943,9 +4949,9 @@ declare module ol { * @fires ol.DragBoxEvent * @param {olx.interaction.DragBoxOptions=} opt_options Options. * @api stable - */ + */ class DragBox extends ol.interaction.Pointer { - /** + /** * @classdesc * Allows the user to draw a vector box by clicking and dragging on the map, * normally combined with an {@link ol.events.condition} that limits @@ -4961,14 +4967,14 @@ declare module ol { * @fires ol.DragBoxEvent * @param {olx.interaction.DragBoxOptions=} opt_options Options. * @api stable - */ + */ constructor(opt_options?: olx.interaction.DragBoxOptions); - /** + /** * Returns geometry of last drawn box. * @return {ol.geom.Polygon} Geometry. * @api stable - */ + */ getGeometry(): ol.geom.Polygon; } @@ -4981,9 +4987,9 @@ declare module ol { * @extends {ol.interaction.Pointer} * @param {olx.interaction.DragPanOptions=} opt_options Options. * @api stable - */ + */ class DragPan extends ol.interaction.Pointer { - /** + /** * @classdesc * Allows the user to pan the map by dragging the map. * @@ -4991,7 +4997,7 @@ declare module ol { * @extends {ol.interaction.Pointer} * @param {olx.interaction.DragPanOptions=} opt_options Options. * @api stable - */ + */ constructor(opt_options?: olx.interaction.DragPanOptions); } @@ -5022,10 +5028,10 @@ declare module ol { * @extends {ol.interaction.Pointer} * @param {olx.interaction.DragRotateOptions=} opt_options Options. * @api stable - */ + */ constructor(opt_options?: olx.interaction.DragRotateOptions); - } + } /** * @classdesc @@ -5043,7 +5049,7 @@ declare module ol { * @api stable */ class DragRotateAndZoom extends ol.interaction.Pointer { - /** + /** * @classdesc * Allows the user to zoom and rotate the map by clicking and dragging * on the map. By default, this interaction is limited to when the shift @@ -5057,7 +5063,7 @@ declare module ol { * @extends {ol.interaction.Pointer} * @param {olx.interaction.DragRotateAndZoomOptions=} opt_options Options. * @api stable - */ + */ constructor(opt_options?: olx.interaction.DragRotateAndZoomOptions); } @@ -5077,7 +5083,7 @@ declare module ol { * @api stable */ class DragZoom extends ol.interaction.DragBox { - /** + /** * @classdesc * Allows the user to zoom the map by clicking and dragging on the map, * normally combined with an {@link ol.events.condition} that limits @@ -5090,7 +5096,7 @@ declare module ol { * @extends {ol.interaction.DragBox} * @param {olx.interaction.DragZoomOptions=} opt_options Options. * @api stable - */ + */ constructor(opt_options?: olx.interaction.DragZoomOptions); } @@ -5107,7 +5113,7 @@ declare module ol { * @param {ol.Feature} feature The feature drawn. */ class DrawEvent extends ol.events.Event { - /** + /** * @classdesc * Events emitted by {@link ol.interaction.Draw} instances are instances of * this type. @@ -5117,14 +5123,14 @@ declare module ol { * @implements {oli.DrawEvent} * @param {ol.interaction.DrawEventType} type Type. * @param {ol.Feature} feature The feature drawn. - */ + */ constructor(type: ol.interaction.DrawEventType, feature: ol.Feature); - /** + /** * The feature being drawn. * @type {ol.Feature} * @api stable - */ + */ feature: ol.Feature; } @@ -5142,7 +5148,7 @@ declare module ol { * @api stable */ class Draw extends ol.interaction.Pointer { - /** + /** * @classdesc * Interaction for drawing feature geometries. * @@ -5151,33 +5157,33 @@ declare module ol { * @fires ol.interaction.DrawEvent * @param {olx.interaction.DrawOptions} options Options. * @api stable - */ + */ constructor(options: olx.interaction.DrawOptions); - /** + /** * Remove last point of the feature currently being drawn. * @api - */ + */ removeLastPoint(): void; - /** + /** * Stop drawing and add the sketch feature to the target layer. * The {@link ol.interaction.DrawEventType.DRAWEND} event is dispatched before * inserting the feature. * @api - */ + */ finishDrawing(): void; - /** + /** * Extend an existing geometry by adding additional points. This only works * on features with `LineString` geometries, where the interaction will * extend lines by adding points to the end of the coordinates array. * @param {!ol.Feature} feature Feature to be extended. * @api - */ + */ extend(feature: ol.Feature): void; - /** + /** * Create a `geometryFunction` for `mode: 'Circle'` that will create a regular * polygon with a user specified number of sides and start angle instead of an * `ol.geom.Circle` geometry. @@ -5189,7 +5195,7 @@ declare module ol { * @return {ol.DrawGeometryFunctionType} Function that draws a * polygon. * @api - */ + */ static createRegularPolygon(opt_sides?: number, opt_angle?: number): ol.DrawGeometryFunctionType; } @@ -5237,7 +5243,7 @@ declare module ol { * @api */ class Interaction extends ol.Object { - /** + /** * @classdesc * Abstract base class; normally only used for creating subclasses and not * instantiated in apps. @@ -5253,35 +5259,35 @@ declare module ol { * @param {olx.interaction.InteractionOptions} options Options. * @extends {ol.Object} * @api - */ + */ constructor(options: olx.interaction.InteractionOptions); - /** + /** * Return whether the interaction is currently active. * @return {boolean} `true` if the interaction is active, `false` otherwise. * @observable * @api - */ + */ getActive(): boolean; - /** + /** * Get the map associated with this interaction. * @return {ol.Map} Map. * @api - */ + */ getMap(): ol.Map; - /** + /** * Activate or deactivate the interaction. * @param {boolean} active Active. * @observable * @api - */ + */ setActive(active: boolean): void; - } + } - /** + /** * @classdesc * Allows the user to pan the map using keyboard arrows. * Note that, although this interaction is by default included in maps, @@ -5297,9 +5303,9 @@ declare module ol { * @extends {ol.interaction.Interaction} * @param {olx.interaction.KeyboardPanOptions=} opt_options Options. * @api stable - */ + */ class KeyboardPan extends ol.interaction.Interaction { - /** + /** * @classdesc * Allows the user to pan the map using keyboard arrows. * Note that, although this interaction is by default included in maps, @@ -5315,7 +5321,7 @@ declare module ol { * @extends {ol.interaction.Interaction} * @param {olx.interaction.KeyboardPanOptions=} opt_options Options. * @api stable - */ + */ constructor(opt_options?: olx.interaction.KeyboardPanOptions); /** @@ -5381,7 +5387,7 @@ declare module ol { } - /** + /** * @classdesc * Events emitted by {@link ol.interaction.Modify} instances are instances of * this type. @@ -5426,7 +5432,7 @@ declare module ol { } - /** + /** * @classdesc * Interaction for modifying feature geometries. * @@ -5435,7 +5441,7 @@ declare module ol { * @param {olx.interaction.ModifyOptions} options Options. * @fires ol.interaction.ModifyEvent * @api - */ + */ class Modify extends ol.interaction.Pointer { /** * @classdesc @@ -5458,7 +5464,7 @@ declare module ol { } - /** + /** * @classdesc * Allows the user to zoom the map by scrolling the mouse wheel. * @@ -5466,7 +5472,7 @@ declare module ol { * @extends {ol.interaction.Interaction} * @param {olx.interaction.MouseWheelZoomOptions=} opt_options Options. * @api stable - */ + */ class MouseWheelZoom extends ol.interaction.Interaction { /** * @classdesc @@ -5549,7 +5555,7 @@ declare module ol { } - /** + /** * @classdesc * Base class that calls user-defined functions on `down`, `move` and `up` * events. This class also manages "drag sequences". @@ -5563,7 +5569,7 @@ declare module ol { * @param {olx.interaction.PointerOptions=} opt_options Options. * @extends {ol.interaction.Interaction} * @api - */ + */ class Pointer extends ol.interaction.Interaction { /** * @classdesc @@ -5595,7 +5601,7 @@ declare module ol { } - /** + /** * @classdesc * Events emitted by {@link ol.interaction.Select} instances are instances of * this type. @@ -5649,7 +5655,7 @@ declare module ol { } - /** + /** * @classdesc * Interaction for selecting vector features. By default, selected features are * styled differently, so this interaction can be used for visual highlighting, @@ -5666,7 +5672,7 @@ declare module ol { * @param {olx.interaction.SelectOptions=} opt_options Options. * @fires ol.interaction.SelectEvent * @api stable - */ + */ class Select extends ol.interaction.Interaction { /** * @classdesc @@ -5688,11 +5694,11 @@ declare module ol { */ constructor(opt_options?: olx.interaction.SelectOptions); - /** + /** * Get the selected features. * @return {ol.Collection.} Features collection. * @api stable - */ + */ getFeatures(): ol.Collection; /** @@ -5747,7 +5753,7 @@ declare module ol { * @extends {ol.interaction.Pointer} * @param {olx.interaction.SnapOptions=} opt_options Options. * @api - */ + */ class Snap extends ol.interaction.Pointer { /** * @classdesc @@ -5793,7 +5799,7 @@ declare module ol { } - /** + /** * @classdesc * Events emitted by {@link ol.interaction.Translate} instances are instances of * this type. @@ -5804,7 +5810,7 @@ declare module ol { * @param {ol.interaction.TranslateEventType} type Type. * @param {ol.Collection.} features The features translated. * @param {ol.Coordinate} coordinate The event coordinate. - */ + */ class TranslateEvent extends ol.events.Event { /** * @classdesc @@ -5839,7 +5845,7 @@ declare module ol { type TranslateEventType = string; - /** + /** * @classdesc * Interaction for translating (moving) features. * @@ -5848,7 +5854,7 @@ declare module ol { * @fires ol.interaction.TranslateEvent * @param {olx.interaction.TranslateOptions} options Options. * @api - */ + */ class Translate extends ol.interaction.Pointer { /** * @classdesc @@ -5866,7 +5872,7 @@ declare module ol { } - /** + /** * @classdesc * Implementation of inertial deceleration for map movement. * @@ -5877,9 +5883,9 @@ declare module ol { * initial values (milliseconds). * @struct * @api - */ + */ class Kinetic { - /** + /** * @classdesc * Implementation of inertial deceleration for map movement. * @@ -5890,14 +5896,14 @@ declare module ol { * initial values (milliseconds). * @struct * @api - */ + */ constructor(decay: number, minVelocity: number, delay: number); - } + } - /** + /** * @namespace ol.layer - */ + */ module layer { /** * @classdesc @@ -5995,12 +6001,12 @@ declare module ol { */ setMaxResolution(maxResolution: number): void; - /** + /** * Set the minimum resolution at which the layer is visible. * @param {number} minResolution The minimum resolution of the layer. * @observable * @api stable - */ + */ setMinResolution(minResolution: number): void; /** @@ -6030,12 +6036,12 @@ declare module ol { } - /** + /** * @classdesc * A {@link ol.Collection} of layers that are handled together. - * + * * A generic `change` event is triggered when the group/Collection changes. - * + * * @constructor * @extends {ol.layer.Base} * @param {olx.layer.GroupOptions=} opt_options Layer options. @@ -6077,7 +6083,7 @@ declare module ol { } - /** + /** * @classdesc * Layer for rendering vector data as a heatmap. * Note that any property set in the options is set as a {@link ol.Object} @@ -6089,7 +6095,7 @@ declare module ol { * @fires ol.render.Event * @param {olx.layer.HeatmapOptions=} opt_options Options. * @api - */ + */ class Heatmap extends ol.layer.Vector { /** * @classdesc @@ -6122,12 +6128,12 @@ declare module ol { */ getGradient(): string[]; - /** + /** * Return the size of the radius in pixels. * @return {number} Radius size in pixel. * @api * @observable - */ + */ getRadius(): number; /** @@ -6156,7 +6162,7 @@ declare module ol { } - /** + /** * @classdesc * Server-rendered images that are available for arbitrary extents and * resolutions. @@ -6169,7 +6175,7 @@ declare module ol { * @fires ol.render.Event * @param {olx.layer.ImageOptions=} opt_options Layer options. * @api stable - */ + */ class Image extends ol.layer.Layer { /** * @classdesc @@ -6189,7 +6195,7 @@ declare module ol { } - /** + /** * @classdesc * Abstract base class; normally only used for creating subclasses and not * instantiated in apps. @@ -6331,19 +6337,19 @@ declare module ol { } - /** + /** * @classdesc * Vector data that is rendered client-side. * Note that any property set in the options is set as a {@link ol.Object} * property on the layer object; for example, setting `title: 'My Title'` in the * options means that `title` is observable, and has get/set accessors. - * + * * @constructor * @extends {ol.layer.Layer} * @fires ol.render.Event * @param {olx.layer.VectorOptions=} opt_options Options. * @api stable - */ + */ class Vector extends ol.layer.Layer { /** * @classdesc @@ -6410,10 +6416,10 @@ declare module ol { * * `'vector'`: Vector tiles are rendered as vectors. Most accurate rendering * even during animations, but slower performance than the other options. * @api - */ + */ type VectorTileRenderType = string; - /** + /** * @classdesc * Layer for vector tile data that is rendered client-side. * Note that any property set in the options is set as a {@link ol.Object} @@ -6424,7 +6430,7 @@ declare module ol { * @extends {ol.layer.Vector} * @param {olx.layer.VectorTileOptions=} opt_options Options. * @api - */ + */ class VectorTile extends ol.layer.Vector { /** * @classdesc @@ -6476,41 +6482,41 @@ declare module ol { } - /** + /** * Strategies for loading vector data. * @namespace ol.loadingstrategy - */ + */ module loadingstrategy { - /** + /** * Strategy function for loading all features with a single request. * @param {ol.Extent} extent Extent. * @param {number} resolution Resolution. * @return {Array.} Extents. * @api - */ + */ function all(extent: ol.Extent, resolution: number): ol.Extent[]; - /** + /** * Strategy function for loading features based on the view's extent and * resolution. * @param {ol.Extent} extent Extent. * @param {number} resolution Resolution. * @return {Array.} Extents. * @api - */ + */ function bbox(extent: ol.Extent, resolution: number): ol.Extent[]; - /** + /** * Creates a strategy function for loading features based on a tile grid. * @param {ol.tilegrid.TileGrid} tileGrid Tile grid. * @return {function(ol.Extent, number): Array.} Loading strategy. * @api - */ + */ function tile(tileGrid: ol.tilegrid.TileGrid): ((extent: ol.Extent, i: number) => ol.Extent[]); } - /** + /** * @classdesc * The map is the core component of OpenLayers. For a map to render, a view, * one or more layers, and a target container are needed: @@ -6558,13 +6564,13 @@ declare module ol { * @fires ol.render.Event#postcompose * @fires ol.render.Event#precompose * @api stable - */ + */ class Map extends ol.Object { - /** + /** * @classdesc * The map is the core component of OpenLayers. For a map to render, a view, * one or more layers, and a target container are needed: - * + * * var map = new ol.Map({ * view: new ol.View({ * center: [0, 0], @@ -6608,49 +6614,49 @@ declare module ol { * @fires ol.render.Event#postcompose * @fires ol.render.Event#precompose * @api stable - */ + */ constructor(options: olx.MapOptions); - /** + /** * Add the given control to the map. * @param {ol.control.Control} control Control. * @api stable - */ + */ addControl(control: ol.control.Control): void; - /** + /** * Add the given interaction to the map. * @param {ol.interaction.Interaction} interaction Interaction to add. * @api stable - */ + */ addInteraction(interaction: ol.interaction.Interaction): void; - /** + /** * Adds the given layer to the top of this map. If you want to add a layer * elsewhere in the stack, use `getLayers()` and the methods available on * {@link ol.Collection}. * @param {ol.layer.Base} layer Layer. * @api stable - */ + */ addLayer(layer: ol.layer.Base): void; - /** + /** * Add the given overlay to the map. * @param {ol.Overlay} overlay Overlay. * @api stable - */ + */ addOverlay(overlay: ol.Overlay): void; - /** + /** * Add functions to be called before rendering. This can be used for attaching * animations before updating the map's view. The {@link ol.animation} * namespace provides several static methods for creating prerender functions. * @param {...ol.PreRenderFunction} var_args Any number of pre-render functions. * @api - */ + */ beforeRender(var_args: ol.PreRenderFunction): void; - /** + /** * Detect features that intersect a pixel on the viewport, and execute a * callback with each intersecting feature. Layers included in the detection can * be configured through `opt_layerFilter`. @@ -6728,15 +6734,15 @@ declare module ol { */ getEventCoordinate(event: Event): ol.Coordinate; - /** + /** * Returns the map pixel position for a browser event relative to the viewport. * @param {Event} event Event. * @return {ol.Pixel} Pixel. * @api stable - */ + */ getEventPixel(event: Event): ol.Pixel; - /** + /** * Get the target in which this map is rendered. * Note that this returns what is entered as an option or in setTarget: * if that was an element, it returns an element; if a string, it returns that. @@ -6744,33 +6750,33 @@ declare module ol { * map is rendered in. * @observable * @api stable - */ + */ getTarget(): (Element | string); - /** + /** * Get the DOM element into which this map is rendered. In contrast to * `getTarget` this method always return an `Element`, or `null` if the * map has no target. * @return {Element} The element that the map is rendered in. * @api - */ + */ getTargetElement(): Element; - /** + /** * Get the coordinate for a given pixel. This returns a coordinate in the * map view projection. * @param {ol.Pixel} pixel Pixel position in the map viewport. * @return {ol.Coordinate} The coordinate for the pixel position. * @api stable - */ + */ getCoordinateFromPixel(pixel: ol.Pixel): ol.Coordinate; - /** + /** * Get the map controls. Modifying this collection changes the controls * associated with the map. * @return {ol.Collection.} Controls. * @api stable - */ + */ getControls(): ol.Collection; /** @@ -6809,11 +6815,11 @@ declare module ol { */ getLayerGroup(): ol.layer.Group; - /** + /** * Get the collection of layers associated with this map. * @return {!ol.Collection.} Layers. * @api stable - */ + */ getLayers(): ol.Collection; /** @@ -6861,31 +6867,31 @@ declare module ol { */ render(): void; - /** + /** * Remove the given control from the map. * @param {ol.control.Control} control Control. * @return {ol.control.Control|undefined} The removed control (or undefined * if the control was not found). * @api stable - */ + */ removeControl(control: ol.control.Control): (ol.control.Control); - /** + /** * Remove the given interaction from the map. * @param {ol.interaction.Interaction} interaction Interaction to remove. * @return {ol.interaction.Interaction|undefined} The removed interaction (or * undefined if the interaction was not found). * @api stable - */ + */ removeInteraction(interaction: ol.interaction.Interaction): (ol.interaction.Interaction); - /** + /** * Removes the given layer from the map. * @param {ol.layer.Base} layer Layer. * @return {ol.layer.Base|undefined} The removed layer (or undefined if the * layer was not found). * @api stable - */ + */ removeLayer(layer: ol.layer.Base): (ol.layer.Base); /** @@ -6897,30 +6903,30 @@ declare module ol { */ removeOverlay(overlay: ol.Overlay): (ol.Overlay); - /** + /** * Sets the layergroup of this map. * @param {ol.layer.Group} layerGroup A layer group containing the layers in * this map. * @observable * @api stable - */ + */ setLayerGroup(layerGroup: ol.layer.Group): void; - /** + /** * Set the size of this map. * @param {ol.Size|undefined} size The size in pixels of the map in the DOM. * @observable * @api - */ + */ setSize(size: (ol.Size)): void; - /** + /** * Set the target element to render this map into. * @param {Element|string|undefined} target The Element or id of the Element * that the map is rendered in. * @observable * @api stable - */ + */ setTarget(target: (Element | string)): void; /** @@ -6938,9 +6944,9 @@ declare module ol { */ updateSize(): void; - } + } - /** + /** * @classdesc * Events emitted as map browser events are instances of this type. * See {@link ol.Map} for which events trigger a map browser event. @@ -7002,9 +7008,9 @@ declare module ol { */ dragging: boolean; - } + } - /** + /** * @constructor * @extends {ol.MapBrowserEvent} * @param {string} type Event type. @@ -7037,16 +7043,16 @@ declare module ol { * @classdesc * Events emitted as map events are instances of this type. * See {@link ol.Map} for which events trigger a map event. - * + * * @constructor * @extends {ol.events.Event} * @implements {oli.MapEvent} * @param {string} type Event type. * @param {ol.Map} map Map. * @param {?olx.FrameState=} opt_frameState Frame state. - */ + */ class MapEvent extends ol.events.Event { - /** + /** * @classdesc * Events emitted as map events are instances of this type. * See {@link ol.Map} for which events trigger a map event. @@ -7057,7 +7063,7 @@ declare module ol { * @param {string} type Event type. * @param {ol.Map} map Map. * @param {?olx.FrameState=} opt_frameState Frame state. - */ + */ constructor(type: string, map: ol.Map, opt_frameState?: olx.FrameState); /** @@ -7067,16 +7073,16 @@ declare module ol { */ map: ol.Map; - /** + /** * The frame state at the time of the event. * @type {?olx.FrameState} * @api - */ + */ frameState: olx.FrameState; } - /** + /** * @classdesc * Events emitted by {@link ol.Object} instances are instances of this type. * @@ -7086,9 +7092,9 @@ declare module ol { * @extends {ol.events.Event} * @implements {oli.ObjectEvent} * @constructor - */ + */ class ObjectEvent extends ol.events.Event { - /** + /** * @classdesc * Events emitted by {@link ol.Object} instances are instances of this type. * @@ -7098,27 +7104,27 @@ declare module ol { * @extends {ol.events.Event} * @implements {oli.ObjectEvent} * @constructor - */ + */ constructor(type: string, key: string, oldValue: any); - /** + /** * The name of the property whose value is changing. * @type {string} * @api stable - */ + */ key: string; - /** + /** * The old value. To get the new value use `e.target.get(e.key)` where * `e` is the event object. * @type {*} * @api stable - */ + */ oldValue: any; } - /** + /** * @classdesc * Abstract base class; normally only used for creating subclasses and not * instantiated in apps. @@ -7162,9 +7168,9 @@ declare module ol { * @param {Object.=} opt_values An object with key-value pairs. * @fires ol.ObjectEvent * @api - */ + */ class Object extends ol.Observable { - /** + /** * @classdesc * Abstract base class; normally only used for creating subclasses and not * instantiated in apps. @@ -7208,7 +7214,7 @@ declare module ol { * @param {Object.=} opt_values An object with key-value pairs. * @fires ol.ObjectEvent * @api - */ + */ constructor(opt_values?: { [k: string]: any }); /** @@ -7261,7 +7267,7 @@ declare module ol { } - /** + /** * @classdesc * Abstract base class; normally only used for creating subclasses and not * instantiated in apps. @@ -7284,29 +7290,29 @@ declare module ol { * and unregistration. A generic `change` event is always available through * {@link ol.Observable#changed}. * - * @constructor + * @constructor * @extends {ol.events.EventTarget} * @fires ol.events.Event * @struct * @api stable - */ + */ constructor(); - /** + /** * Removes an event listener using the key returned by `on()` or `once()`. * @param {ol.EventsKey|Array.} key The key returned by `on()` * or `once()` (or an array of keys). * @api stable - */ + */ static unByKey(key: (ol.EventsKey | ol.EventsKey[])): void; - /** + /** * Increases the revision counter and dispatches a 'change' event. * @api - */ + */ changed(): void; - /** + /** * Dispatches an event and calls all listeners listening for events * of this type. The event parameter can either be a string or an * Object with a `type` property. @@ -7316,18 +7322,18 @@ declare module ol { * string} event Event object. * @function * @api - */ + */ dispatchEvent(event: (GlobalObject | ol.events.Event | string)): void; - /** + /** * Get the version number for this object. Each time the object is modified, * its version number will be incremented. * @return {number} Revision. * @api - */ + */ getRevision(): number; - /** + /** * Listen for a certain type of event. * @param {string|Array.} type The event type or array of event types. * @param {function(?): ?} listener The listener function. @@ -7336,10 +7342,10 @@ declare module ol { * called with an array of event types as the first argument, the return * will be an array of keys. * @api stable - */ + */ on(type: (string | string[]), listener: Function, opt_this?: GlobalObject): (ol.EventsKey | ol.EventsKey[]); - /** + /** * Listen once for a certain type of event. * @param {string|Array.} type The event type or array of event types. * @param {function(?): ?} listener The listener function. @@ -7348,20 +7354,20 @@ declare module ol { * called with an array of event types as the first argument, the return * will be an array of keys. * @api stable - */ + */ once(type: (string | string[]), listener: Function, opt_this?: GlobalObject): (ol.EventsKey | ol.EventsKey[]); - /** + /** * Unlisten for a certain type of event. * @param {string|Array.} type The event type or array of event types. * @param {function(?): ?} listener The listener function. * @param {Object=} opt_this The object which was used as `this` by the * `listener`. * @api stable - */ + */ un(type: (string | string[]), listener: Function, opt_this?: GlobalObject): void; - /** + /** * Removes an event listener using the key returned by `on()` or `once()`. * Note that using the {@link ol.Observable.unByKey} static function is to * be preferred. @@ -7369,20 +7375,20 @@ declare module ol { * or `once()` (or an array of keys). * @function * @api stable - */ + */ unByKey(key: (ol.EventsKey | ol.EventsKey[])): void; } - /** + /** * Overlay position: `'bottom-left'`, `'bottom-center'`, `'bottom-right'`, * `'center-left'`, `'center-center'`, `'center-right'`, `'top-left'`, * `'top-center'`, `'top-right'` * @enum {string} - */ + */ type OverlayPositioning = string; - /** + /** * @classdesc * An element to be displayed over the map and attached to a single map * location. Like {@link ol.control.Control}, Overlays are visible widgets. @@ -7402,9 +7408,9 @@ declare module ol { * @extends {ol.Object} * @param {olx.OverlayOptions} options Overlay options. * @api stable - */ + */ class Overlay extends ol.Object { - /** + /** * @classdesc * An element to be displayed over the map and attached to a single map * location. Like {@link ol.control.Control}, Overlays are visible widgets. @@ -7424,64 +7430,64 @@ declare module ol { * @extends {ol.Object} * @param {olx.OverlayOptions} options Overlay options. * @api stable - */ + */ constructor(options: olx.OverlayOptions); - /** + /** * Get the DOM element of this overlay. * @return {Element|undefined} The Element containing the overlay. * @observable * @api stable - */ + */ getElement(): (Element); - /** + /** * Get the overlay identifier which is set on constructor. * @return {number|string|undefined} Id. * @api - */ + */ getId(): (number | string); - /** + /** * Get the map associated with this overlay. * @return {ol.Map|undefined} The map that the overlay is part of. * @observable * @api stable - */ + */ getMap(): (ol.Map); - /** + /** * Get the offset of this overlay. * @return {Array.} The offset. * @observable * @api stable - */ + */ getOffset(): number[]; - /** + /** * Get the current position of this overlay. * @return {ol.Coordinate|undefined} The spatial point that the overlay is * anchored at. * @observable * @api stable - */ + */ getPosition(): (ol.Coordinate); - /** + /** * Get the current positioning of this overlay. * @return {ol.OverlayPositioning} How the overlay is positioned * relative to its point on the map. * @observable * @api stable - */ + */ getPositioning(): ol.OverlayPositioning; - /** + /** * Set the DOM element to be associated with this overlay. * @param {Element|undefined} element The Element containing the overlay. * @observable * @api stable - */ + */ setElement(element: (Element)): void; /** @@ -7492,56 +7498,56 @@ declare module ol { */ setMap(map: (ol.Map)): void; - /** + /** * Set the offset for this overlay. * @param {Array.} offset Offset. * @observable * @api stable - */ + */ setOffset(offset: number[]): void; - /** + /** * Set the position for this overlay. If the position is `undefined` the * overlay is hidden. * @param {ol.Coordinate|undefined} position The spatial point that the overlay * is anchored at. * @observable * @api stable - */ + */ setPosition(position: (ol.Coordinate)): void; - /** + /** * Set the positioning for this overlay. * @param {ol.OverlayPositioning} positioning how the overlay is * positioned relative to its point on the map. * @observable * @api stable - */ + */ setPositioning(positioning: ol.OverlayPositioning): void; - } + } module pointer { - /** + /** * @classdesc * A class for pointer events. * * This class is used as an abstraction for mouse events, * touch events and even native pointer events. * - * @constructor + * @constructor * @extends {ol.events.Event} * @param {string} type The type of the event to create. * @param {Event} originalEvent The event. * @param {Object.=} opt_eventDict An optional dictionary of * initial event properties. - */ + */ class PointerEvent { } } - /** + /** * The ol.proj namespace stores: * * a list of {@link ol.proj.Projection} * objects, one for each projection supported by the application @@ -7594,25 +7600,25 @@ declare module ol { * this. * * @namespace ol.proj - */ + */ module proj { - /** + /** * Projection units: `'degrees'`, `'ft'`, `'m'`, `'pixels'`, `'tile-pixels'` or * `'us-ft'`. * @enum {string} - */ + */ type Units = string; - /** + /** * Meters per unit lookup table. * @const * @type {Object.} * @api stable - */ + */ const METERS_PER_UNIT: { [k: string]: number }; - /** + /** * @classdesc * Projection definition class. One of these is created for each projection * supported in the application and stored in the {@link ol.proj} namespace. @@ -7641,7 +7647,7 @@ declare module ol { * @param {olx.ProjectionOptions} options Projection options. * @struct * @api stable - */ + */ class Projection { /** * @classdesc @@ -7682,11 +7688,11 @@ declare module ol { */ getCode(): string; - /** + /** * Get the validity extent for this projection. * @return {ol.Extent} Extent. * @api stable - */ + */ getExtent(): ol.Extent; /** @@ -7705,11 +7711,11 @@ declare module ol { */ getMetersPerUnit(): (number); - /** + /** * Get the world extent for this projection. * @return {ol.Extent} Extent. * @api - */ + */ getWorldExtent(): ol.Extent; /** @@ -7733,12 +7739,12 @@ declare module ol { */ setExtent(extent: ol.Extent): void; - /** + /** * Set the world extent for this projection. * @param {ol.Extent} worldExtent World extent * [minlon, minlat, maxlon, maxlat]. * @api - */ + */ setWorldExtent(worldExtent: ol.Extent): void; /** @@ -7781,25 +7787,25 @@ declare module ol { */ function setProj4(proj4: any): void; - /** + /** * Registers transformation functions that don't alter coordinates. Those allow * to transform between projections with equal meaning. * * @param {Array.} projections Projections. * @api - */ + */ function addEquivalentProjections(projections: ol.proj.Projection[]): void; - /** + /** * Add a Projection object to the list of supported projections that can be * looked up by their code. * * @param {ol.proj.Projection} projection Projection instance. * @api stable - */ + */ function addProjection(projection: ol.proj.Projection): void; - /** + /** * Registers coordinate transform functions to convert coordinates between the * source projection and the destination projection. * The forward and inverse functions convert coordinate pairs; this function @@ -7817,7 +7823,7 @@ declare module ol { * projection) that takes a {@link ol.Coordinate} as argument and returns * the transformed {@link ol.Coordinate}. * @api stable - */ + */ function addCoordinateTransforms(source: ol.ProjectionLike, destination: ol.ProjectionLike, forward: ((coords: ol.Coordinate) => ol.Coordinate), inverse: ((coords: ol.Coordinate) => ol.Coordinate)): void; /** @@ -7831,7 +7837,7 @@ declare module ol { */ function fromLonLat(coordinate: ol.Coordinate, opt_projection?: ol.ProjectionLike): ol.Coordinate; - /** + /** * Transforms a coordinate to longitude/latitude. * @param {ol.Coordinate} coordinate Projected coordinate. * @param {ol.ProjectionLike=} opt_projection Projection of the coordinate. @@ -7839,10 +7845,10 @@ declare module ol { * @return {ol.Coordinate} Coordinate as longitude and latitude, i.e. an array * with longitude as 1st and latitude as 2nd element. * @api stable - */ + */ function toLonLat(coordinate: ol.Coordinate, opt_projection?: ol.ProjectionLike): ol.Coordinate; - /** + /** * Fetches a Projection object for the code specified. * * @param {ol.ProjectionLike} projectionLike Either a code string which is @@ -7850,10 +7856,10 @@ declare module ol { * existing projection object, or undefined. * @return {ol.proj.Projection} Projection object, or null if not in list. * @api stable - */ + */ function get(projectionLike: ol.ProjectionLike): ol.proj.Projection; - /** + /** * Checks if two projections are the same, that is every coordinate in one * projection does represent the same geographic point as the same coordinate in * the other projection. @@ -7862,10 +7868,10 @@ declare module ol { * @param {ol.proj.Projection} projection2 Projection 2. * @return {boolean} Equivalent. * @api - */ + */ function equivalent(projection1: ol.proj.Projection, projection2: ol.proj.Projection): boolean; - /** + /** * Given the projection-like objects, searches for a transformation * function to convert a coordinates array from the source projection to the * destination projection. @@ -7874,10 +7880,10 @@ declare module ol { * @param {ol.ProjectionLike} destination Destination. * @return {ol.TransformFunction} Transform function. * @api stable - */ + */ function getTransform(source: ol.ProjectionLike, destination: ol.ProjectionLike): ol.TransformFunction; - /** + /** * Transforms a coordinate from source projection to destination projection. * This returns a new coordinate (and does not modify the original). * @@ -7888,10 +7894,10 @@ declare module ol { * @param {ol.Coordinate} coordinate Coordinate. * @param {ol.ProjectionLike} source Source projection-like. * @param {ol.ProjectionLike} destination Destination projection-like. - */ + */ function transform(coordinate: ol.Coordinate, source: ol.ProjectionLike, destination: ol.ProjectionLike): ol.Coordinate; - /** + /** * Transforms an extent from source projection to destination projection. This * returns a new extent (and does not modify the original). * @@ -7900,18 +7906,18 @@ declare module ol { * @param {ol.ProjectionLike} destination Destination projection-like. * @return {ol.Extent} The transformed extent. * @api stable - */ + */ function transformExtent(extent: ol.Extent, source: ol.ProjectionLike, destination: ol.ProjectionLike): ol.Extent; } - /** + /** * @namespace ol.render - */ + */ module render { - /** + /** * @namespace ol.render.canvas - */ + */ module canvas { /** * @classdesc @@ -7949,37 +7955,37 @@ declare module ol { * @param {ol.Transform} transform Transform. * @param {number} viewRotation View rotation. * @struct - */ + */ constructor(context: CanvasRenderingContext2D, pixelRatio: number, extent: ol.Extent, transform: any, viewRotation: number); - /** + /** * Render a circle geometry into the canvas. Rendering is immediate and uses * the current fill and stroke styles. * * @param {ol.geom.Circle} geometry Circle geometry. * @api - */ + */ drawCircle(geometry: ol.geom.Circle): void; - /** + /** * Set the rendering style. Note that since this is an immediate rendering API, * any `zIndex` on the provided style will be ignored. * * @param {ol.style.Style} style The rendering style. * @api - */ + */ setStyle(style: ol.style.Style): void; - /** + /** * Render a geometry into the canvas. Call * {@link ol.render.canvas.Immediate#setStyle} first to set the rendering style. * * @param {ol.geom.Geometry|ol.render.Feature} geometry The geometry to render. * @api - */ + */ drawGeometry(geometry: (ol.geom.Geometry | ol.render.Feature)): void; - /** + /** * Render a feature into the canvas. Note that any `zIndex` on the provided * style will be ignored - features are rendered immediately in the order that * this method is called. If you need `zIndex` support, you should be using an @@ -7988,7 +7994,7 @@ declare module ol { * @param {ol.Feature} feature Feature. * @param {ol.style.Style} style Style. * @api - */ + */ drawFeature(feature: ol.Feature, style: ol.style.Style): void; } @@ -8006,7 +8012,7 @@ declare module ol { * @param {?ol.webgl.Context=} opt_glContext WebGL Context. */ class Event extends ol.events.Event { - /** + /** * @constructor * @extends {ol.events.Event} * @implements {oli.render.Event} @@ -8015,37 +8021,37 @@ declare module ol { * @param {olx.FrameState=} opt_frameState Frame state. * @param {?CanvasRenderingContext2D=} opt_context Context. * @param {?ol.webgl.Context=} opt_glContext WebGL Context. - */ + */ constructor(type: ol.render.EventType, opt_vectorContext?: ol.render.VectorContext, opt_frameState?: olx.FrameState, opt_context?: CanvasRenderingContext2D, opt_glContext?: any); - /** + /** * For canvas, this is an instance of {@link ol.render.canvas.Immediate}. * @type {ol.render.VectorContext|undefined} * @api - */ + */ vectorContext: ol.render.VectorContext; - /** + /** * An object representing the current render frame state. * @type {olx.FrameState|undefined} * @api - */ + */ frameState: olx.FrameState; - /** + /** * Canvas context. Only available when a Canvas renderer is used, null * otherwise. * @type {CanvasRenderingContext2D|null|undefined} * @api - */ + */ context: CanvasRenderingContext2D; - /** + /** * WebGL context. Only available when a WebGL renderer is used, null * otherwise. * @type {ol.webgl.Context|null|undefined} * @api - */ + */ glContext: any; } @@ -8065,7 +8071,7 @@ declare module ol { * @param {Object.} properties Properties. */ class Feature { - /** + /** * Lightweight, read-only, {@link ol.Feature} and {@link ol.geom.Geometry} like * structure, optimized for rendering and styling. Geometry access through the * API is limited to getting the type and extent of the geometry. @@ -8076,15 +8082,15 @@ declare module ol { * to be right-handed for polygons. * @param {Array.|Array.>} ends Ends or Endss. * @param {Object.} properties Properties. - */ + */ constructor(type: ol.geom.GeometryType, flatCoordinates: number[], ends: (number[] | number[][]), properties: { [k: string]: any }); - /** + /** * Get a feature property by its key. * @param {string} key Key * @return {*} Value for the requested key. * @api - */ + */ get(key: string): any; /** @@ -8158,7 +8164,7 @@ declare module ol { */ function toContext(context: CanvasRenderingContext2D, opt_options?: olx.render.ToContextOptions): ol.render.canvas.Immediate; - } + } /** * Available renderers: `'canvas'`, `'dom'` or `'webgl'`. @@ -8255,7 +8261,7 @@ declare module ol { } - /** + /** * @classdesc * Layer source to cluster vector data. Works out of the box with point * geometries. For other geometry types, or if not all geometries should be @@ -8265,7 +8271,7 @@ declare module ol { * @param {olx.source.ClusterOptions} options Constructor options. * @extends {ol.source.Vector} * @api - */ + */ class Cluster extends ol.source.Vector { /** * @classdesc @@ -8357,7 +8363,7 @@ declare module ol { } - /** + /** * @classdesc * Source for data from ArcGIS Rest services providing single, untiled images. * Useful when underlying map service has labels. @@ -8371,7 +8377,7 @@ declare module ol { * @extends {ol.source.Image} * @param {olx.source.ImageArcGISRestOptions=} opt_options Image ArcGIS Rest Options. * @api - */ + */ class ImageArcGISRest extends ol.source.Image { /** * @classdesc @@ -8435,7 +8441,7 @@ declare module ol { } - /** + /** * @classdesc * Base class for image sources where a canvas element is the image. * @@ -8458,7 +8464,7 @@ declare module ol { } - /** + /** * @classdesc * Source for images from Mapguide servers * @@ -8467,7 +8473,7 @@ declare module ol { * @extends {ol.source.Image} * @param {olx.source.ImageMapGuideOptions} options Options. * @api stable - */ + */ class ImageMapGuide extends ol.source.Image { /** * @classdesc @@ -12646,7 +12652,7 @@ declare module olx { * updateWhileAnimating: (boolean|undefined), * updateWhileInteracting: (boolean|undefined), * visible: (boolean|undefined)}} - */ + */ interface VectorTileOptions { renderBuffer?: number; renderMode?: (ol.layer.VectorTileRenderType | string); @@ -12664,11 +12670,11 @@ declare module olx { } - } + } - /** + /** * @namespace olx.parser - */ + */ module parser { } @@ -12688,7 +12694,7 @@ declare module olx { } - /** + /** * @namespace olx.source */ module source { @@ -13132,7 +13138,7 @@ declare module olx { * url: (string|undefined), * urls: (Array.|undefined), * wrapX: (boolean|undefined)}} - */ + */ interface TileWMSOptions { attributions?: ol.AttributionLike; cacheSize?: number; @@ -13152,7 +13158,7 @@ declare module olx { } - /** + /** * @typedef {{attributions: (ol.AttributionLike|undefined), * features: (Array.|ol.Collection.|undefined), * format: (ol.format.Feature|undefined), @@ -13163,7 +13169,7 @@ declare module olx { * url: (string|ol.FeatureUrlFunction|undefined), * useSpatialIndex: (boolean|undefined), * wrapX: (boolean|undefined)}} - */ + */ interface VectorOptions { attributions?: ol.AttributionLike; features?: (ol.Feature[] | ol.Collection); @@ -13178,7 +13184,7 @@ declare module olx { } - /** + /** * @typedef {{attributions: (ol.AttributionLike|undefined), * cacheSize: (number|undefined), * crossOrigin: (string|null|undefined), @@ -13201,7 +13207,7 @@ declare module olx { * ol.Tile.State, string, ?string, * ol.TileLoadFunctionType)|undefined), * wrapX: (boolean|undefined)}} - */ + */ interface WMTSOptions { attributions?: ol.AttributionLike; cacheSize?: number; @@ -13226,7 +13232,7 @@ declare module olx { } - /** + /** * @typedef {{attributions: (ol.AttributionLike|undefined), * cacheSize: (number|undefined), * crossOrigin: (null|string|undefined), @@ -13244,7 +13250,7 @@ declare module olx { * url: (string|undefined), * urls: (Array.|undefined), * wrapX: (boolean|undefined)}} - */ + */ interface XYZOptions { attributions?: ol.AttributionLike; cacheSize?: number; @@ -13266,7 +13272,7 @@ declare module olx { } - /** + /** * @typedef {{attributions: (ol.AttributionLike|undefined), * cacheSize: (number|undefined), * crossOrigin: (null|string|undefined), @@ -13278,7 +13284,7 @@ declare module olx { * config: (Object|undefined), * map: (string|undefined), * account: string}} - */ + */ interface CartoDBOptions { attributions?: ol.AttributionLike; cacheSize?: number; @@ -13294,7 +13300,7 @@ declare module olx { } - /** + /** * @typedef {{attributions: (ol.AttributionLike|undefined), * cacheSize: (number|undefined), * crossOrigin: (null|string|undefined), @@ -13303,7 +13309,7 @@ declare module olx { * url: !string, * tierSizeCalculation: (string|undefined), * size: ol.Size}} - */ + */ interface ZoomifyOptions { attributions?: ol.AttributionLike; cacheSize?: number; @@ -13318,17 +13324,17 @@ declare module olx { } - /** + /** * @namespace olx.style - */ + */ module style { - /** + /** * @typedef {{fill: (ol.style.Fill|undefined), * radius: number, * snapToPixel: (boolean|undefined), * stroke: (ol.style.Stroke|undefined), * atlasManager: (ol.style.AtlasManager|undefined)}} - */ + */ interface CircleOptions { fill?: ol.style.Fill; radius: number; @@ -13343,7 +13349,7 @@ declare module olx { */ interface FillOptions { color?: (ol.Color | ol.ColorLike); - } + } /** @@ -13386,7 +13392,7 @@ declare module olx { } - /** + /** * Specify radius for regular polygons, or radius1 and radius2 for stars. * @typedef {{fill: (ol.style.Fill|undefined), * points: number, @@ -13399,7 +13405,7 @@ declare module olx { * rotation: (number|undefined), * rotateWithView: (boolean|undefined), * atlasManager: (ol.style.AtlasManager|undefined)}} - */ + */ interface RegularShapeOptions { fill?: ol.style.Fill; points: number; @@ -13412,14 +13418,14 @@ declare module olx { } - /** + /** * @typedef {{color: (ol.Color|string|undefined), * lineCap: (string|undefined), * lineJoin: (string|undefined), * lineDash: (Array.|undefined), * miterLimit: (number|undefined), * width: (number|undefined)}} - */ + */ interface StrokeOptions { color?: ol.Color | string; lineCap?: string; @@ -13430,7 +13436,7 @@ declare module olx { } - /** + /** * @typedef {{font: (string|undefined), * offsetX: (number|undefined), * offsetY: (number|undefined), @@ -13442,7 +13448,7 @@ declare module olx { * textBaseline: (string|undefined), * fill: (ol.style.Fill|undefined), * stroke: (ol.style.Stroke|undefined)}} - */ + */ interface TextOptions { font?: string; offsetX?: number; @@ -13457,14 +13463,14 @@ declare module olx { } - /** + /** * @typedef {{geometry: (undefined|string|ol.geom.Geometry|ol.StyleGeometryFunction), * fill: (ol.style.Fill|undefined), * image: (ol.style.Image|undefined), * stroke: (ol.style.Stroke|undefined), * text: (ol.style.Text|undefined), * zIndex: (number|undefined)}} - */ + */ interface StyleOptions { geometry?: (string | ol.geom.Geometry | ol.StyleGeometryFunction); fill?: ol.style.Fill; @@ -13475,11 +13481,11 @@ declare module olx { } - /** + /** * @typedef {{initialSize: (number|undefined), * maxSize: (number|undefined), * space: (number|undefined)}} - */ + */ interface AtlasManagerOptions { initialSize?: number; maxSize?: number; @@ -13489,11 +13495,11 @@ declare module olx { } - /** + /** * @namespace olx.tilegrid - */ + */ module tilegrid { - /** + /** * @typedef {{extent: (ol.Extent|undefined), * minZoom: (number|undefined), * origin: (ol.Coordinate|undefined), @@ -13502,7 +13508,7 @@ declare module olx { * sizes: (Array.|undefined), * tileSize: (number|ol.Size|undefined), * tileSizes: (Array.|undefined)}} - */ + */ interface TileGridOptions { extent?: ol.Extent; minZoom?: number; @@ -13514,7 +13520,7 @@ declare module olx { } - /** + /** * @typedef {{extent: (ol.Extent|undefined), * origin: (ol.Coordinate|undefined), * origins: (Array.|undefined), @@ -13523,7 +13529,7 @@ declare module olx { * sizes: (Array.|undefined), * tileSize: (number|ol.Size|undefined), * tileSizes: (Array.|undefined)}} - */ + */ interface WMTSOptions { extent?: ol.Extent; origin?: ol.Coordinate; @@ -13548,32 +13554,32 @@ declare module olx { maxZoom?: number; minZoom?: number; tileSize?: (number | ol.Size); - } + } } - /** + /** * @typedef {{html: string, * tileRanges: (Object.>|undefined)}} - */ + */ interface AttributionOptions { html: string; } - /** + /** * @typedef {{tracking: (boolean|undefined)}} - */ + */ interface DeviceOrientationOptions { tracking?: boolean; } - /** + /** * @typedef {{tracking: (boolean|undefined), * trackingOptions: (PositionOptions|undefined), * projection: ol.ProjectionLike}} - */ + */ interface GeolocationOptions { tracking?: boolean; trackingOptions?: PositionOptions; @@ -13686,14 +13692,14 @@ declare module olx { } module view { - /** + /** * @typedef {{ * padding: (!Array.|undefined), * constrainResolution: (boolean|undefined), * nearest: (boolean|undefined), * maxZoom: (number|undefined), * minResolution: (number|undefined)}} - */ + */ interface FitOptions { padding?: number[]; constrainResolution?: boolean; diff --git a/opentype.js/index.d.ts b/opentype.js/index.d.ts new file mode 100644 index 0000000000..24df752461 --- /dev/null +++ b/opentype.js/index.d.ts @@ -0,0 +1,240 @@ +// Type definitions for opentype.js +// Project: https://github.com/nodebox/opentype.js +// Definitions by: Dan Marshall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace opentype; + +interface Contour extends Array { +} + +export class Encoding { + charset: string; + charToGlyphIndex(c: string): number; + font: Font; +} + +interface Field { + name: string; + type: string; + value: any; +} + +export class Font { + private nametoGlyphIndex; + private supported; + constructor(options: FontOptions); + ascender: number; + cffEncoding: Encoding; + charToGlyph(c: string): Glyph; + charToGlyphIndex(s: string): number; + descender: number; + download(): void; + draw(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; + drawMetrics(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; + drawPoints(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; + encoding: Encoding; + forEachGlyph(text: string, x: number, y: number, fontSize: number, options: RenderOptions, callback: { (glyph: Glyph, x: number, y: number, fontSize: number, options?: RenderOptions): void; }): void; + getEnglishName(name: string): string; + getGposKerningValue: { (leftGlyph: Glyph | number, rightGlyph: Glyph | number): number; }; + getKerningValue(leftGlyph: Glyph | number, rightGlyph: Glyph | number): number; + getPath(text: string, x: number, y: number, fontSize: number, options?: RenderOptions): Path; + getPaths(text: string, x: number, y: number, fontSize: number, options?: RenderOptions): Path[]; + glyphs: GlyphSet; + glyphIndexToName(gid: number): string; + glyphNames: GlyphNames; + hasChar(c: string): boolean; + kerningPairs: KerningPairs; + names: FontNames; + nameToGlyph(name: string): Glyph; + nameToGlyphIndex(name: string): number; + numberOfHMetrics: number; + numGlyphs: number; + outlinesFormat: string; + stringToGlyphs(s: string): Glyph[]; + tables: { [tableName: string]: Table; }; + toArrayBuffer(): ArrayBuffer; + toBuffer(): ArrayBuffer; + toTables(): Table; + unitsPerEm: number; + validate(): void; +} + +interface FontNames { + copyright: LocalizedName; + description: LocalizedName; + designer: LocalizedName; + designerURL: LocalizedName; + fontFamily: LocalizedName; + fontSubfamily: LocalizedName; + fullName: LocalizedName; + license: LocalizedName; + licenseURL: LocalizedName; + manufacturer: LocalizedName; + manufacturerURL: LocalizedName; + postScriptName: LocalizedName; + trademark: LocalizedName; + version: LocalizedName; +} + +interface FontOptions { + copyright?: string; + ascender?: number; + descender?: number; + description?: string; + designer?: string; + designerURL?: string; + empty?: boolean; + familyName?: string; + fullName?: string; + glyphs?: Glyph[] | GlyphSet; + license?: string; + licenseURL?: string; + manufacturer?: string; + manufacturerURL?: string; + postScriptName?: string; + styleName?: string; + unitsPerEm?: number; + trademark?: string; + version?: string; +} + +export class Glyph { + private index; + private xMin; + private xMax; + private yMin; + private yMax; + private points; + constructor(options: GlyphOptions); + addUnicode(unicode: number): void; + advanceWidth: number; + bindConstructorValues(options: GlyphOptions): void; + draw(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; + drawMetrics(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; + drawPoints(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; + getContours(): Contour[]; + getMetrics(): Metrics; + getPath(x: number, y: number, fontSize: number): Path; + name: string; + path: Path | { (): Path; }; + unicode: number; + unicodes: number[]; +} + +interface GlyphOptions { + advanceWidth?: number; + index?: number; + font?: Font; + name?: string; + path?: Path; + unicode?: number; + unicodes?: number[]; + xMax?: number; + xMin?: number; + yMax?: number; + yMin?: number; +} + +export class GlyphNames { + private names; + constructor(post: Post); + glyphIndexToName(gid: number): string; + nameToGlyphIndex(name: string): number; +} + +export class GlyphSet { + private font; + private glyphs; + constructor(font: Font, glyphs: Glyph[] | { (): Glyph; }[]); + get(index: number): Glyph; + length: number; + push(index: number, loader: { (): Glyph; }): void; +} + +interface KerningPairs { + [pair: string]: number; +} + +export function load(url: string, callback: { (error: any, font?: Font): void; }): void; + +export function loadSync(url: string): Font; + +interface LocalizedName { + [lang: string]: string; +} + +interface Metrics { + leftSideBearing: number; + rightSideBearing?: number; + xMax: number; + xMin: number; + yMax: number; + yMin: number; +} + +export function parse(buffer: any): Font; + +export class Path { + private fill; + private stroke; + private strokeWidth; + constructor(); + bezierCurveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): void; + close: () => void; + closePath(): void; + commands: PathCommand[]; + curveTo: (x1: number, y1: number, x2: number, y2: number, x: number, y: number) => void; + draw(ctx: CanvasRenderingContext2D): void; + extend(pathOrCommands: Path | PathCommand[]): void; + lineTo(x: number, y: number): void; + moveTo(x: number, y: number): void; + quadraticCurveTo(x1: number, y1: number, x: number, y: number): void; + quadTo: (x1: number, y1: number, x: number, y: number) => void; + toPathData(decimalPlaces: number): string; + toSVG(decimalPlaces: number): string; + unitsPerEm: number; +} + +interface PathCommand { + type: string; + x?: number; + y?: number; + x1?: number; + y1?: number; + x2?: number; + y2?: number; +} + +interface Point { + lastPointOfContour?: boolean; +} + +interface Post { + glyphNameIndex?: number[]; + isFixedPitch: number; + italicAngle: number; + maxMemType1: number; + minMemType1: number; + maxMemType42: number; + minMemType42: number; + names?: string[]; + numberOfGlyphs?: number; + offset?: number[]; + underlinePosition: number; + underlineThickness: number; + version: number; +} + +interface RenderOptions { + kerning: boolean; +} + +interface Table { + [propName: string]: any; + encode(): number[]; + fields: Field[]; + sizeOf(): number; + tables: Table[]; + tableName: string; +} diff --git a/opentype/opentype-tests.ts b/opentype.js/opentype.js-tests.ts similarity index 100% rename from opentype/opentype-tests.ts rename to opentype.js/opentype.js-tests.ts diff --git a/opentype.js/tsconfig.json b/opentype.js/tsconfig.json new file mode 100644 index 0000000000..d46b9ebabf --- /dev/null +++ b/opentype.js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "opentype.js-tests.ts" + ] +} \ No newline at end of file diff --git a/opentype/index.d.ts b/opentype/index.d.ts deleted file mode 100644 index fec42369a1..0000000000 --- a/opentype/index.d.ts +++ /dev/null @@ -1,248 +0,0 @@ -// Type definitions for opentype.js -// Project: https://github.com/nodebox/opentype.js -// Definitions by: Dan Marshall -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace opentypejs { - - interface Contour extends Array { - } - - class Encoding { - charset: string; - charToGlyphIndex(c: string): number; - font: Font; - } - - interface Field { - name: string; - type: string; - value: any; - } - - class Font { - private nametoGlyphIndex; - private supported; - constructor(options: FontOptions); - ascender: number; - cffEncoding: Encoding; - charToGlyph(c: string): Glyph; - charToGlyphIndex(s: string): number; - descender: number; - download(): void; - draw(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; - drawMetrics(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; - drawPoints(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, fontSize: number, options?: RenderOptions): void; - encoding: Encoding; - forEachGlyph(text: string, x: number, y: number, fontSize: number, options: RenderOptions, callback: { (glyph: Glyph, x: number, y: number, fontSize: number, options?: RenderOptions): void; }): void; - getEnglishName(name: string): string; - getGposKerningValue: { (leftGlyph: Glyph | number, rightGlyph: Glyph | number): number; }; - getKerningValue(leftGlyph: Glyph | number, rightGlyph: Glyph | number): number; - getPath(text: string, x: number, y: number, fontSize: number, options?: RenderOptions): Path; - getPaths(text: string, x: number, y: number, fontSize: number, options?: RenderOptions): Path[]; - glyphs: GlyphSet; - glyphIndexToName(gid: number): string; - glyphNames: GlyphNames; - hasChar(c: string): boolean; - kerningPairs: KerningPairs; - names: FontNames; - nameToGlyph(name: string): Glyph; - nameToGlyphIndex(name: string): number; - numberOfHMetrics: number; - numGlyphs: number; - outlinesFormat: string; - stringToGlyphs(s: string): Glyph[]; - tables: { [tableName: string]: Table; }; - toArrayBuffer(): ArrayBuffer; - toBuffer(): ArrayBuffer; - toTables(): Table; - unitsPerEm: number; - validate(): void; - } - - interface FontNames { - copyright: LocalizedName; - description: LocalizedName; - designer: LocalizedName; - designerURL: LocalizedName; - fontFamily: LocalizedName; - fontSubfamily: LocalizedName; - fullName: LocalizedName; - license: LocalizedName; - licenseURL: LocalizedName; - manufacturer: LocalizedName; - manufacturerURL: LocalizedName; - postScriptName: LocalizedName; - trademark: LocalizedName; - version: LocalizedName; - } - - interface FontOptions { - copyright?: string; - ascender?: number; - descender?: number; - description?: string; - designer?: string; - designerURL?: string; - empty?: boolean; - familyName?: string; - fullName?: string; - glyphs?: Glyph[] | GlyphSet; - license?: string; - licenseURL?: string; - manufacturer?: string; - manufacturerURL?: string; - postScriptName?: string; - styleName?: string; - unitsPerEm?: number; - trademark?: string; - version?: string; - } - - class Glyph { - private index; - private xMin; - private xMax; - private yMin; - private yMax; - private points; - constructor(options: GlyphOptions); - addUnicode(unicode: number): void; - advanceWidth: number; - bindConstructorValues(options: GlyphOptions): void; - draw(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; - drawMetrics(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; - drawPoints(ctx: CanvasRenderingContext2D, x: number, y: number, fontSize: number): void; - getContours(): Contour[]; - getMetrics(): Metrics; - getPath(x: number, y: number, fontSize: number): Path; - name: string; - path: Path | { (): Path; }; - unicode: number; - unicodes: number[]; - } - - interface GlyphOptions { - advanceWidth?: number; - index?: number; - font?: Font; - name?: string; - path?: Path; - unicode?: number; - unicodes?: number[]; - xMax?: number; - xMin?: number; - yMax?: number; - yMin?: number; - } - - class GlyphNames { - private names; - constructor(post: Post); - glyphIndexToName(gid: number): string; - nameToGlyphIndex(name: string): number; - } - - class GlyphSet { - private font; - private glyphs; - constructor(font: Font, glyphs: Glyph[] | { (): Glyph; }[]); - get(index: number): Glyph; - length: number; - push(index: number, loader: { (): Glyph; }): void; - } - - interface KerningPairs { - [pair: string]: number; - } - - function load(url: string, callback: { (error: any, font?: Font): void; }): void; - - function loadSync(url: string): Font; - - interface LocalizedName { - [lang: string]: string; - } - - interface Metrics { - leftSideBearing: number; - rightSideBearing?: number; - xMax: number; - xMin: number; - yMax: number; - yMin: number; - } - - function parse(buffer: any): Font; - - class Path { - private fill; - private stroke; - private strokeWidth; - constructor(); - bezierCurveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): void; - close: () => void; - closePath(): void; - commands: PathCommand[]; - curveTo: (x1: number, y1: number, x2: number, y2: number, x: number, y: number) => void; - draw(ctx: CanvasRenderingContext2D): void; - extend(pathOrCommands: Path | PathCommand[]): void; - lineTo(x: number, y: number): void; - moveTo(x: number, y: number): void; - quadraticCurveTo(x1: number, y1: number, x: number, y: number): void; - quadTo: (x1: number, y1: number, x: number, y: number) => void; - toPathData(decimalPlaces: number): string; - toSVG(decimalPlaces: number): string; - unitsPerEm: number; - } - - interface PathCommand { - type: string; - x?: number; - y?: number; - x1?: number; - y1?: number; - x2?: number; - y2?: number; - } - - interface Point { - lastPointOfContour?: boolean; - } - - interface Post { - glyphNameIndex?: number[]; - isFixedPitch: number; - italicAngle: number; - maxMemType1: number; - minMemType1: number; - maxMemType42: number; - minMemType42: number; - names?: string[]; - numberOfGlyphs?: number; - offset?: number[]; - underlinePosition: number; - underlineThickness: number; - version: number; - } - - interface RenderOptions { - kerning: boolean; - } - - interface Table { - [propName: string]: any; - encode(): number[]; - fields: Field[]; - sizeOf(): number; - tables: Table[]; - tableName: string; - } - -} - -declare var opentype: typeof opentypejs; - -declare module "opentype.js" { - export = opentype; -} diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/index.d.ts similarity index 100% rename from passport-local-mongoose/passport-local-mongoose.d.ts rename to passport-local-mongoose/index.d.ts diff --git a/passport-local-mongoose/tsconfig.json b/passport-local-mongoose/tsconfig.json index 96c1a13bf1..a30ca49bbf 100644 --- a/passport-local-mongoose/tsconfig.json +++ b/passport-local-mongoose/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "passport-local-mongoose.d.ts", + "index.d.ts", "passport-local-mongoose-tests.ts" ] } \ No newline at end of file diff --git a/pbf/index.d.ts b/pbf/index.d.ts new file mode 100644 index 0000000000..fdcb9b53ce --- /dev/null +++ b/pbf/index.d.ts @@ -0,0 +1,77 @@ +// Type definitions for pbf 3.0 +// Project: https://github.com/mapbox/pbf +// Definitions by: Christian Schwarz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Pbf { + buf: Uint8Array; + pos: number; + type: number; + length: number; + + constructor(buffer?: Uint8Array); + + destroy(): void; + readFields(readField: (tag: number, result?: T, pbf?: Pbf) => void, result?: T, end?: number): T; + readMessage(readField: (tag: number, result?: T, pbf?: Pbf) => void, result?: T): T; + readFixed32(): number; + readSFixed32(): number; + readFixed64(): number; + readSFixed64(): number; + readFloat(): number; + readDouble(): number; + readVarint(isSigned?: boolean): number; + readVarint64(): number; + readSVarint(): number; + readBoolean(): boolean; + readString(): string; + readBytes(): Uint8Array; + readPackedVarint(arr?: number[], isSigned?: boolean): number[]; + readPackedSVarint(arr?: number[]): number[]; + readPackedBoolean(arr?: boolean[]): boolean[]; + readPackedFloat(arr?: number[]): number[]; + readPackedDouble(arr?: number[]): number[]; + readPackedFixed32(arr?: number[]): number[]; + readPackedSFixed32(arr?: number[]): number[]; + readPackedFixed64(arr?: number[]): number[]; + readPackedSFixed64(arr?: number[]): number[]; + skip(val: number): void; + writeTag(tag: number, type: number): void; + realloc(min: number): void; + finish(): Uint8Array; + writeFixed32(val: number): void; + writeSFixed32(val: number): void; + writeFixed64(val: number): void; + writeSFixed64(val: number): void; + writeVarint(val: number): void; + writeSVarint(val: number): void; + writeBoolean(val: boolean): void; + writeString(str: string): void; + writeFloat(val: number): void; + writeDouble(val: number): void; + writeBytes(buffer: Uint8Array): void; + writeRawMessage(fn: (obj: T, pbf?: Pbf) => void, obj?: T): void; + writeMessage(tag: number, fn: (obj: T, pbf?: Pbf) => void, obj?: T): void; + writePackedVarint(tag: number, arr: number[]): void; + writePackedSVarint(tag: number, arr: number[]): void; + writePackedBoolean(tag: number, arr: boolean[]): void; + writePackedFloat(tag: number, arr: number[]): void; + writePackedDouble(tag: number, arr: number[]): void; + writePackedFixed32(tag: number, arr: number[]): void; + writePackedSFixed32(tag: number, arr: number[]): void; + writePackedFixed64(tag: number, arr: number[]): void; + writePackedSFixed64(tag: number, arr: number[]): void; + writeBytesField(tag: number, buffer: Uint8Array): void; + writeFixed32Field(tag: number, val: number): void; + writeSFixed32Field(tag: number, val: number): void; + writeFixed64Field(tag: number, val: number): void; + writeSFixed64Field(tag: number, val: number): void; + writeVarintField(tag: number, val: number): void; + writeSVarintField(tag: number, val: number): void; + writeStringField(tag: number, str: string): void; + writeFloatField(tag: number, val: number): void; + writeDoubleField(tag: number, val: number): void; + writeBooleanField(tag: number, val: boolean): void; +} + +export = Pbf; diff --git a/pbf/pbf-tests.ts b/pbf/pbf-tests.ts new file mode 100644 index 0000000000..533c183801 --- /dev/null +++ b/pbf/pbf-tests.ts @@ -0,0 +1,88 @@ +import Pbf = require('pbf'); + +var pbf = new Pbf(new Uint8Array(1)); +new Pbf(); +pbf.buf; +pbf.pos; +pbf.type; +pbf.length; +pbf.destroy(); +pbf.readFields(function (tag) {}); +pbf.readFields(function (tag, result) {}); +pbf.readFields(function (tag, result, pbf) {}); +pbf.readFields(function (tag) {}, {}, 1); +pbf.readMessage(function (tag) {}); +pbf.readMessage(function (tag, result) {}); +pbf.readMessage(function (tag, result, pbf) {}); +pbf.readFixed32(); +pbf.readSFixed32(); +pbf.readFixed64(); +pbf.readSFixed64(); +pbf.readFloat(); +pbf.readDouble(); +pbf.readVarint(); +pbf.readVarint(true); +pbf.readVarint64(); +pbf.readSVarint(); +pbf.readBoolean(); +pbf.readString(); +pbf.readBytes(); +pbf.readPackedVarint(); +pbf.readPackedVarint([], true); +pbf.readPackedSVarint(); +pbf.readPackedSVarint([]); +pbf.readPackedBoolean(); +pbf.readPackedBoolean([]); +pbf.readPackedFloat(); +pbf.readPackedFloat([]); +pbf.readPackedDouble(); +pbf.readPackedDouble([]); +pbf.readPackedFixed32(); +pbf.readPackedFixed32([]); +pbf.readPackedSFixed32(); +pbf.readPackedSFixed32([]); +pbf.readPackedFixed64(); +pbf.readPackedFixed64([]); +pbf.readPackedSFixed64(); +pbf.readPackedSFixed64([]); +pbf.skip(1); +pbf.writeTag(1, 2); +pbf.realloc(1); +pbf.finish(); +pbf.writeFixed32(1); +pbf.writeSFixed32(1); +pbf.writeFixed64(1); +pbf.writeSFixed64(1); +pbf.writeVarint(1); +pbf.writeSVarint(1); +pbf.writeBoolean(true); +pbf.writeString(''); +pbf.writeFloat(1); +pbf.writeDouble(1); +pbf.writeBytes(new Uint8Array(1)); +pbf.writeRawMessage(function (obj) {}); +pbf.writeRawMessage(function (obj, pbf) {}); +pbf.writeRawMessage(function (obj) {}, {}); +pbf.writeMessage(1, function (obj) {}); +pbf.writeMessage(1, function (obj, pbf) {}); +pbf.writeMessage(1, function (obj) {}, {}); +pbf.writePackedVarint(1, []); +pbf.writePackedSVarint(1, []); +pbf.writePackedBoolean(1, []); +pbf.writePackedFloat(1, []); +pbf.writePackedDouble(1, []); +pbf.writePackedFixed32(1, []); +pbf.writePackedSFixed32(1, []); +pbf.writePackedFixed64(1, []); +pbf.writePackedSFixed64(1, []); +pbf.writeBytesField(1, new Uint8Array(1)); +pbf.writeFixed32Field(1, 2); +pbf.writeSFixed32Field(1, 2); +pbf.writeFixed64Field(1, 2); +pbf.writeSFixed64Field(1, 2); +pbf.writeVarintField(1, 2); +pbf.writeSVarintField(1, 2); +pbf.writeStringField(1, ''); +pbf.writeFloatField(1, 2); +pbf.writeDoubleField(1, 2); +pbf.writeBooleanField(1, true); \ No newline at end of file diff --git a/pbf/tsconfig.json b/pbf/tsconfig.json new file mode 100644 index 0000000000..640b85fc41 --- /dev/null +++ b/pbf/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pbf-tests.ts" + ] +} diff --git a/pbf/tslint.json b/pbf/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/pbf/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/phantomcss/index.d.ts b/phantomcss/index.d.ts index 48829a1bbe..9f57e26c46 100644 --- a/phantomcss/index.d.ts +++ b/phantomcss/index.d.ts @@ -138,7 +138,7 @@ declare namespace PhantomCSS { prefixCount?: boolean; hideElements?: string; - outputSettings?: Resemble.OutputSettings; + outputSettings?: resemble.OutputSettings; } } diff --git a/pikaday-time/index.d.ts b/pikaday-time/index.d.ts new file mode 100644 index 0000000000..cb31683f82 --- /dev/null +++ b/pikaday-time/index.d.ts @@ -0,0 +1,343 @@ +// Type definitions for pikaday-time +// Project: https://github.com/owenmead/Pikaday +// Definitions by: Sayan Pal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as moment from 'moment'; + +export as namespace Pikaday; + +export = Pikaday; + +declare class Pikaday { + el: HTMLElement; + + constructor(options: Pikaday.PikadayOptions); + + /** + * Extends the existing configuration options for Pikaday object with the options provided. + * Can be used to change/extend the configurations on runtime. + * @param options full/partial configuration options. + * @returns {} extended configurations. + */ + config(options: Pikaday.PikadayOptions): Pikaday.PikadayOptions; + + /** + * Returns the selected date in a string format. If Moment.js exists + * (recommended) then Pikaday can return any format that Moment + * understands, otherwise you're stuck with JavaScript's default. + */ + toString(format?: string): string; + + /** + * Returns a JavaScript Date object for the selected day, or null if + * no date is selected. + */ + getDate(): Date; + + /** + * Set the current selection. This will be restricted within the bounds + * of minDate and maxDate options if they're specified. A boolean (true) + * can optionally be passed as the second parameter to prevent triggering + * of the onSelect callback, allowing the date to be set silently. + */ + setDate(date: string | Date, triggerOnSelect?: boolean): void; + + /** + * Returns a Moment.js object for the selected date (Moment must be + * loaded before Pikaday). + */ + getMoment(): moment.Moment; + + /** + * Set the current selection with a Moment.js object (see setDate). + */ + setMoment(moment: any): void; + + /** + * Change the current view to see a specific date. + */ + gotoDate(date: Date): void; + + /** + * Shortcut for picker.gotoDate(new Date()) + */ + gotoToday(): void; + + /** + * Change the current view by month (0: January, 1: Februrary, etc). + */ + gotoMonth(monthIndex: number): void; + + /** + * Go to the next month (this will change year if necessary). + */ + nextMonth(): void; + + /** + * Go to the previous month (this will change year if necessary). + */ + prevMonth(): void; + + /** + * Change the year being viewed. + */ + gotoYear(year: number): void; + + /** + * Update the minimum/earliest date that can be selected. + */ + setMinDate(date: Date): void; + + /** + * Update the maximum/latest date that can be selected. + */ + setMaxDate(date: Date): void; + + /** + * Update the range start date. For using two Pikaday instances to + * select a date range. + */ + setStartRange(date: Date): void; + + /** + * Update the range end date. For using two Pikaday instances to select + * a date range. + */ + setEndRange(date: Date): void; + + /** + * Update the HTML. + */ + draw(force: boolean): void; + + /** + * Returns true if the picker is visible. + */ + isVisible(): boolean; + + /** + * Make the picker visible. + */ + show(): void; + + /** + * Hide the picker making it invisible. + */ + hide(): void; + + /** + * Recalculate and change the position of the picker. + */ + adjustPosition(): void; + + /** + * Hide the picker and remove all event listeners - no going back! + */ + destroy(): void; +} + +// merge the Pikaday class declaration with a module +declare namespace Pikaday { + interface PikadayI18nConfig { + previousMonth: string; + nextMonth: string; + months: string[]; + weekdays: string[]; + weekdaysShort: string[]; + } + + interface PikadayOptions { + /** + * Bind the datepicker to a form field. + */ + field?: HTMLElement; + + /** + * The default output format for toString() and field value. + * Requires Moment.js for custom formatting. + */ + format?: string; + + /** + * Use a different element to trigger opening the datepicker. + * Default: field element. + */ + trigger?: HTMLElement; + + /** + * Automatically show/hide the datepicker on field focus. + * Default: true if field is set. + */ + bound?: boolean; + + /** + * Preferred position of the datepicker relative to the form field + * (e.g. 'top right'). Automatic adjustment may occur to avoid + * displaying outside the viewport. Default: 'bottom left'. + */ + position?: string; + + /** + * Can be set to false to not reposition the datepicker within the + * viewport, forcing it to take the configured position. Default: true. + */ + reposition?: boolean; + + /** + * DOM node to render calendar into, see container example. + * Default: undefined. + */ + container?: HTMLElement; + + /** + * The initial date to view when first opened. + */ + defaultDate?: Date; + + /** + * Make the defaultDate the initial selected value. + */ + setDefaultDate?: boolean; + + /** + * First day of the week (0: Sunday, 1: Monday, etc). + */ + firstDay?: number; + + /** + * The earliest date that can be selected (this should be a native + * Date object - e.g. new Date() or moment().toDate()). + */ + minDate?: Date; + + /** + * The latest date that can be selected (this should be a native + * Date object - e.g. new Date() or moment().toDate()). + */ + maxDate?: Date; + + /** + * Disallow selection of Saturdays and Sundays. + */ + disableWeekends?: boolean; + + /** + * Callback function that gets passed a Date object for each day + * in view. Should return true to disable selection of that day. + */ + disableDayFn?: (date: Date) => boolean; + + /** + * Number of years either side (e.g. 10) or array of upper/lower range + * (e.g. [1900, 2015]). + */ + yearRange?: number | number[]; + + /** + * Show the ISO week number at the head of the row. Default: false. + */ + showWeekNumber?: boolean; + + /** + * Reverse the calendar for right-to-left languages. Default: false. + */ + isRTL?: boolean; + + /** + * Language defaults for month and weekday names. + */ + i18n?: PikadayI18nConfig; + + /** + * Additional text to append to the year in the title. + */ + yearSuffix?: string; + + /** + * Render the month after the year in the title. Default: false. + */ + showMonthAfterYear?: boolean; + + /** + * Render days of the calendar grid that fall in the next or previous months to the current month instead of rendering an empty table cell. Default: false. + */ + showDaysInNextAndPreviousMonths?: boolean; + + /** + * Number of visible calendars. + */ + numberOfMonths?: number; + + /** + * When numberOfMonths is used, this will help you to choose where the + * main calendar will be (default left, can be set to right). Only used + * for the first display or when a selected date is not already visible. + */ + mainCalendar?: string; + + /** + * Define a class name that can be used as a hook for styling different + * themes. Default: null. + */ + theme?: string; + + /** + * Callback function for when a date is selected. + */ + onSelect?: (date: Date) => void; + + /** + * Callback function for when the picker becomes visible. + */ + onOpen?: () => void; + + /** + * Callback function for when the picker is hidden. + */ + onClose?: () => void; + + /** + * Callback function for when the picker draws a new month. + */ + onDraw?: () => void; + + /*--pikaday-time specific addition--*/ + /** + * Optional boolean property to specify whether to show time controls with calendar or not. + */ + showTime?: boolean; + /** + * Optional boolean property to specify whether to show minute controls with calendar or not. + */ + showMinutes?: boolean; + /** + * Optional boolean property to specify whether to show second controls with calendar or not. + */ + showSeconds?: boolean; + /** + * Optional boolean property to specify whether to use 24 hours format or not. + */ + use24hour?: boolean; + /** + * Optional numeric property to specify the increment step for hour. + */ + incrementHourBy?: number; + /** + * Optional numeric property to specify the increment step for minute. + */ + incrementMinuteBy?: number; + /** + * Optional numeric property to specify the increment step for second. + */ + incrementSecondBy?: number; + /** + * Optional numeric property to prevent calendar from auto-closing after date is selected. + */ + autoClose?: boolean; + /** + * Optional string added to left of time select + */ + timeLabel?: string; + } +} diff --git a/pikaday-time/package.json b/pikaday-time/package.json new file mode 100644 index 0000000000..d33ff913ce --- /dev/null +++ b/pikaday-time/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "moment": ">=2.14.0" + } +} diff --git a/pikaday-time/pikaday-time-tests.ts b/pikaday-time/pikaday-time-tests.ts new file mode 100644 index 0000000000..d118639229 --- /dev/null +++ b/pikaday-time/pikaday-time-tests.ts @@ -0,0 +1,83 @@ +/// + +import * as Pikaday from "pikaday-time"; +import * as moment from "moment"; + +new Pikaday({field: document.getElementById('datepicker')}); +new Pikaday({field: $('#datepicker')[0]}); + +(() => { + var field:HTMLInputElement = document.getElementById('datepicker'); + var picker = new Pikaday({ + onSelect: function (date:Date) { + field.value = picker.toString(); + console.log(date.toISOString()); + } + }); + field.parentNode.insertBefore(picker.el, field.nextSibling); +})(); + +(() => { + var picker = new Pikaday({ + field: document.getElementById('datepicker'), + format: 'D MMM YYYY', + onSelect: function () { + console.log(this.getMoment().format('Do MMMM YYYY')); + } + }); + + picker.toString(); + picker.toString('YYYY-MM-DD'); + picker.getDate(); + picker.setDate('2015-01-01'); + picker.getMoment(); + picker.setMoment(moment('14th February 2014', 'DDo MMMM YYYY')); + picker.gotoDate(new Date(2014, 1)); + picker.gotoToday(); + picker.gotoMonth(2); + picker.nextMonth(); + picker.prevMonth(); + picker.gotoYear(2015); + picker.setMinDate(new Date); + picker.setMaxDate(new Date); + picker.setStartRange(new Date); + picker.setEndRange(new Date); + picker.isVisible(); + picker.show(); + picker.adjustPosition(); + picker.hide(); + picker.destroy(); +})(); + +(() => { + var i18n: Pikaday.PikadayI18nConfig = { + previousMonth: 'Previous Month', + nextMonth: 'Next Month', + months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + weekdaysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] + }; + new Pikaday({i18n}); +})(); + +(() => { + new Pikaday( + { + field: document.getElementById('datepicker'), + firstDay: 1, + minDate: new Date('2000-01-01'), + maxDate: new Date('2020-12-31'), + yearRange: [2000, 2020] + }); +})(); + +(() => { + new Pikaday( + { + field: document.getElementById('datepicker'), + firstDay: 1, + minDate: new Date('2000-01-01'), + maxDate: new Date('2020-12-31'), + showDaysInNextAndPreviousMonths: true + }); +})(); diff --git a/pikaday-time/tsconfig.json b/pikaday-time/tsconfig.json new file mode 100644 index 0000000000..c4855f97f0 --- /dev/null +++ b/pikaday-time/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pikaday-time-tests.ts" + ] +} diff --git a/pikaday-time/tslint.json b/pikaday-time/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/pikaday-time/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/pino/pino.d.ts b/pino/index.d.ts similarity index 100% rename from pino/pino.d.ts rename to pino/index.d.ts diff --git a/pino/tsconfig.json b/pino/tsconfig.json index d1c0f04972..f80ebefe14 100644 --- a/pino/tsconfig.json +++ b/pino/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "pino.d.ts", + "index.d.ts", "pino-tests.ts" ] } \ No newline at end of file diff --git a/pixi-spine/index.d.ts b/pixi-spine/index.d.ts index 77415c00a8..432b9f6129 100644 --- a/pixi-spine/index.d.ts +++ b/pixi-spine/index.d.ts @@ -1,814 +1,1039 @@ -// Type definitions for pixi-spine 1.0.4 -// Project: https://github.com/pixijs/pixi-spine/ -// Definitions by: martijncroezen +// Type definitions for Pixi-spine v1.3, works with pixi.js v4 +// Project: https://github.com/pixijs/pixi-spine/tree/master +// Definitions by: Ivan Popelyshev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -import * as PIXI from 'pixi.js'; - -declare module 'pixi.js' { - - export module spine { - - export interface Timeline { - - frames: number[]; - - getFrameCount(): number; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; - - } - - export interface Attachment { - - name: string; - type: number; - - } - - export class Animation { - - constructor(name: string, timelines?: Timeline[], duration?: number); - - apply(skeleton: Skeleton, lastTime: number, time: number, loop?: boolean, events?: Event[]): void; - mix(skeleton: Skeleton, lastTime: number, time: number, loop?: boolean, events?: any[], alpha?: number): void; - binarySearch(values: number[], target: number, step: number): number; - binarySearch1(values: number[], target: number): number; - linearSearch(values: number[], target: number, step: number): number; - - name: string; - timelines: Timeline[]; - duration: number; - - } - - export class AnimationState { - - data: AnimationStateData; - tracks: TrackEntry[]; - events: Event[]; - onStart: (index: number) => void; - onEnd: (trackIndex: number) => void; - onComplete: (i: number, count: number) => void; - onEvent: (i: number, event: Event) => void; - timeScale: number; - - constructor(stateData: AnimationStateData); - - update(delta: number): void; - apply(skeleton: Skeleton): void; - clearTracks(): void; - clearTrack(trackIndex: number): void; - private _expandToIndex(index: number): TrackEntry; - setCurrent(index: number, entry: TrackEntry): void; - setAnimationByName(trackIndex: number, animationName: string, loop: boolean): TrackEntry; - setAnimation(trackIndex: number, animation: Animation, loop: boolean): TrackEntry; - addAnimationByName(trackIndex: number, animationName: string, loop: boolean, delay: number): TrackEntry; - addAnimation(trackIndex: number, animation: Animation, loop: boolean, delay: number): TrackEntry; - getCurrent(trackIndex: number): TrackEntry; - - } - - export class Spine extends PIXI.Container { - - constructor(spineData: any); - - static fromAtlas(resourceName: string): Spine; - - update(dt: number): void; - - private autoUpdateTransform(): void; - private createSprite(slot: Slot, attachment: Attachment): Sprite; - private createMesh(slot, attachment) - - spineData: any; - skeleton: Skeleton; - stateData: AnimationStateData; - state: AnimationState; - slotContainers: PIXI.Container[]; - autoUpdate: boolean; - - } - - export class AnimationStateData { - - constructor(skeletonData: SkeletonData); - - private _skelentonData: SkeletonData; - private animationToMixTime: number; - defaultMix: number; - skeletonData: SkeletonData; - setMixByName(fromName: string, toName: string, duration: number): void; - setMix(from: Animation, to: Animation, duration: number): void; - getMix(from: Animation, to: Animation): number; - - } - - export class AttachmentType { - - static region: number; - static boundingbox: number; - static mesh: number; - static skinnedmesh: number; - - } - - export class Bone { - - data: BoneData; - skeleton: Skeleton; - parent: Bone; - - constructor(boneData: BoneData, skeleton: Skeleton, parent: Bone); - - x: number; - y: number; - rotation: number; - rotationIK: number; - scaleX: number; - scaleY: number; - flipX: boolean; - flipY: boolean; - m00: number; - m01: number; - worldX: number; - m10: number; - m11: number; - worldY: number; - worldRotation: number;; - worldScaleX: number; - worldScaleY: number; - worldFlipX: boolean; - worldFlipY: boolean; - - updateWorldTransform(): void; - setToSetupPose(): void; - worldToLocal(world: number[]): void; - localToWorld(local: number[]): void; - - } - - export class BoneData { - - name: string; - parent: Bone; - - constructor(name: string, parent: Bone); - - length: number; - x: number; - y: number; - rotation: number; - scaleX: number; - scaleY: number; - inheritScale: boolean; - inheritRotation: boolean; - flipX: boolean; - flipY: boolean; - - } - - export class BoundingBoxAttachment implements Attachment { - - constructor(name: string); - - name: string; - vertices: number[]; - type: number; - - computeWorldVertices(x: number, y: number, bone: Bone, worldVertices: number[]): void; - - } - - export class ColorTimeline implements Timeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - slotIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; - - } - - export class Curves { - - constructor(frameCount: number[]); - - curves: number[]; - - setLinear(frameIndex: number): void; - setStepped(frameIndex: number): void; - setCurve(frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void; - getCurvePercent(frameIndex: number, percent: number): number; - - } - - export class DrawOrderTimeline implements Timeline { - - constructor(frameCount: number); - - frames: number[]; - drawOrders: number[]; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, drawOrder: number[]): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; - - } - - export class Event { - - constructor(data: any); - - data: any; - intValue: number; - floatValue: number; - stringValue: string; - - } - - export class EventData { - - constructor(name: string); - - name: string; - - intValue: number; - floatValue: number; - stringValue: string; - - } - - export class EventTimeline implements Timeline { - - constructor(frameCount: number); - - frames: number[]; - events: Event[]; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, event: Event): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; - - } - - - export class FfdTimeline implements Timeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - frameVertices: number[]; - slotIndex: number; - attachment: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, vertices: number[]): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; - - } - - export class FlipXTimeline implements Timeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - boneIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, vertices: number[]): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; - - } - - export class FlipYTimeline implements Timeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - boneIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, vertices: number[]): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; - - } - - export class IkConstraint { - - constructor(data: IkConstraintData, skeleton: Skeleton); - - data: IkConstraintData; - mix: number; - bendDirection: number; - bones: Bone[]; - target: Bone; - - apply(): void; - apply1(bone: Bone, targetX: number, targetY: number, alpha: number): void; - apply2(parent: Bone, child: Bone, targetX: number, targetY: number, bendDirection: number, alpha: number): void; - - } - - export class IkConstraintData { - - constructor(name: string); - - name: string; - bones: Bone[]; - target: Bone; - bendDirection: number; - mix: number; - - } - - export class IkConstraintTimeline implements Timeline { - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - ikConstraintIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, mix: number, bendDirection: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; - - } - - export class MeshAttachment implements Attachment { - - constructor(name: string); - - name: string; - type: number; - vertices: number[]; - uvs: number[] - regionUVs: number[] - triangles: number[] - hullLength: number; - r: number; - g: number; - b: number; - a: number; - path: string; - rendererObject: any; - regionU: number; - regionV: number; - regionU2: number; - regionV2: number; - regionRotate: boolean; - regionOffsetX: number; - regionOffsetY: number; - regionWidth: number; - regionHeight: number; - regionOriginalWidth: number; - regionOriginalHeight: number; - edges: number[]; - width: number; - height: number; - - updateUVs(): void; - computeWorldVertices(x: number, y: number, slot: Slot, worldVertices: number[]): void; - - } - - export class RegionAttachment implements Attachment { - - constructor(name: string); - - name: string; - offset: number[]; - uvs: number[] - type: number; - x: number; - y: number; - rotation: number; - scaleX: number; - scaleY: number; - width: number; - height: number; - r: number; - g: number; - b: number; - a: number; - path: string; - rendererObject: any; - regionOffsetX: number; - regionOffsetY: number; - regionWidth: number; - regionHeight: number; - regionOriginalWidth: number; - regionOriginalHeight: number; - - updateOffset(): void; - setUVs(u: number, v: number, u2: number, v2: number, rotate: number): void; - computeVertices(x: number, y: number, bone: Bone, vertices: number[]): void; - - } - - export class RotateTimeline implements Timeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - boneIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, mix: number, bendDirection: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; - - } - - export class ScaleTimeline implements Timeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - boneIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, mix: number, bendDirection: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; - - } - - export class Skeleton { - - constructor(skeletonData: SkeletonData); - - data: SkeletonData; - bones: Bone[]; - slots: Slot[]; - drawOrder: Slot[]; - ikConstraints: IkConstraint[]; - boneCache: Bone[][]; - x: number; - y: number; - skin: Skin; - r: number; - g: number; - b: number; - a: number; - time: number; - flipX: boolean; - flipY: boolean; - - updateCache(): void; - updateWorldTransform(): void; - setToSetupPose(): void; - setBonesToSetupPose(): void; - setSlotsToSetupPose(): void; - getRootBone(): Bone; - findBone(boneName: string): Bone; - findBoneIndex(boneName: string): number; - findSlot(slotName: string): Slot; - findSlotIndex(slotName: string): number; - setSkinByName(skinName: string): Skin; - setSkin(newSkin: Skin): void; - getAttachmentBySlotName(slotName: string, attachmentName: string): Attachment; - getAttachmentBySlotIndex(slotIndex: number, attachmentName: string): Attachment - setAttachment(slotName: string, attachmentName: string): void; - findIkConstraint(ikConstraintName: string): IkConstraint; - update(delta: number): void; - resetDrawOrder(): void; - - } - - export class SkeletonBounds { - - polygonPool: Polygon[]; - polygons: Polygon[]; - boundingBoxes: BoundingBoxAttachment[]; - minX: number; - minY: number; - maxX: number; - maxY: number; - - update(skeleton: Skeleton, updateAabb: boolean): void; - aabbCompute(): void; - aabbContainsPoint(x: number, y: number): void; - aabbIntersectsSegment(x1: number, y1: number, x2: number, y2: number): boolean; - aabbIntersectsSkeleton(bounds: SkeletonBounds): boolean; - containsPoint(x: number, y: number): BoundingBoxAttachment; - intersectsSegment(x1: number, y1: number, x2: number, y2: number): BoundingBoxAttachment; - polygonContainsPoint(polygon: Polygon, x: number, y: number): boolean; - polygonIntersectsSegment(polygon: Polygon, x1: number, y1: number, x2: number, y2: number): boolean; - getPolygon(attachment: Attachment): Polygon; - getWidth(): number; - getHeight(): number; - - } - - export class SkeletonData { - - bones: Bone[]; - slots: Slot[]; - skins: Skin[]; - events: Event[]; - animations: Animation[]; - ikConstraints: IkConstraint[]; - name: string; - defaultSkin: Skin; - width: number; - height: number; - version: any; - hash: any; - - findBone(boneName: string): Bone; - findBoneIndex(boneName: string): number; - findSlot(slotName: string): Slot; - findSlotIndex(slotName: string): number; - findSkin(skinName: string): Skin; - findEvent(eventName: string): Event; - findAnimation(animationName: string): Animation - findIkConstraint(ikConstraintName: string): IkConstraint; - - } - - export class SkeletonJsonParser { - - constructor(attachmentLoader: any); - - attachmentLoader: any; - scale: number; - - readSkeletonData(root: Bone, name: string): void; - readAttachment(skin: Skin, name: string, map: any): void; - readAnimation(name: string, map: any, skeletonData: SkeletonData): void; - readCurve(timeline: Timeline, frameIndex: number, valueMap: any): void; - toColor(hexString: string, colorIndex: string): number; - getFloatArray(map: any, name: string, scale: number): number[]; - getIntArray(map: any, name: string): number[]; - - } - - export class Skin { - - constructor(name: string); - - name: string; - attachments: Attachment[]; - addAttachment(slotIndex: number, name: string, attachment: Attachment): void; - getAttachment(slotIndex: number, name: string): Attachment; - - protected _attachAll(skeleton: Skeleton, oldSkin: Skin): void; - - } - - export class SkinnedMeshAttachment implements Attachment { - - constructor(name: string); - - name: string; - type: number; - bones: number[]; - weights: number[]; - uvs: number[]; - regionUVs: number[]; - triangles: number[]; - hullLength: number; - r: number; - g: number; - b: number; - a: number; - path: string; - rendererObject: any; - regionU: number; - regionV: number; - regionU2: number; - regionV2: number; - regionRotate: boolean; - regionOffsetX: number; - regionOffsetY: number; - regionWidth: number; - regionHeight: number; - regionOriginalWidth: number; - regionOriginalHeight: number; - edges: number[]; - width: number; - height: number; - - updateUVs(u: number, v: number, u2: number, v2: number, rotate: boolean): void; - computeWorldVertices(x: number, y: number, slot: Slot, worldVertices: number[]): void; - - } - - export class Slot { - - constructor(slotData: SlotData, bone: Bone); - - data: SlotData; - bone: Bone; - r: number; - g: number; - b: number; - a: number; - _attachmentTime: number; - attachment: Attachment; - attachmentVertices: number[]; - setAttachment(attachment: Attachment): void; - setAttachmentTime(time: number): void; - getAttachmentTime(): number; - setToSetupPose(): void; - - } - - export class SlotData { - - constructor(name: string, boneData: BoneData); - - name: string; - boneData: BoneData; - - static PIXI_BLEND_MODE_MAP: { - multiply: number; - screen: number; - additive: number; - normal: number; - }; - r: number; - g: number; - b: number; - a: number; - attachmentName: string; - blendMode: number; - - } - - export class TrackEntry { - - next: TrackEntry; - previous: TrackEntry; - animation: Animation; - loop: boolean; - delay: number; - time: number; - lastTime: number; - endTime: number; - timeScale: number; - mixTime: number; - mixDuration: number; - mix: number; - onStart: (index: number) => void; - onEnd: (trackIndex: number) => void; - onComplete: (i: number, count: number) => void; - onEvent: (i: number, event: Event) => void; - - } - - export class TranslateTimeline implements Timeline { - - constructor(frameCount: number); - - curves: Curves[]; - frames: number[]; - boneIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, x: number, y: number): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; - - } - - export class Atlas { - - constructor(atlasText: string, baseUrl: string, crossOrigin: any); - - pages: AtlasPage[]; - regions: AtlasRegion[]; - texturesLoading: number; - - findRegion(name: string): AtlasRegion; - dispose(): void; - updateUVs(page: AtlasPage): void; - - Format: { - - alpha: number; - intensity: number; - luminanceAlpha: number; - rgb565: number; - rgba4444: number; - rgb888: number; - rgba8888: number; - - }; - - TextureFilter: { - - nearest: number; - linear: number; - mipMap: number; - mipMapNearestNearest: number; - mipMapLinearNearest: number; - mipMapNearestLinear: number; - mipMapLinearLinear: number; - - }; - - TextureWrap: { - - mirroredRepeat: number; - clampToEdge: number; - repeat: number; - - }; - - } - - export class AtlasAttachmentParser { - - constructor(atlas: Atlas); - - newRegionAttachment(skin: Skin, name: string, path: string): RegionAttachment; - newMeshAttachment(skin: Skin, name: string, path: string): SkinnedMeshAttachment; - newSkinnedMeshAttachment(skin: Skin, name: string, path: string): SkinnedMeshAttachment; - newBoundingBoxAttachment(skin: Skin, name: string): BoundingBoxAttachment; - - } - - export class AtlasPage { - name: string; - format: any; - minFilter: any; - magFilter: any; - uWrap: any; - vWrap: any; - rendererObject: any; - width: number; - height: number; - - } - - export class AtlasReader { - constructor(text: string); - - lines: string[]; - index: number; - - trim(value: string): string; - readLine(): string; - readValue(): string; - readTuple(tuple: number): number; - - } - - export class AtlasRegion { - - page: AtlasPage; - name: string; - x: number; - y: number; - width: number; - height: number; - u: number; - v: number; - u2: number; - v2: number; - offsetX: number; - offsetY: number; - originalWidth: number; - originalHeight: number; - index: number; - rotate: boolean; - splits: any; - pads: any; - - - } - - export class AttachmentTimeline implements Timeline { - - constructor(frameCount: number); - - slotIndex: number; - frames: number[]; - attachmentNames: string[]; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, attachmentName: string): void; - apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; - - } - - export class atlasParser { - - constructor(resource: any, next: any); - - AnimCache: any; - enableCaching: boolean; - - } - +declare module PIXI.spine.core { + class Animation { + name: string; + timelines: Array; + duration: number; + constructor(name: string, timelines: Array, duration: number); + apply(skeleton: Skeleton, lastTime: number, time: number, loop: boolean, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + static binarySearch(values: ArrayLike, target: number, step?: number): number; + static linearSearch(values: ArrayLike, target: number, step: number): number; + } + interface Timeline { + apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + getPropertyId(): number; + } + enum TimelineType { + rotate = 0, + translate = 1, + scale = 2, + shear = 3, + attachment = 4, + color = 5, + deform = 6, + event = 7, + drawOrder = 8, + ikConstraint = 9, + transformConstraint = 10, + pathConstraintPosition = 11, + pathConstraintSpacing = 12, + pathConstraintMix = 13, + } + abstract class CurveTimeline implements Timeline { + static LINEAR: number; + static STEPPED: number; + static BEZIER: number; + static BEZIER_SIZE: number; + private curves; + abstract getPropertyId(): number; + constructor(frameCount: number); + getFrameCount(): number; + setLinear(frameIndex: number): void; + setStepped(frameIndex: number): void; + getCurveType(frameIndex: number): number; + setCurve(frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void; + getCurvePercent(frameIndex: number, percent: number): number; + abstract apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class RotateTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_ROTATION: number; + static ROTATION: number; + boneIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, degrees: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class TranslateTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_X: number; + static PREV_Y: number; + static X: number; + static Y: number; + boneIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, x: number, y: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class ScaleTimeline extends TranslateTimeline { + constructor(frameCount: number); + getPropertyId(): number; + apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class ShearTimeline extends TranslateTimeline { + constructor(frameCount: number); + getPropertyId(): number; + apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class ColorTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_R: number; + static PREV_G: number; + static PREV_B: number; + static PREV_A: number; + static R: number; + static G: number; + static B: number; + static A: number; + slotIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class AttachmentTimeline implements Timeline { + slotIndex: number; + frames: ArrayLike; + attachmentNames: Array; + constructor(frameCount: number); + getPropertyId(): number; + getFrameCount(): number; + setFrame(frameIndex: number, time: number, attachmentName: string): void; + apply(skeleton: Skeleton, lastTime: number, time: number, events: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class DeformTimeline extends CurveTimeline { + slotIndex: number; + attachment: VertexAttachment; + frames: ArrayLike; + frameVertices: Array>; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, vertices: ArrayLike): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class EventTimeline implements Timeline { + frames: ArrayLike; + events: Array; + constructor(frameCount: number); + getPropertyId(): number; + getFrameCount(): number; + setFrame(frameIndex: number, event: Event): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class DrawOrderTimeline implements Timeline { + frames: ArrayLike; + drawOrders: Array>; + constructor(frameCount: number); + getPropertyId(): number; + getFrameCount(): number; + setFrame(frameIndex: number, time: number, drawOrder: Array): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class IkConstraintTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_MIX: number; + static PREV_BEND_DIRECTION: number; + static MIX: number; + static BEND_DIRECTION: number; + ikConstraintIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, mix: number, bendDirection: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class TransformConstraintTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_ROTATE: number; + static PREV_TRANSLATE: number; + static PREV_SCALE: number; + static PREV_SHEAR: number; + static ROTATE: number; + static TRANSLATE: number; + static SCALE: number; + static SHEAR: number; + transformConstraintIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, rotateMix: number, translateMix: number, scaleMix: number, shearMix: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class PathConstraintPositionTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_VALUE: number; + static VALUE: number; + pathConstraintIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, value: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class PathConstraintSpacingTimeline extends PathConstraintPositionTimeline { + constructor(frameCount: number); + getPropertyId(): number; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } + class PathConstraintMixTimeline extends CurveTimeline { + static ENTRIES: number; + static PREV_TIME: number; + static PREV_ROTATE: number; + static PREV_TRANSLATE: number; + static ROTATE: number; + static TRANSLATE: number; + pathConstraintIndex: number; + frames: ArrayLike; + constructor(frameCount: number); + getPropertyId(): number; + setFrame(frameIndex: number, time: number, rotateMix: number, translateMix: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Array, alpha: number, setupPose: boolean, mixingOut: boolean): void; + } +} +declare module PIXI.spine.core { + class AnimationState { + static emptyAnimation: Animation; + data: AnimationStateData; + tracks: TrackEntry[]; + events: Event[]; + listeners: AnimationStateListener2[]; + queue: EventQueue; + propertyIDs: IntSet; + animationsChanged: boolean; + timeScale: number; + trackEntryPool: Pool; + constructor(data: AnimationStateData); + update(delta: number): void; + updateMixingFrom(entry: TrackEntry, delta: number, canEnd: boolean): void; + apply(skeleton: Skeleton): void; + applyMixingFrom(entry: TrackEntry, skeleton: Skeleton): number; + applyRotateTimeline(timeline: Timeline, skeleton: Skeleton, time: number, alpha: number, setupPose: boolean, timelinesRotation: Array, i: number, firstFrame: boolean): void; + queueEvents(entry: TrackEntry, animationTime: number): void; + clearTracks(): void; + clearTrack(trackIndex: number): void; + setCurrent(index: number, current: TrackEntry): void; + setAnimation(trackIndex: number, animationName: string, loop: boolean): TrackEntry; + setAnimationWith(trackIndex: number, animation: Animation, loop: boolean): TrackEntry; + addAnimation(trackIndex: number, animationName: string, loop: boolean, delay: number): TrackEntry; + addAnimationWith(trackIndex: number, animation: Animation, loop: boolean, delay: number): TrackEntry; + setEmptyAnimation(trackIndex: number, mixDuration: number): TrackEntry; + addEmptyAnimation(trackIndex: number, mixDuration: number, delay: number): TrackEntry; + setEmptyAnimations(mixDuration: number): void; + expandToIndex(index: number): TrackEntry; + trackEntry(trackIndex: number, animation: Animation, loop: boolean, last: TrackEntry): TrackEntry; + disposeNext(entry: TrackEntry): void; + _animationsChanged(): void; + setTimelinesFirst(entry: TrackEntry): void; + checkTimelinesFirst(entry: TrackEntry): void; + checkTimelinesUsage(entry: TrackEntry, usageArray: Array): void; + getCurrent(trackIndex: number): TrackEntry; + addListener(listener: AnimationStateListener2): void; + removeListener(listener: AnimationStateListener2): void; + clearListeners(): void; + clearListenerNotifications(): void; + onComplete: (trackIndex: number, loopCount: number) => any; + onEvent: (trackIndex: number, event: Event) => any; + onStart: (trackIndex: number) => any; + onEnd: (trackIndex: number) => any; + private static deprecatedWarning1; + setAnimationByName(trackIndex: number, animationName: string, loop: boolean): void; + private static deprecatedWarning2; + addAnimationByName(trackIndex: number, animationName: string, loop: boolean, delay: number): void; + private static deprecatedWarning3; + hasAnimationByName(animationName: string): boolean; + } + class TrackEntry { + animation: Animation; + next: TrackEntry; + mixingFrom: TrackEntry; + listener: AnimationStateListener2; + trackIndex: number; + loop: boolean; + eventThreshold: number; + attachmentThreshold: number; + drawOrderThreshold: number; + animationStart: number; + animationEnd: number; + animationLast: number; + nextAnimationLast: number; + delay: number; + trackTime: number; + trackLast: number; + nextTrackLast: number; + trackEnd: number; + timeScale: number; + alpha: number; + mixTime: number; + mixDuration: number; + mixAlpha: number; + timelinesFirst: boolean[]; + timelinesRotation: number[]; + reset(): void; + getAnimationTime(): number; + setAnimationLast(animationLast: number): void; + isComplete(): boolean; + resetRotationDirections(): void; + onComplete: (trackIndex: number, loopCount: number) => any; + onEvent: (trackIndex: number, event: Event) => any; + onStart: (trackIndex: number) => any; + onEnd: (trackIndex: number) => any; + private static deprecatedWarning1; + private static deprecatedWarning2; + time: number; + endTime: number; + loopsCount(): number; + } + class EventQueue { + objects: Array; + drainDisabled: boolean; + animState: AnimationState; + constructor(animState: AnimationState); + start(entry: TrackEntry): void; + interrupt(entry: TrackEntry): void; + end(entry: TrackEntry): void; + dispose(entry: TrackEntry): void; + complete(entry: TrackEntry): void; + event(entry: TrackEntry, event: Event): void; + private static deprecatedWarning1; + deprecateStuff(): boolean; + drain(): void; + clear(): void; + } + enum EventType { + start = 0, + interrupt = 1, + end = 2, + dispose = 3, + complete = 4, + event = 5, + } + interface AnimationStateListener2 { + start(entry: TrackEntry): void; + interrupt(entry: TrackEntry): void; + end(entry: TrackEntry): void; + dispose(entry: TrackEntry): void; + complete(entry: TrackEntry): void; + event(entry: TrackEntry, event: Event): void; + } + abstract class AnimationStateAdapter2 implements AnimationStateListener2 { + start(entry: TrackEntry): void; + interrupt(entry: TrackEntry): void; + end(entry: TrackEntry): void; + dispose(entry: TrackEntry): void; + complete(entry: TrackEntry): void; + event(entry: TrackEntry, event: Event): void; + } +} +declare module PIXI.spine.core { + class AnimationStateData { + skeletonData: SkeletonData; + animationToMixTime: Map; + defaultMix: number; + constructor(skeletonData: SkeletonData); + setMix(fromName: string, toName: string, duration: number): void; + private static deprecatedWarning1; + setMixByName(fromName: string, toName: string, duration: number): void; + setMixWith(from: Animation, to: Animation, duration: number): void; + getMix(from: Animation, to: Animation): number; + } +} +declare module PIXI.spine.core { + class AtlasAttachmentLoader implements AttachmentLoader { + atlas: TextureAtlas; + constructor(atlas: TextureAtlas); + newRegionAttachment(skin: Skin, name: string, path: string): RegionAttachment; + newMeshAttachment(skin: Skin, name: string, path: string): MeshAttachment; + newBoundingBoxAttachment(skin: Skin, name: string): BoundingBoxAttachment; + newPathAttachment(skin: Skin, name: string): PathAttachment; + } +} +declare module PIXI.spine.core { + abstract class Attachment { + name: string; + constructor(name: string); + } + abstract class VertexAttachment extends Attachment { + bones: Array; + vertices: ArrayLike; + worldVerticesLength: number; + constructor(name: string); + computeWorldVertices(slot: Slot, worldVertices: ArrayLike): void; + computeWorldVerticesWith(slot: Slot, start: number, count: number, worldVertices: ArrayLike, offset: number): void; + applyDeform(sourceAttachment: VertexAttachment): boolean; + } +} +declare module PIXI.spine.core { + interface AttachmentLoader { + newRegionAttachment(skin: Skin, name: string, path: string): RegionAttachment; + newMeshAttachment(skin: Skin, name: string, path: string): MeshAttachment; + newBoundingBoxAttachment(skin: Skin, name: string): BoundingBoxAttachment; + newPathAttachment(skin: Skin, name: string): PathAttachment; + } +} +declare module PIXI.spine.core { + enum AttachmentType { + Region = 0, + BoundingBox = 1, + Mesh = 2, + LinkedMesh = 3, + Path = 4, + } +} +declare module PIXI.spine.core { + class BoundingBoxAttachment extends VertexAttachment { + color: Color; + constructor(name: string); + } +} +declare module PIXI.spine.core { + class MeshAttachment extends VertexAttachment { + region: TextureRegion; + path: string; + regionUVs: ArrayLike; + triangles: Array; + color: Color; + hullLength: number; + private parentMesh; + inheritDeform: boolean; + tempColor: Color; + constructor(name: string); + updateWorldVertices(slot: Slot, premultipliedAlpha: boolean): ArrayLike; + updateUVs(region: TextureRegion, uvs: ArrayLike): ArrayLike; + applyDeform(sourceAttachment: VertexAttachment): boolean; + getParentMesh(): MeshAttachment; + setParentMesh(parentMesh: MeshAttachment): void; + } +} +declare module PIXI.spine.core { + class PathAttachment extends VertexAttachment { + lengths: Array; + closed: boolean; + constantSpeed: boolean; + color: Color; + constructor(name: string); + } +} +declare module PIXI.spine.core { + class RegionAttachment extends Attachment { + x: number; + y: number; + scaleX: number; + scaleY: number; + rotation: number; + width: number; + height: number; + color: Color; + path: string; + region: TextureRegion; + constructor(name: string); + updateWorldVertices(slot: Slot, premultipliedAlpha: boolean): ArrayLike; + } +} +declare module PIXI.spine.core { + enum BlendMode { + Normal = 0, + Additive = 1, + Multiply = 2, + Screen = 3, + } +} +declare module PIXI.spine.core { + class Bone implements Updatable { + static yDown: boolean; + matrix: Matrix; + readonly worldX: number; + readonly worldY: number; + data: BoneData; + skeleton: Skeleton; + parent: Bone; + children: Bone[]; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + shearX: number; + shearY: number; + ax: number; + ay: number; + arotation: number; + ascaleX: number; + ascaleY: number; + ashearX: number; + ashearY: number; + appliedValid: boolean; + sorted: boolean; + constructor(data: BoneData, skeleton: Skeleton, parent: Bone); + update(): void; + updateWorldTransform(): void; + updateWorldTransformWith(x: number, y: number, rotation: number, scaleX: number, scaleY: number, shearX: number, shearY: number): void; + setToSetupPose(): void; + getWorldRotationX(): number; + getWorldRotationY(): number; + getWorldScaleX(): number; + getWorldScaleY(): number; + worldToLocalRotationX(): number; + worldToLocalRotationY(): number; + rotateWorld(degrees: number): void; + updateAppliedTransform(): void; + worldToLocal(world: Vector2): Vector2; + localToWorld(local: Vector2): Vector2; + } +} +declare module PIXI.spine.core { + class BoneData { + index: number; + name: string; + parent: BoneData; + length: number; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + shearX: number; + shearY: number; + transformMode: TransformMode; + constructor(index: number, name: string, parent: BoneData); + } + enum TransformMode { + Normal = 0, + OnlyTranslation = 1, + NoRotationOrReflection = 2, + NoScale = 3, + NoScaleOrReflection = 4, + } +} +declare module PIXI.spine.core { + interface Constraint extends Updatable { + getOrder(): number; + } +} +declare module PIXI.spine.core { + class Event { + data: EventData; + intValue: number; + floatValue: number; + stringValue: string; + time: number; + constructor(time: number, data: EventData); + } +} +declare module PIXI.spine.core { + class EventData { + name: string; + intValue: number; + floatValue: number; + stringValue: string; + constructor(name: string); + } +} +declare module PIXI.spine.core { + class IkConstraint implements Constraint { + data: IkConstraintData; + bones: Array; + target: Bone; + mix: number; + bendDirection: number; + level: number; + constructor(data: IkConstraintData, skeleton: Skeleton); + getOrder(): number; + apply(): void; + update(): void; + apply1(bone: Bone, targetX: number, targetY: number, alpha: number): void; + apply2(parent: Bone, child: Bone, targetX: number, targetY: number, bendDir: number, alpha: number): void; + } +} +declare module PIXI.spine.core { + class IkConstraintData { + name: string; + order: number; + bones: BoneData[]; + target: BoneData; + bendDirection: number; + mix: number; + constructor(name: string); + } +} +declare module PIXI.spine.core { + class PathConstraint implements Constraint { + static NONE: number; + static BEFORE: number; + static AFTER: number; + data: PathConstraintData; + bones: Array; + target: Slot; + position: number; + spacing: number; + rotateMix: number; + translateMix: number; + spaces: number[]; + positions: number[]; + world: number[]; + curves: number[]; + lengths: number[]; + segments: number[]; + constructor(data: PathConstraintData, skeleton: Skeleton); + apply(): void; + update(): void; + computeWorldPositions(path: PathAttachment, spacesCount: number, tangents: boolean, percentPosition: boolean, percentSpacing: boolean): number[]; + addBeforePosition(p: number, temp: Array, i: number, out: Array, o: number): void; + addAfterPosition(p: number, temp: Array, i: number, out: Array, o: number): void; + addCurvePosition(p: number, x1: number, y1: number, cx1: number, cy1: number, cx2: number, cy2: number, x2: number, y2: number, out: Array, o: number, tangents: boolean): void; + getOrder(): number; + } +} +declare module PIXI.spine.core { + class PathConstraintData { + name: string; + order: number; + bones: BoneData[]; + target: SlotData; + positionMode: PositionMode; + spacingMode: SpacingMode; + rotateMode: RotateMode; + offsetRotation: number; + position: number; + spacing: number; + rotateMix: number; + translateMix: number; + constructor(name: string); + } + enum PositionMode { + Fixed = 0, + Percent = 1, + } + enum SpacingMode { + Length = 0, + Fixed = 1, + Percent = 2, + } + enum RotateMode { + Tangent = 0, + Chain = 1, + ChainScale = 2, + } +} +declare module PIXI.spine.core { + class Skeleton { + data: SkeletonData; + bones: Array; + slots: Array; + drawOrder: Array; + ikConstraints: Array; + transformConstraints: Array; + pathConstraints: Array; + _updateCache: Updatable[]; + updateCacheReset: Updatable[]; + skin: Skin; + color: Color; + time: number; + flipX: boolean; + flipY: boolean; + x: number; + y: number; + constructor(data: SkeletonData); + updateCache(): void; + sortIkConstraint(constraint: IkConstraint): void; + sortPathConstraint(constraint: PathConstraint): void; + sortTransformConstraint(constraint: TransformConstraint): void; + sortPathConstraintAttachment(skin: Skin, slotIndex: number, slotBone: Bone): void; + sortPathConstraintAttachmentWith(attachment: Attachment, slotBone: Bone): void; + sortBone(bone: Bone): void; + sortReset(bones: Array): void; + updateWorldTransform(): void; + setToSetupPose(): void; + setBonesToSetupPose(): void; + setSlotsToSetupPose(): void; + getRootBone(): Bone; + findBone(boneName: string): Bone; + findBoneIndex(boneName: string): number; + findSlot(slotName: string): Slot; + findSlotIndex(slotName: string): number; + setSkinByName(skinName: string): void; + setSkin(newSkin: Skin): void; + getAttachmentByName(slotName: string, attachmentName: string): Attachment; + getAttachment(slotIndex: number, attachmentName: string): Attachment; + setAttachment(slotName: string, attachmentName: string): void; + findIkConstraint(constraintName: string): IkConstraint; + findTransformConstraint(constraintName: string): TransformConstraint; + findPathConstraint(constraintName: string): PathConstraint; + getBounds(offset: Vector2, size: Vector2): void; + update(delta: number): void; + } +} +declare module PIXI.spine.core { + class SkeletonBounds { + minX: number; + minY: number; + maxX: number; + maxY: number; + boundingBoxes: BoundingBoxAttachment[]; + polygons: ArrayLike[]; + private polygonPool; + update(skeleton: Skeleton, updateAabb: boolean): void; + aabbCompute(): void; + aabbContainsPoint(x: number, y: number): boolean; + aabbIntersectsSegment(x1: number, y1: number, x2: number, y2: number): boolean; + aabbIntersectsSkeleton(bounds: SkeletonBounds): boolean; + containsPoint(x: number, y: number): BoundingBoxAttachment; + containsPointPolygon(polygon: ArrayLike, x: number, y: number): boolean; + intersectsSegment(x1: number, y1: number, x2: number, y2: number): BoundingBoxAttachment; + intersectsSegmentPolygon(polygon: ArrayLike, x1: number, y1: number, x2: number, y2: number): boolean; + getPolygon(boundingBox: BoundingBoxAttachment): ArrayLike; + getWidth(): number; + getHeight(): number; + } +} +declare module PIXI.spine.core { + class SkeletonData { + name: string; + bones: BoneData[]; + slots: SlotData[]; + skins: Skin[]; + defaultSkin: Skin; + events: EventData[]; + animations: Animation[]; + ikConstraints: IkConstraintData[]; + transformConstraints: TransformConstraintData[]; + pathConstraints: PathConstraintData[]; + width: number; + height: number; + version: string; + hash: string; + fps: number; + imagesPath: string; + findBone(boneName: string): BoneData; + findBoneIndex(boneName: string): number; + findSlot(slotName: string): SlotData; + findSlotIndex(slotName: string): number; + findSkin(skinName: string): Skin; + findEvent(eventDataName: string): EventData; + findAnimation(animationName: string): Animation; + findIkConstraint(constraintName: string): IkConstraintData; + findTransformConstraint(constraintName: string): TransformConstraintData; + findPathConstraint(constraintName: string): PathConstraintData; + findPathConstraintIndex(pathConstraintName: string): number; + } +} +declare module PIXI.spine.core { + class SkeletonJson { + attachmentLoader: AttachmentLoader; + scale: number; + private linkedMeshes; + constructor(attachmentLoader: AttachmentLoader); + readSkeletonData(json: string | any): SkeletonData; + readAttachment(map: any, skin: Skin, slotIndex: number, name: string): Attachment; + readVertices(map: any, attachment: VertexAttachment, verticesLength: number): void; + readAnimation(map: any, name: string, skeletonData: SkeletonData): void; + readCurve(map: any, timeline: CurveTimeline, frameIndex: number): void; + getValue(map: any, prop: string, defaultValue: any): any; + static blendModeFromString(str: string): number; + static positionModeFromString(str: string): PositionMode; + static spacingModeFromString(str: string): SpacingMode; + static rotateModeFromString(str: string): RotateMode; + static transformModeFromString(str: string): TransformMode; + static transformModeLegacy(inheritRotation: boolean, inheritScale: boolean): TransformMode; + } +} +declare module PIXI.spine.core { + class Skin { + name: string; + attachments: Map[]; + constructor(name: string); + addAttachment(slotIndex: number, name: string, attachment: Attachment): void; + getAttachment(slotIndex: number, name: string): Attachment; + attachAll(skeleton: Skeleton, oldSkin: Skin): void; + } +} +declare module PIXI.spine.core { + class Slot { + currentMesh: any; + currentSprite: any; + meshes: any; + currentMeshName: String; + sprites: any; + currentSpriteName: String; + blendMode: number; + tempRegion: TextureRegion; + tempAttachment: Attachment; + data: SlotData; + bone: Bone; + color: Color; + attachment: Attachment; + private attachmentTime; + attachmentVertices: number[]; + constructor(data: SlotData, bone: Bone); + getAttachment(): Attachment; + setAttachment(attachment: Attachment): void; + setAttachmentTime(time: number): void; + getAttachmentTime(): number; + setToSetupPose(): void; + } +} +declare module PIXI.spine.core { + class SlotData { + index: number; + name: string; + boneData: BoneData; + color: Color; + attachmentName: string; + blendMode: number; + constructor(index: number, name: string, boneData: BoneData); + } +} +declare module PIXI.spine.core { + abstract class Texture { + protected _image: HTMLImageElement; + constructor(image: HTMLImageElement); + getImage(): HTMLImageElement; + abstract setFilters(minFilter: TextureFilter, magFilter: TextureFilter): void; + abstract setWraps(uWrap: TextureWrap, vWrap: TextureWrap): void; + abstract dispose(): void; + static filterFromString(text: string): TextureFilter; + static wrapFromString(text: string): TextureWrap; + } + enum TextureFilter { + Nearest = 9728, + Linear = 9729, + MipMap = 9987, + MipMapNearestNearest = 9984, + MipMapLinearNearest = 9985, + MipMapNearestLinear = 9986, + MipMapLinearLinear = 9987, + } + enum TextureWrap { + MirroredRepeat = 33648, + ClampToEdge = 33071, + Repeat = 10497, + } + class TextureRegion { + texture: PIXI.Texture; + size: PIXI.Rectangle; + readonly width: number; + readonly height: number; + readonly u: number; + readonly v: number; + readonly u2: number; + readonly v2: number; + readonly offsetX: number; + readonly offsetY: number; + readonly pixiOffsetY: number; + readonly spineOffsetY: number; + readonly originalWidth: number; + readonly originalHeight: number; + readonly x: number; + readonly y: number; + readonly rotate: boolean; + } +} +declare module PIXI.spine.core { + class TextureAtlas implements Disposable { + pages: TextureAtlasPage[]; + regions: TextureAtlasRegion[]; + constructor(atlasText: string, textureLoader: (path: string, loaderFunction: (tex: PIXI.BaseTexture) => any) => any, callback: (obj: TextureAtlas) => any); + addTexture(name: string, texture: PIXI.Texture): TextureAtlasRegion; + addTextureHash(textures: Map, stripExtension: boolean): void; + addSpineAtlas(atlasText: string, textureLoader: (path: string, loaderFunction: (tex: PIXI.BaseTexture) => any) => any, callback: (obj: TextureAtlas) => any): void; + private load(atlasText, textureLoader, callback); + findRegion(name: string): TextureAtlasRegion; + dispose(): void; + } + class TextureAtlasPage { + name: string; + minFilter: TextureFilter; + magFilter: TextureFilter; + uWrap: TextureWrap; + vWrap: TextureWrap; + baseTexture: PIXI.BaseTexture; + width: number; + height: number; + setFilters(): void; + } + class TextureAtlasRegion extends TextureRegion { + page: TextureAtlasPage; + name: string; + index: number; + } +} +declare module PIXI.spine.core { + class TransformConstraint implements Constraint { + data: TransformConstraintData; + bones: Array; + target: Bone; + rotateMix: number; + translateMix: number; + scaleMix: number; + shearMix: number; + temp: Vector2; + constructor(data: TransformConstraintData, skeleton: Skeleton); + apply(): void; + update(): void; + getOrder(): number; + } +} +declare module PIXI.spine.core { + class TransformConstraintData { + name: string; + order: number; + bones: BoneData[]; + target: BoneData; + rotateMix: number; + translateMix: number; + scaleMix: number; + shearMix: number; + offsetRotation: number; + offsetX: number; + offsetY: number; + offsetScaleX: number; + offsetScaleY: number; + offsetShearY: number; + constructor(name: string); + } +} +declare module PIXI.spine.core { + interface Updatable { + update(): void; + } +} +declare module PIXI.spine.core { + interface Map { + [key: string]: T; + } + class IntSet { + array: number[]; + add(value: number): boolean; + contains(value: number): boolean; + remove(value: number): void; + clear(): void; + } + interface Disposable { + dispose(): void; + } + class Color { + r: number; + g: number; + b: number; + a: number; + static WHITE: Color; + static RED: Color; + static GREEN: Color; + static BLUE: Color; + static MAGENTA: Color; + constructor(r?: number, g?: number, b?: number, a?: number); + set(r: number, g: number, b: number, a: number): this; + setFromColor(c: Color): this; + setFromString(hex: string): this; + add(r: number, g: number, b: number, a: number): this; + clamp(): this; + } + class MathUtils { + static PI: number; + static PI2: number; + static radiansToDegrees: number; + static radDeg: number; + static degreesToRadians: number; + static degRad: number; + static clamp(value: number, min: number, max: number): number; + static cosDeg(degrees: number): number; + static sinDeg(degrees: number): number; + static signum(value: number): number; + static toInt(x: number): number; + static cbrt(x: number): number; + } + class Utils { + static SUPPORTS_TYPED_ARRAYS: boolean; + static arrayCopy(source: ArrayLike, sourceStart: number, dest: ArrayLike, destStart: number, numElements: number): void; + static setArraySize(array: Array, size: number, value?: any): Array; + static ensureArrayCapacity(array: Array, size: number, value?: any): Array; + static newArray(size: number, defaultValue: T): Array; + static newFloatArray(size: number): ArrayLike; + static toFloatArray(array: Array): number[] | Float32Array; + } + class DebugUtils { + static logBones(skeleton: Skeleton): void; + } + class Pool { + private items; + private instantiator; + constructor(instantiator: () => T); + obtain(): T; + free(item: T): void; + freeAll(items: ArrayLike): void; + clear(): void; + } + class Vector2 { + x: number; + y: number; + constructor(x?: number, y?: number); + set(x: number, y: number): Vector2; + length(): number; + normalize(): this; + } + class TimeKeeper { + maxDelta: number; + framesPerSecond: number; + delta: number; + totalTime: number; + private lastTime; + private frameCount; + private frameTime; + update(): void; + } + interface ArrayLike { + length: number; + [n: number]: T; + } +} +declare module PIXI.spine { + function atlasParser(): (resource: loaders.Resource, next: () => any) => any; + function imageLoaderAdapter(loader: any, namePrefix: any, baseUrl: any, imageOptions: any): (line: String, callback: (baseTexture: BaseTexture) => any) => void; + function syncImageLoaderAdapter(baseUrl: any, crossOrigin: any): (line: any, callback: any) => void; +} +declare module PIXI.spine { + class SpineSprite extends PIXI.Sprite { + region: core.TextureRegion; + constructor(tex: PIXI.Texture); + } + class SpineMesh extends PIXI.mesh.Mesh { + region: core.TextureRegion; + constructor(texture: PIXI.Texture, vertices?: Float32Array, uvs?: Float32Array, indices?: Uint16Array, drawMode?: number); + } + class Spine extends PIXI.Container { + static globalAutoUpdate: boolean; + tintRgb: ArrayLike; + spineData: core.SkeletonData; + skeleton: core.Skeleton; + stateData: core.AnimationStateData; + state: core.AnimationState; + slotContainers: Array; + constructor(spineData: core.SkeletonData); + autoUpdate: boolean; + tint: number; + update(dt: number): void; + private setSpriteRegion(attachment, sprite, region); + private setMeshRegion(attachment, mesh, region); + protected lastTime: number; + autoUpdateTransform(): void; + createSprite(slot: core.Slot, attachment: core.RegionAttachment, defName: string): SpineSprite; + createMesh(slot: core.Slot, attachment: core.MeshAttachment): SpineMesh; + hackTextureBySlotIndex(slotIndex: number, texture?: PIXI.Texture, size?: PIXI.Rectangle): boolean; + hackTextureBySlotName: (slotName: String, texture?: Texture, size?: Rectangle) => any; } - } diff --git a/pixi-spine/pixi-spine-tests.ts b/pixi-spine/pixi-spine-tests.ts index 473e49ae29..55478c3392 100644 --- a/pixi-spine/pixi-spine-tests.ts +++ b/pixi-spine/pixi-spine-tests.ts @@ -1,5 +1,5 @@ /// - +/// namespace Spine { @@ -48,7 +48,7 @@ namespace Spine { this.stage.addChild(dragonCage); // once position and scaled, set the animation to play - this.dragon.state.setAnimationByName(0, 'flying', true); + this.dragon.state.setAnimation(0, 'flying', true); this.animate(); @@ -186,10 +186,10 @@ namespace Spine { this.stage.addChild(this.pixie); - this.pixie.stateData.setMixByName('running', 'jump', 0.2); - this.pixie.stateData.setMixByName('jump', 'running', 0.4); + this.pixie.stateData.setMix('running', 'jump', 0.2); + this.pixie.stateData.setMix('jump', 'running', 0.4); - this.pixie.state.setAnimationByName(0, 'running', true); + this.pixie.state.setAnimation(0, 'running', true); this.stage.on('mousedown', this.onTouchStart); this.stage.on('touchstart', this.onTouchStart); @@ -200,8 +200,8 @@ namespace Spine { private onTouchStart = (): void => { - this.pixie.state.setAnimationByName(0, 'jump', false); - this.pixie.state.addAnimationByName(0, 'running', true, 0); + this.pixie.state.setAnimation(0, 'jump', false); + this.pixie.state.addAnimation(0, 'running', true, 0); } @@ -277,19 +277,19 @@ namespace Spine { this.spineboy.scale.set(1.5); // set up the mixes! - this.spineboy.stateData.setMixByName('walk', 'jump', 0.2); - this.spineboy.stateData.setMixByName('jump', 'walk', 0.4); + this.spineboy.stateData.setMix('walk', 'jump', 0.2); + this.spineboy.stateData.setMix('jump', 'walk', 0.4); // play animation - this.spineboy.state.setAnimationByName(0, 'walk', true); + this.spineboy.state.setAnimation(0, 'walk', true); this.stage.addChild(this.spineboy); this.stage.on('click', () => { - this.spineboy.state.setAnimationByName(0, 'jump', false); - this.spineboy.state.addAnimationByName(0, 'walk', true, 0); + this.spineboy.state.setAnimation(0, 'jump', false); + this.spineboy.state.addAnimation(0, 'walk', true, 0); }); diff --git a/pixi.js/index.d.ts b/pixi.js/index.d.ts index 6e8640e91c..bf5ee7c0df 100644 --- a/pixi.js/index.d.ts +++ b/pixi.js/index.d.ts @@ -1,100 +1,80 @@ -// Type definitions for Pixi.js 3.0.9 dev -// Project: https://github.com/GoodBoyDigital/pixi.js/ +// Type definitions for Pixi.js 4.1 +// Project: https://github.com/pixijs/pixi.js/tree/dev // Definitions by: clark-stevenson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = PIXI; -export as namespace PIXI; +declare module PIXI { -declare class PIXI { + // from CONST + export var VERSION: typeof CONST.VERSION; + export var PI_2: typeof CONST.PI_2; + export var RAD_TO_DEG: typeof CONST.RAD_TO_DEG; + export var DEG_TO_RAD: typeof CONST.DEG_TO_RAD; + export var TARGET_FPMS: typeof CONST.TARGET_FPMS; + export var RENDERER_TYPE: typeof CONST.RENDERER_TYPE; + export var BLEND_MODES: typeof CONST.BLEND_MODES; + export var DRAW_MODES: typeof CONST.DRAW_MODES; + export var SCALE_MODES: typeof CONST.SCALE_MODES; + export var WRAP_MODES: typeof CONST.WRAP_MODES; + export var TRANSFORM_MODE: typeof CONST.TRANSFORM_MODE; + export var SPRITE_MAX_TEXTURES: typeof CONST.SPRITE_MAX_TEXTURES; + export var PRECISION: typeof CONST.PRECISION; + export var TEXT_STYLE_CHANGED: typeof CONST.TEXT_STYLE_CHANGED; + export var GC_MODES: typeof CONST.GC_MODES; + export var MIPMAP_TEXTURES: typeof CONST.MIPMAP_TEXTURES; + export var RETINA_PREFIX: typeof CONST.RETINA_PREFIX; + export var RESOLUTION: typeof CONST.RESOLUTION; + export var FILTER_RESOLUTION: typeof CONST.FILTER_RESOLUTION; + export var DEFAULT_RENDER_OPTIONS: typeof CONST.DEFAULT_RENDER_OPTIONS; + export var SHAPES: typeof CONST.SHAPES; + export var SPRITE_BATCH_SIZE: typeof CONST.SPRITE_BATCH_SIZE; + export var TEXT_GRADIENT: typeof CONST.TEXT_GRADIENT; - static VERSION: string; - static PI_2: number; - static RAD_TO_DEG: number; - static DEG_TO_RAD: number; - static TARGET_FPMS: number; - static RENDERER_TYPE: { - UNKNOWN: number; - WEBGL: number; - CANVAS: number; - }; - static BLEND_MODES: { - NORMAL: number; - ADD: number; - MULTIPLY: number; - SCREEN: number; - OVERLAY: number; - DARKEN: number; - LIGHTEN: number; - COLOR_DODGE: number; - COLOR_BURN: number; - HARD_LIGHT: number; - SOFT_LIGHT: number; - DIFFERENCE: number; - EXCLUSION: number; - HUE: number; - SATURATION: number; - COLOR: number; - LUMINOSITY: number; - - }; - static DRAW_MODES: { - POINTS: number; - LINES: number; - LINE_LOOP: number; - LINE_STRIP: number; - TRIANGLES: number; - TRIANGLE_STRIP: number; - TRIANGLE_FAN: number; - }; - static SCALE_MODES: { - DEFAULT: number; - LINEAR: number; - NEAREST: number; - }; - static RETINA_PREFIX: string; - static RESOLUTION: number; - static FILTER_RESOLUTION: number; - static DEFAULT_RENDER_OPTIONS: { - view: HTMLCanvasElement; - resolution: number; - antialias: boolean; - forceFXAA: boolean; - autoResize: boolean; - transparent: boolean; - backgroundColor: number; - clearBeforeRender: boolean; - preserveDrawingBuffer: boolean; - roundPixels: boolean; - }; - static SHAPES: { - POLY: number; - RECT: number; - CIRC: number; - ELIP: number; - RREC: number; - }; - static SPRITE_BATCH_SIZE: number; - -} - -declare namespace PIXI { - - export function autoDetectRenderer(width: number, height: number, options?: PIXI.RendererOptions, noWebGL?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; + export function autoDetectRenderer(width: number, height: number, options?: PIXI.IRendererOptions, noWebGL?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; export var loader: PIXI.loaders.Loader; - //https://github.com/primus/eventemitter3 - export class EventEmitter { + ////////////////////////////////////////////////////////////////////////////// + /////////////////////////////ACCESSIBILITY//////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - on(event: string, fn: Function, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; - removeListener(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; - removeAllListeners(event?: string): EventEmitter; + export module accessibility { - off(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; - addListener(event: string, fn: Function, context?: any): EventEmitter; + // accessibility + export class AccessibilityManager { + + constructor(renderer: CanvasRenderer | WebGLRenderer); + + protected div: HTMLElement; + protected pool: HTMLElement[]; + protected renderId: number; + debug: boolean; + renderer: SystemRenderer; + protected children: IAccessibleTarget[]; + protected isActive: boolean; + + protected activate(): void; + protected deactivate(): void; + protected updateAccessibleObjects(displayObject: DisplayObject): void; + protected update(): void; + protected capHitArea(hitArea: IHitArea): void; + protected addChild(displayObject: DisplayObject): void; + protected _onClick(e: interaction.InteractionEvent): void; + protected _onFocus(e: interaction.InteractionEvent): void; + protected _onFocusOut(e: interaction.InteractionEvent): void; + protected _onKeyDown(e: interaction.InteractionEvent): void; + protected _onMouseMove(): void; + + destroy(): void; + + } + export interface IAccessibleTarget { + + accessible: boolean; + accessibleTitle: string; + accessibleHint: string; + tabIndex: number; + + } } @@ -102,124 +82,149 @@ declare namespace PIXI { ////////////////////////////////CORE////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - //display + // const - export class DisplayObject extends EventEmitter implements interaction.InteractiveTarget { - - //begin extras.cacheAsBitmap see https://github.com/pixijs/pixi-typescript/commit/1207b7f4752d79a088d6a9a465a3ec799906b1db - protected _originalRenderWebGL: WebGLRenderer; - protected _originalRenderCanvas: CanvasRenderer; - protected _originalUpdateTransform: boolean; - protected _originalHitTest: any; - protected _cachedSprite: any; - protected _originalDestroy: any; - - cacheAsBitmap: boolean; - - protected _renderCachedWebGL(renderer: WebGLRenderer): void; - protected _initCachedDisplayObject(renderer: WebGLRenderer): void; - protected _renderCachedCanvas(renderer: CanvasRenderer): void; - protected _initCachedDisplayObjectCanvas(renderer: CanvasRenderer): void; - protected _getCachedBounds(): Rectangle; - protected _destroyCachedDisplayObject(): void; - protected _cacheAsBitmapDestroy(): void; - //end extras.cacheAsBitmap - - protected _sr: number; - protected _cr: number; - protected _bounds: Rectangle; - protected _currentBounds: Rectangle; - protected _mask: Rectangle; - protected _cachedObject: any; - - updateTransform(): void; - - position: Point; - scale: Point; - pivot: Point; - rotation: number; - renderable: boolean; - alpha: number; - visible: boolean; - parent: Container; - worldAlpha: number; - worldTransform: Matrix; - filterArea: Rectangle; - - x: number; - y: number; - worldVisible: boolean; - mask: Graphics | Sprite; - filters: AbstractFilter[]; - name: string; - - getBounds(matrix?: Matrix): Rectangle; - getLocalBounds(): Rectangle; - toGlobal(position: Point): Point; - toLocal(position: Point, from?: DisplayObject): Point; - generateTexture(renderer: CanvasRenderer | WebGLRenderer, scaleMode: number, resolution: number): Texture; - setParent(container: Container): Container; - setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, pivotX?: number, pivotY?: number): DisplayObject; - destroy(): void; - getChildByName(name: string): DisplayObject; - getGlobalPosition(point: Point): Point; - - interactive: boolean; - buttonMode: boolean; - interactiveChildren: boolean; - defaultCursor: string; - hitArea: HitArea; - - on(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: string, fn: Function, context?: any): EventEmitter; - - once(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; + export module CONST { + export var VERSION: string; + export var PI_2: number; + export var RAD_TO_DEG: number; + export var DEG_TO_RAD: number; + export var TARGET_FPMS: number; + export var RENDERER_TYPE: { + UNKNOWN: number; + WEBGL: number; + CANVAS: number; + }; + export var BLEND_MODES: { + NORMAL: number; + ADD: number; + MULTIPLY: number; + SCREEN: number; + OVERLAY: number; + DARKEN: number; + LIGHTEN: number; + COLOR_DODGE: number; + COLOR_BURN: number; + HARD_LIGHT: number; + SOFT_LIGHT: number; + DIFFERENCE: number; + EXCLUSION: number; + HUE: number; + SATURATION: number; + COLOR: number; + LUMINOSITY: number; + }; + export var DRAW_MODES: { + POINTS: number; + LINES: number; + LINE_LOOP: number; + LINE_STRIP: number; + TRIANGLES: number; + TRIANGLE_STRIP: number; + TRIANGLE_FAN: number; + }; + export var SCALE_MODES: { + DEFAULT: number, + LINEAR: number, + NEAREST: number + }; + export var GC_MODES: { + DEFAULT: number; + AUTO: number; + MANUAL: number; + }; + export var WRAP_MODES: { + CLAMP: number; + DEFAULT: number; + MIRRORED_REPEAT: number; + REPEAT: number; + }; + export var TRANSFORM_MODE: { + DEFAULT: number; + DYNAMIC: number; + STATIC: number; + }; + export var MIPMAP_TEXTURES: boolean; + export var RETINA_PREFIX: RegExp; + export var RESOLUTION: number; + export var FILTER_RESOLUTION: number; + export var DEFAULT_RENDER_OPTIONS: { + view: HTMLCanvasElement; + antialias: boolean; + forceFXAA: boolean; + autoResize: boolean; + transparent: boolean; + backgroundColor: number; + clearBeforeRender: boolean; + preserveDrawingBuffer: boolean; + roundPixels: boolean; + }; + export var URL_FILE_EXTENSION: RegExp | string; + export var DATA_URI: RegExp | string; + export var SVG_SIZE: RegExp | string; + export var SHAPES: { + POLY: number; + RECT: number; + CIRC: number; + ELIP: number; + RREC: number; + }; + export var PRECISION: { + DEFAULT: string; + LOW: string; + MEDIUM: string; + HIGH: string; + }; + export var TEXT_GRADIENT: { + LINEAR_VERTICAL: number; + LINEAR_HORIZONTAL: number; + }; + export var SPRITE_BATCH_SIZE: number; + export var SPRITE_MAX_TEXTURES: number; + export var TEXT_STYLE_CHANGED: string; } + // display + + export interface IDestroyOptions { + children?: boolean; + texture?: boolean; + baseTexture?: boolean; + } + export class Bounds { + + minX: number; + minY: number; + maxX: number; + maxY: number; + rect: Rectangle; + + isEmpty(): boolean; + clear(): void; + + getRectangle(rect?: Rectangle): Rectangle; + addPoint(point: Point): void; + addQuad(vertices: number[]): Bounds; + addFrame(transform: Transform, x0: number, y0: number, x1: number, y1: number): void; + addVertices(transform: Transform, vertices: number[], beginOffset: number, endOffset: number): void; + addBounds(bounds: Bounds): void; + addBoundsMask(bounds: Bounds, mask: Bounds): void; + addBoundsArea(bounds: Bounds, area: Rectangle): void; + + } export class Container extends DisplayObject { - protected _renderWebGL(renderer: WebGLRenderer): void; - protected _renderCanvas(renderer: CanvasRenderer): void; - - protected onChildrenChange: () => void; + // begin extras.getChildByName + getChildByName(name: string): DisplayObject; + // end extras.getChildByName children: DisplayObject[]; - width: number; height: number; + protected onChildrenChange: (...args: any[]) => void; + addChild(child: DisplayObject): DisplayObject; addChild(...child: DisplayObject[]): DisplayObject; addChildAt(child: DisplayObject, index: number): DisplayObject; swapChildren(child: DisplayObject, child2: DisplayObject): void; @@ -228,58 +233,257 @@ declare namespace PIXI { getChildAt(index: number): DisplayObject; removeChild(child: DisplayObject): DisplayObject; removeChildAt(index: number): DisplayObject; - removeChildren(beginIndex?: number, endIndex?: number): DisplayObject[]; - destroy(destroyChildren?: boolean): void; - generateTexture(renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer, resolution?: number, scaleMode?: number): Texture; - + removeChildren(beginIndex?: number, endIndex?: number): DisplayObject | DisplayObject[]; + updateTransform(): void; + calculateBounds(): void; + protected _calculateBounds(): void; + protected containerUpdateTransform(): void; renderWebGL(renderer: WebGLRenderer): void; + renderAdvancedWebGL(renderer: WebGLRenderer): void; + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; renderCanvas(renderer: CanvasRenderer): void; + destroy(options?: IDestroyOptions | boolean): void; - once(event: 'added', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; - once(event: 'removed', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; - on(event: 'added', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: string, fn: Function, context?: any): EventEmitter; - on(event: 'removed', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; - on(event: string, fn: Function, context?: any): EventEmitter; + once(event: "added", fn: (displayObject: DisplayObject) => void, context?: any): utils.EventEmitter; + once(event: "removed", fn: (DisplayObject: DisplayObject) => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + on(event: "added", fn: (displayObject: DisplayObject) => void, context?: any): utils.EventEmitter; + on(event: "removed", fn: (DisplayObject: DisplayObject) => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; + + } + export class DisplayObject extends utils.EventEmitter implements interaction.InteractiveTarget { + + // begin extras.cacheAsBitmap + protected _cacheAsBitmap: boolean; + protected _cacheData: boolean; + cacheAsBitmap: boolean; + protected _renderCachedWebGL(renderer: WebGLRenderer): void; + protected _initCachedDisplayObject(renderer: WebGLRenderer): void; + protected _renderCachedCanvas(renderer: CanvasRenderer): void; + protected _initCachedDisplayObjectCanvas(renderer: CanvasRenderer): void; + protected _calculateCachedBounds(): Rectangle; + protected _getCachedLocalBounds(): Rectangle; + protected _destroyCachedDisplayObject(): void; + protected _cacheAsBitmapDestroy(): void; + // end extras.cacheAsBitmap + + // begin extras.getChildByName + name: string; + // end extras.getChildByName + + // begin extras.getGlobalPosition + getGlobalPosition(point?: Point, skipUpdate?: boolean): Point; + // end extras.getGlobalPosition + + // begin accessible target + accessible: boolean; + accessibleTitle: string; + accessibleHint: string; + tabIndex: number; + // end accessible target + + // begin interactive target + interactive: boolean; + buttonMode: boolean; + hitArea: IHitArea; + interactiveChildren: boolean; + defaultCursor: string; + _isRightDown: boolean; + _isLeftDown: boolean; + // end interactive target + + transform: TransformBase; + alpha: number; + visible: boolean; + renderable: boolean; + parent: Container; + worldAlpha: number; + filterArea: Rectangle; + protected _filters: Filter[]; + protected _enabledFilters: Filter[]; + protected _bounds: Bounds; + protected _boundsID: number; + protected _lastBoundsID: number; + protected _boundsRect: Rectangle; + protected _localBoundsRect: Rectangle; + protected _mask: Rectangle; + x: number; + y: number; + worldTransform: Matrix; + localTransform: Matrix; + position: Point; + scale: Point; + pivot: Point; + skew: Point; + rotation: number; + worldVisible: boolean; + mask: PIXI.Graphics | PIXI.Sprite; + filters: Filter[]; + + updateTransform(): void; + protected displayObjectUpdateTransform(): void; + protected _recursivePostUpdateTransform(): void; + getBounds(skipUpdate?: boolean, rect?: Rectangle): Rectangle; + getLocalBounds(rect?: Rectangle): Rectangle; + toGlobal(position: Point, point?: Point, skipUpdate?: boolean): Point; + toLocal(position: Point, from?: DisplayObject, point?: Point, skipUpdate?: boolean): Point; + protected renderWebGL(renderer: WebGLRenderer): void; + protected renderCanvas(renderer: CanvasRenderer): void; + setParent(container: Container): Container; + setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, pivotX?: number, pivotY?: number): DisplayObject; + destroy(): void; + + on(event: string, fn: Function, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; + + /* + on(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + on(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + + once(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + once(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): utils.EventEmitter; + */ } - //graphics + export class TransformBase { + + static IDENTITY: TransformBase; + + worldTransform: Matrix; + localTransform: Matrix; + protected _worldID: number; + updateLocalTransform(): void; + updateTransform(parentTransform: TransformBase): void; + updateWorldTransform(parentTransform: TransformBase): void; + + } + export class TransformStatic extends TransformBase { + + position: ObservablePoint; + scale: ObservablePoint; + pivot: ObservablePoint; + skew: ObservablePoint; + + protected _rotation: number; + protected _sr: number; + protected _cr: number; + protected _cy: number; + protected _sy: number; + protected _nsx: number; + protected _cx: number; + protected _currentLocalID: number; + + protected onChange(): void; + updateSkew(): void; + updateLocalTransform(): void; + updateTransform(parentTransform: TransformBase): void; + setFromMatrix(matrix: Matrix): void; + + rotation: number; + + } + export class Transform extends TransformBase { + + constructor(); + + position: Point; + scale: Point; + skew: ObservablePoint; + pivot: Point; + + protected _rotation: number; + protected _sr: number; + protected _cr: number; + protected _cy: number; + protected _sy: number; + protected _nsx: number; + protected _cx: number; + + updateSkew(): void; + setFromMatrix(matrix: Matrix): void; + + rotation: number; + + } + + // graphics export class GraphicsData { - constructor(lineWidth: number, lineColor: number, lineAlpha: number, fillColor: number, fillAlpha: number, fill: boolean, shape: Circle | Rectangle | Ellipse | Polygon); + constructor(lineWidth: number, lineColor: number, lineAlpha: number, fillColor: number, fillAlpha: number, fill: boolean, shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon); lineWidth: number; lineColor: number; lineAlpha: number; + protected _lineTint: number; fillColor: number; fillAlpha: number; - fill: boolean; - shape: Circle | Rectangle | Ellipse | Polygon; - type: number; - - clone(): GraphicsData; - - protected _lineTint: number; protected _fillTint: number; + fill: boolean; + protected holes: IShape[]; + shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon; + type: number; + clone(): GraphicsData; + addHole(shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon): void; + destroy(options?: IDestroyOptions | boolean): void; } export class Graphics extends Container { - protected boundsDirty: boolean; - protected dirty: boolean; - protected glDirty: boolean; - fillAlpha: number; lineWidth: number; lineColor: number; + protected graphicsData: GraphicsData[]; tint: number; + protected _prevTint: number; blendMode: number; + currentPath: GraphicsData; + protected _webGL: any; isMask: boolean; boundsPadding: number; + protected _localBounds: Bounds; + dirty: boolean; + fastRectDirty: number; + clearDirty: number; + boundsDirty: number; + protected cachedSpriteDirty: boolean; + protected _spriteRect: Rectangle; + protected _fastRect: boolean; + + static _SPRITE_TEXTURE: Texture; clone(): Graphics; lineStyle(lineWidth?: number, color?: number, alpha?: number): Graphics; @@ -297,34 +501,93 @@ declare namespace PIXI { drawEllipse(x: number, y: number, width: number, height: number): Graphics; drawPolygon(path: number[] | Point[]): Graphics; clear(): Graphics; - //todo - generateTexture(renderer: WebGLRenderer | CanvasRenderer, resolution?: number, scaleMode?: number): Texture; - getBounds(matrix?: Matrix): Rectangle; + isFastRect(): boolean; + protected _renderCanvas(renderer: CanvasRenderer): void; + protected _calculateBounds(): Rectangle; + protected _renderSpriteRect(renderer: PIXI.SystemRenderer): void; containsPoint(point: Point): boolean; updateLocalBounds(): void; - drawShape(shape: Circle | Rectangle | Ellipse | Polygon): GraphicsData; + drawShape(shape: IShape | Circle | Rectangle | Ellipse | Polygon | RoundedRectangle): GraphicsData; + generateCanvasTexture(scaleMode?: number, resolution?: number): Texture; + protected closePath(): Graphics; + protected addHole(): Graphics; + destroy(options?: IDestroyOptions | boolean): void; } - export interface GraphicsRenderer extends ObjectRenderer { - //yikes todo + export class CanvasGraphicsRenderer { + + constructor(renderer: SystemRenderer); + render(graphics: Graphics): void; + protected updateGraphicsTint(graphics: Graphics): void; + protected renderPolygon(points: Point[], close: boolean, context: CanvasRenderingContext2D): void; + destroy(): void; + } - export interface WebGLGraphicsData { - //yikes todo! + export class GraphicsRenderer extends ObjectRenderer { + + constructor(renderer: PIXI.CanvasRenderer); + + protected graphicsDataPool: GraphicsData[]; + protected primitiveShader: PrimitiveShader; + gl: WebGLRenderingContext; + + CONTEXT_UID: number; + + destroy(): void; + render(graphics: Graphics): void; + protected updateGraphics(graphics: PIXI.Graphics): void; + getWebGLData(webGL: WebGLRenderingContext, type: number): WebGLGraphicsData; + } + export class WebGLGraphicsData { - //math + constructor(gl: WebGLRenderingContext, shader: glCore.GLShader, attribsState: glCore.IAttribState); - export class Point { + gl: WebGLRenderingContext; + color: number[]; + points: Point[]; + indices: number[]; + buffer: WebGLBuffer; + indexBuffer: WebGLBuffer; + dirty: boolean; + glPoints: number[]; + glIndices: number[]; + shader: glCore.GLShader; + vao: glCore.VertexArrayObject; - x: number; - y: number; + reset(): void; + upload(): void; + destroy(): void; - constructor(x?: number, y?: number); + } + export class PrimitiveShader extends glCore.GLShader { } - clone(): Point; - copy(p: Point): void; - equals(p: Point): boolean; - set(x?: number, y?: number): void; + // math + + export module GroupD8 { + + export var E: number; + export var SE: number; + export var S: number; + export var SW: number; + export var W: number; + export var NW: number; + export var N: number; + export var NE: number; + export var MIRROR_HORIZONTAL: number; + export var MIRROR_VERTICAL: number; + + export function uX(ind: number): number; + export function uY(ind: number): number; + export function vX(ind: number): number; + export function vY(ind: number): number; + export function inv(rotation: number): number; + export function add(rotationSecond: number, rotationFirst: number): number; + export function sub(rotationSecond: number, rotationFirst: number): number; + export function rotate180(rotation: number): number; + export function isSwapWidthHeight(rotation: number): boolean; + export function byDirection(dx: number, dy: number): number; + export function matrixAppendRotationInv(matrix: Matrix, rotation: number, tx: number, ty: number): void; } export class Matrix { @@ -337,6 +600,7 @@ declare namespace PIXI { ty: number; fromArray(array: number[]): void; + set(a: number, b: number, c: number, d: number, tx: number, ty: number): Matrix; toArray(transpose?: boolean, out?: number[]): number[]; apply(pos: Point, newPos?: Point): Point; applyInverse(pos: Point, newPos?: Point): Point; @@ -344,26 +608,53 @@ declare namespace PIXI { scale(x: number, y: number): Matrix; rotate(angle: number): Matrix; append(matrix: Matrix): Matrix; + setTransform(x: number, y: number, pivotX: number, pivotY: number, scaleX: number, scaleY: number, rotation: number, skewX: number, skewY: number): PIXI.Matrix; prepend(matrix: Matrix): Matrix; invert(): Matrix; identity(): Matrix; + decompose(transform: TransformBase): TransformBase; clone(): Matrix; copy(matrix: Matrix): Matrix; - set(a: number, b: number, c: number, d: number, tx: number, ty: number): Matrix; - setTransform(a: number, b: number, c: number, d: number, sr: number, cr: number, cy: number, sy: number, nsx: number, cs: number): PIXI.Matrix; static IDENTITY: Matrix; static TEMP_MATRIX: Matrix; } + export class ObservablePoint { - export interface HitArea { + constructor(cb: Function, scope?: any, x?: number, y?: number); + + x: number; + y: number; + cb: () => void; + scope: any; + + set(x?: number, y?: number): void; + copy(point: Point | ObservablePoint): void; + + } + export class Point { + + constructor(x?: number, y?: number); + + x: number; + y: number; + + clone(): Point; + copy(p: Point): void; + equals(p: Point): boolean; + set(x?: number, y?: number): void; + + } + + export interface IShape { + } + export interface IHitArea extends IShape { contains(x: number, y: number): boolean; } - - export class Circle implements HitArea { + export class Circle { constructor(x?: number, y?: number, radius?: number); @@ -377,7 +668,7 @@ declare namespace PIXI { getBounds(): Rectangle; } - export class Ellipse implements HitArea { + export class Ellipse { constructor(x?: number, y?: number, width?: number, height?: number); @@ -392,10 +683,9 @@ declare namespace PIXI { getBounds(): Rectangle; } - export class Polygon implements HitArea { + export class Polygon { - constructor(points: Point[]); - constructor(points: number[]); + constructor(points: Point[] | number[]); constructor(...points: Point[]); constructor(...points: number[]); @@ -405,10 +695,10 @@ declare namespace PIXI { clone(): Polygon; contains(x: number, y: number): boolean; - + close(): void; } - export class Rectangle implements HitArea { + export class Rectangle { constructor(x?: number, y?: number, width?: number, height?: number); @@ -417,14 +707,22 @@ declare namespace PIXI { width: number; height: number; type: number; + left: number; + right: number; + top: number; + bottom: number; static EMPTY: Rectangle; clone(): Rectangle; + copy(rectangle: Rectangle): Rectangle; contains(x: number, y: number): boolean; + pad(paddingX: number, paddingY: number): void; + fit(rectangle: Rectangle): void; + enlarge(rect: Rectangle): void; } - export class RoundedRectangle implements HitArea { + export class RoundedRectangle { constructor(x?: number, y?: number, width?: number, height?: number, radius?: number); @@ -435,96 +733,29 @@ declare namespace PIXI { radius: number; type: number; - static EMPTY: Rectangle; - - clone(): Rectangle; + clone(): RoundedRectangle; contains(x: number, y: number): boolean; } - //particles + // renderers - export interface ParticleContainerProperties { - - scale?: boolean; - position?: boolean; - rotation?: boolean; - uvs?: boolean; - alpha?: boolean; - - } - export class ParticleContainer extends Container { - - constructor(size?: number, properties?: ParticleContainerProperties, batchSize?: number); - - protected _maxSize: number; - protected _batchSize: number; - protected _properties: boolean[]; - protected _buffers: WebGLBuffer[]; - protected _bufferToUpdate: number; - - protected onChildrenChange: (smallestChildIndex?: number) => void; - - interactiveChildren: boolean; - blendMode: number; - roundPixels: boolean; - - setProperties(properties: ParticleContainerProperties): void; - - } - export interface ParticleBuffer { - - gl: WebGLRenderingContext; - vertSize: number; - vertByteSize: number; - size: number; - dynamicProperties: any[]; - staticProperties: any[]; - - staticStride: number; - staticBuffer: any; - staticData: any; - dynamicStride: number; - dynamicBuffer: any; - dynamicData: any; - - initBuffers(): void; - bind(): void; - destroy(): void; - - } - export interface ParticleRenderer { - - } - export interface ParticleShader { - - } - - //renderers - - export interface RendererOptions { + export interface IRendererOptions { view?: HTMLCanvasElement; transparent?: boolean; - antialias?: boolean; autoResize?: boolean; + antialias?: boolean; resolution?: number; - clearBeforeRendering?: boolean; - preserveDrawingBuffer?: boolean; - forceFXAA?: boolean; - roundPixels?: boolean; + clearBeforeRender?: boolean; backgroundColor?: number; + roundPixels?: boolean; + context?: WebGLRenderingContext; } - export class SystemRenderer extends EventEmitter { + export class SystemRenderer extends utils.EventEmitter { - protected _backgroundColor: number; - protected _backgroundColorRgb: number[]; - protected _backgroundColorString: string; - protected _tempDisplayObjectParent: any; - protected _lastObjectRendered: DisplayObject; - - constructor(system: string, width?: number, height?: number, options?: RendererOptions); + constructor(system: string, width?: number, height?: number, options?: IRendererOptions); type: number; width: number; @@ -533,82 +764,107 @@ declare namespace PIXI { resolution: number; transparent: boolean; autoResize: boolean; - blendModes: any; //todo? + blendModes: any; // todo? preserveDrawingBuffer: boolean; clearBeforeRender: boolean; roundPixels: boolean; + protected _backgroundColor: number; + protected _backgroundColorRgba: number[]; + protected _backgroundColorString: string; + protected _tempDisplayObjectParent: Container; + protected _lastObjectRendered: DisplayObject; backgroundColor: number; - render(object: DisplayObject): void; resize(width: number, height: number): void; + generateTexture(displayObject: DisplayObject, scaleMode?: number, resolution?: number): RenderTexture; + render(...args: any[]): void; destroy(removeView?: boolean): void; } export class CanvasRenderer extends SystemRenderer { - protected renderDisplayObject(displayObject: DisplayObject, context: CanvasRenderingContext2D): void; - protected _mapBlendModes(): void; + // plugintarget mixin start + protected __plugins: any[]; + plugins: any; + registerPlugin(pluginName: string, ctor: Function): void; + initPlugins(): void; + destroyPlugins(): void; + // plugintarget mixin end - constructor(width?: number, height?: number, options?: RendererOptions); + constructor(width?: number, height?: number, options?: IRendererOptions); - context: CanvasRenderingContext2D; + rootContext: CanvasRenderingContext2D; + rootResolution: number; refresh: boolean; maskManager: CanvasMaskManager; - roundPixels: boolean; smoothProperty: string; - render(object: DisplayObject): void; + render(displayObject: PIXI.DisplayObject, renderTexture?: PIXI.RenderTexture, clear?: boolean, transform?: PIXI.Transform, skipUpdateTransform?: boolean): void + setBlendMode(blendMode: number): void; + destroy(removeView?: boolean): void; resize(w: number, h: number): void; - } - export class CanvasBuffer { - - protected clear(): void; - - constructor(width: number, height: number); - - canvas: HTMLCanvasElement; - context: CanvasRenderingContext2D; - - width: number; - height: number; - - resize(width: number, height: number): void; - destroy(): void; - - } - export class CanvasGraphics { - - static renderGraphicsMask(graphics: Graphics, context: CanvasRenderingContext2D): void; - static updateGraphicsTint(graphics: Graphics): void; - - static renderGraphics(graphics: Graphics, context: CanvasRenderingContext2D): void; + on(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; + on(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + once(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; + once(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; } export class CanvasMaskManager { - pushMask(maskData: any, renderer: WebGLRenderer | CanvasRenderer): void; + constructor(renderer: CanvasRenderer); + + pushMask(maskData: any): void; + protected renderGraphicsShape(graphics: Graphics): void; popMask(renderer: WebGLRenderer | CanvasRenderer): void; destroy(): void; } - export class CanvasTinter { + export class CanvasRenderTarget { - static getTintedTexture(sprite: DisplayObject, color: number): HTMLCanvasElement; - static tintWithMultiply(texture: Texture, color: number, canvas: HTMLDivElement): void; - static tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - static tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - static roundColor(color: number): number; - static cacheStepsPerColorChannel: number; - static convertTintToImage: boolean; - static vanUseMultiply: boolean; - static tintMethod: Function; + constructor(width: number, height: number, resolution: number); + + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; + resolution: number; + + width: number; + height: number; + + clear(): void; + resize(width: number, height: number): void; + destroy(): void; + + } + + export interface IWebGLRendererOptions { + + view?: HTMLCanvasElement; + transparent?: boolean; + autoResize?: boolean; + antialias?: boolean; + forceFXAA?: boolean; + resolution?: number; + clearBeforeRender?: boolean; + preserveDrawingBuffer?: boolean; + roundPixels?: boolean; } export class WebGLRenderer extends SystemRenderer { - protected _useFXAA: boolean; - protected _FXAAFilter: filters.FXAAFilter; + // plugintarget mixin start + protected __plugins: any[]; + plugins: any; + registerPlugin(pluginName: string, ctor: Function): void; + initPlugins(): void; + destroyPlugins(): void; + // plugintarget mixin end + + constructor(width?: number, height?: number, options?: IWebGLRendererOptions); + protected _contextOptions: { alpha: boolean; antiAlias: boolean; @@ -616,363 +872,510 @@ declare namespace PIXI { stencil: boolean; preseveDrawingBuffer: boolean; }; - protected _renderTargetStack: RenderTarget[]; - - protected _initContext(): void; - protected _createContext(): void; - protected handleContextLost: (event: WebGLContextEvent) => void; - protected _mapGlModes(): void; - protected _managedTextures: Texture[]; - - constructor(width?: number, height?: number, options?: RendererOptions); - - drawCount: number; - shaderManager: ShaderManager; + protected _backgroundColorRgba: number[]; maskManager: MaskManager; stencilManager: StencilManager; - filterManager: FilterManager; - blendModeManager: BlendModeManager; - currentRenderTarget: RenderTarget; + emptyRenderer: ObjectRenderer; currentRenderer: ObjectRenderer; + gl: WebGLRenderingContext; + state: WebGLState; + renderingToScreen: boolean; + boundTextures: Texture[]; + filterManager: FilterManager; + textureManager: TextureManager; + protected drawModes: any; + protected _activeShader: Shader; + protected _activeRenderTarget: RenderTarget; + protected _initContext(): void; - render(object: DisplayObject): void; - renderDisplayObject(displayObject: DisplayObject, renderTarget: RenderTarget, clear: boolean): void; + render(displayObject: PIXI.DisplayObject, renderTexture?: PIXI.RenderTexture, clear?: boolean, transform?: PIXI.Transform, skipUpdateTransform?: boolean): void setObjectRenderer(objectRenderer: ObjectRenderer): void; - setRenderTarget(renderTarget: RenderTarget): void; - updateTexture(texture: BaseTexture | Texture): BaseTexture | Texture; - destroyTexture(texture: BaseTexture | Texture, _skipRemove?: boolean): void; + flush(): void; + resize(width: number, height: number): void; + setBlendMode(blendMode: number): void; + clear(clearColor?: number): void; + setTransform(matrix: Matrix): void; + bindRenderTexture(renderTexture: RenderTexture, transform: Transform): WebGLRenderer; + bindRenderTarget(renderTarget: RenderTarget): WebGLRenderer; + bindShader(shader: Shader): WebGLRenderer; + bindTexture(texture: Texture, location: number, forceLocation?: boolean): WebGLRenderer; + unbindTexture(texture: Texture): WebGLRenderer; + protected createVao(): glCore.VertexArrayObject; + reset(): WebGLRenderer; + handleContextLost: (event: WebGLContextEvent) => void; + handleContextRestored: () => void; + destroy(removeView?: boolean): void; + + on(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): utils.EventEmitter; + on(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; + on(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + once(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): utils.EventEmitter; + once(event: "prerender", fn: () => void, context?: any): utils.EventEmitter; + once(event: "postrender", fn: () => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; } - export class AbstractFilter { + export class WebGLState { - protected vertexSrc: string[]; - protected fragmentSrc: string[]; + constructor(gl: WebGLRenderingContext); - constructor(vertexSrc?: string | string[], fragmentSrc?: string | string[], uniforms?: any); + activeState: number[]; + defaultState: number[]; + stackIndex: number; + stack: number[]; + gl: WebGLRenderingContext; + maxAttribs: number; + attribState: glCore.IAttribState; + nativeVaoExtension: any; - uniforms: any; - - padding: number; - - getShader(renderer: WebGLRenderer): Shader; - applyFilter(renderer: WebGLRenderer, input: RenderTarget, output: RenderTarget, clear?: boolean): void; - syncUniform(uniform: WebGLUniformLocation): void; + push(): void; + pop(): void; + setState(state: number[]): void; + setBlend(value: number): void; + setBlendMode(value: number): void; + setDepthTest(value: number): void; + setCullFace(value: number): void; + setFrontFace(value: number): void; + resetAttributes(): void; + resetToDefault(): void; } - export class SpriteMaskFilter extends AbstractFilter { - - constructor(sprite: Sprite); - - maskSprite: Sprite; - maskMatrix: Matrix; - - applyFilter(renderer: WebGLRenderbuffer, input: RenderTarget, output: RenderTarget): void; - map: Texture; - offset: Point; - - } - export class BlendModeManager extends WebGLManager { + export class TextureManager { constructor(renderer: WebGLRenderer); - setBlendMode(blendMode: number): boolean; - - } - - export class FilterManager extends WebGLManager { - - constructor(renderer: WebGLRenderer); - - filterStack: any[]; renderer: WebGLRenderer; - texturePool: any[]; + gl: WebGLRenderingContext; + protected _managedTextures: WebGLTexture[]; - onContextChange: () => void; - setFilterStack(filterStack: any[]): void; - pushFilter(target: RenderTarget, filters: any[]): void; - popFilter(): AbstractFilter; - getRenderTarget(clear?: boolean): RenderTarget; - protected returnRenderTarget(renderTarget: RenderTarget): void; - applyFilter(shader: Shader | AbstractFilter, inputTarget: RenderTarget, outputTarget: RenderTarget, clear?: boolean): void; - calculateMappedMatrix(filterArea: Rectangle, sprite: Sprite, outputMatrix?: Matrix): Matrix; - capFilterArea(filterArea: Rectangle): void; + bindTexture(): void; + getTexture(): WebGLTexture; + updateTexture(texture: BaseTexture | Texture): WebGLTexture; + destroyTexture(texture: BaseTexture, _skipRemove?: boolean): void; + removeAll(): void; + destroy(): void; + + } + export class TextureGarbageCollector { + + constructor(renderer: WebGLRenderer); + + renderer: WebGLRenderer; + count: number; + checkCount: number; + maxIdle: number; + checkCountMax: number; + mode: number; + + update(): void; + run(): void; + unload(): void; + + } + export abstract class ObjectRenderer extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + start(): void; + stop(): void; + flush(): void; + + render(...args: any[]): void; + + } + export class Quad { + + constructor(gl: WebGLRenderingContext); + + gl: WebGLRenderingContext; + vertices: number[]; + uvs: number[]; + interleaved: number[]; + indices: number[]; + vertexBuffer: WebGLBuffer; + vao: glCore.VertexArrayObject; + initVao(shader: glCore.GLShader): void; + map(targetTextureFrame: Rectangle, destinationFrame: Rectangle): Quad; + draw(): Quad; + upload(): Quad; + destroy(): void; + + } + export class RenderTarget { + + constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: number, resolution: number, root?: boolean); + + gl: WebGLRenderingContext; + frameBuffer: glCore.GLFramebuffer; + texture: Texture; + clearColor: number[]; + size: Rectangle; + resolution: number; + projectionMatrix: Matrix; + transform: Matrix; + frame: Rectangle; + defaultFrame: Rectangle; + destinationFrame: Rectangle; + sourceFrame: Rectangle; + stencilBuffer: glCore.GLFramebuffer; + stencilMaskStack: Graphics[]; + filterData: { + index: number, + stack: { + renderTarget: RenderTarget, + filter: any[]; + bounds: Rectangle + }[] + }; + scaleMode: number; + root: boolean; + + clear(clearColor?: number[]): void; + attachStencilBuffer(): void; + setFrame(destinationFrame: Rectangle, sourceFrame: Rectangle): void; + activate(): void; + calculateProjection(destinationFrame: Rectangle, sourceFrame: Rectangle): void; resize(width: number, height: number): void; destroy(): void; } - export class MaskManager extends WebGLManager { - - stencilStack: StencilMaskStack; - reverse: boolean; - count: number; - alphaMaskPool: any[]; - - pushMask(target: RenderTarget, maskData: any): void; - popMask(target: RenderTarget, maskData: any): void; - pushSpriteMask(target: RenderTarget, maskData: any): void; - popSpriteMask(): void; - pushStencilMask(target: RenderTarget, maskData: any): void; - popStencilMask(target: RenderTarget, maskData: any): void; - - } - export class ShaderManager extends WebGLManager { - - protected _currentId: number; - protected currentShader: Shader; + export class BlendModeManager extends WebGLManager { constructor(renderer: WebGLRenderer); - maxAttibs: number; - attribState: any[]; - tempAttribState: any[]; - stack: any[]; + currentBlendMode: number; - setAttribs(attribs: any[]): void; - setShader(shader: Shader): boolean; - destroy(): void; + setBlendMode(blendMode: number): boolean; } - export class StencilManager extends WebGLManager { + export class FilterManager extends WebGLManager { constructor(renderer: WebGLRenderer); - setMaskStack(stencilMaskStack: StencilMaskStack): void; - pushStencil(graphics: Graphics, webGLData: WebGLGraphicsData): void; - bindGraphics(graphics: Graphics, webGLData: WebGLGraphicsData): void; - popStencil(graphics: Graphics, webGLData: WebGLGraphicsData): void; - destroy(): void; - pushMask(maskData: any[]): void; - popMask(maskData: any[]): void; - - } - export class WebGLManager { - - protected onContextChange: () => void; - - constructor(renderer: WebGLRenderer); - - renderer: WebGLRenderer; - - destroy(): void; - - } - export class Shader { - - protected attributes: any; - protected textureCount: number; - protected uniforms: any; - - protected _glCompile(type: any, src: any): Shader; - - constructor(shaderManager: ShaderManager, vertexSrc: string, fragmentSrc: string, uniforms: any, attributes: any); - - uuid: number; gl: WebGLRenderingContext; - shaderManager: ShaderManager; - program: WebGLProgram; - vertexSrc: string; - fragmentSrc: string; + quad: Quad; + stack: { + renderTarget: RenderTarget; + sourceFrame: Rectangle; + destinationFrame: Rectangle; + filters: Filter[]; + target: any; + resolution: number; + }[]; + stackIndex: number; + shaderCache: any; + filterData: any; - init(): void; - cacheUniformLocations(keys: string[]): void; - cacheAttributeLocations(keys: string[]): void; - compile(): WebGLProgram; - syncUniform(uniform: any): void; - syncUniforms(): void; - initSampler2D(uniform: any): void; + pushFilter(target: RenderTarget, filters: Filter[]): void; + popFilter(): void; + applyFilter(shader: glCore.GLShader | Filter, inputTarget: RenderTarget, outputTarget: RenderTarget, clear?: boolean): void; + syncUniforms(shader: glCore.GLShader, filter: Filter): void; + getRenderTarget(clear?: boolean, resolution?: number): RenderTarget; + returnRenderTarget(renderTarget: RenderTarget): RenderTarget; + calculateScreenSpaceMatrix(outputMatrix: Matrix): Matrix; + calculateNormalisedScreenSpaceMatrix(outputMatrix: Matrix): Matrix; + calculateSpriteMatrix(outputMatrix: Matrix, sprite: Sprite): Matrix; destroy(): void; + emptyPool(): void; + getPotRenderTarget(gl: WebGLRenderingContext, minWidth: number, minHeight: number, resolution: number): RenderTarget; + freePotRenderTarget(renderTarget: RenderTarget): void; } - export class ComplexPrimitiveShader extends Shader { - - constructor(shaderManager: ShaderManager); - - } - export class PrimitiveShader extends Shader { - - constructor(shaderManager: ShaderManager); - - } - export class TextureShader extends Shader { - - constructor(shaderManager: ShaderManager, vertexSrc?: string, fragmentSrc?: string, customUniforms?: any, customAttributes?: any); - - } - export interface StencilMaskStack { + export class StencilMaskStack { stencilStack: any[]; reverse: boolean; count: number; } - export class ObjectRenderer extends WebGLManager { + export class MaskManager extends WebGLManager { - start(): void; - stop(): void; - flush(): void; - render(object?: any): void; + scissor: boolean; + scissorData: any; + scissorRenderTarget: RenderTarget; + enableScissor: boolean; + alphaMaskPool: number[]; + alphaMaskIndex: number; + pushMask(target: RenderTarget, maskData: Sprite | Graphics): void; + popMask(target: RenderTarget, maskData: Sprite | Graphics): void; + pushSpriteMask(target: RenderTarget, maskData: Sprite | Graphics): void; + popSpriteMask(): void; + pushStencilMask(maskData: Sprite | Graphics): void; + popStencilMask(): void; + pushScissorMask(target: RenderTarget, maskData: Sprite | Graphics): void; + popScissorMask(): void; } - export class RenderTarget { + export class StencilManager extends WebGLManager { - constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: number, resolution: number, root: boolean); + constructor(renderer: WebGLRenderer); - gl: WebGLRenderingContext; - frameBuffer: WebGLFramebuffer; - texture: Texture; - size: Rectangle; + stencilMaskStack: Graphics[]; + + setMaskStack(stencilMasStack: Graphics[]): void; + pushStencil(graphics: Graphics): void; + popStencil(): void; + destroy(): void; + + } + export class WebGLManager { + + constructor(renderer: WebGLRenderer); + + renderer: WebGLRenderer; + onContextChange: () => void; + destroy(): void; + + } + export interface IUniformData { + + type: string; + value: any; + + // name is set by pixi if uniforms were automatically extracted from shader code, but not used anywhere + name?: string; + + } + export class Filter { + + // param uniforms should be an object matching type {[name: string]: IUniformData}; + // left untyped as there's no way to define the type without requiring an index signature or making this class generic + constructor(vertexSrc?: string, fragmentSrc?: string, uniforms?: any); + + vertextSrc: string; + fragmentSrc: string; + protected uniformData: { [name: string]: IUniformData }; + uniforms: { [name: string]: any }; + glShaders: any; + glShaderKey: string; + padding: number; resolution: number; - projectionMatrix: Matrix; - transform: Matrix; - frame: Rectangle; - stencilBuffer: WebGLRenderbuffer; - stencilMaskStack: StencilMaskStack; - filterStack: any[]; - scaleMode: number; - root: boolean; + blendMode: number; + enabled: boolean; + apply(filterManager: FilterManager, input: RenderTarget, output: RenderTarget, clear?: boolean): void; - clear(bind?: boolean): void; - attachStencilBuffer(): void; - activate(): void; - calculateProjection(protectionFrame: Matrix): void; - resize(width: number, height: number): void; - destroy(): void; + static defaultVertexSrc: string; + static defaultFragmentSrc: string; } - export interface Quad { + export class SpriteMaskFilter extends Filter { - gl: WebGLRenderingContext; - vertices: number[]; - uvs: number[]; - colors: number[]; - indices: number[]; - vertexBuffer: WebGLBuffer; - indexBuffer: WebGLBuffer; + constructor(sprite: Sprite); - map(rect: Rectangle, rect2: Rectangle): void; - upload(): void; - destroy(): void; + maskSprite: Sprite; + maskMatrix: Matrix; + apply(filterManager: FilterManager, input: RenderTarget, output: RenderTarget): void; } - //sprites + // sprites export class Sprite extends Container { - static fromFrame(frameId: string): Sprite; - static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + constructor(texture?: Texture); + protected _anchor: ObservablePoint; + anchor: ObservablePoint; protected _texture: Texture; protected _width: number; protected _height: number; - protected cachedTint: number; - - protected _onTextureUpdate(): void; - - constructor(texture?: Texture); - - anchor: Point; tint: number; + protected _tint: number; + protected _tintRGB: number; blendMode: number; - shader: Shader | AbstractFilter; + shader: glCore.GLShader | Filter; + protected cachedTint: number; texture: Texture; - + protected textureDirty: boolean; + protected _textureID: number; + protected _transformID: number; + protected vertexTrimmedData: Float32Array; + vertexData: Float32Array; width: number; height: number; - getBounds(matrix?: Matrix): Rectangle; + protected _onTextureUpdate(): void; + calculateVertices(): void; + protected _calculateBounds(): void; + protected calculateTrimmedVertices(): void; + protected onAnchorUpdate(): void; + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; getLocalBounds(): Rectangle; containsPoint(point: Point): boolean; - destroy(destroyTexture?: boolean, destroyBaseTexture?: boolean): void; + destroy(options?: IDestroyOptions | boolean): void; + + static from(source: number | string | BaseTexture | HTMLCanvasElement | HTMLVideoElement): Sprite; + static fromFrame(frameId: string): Sprite; + static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + + } + export class BatchBuffer { + + vertices: ArrayBuffer; + float32View: number[]; + uint32View: number[]; + + destroy(): void; } export class SpriteRenderer extends ObjectRenderer { - protected renderBatch(texture: Texture, size: number, startIndex: number): void; + constructor(renderer: PIXI.WebGLRenderer); vertSize: number; vertByteSize: number; size: number; - vertices: number[]; - positions: number[]; - colors: number[]; + buffers: BatchBuffer[]; indices: number[]; - currentBatchSize: number; + shaders: Shader[]; + currentIndex: number; + tick: number; + groups: any[]; sprites: Sprite[]; - shader: Shader | AbstractFilter; + vertexBuffers: number[]; + vaos: glCore.VertexArrayObject[]; + vaoMax: number; + vertexCount: number; + protected onContextChanged: () => void; + protected onPrerender: () => void; render(sprite: Sprite): void; flush(): void; start(): void; + stop(): void; destroy(): void; } + export class CanvasSpriteRenderer extends ObjectRenderer { - //text + constructor(renderer: WebGLRenderer); - export interface TextStyle { + render(sprite: Sprite): void; + destroy(): void; + + } + export module CanvasTinter { + + export function getTintedTexture(sprite: Sprite, color: number): HTMLCanvasElement; + export function tintWithMultiply(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + export function tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + export function tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + export function roundColor(color: number): number; + + export var cacheStepsPerColorChannel: number; + export var convertTintToImage: boolean; + export var canUseMultiply: boolean; + export var tintMethod: Function; + + } + + // text + + export class TextStyle { - font?: string; - fill?: string | number; align?: string; - stroke?: string | number; - strokeThickness?: number; - wordWrap?: boolean; - wordWrapWidth?: number; - lineHeight?: number; + breakWords?: boolean; dropShadow?: boolean; - dropShadowColor?: string | number; dropShadowAngle?: number; + dropShadowBlur?: number; + dropShadowColor?: string | number; dropShadowDistance?: number; - padding?: number; - textBaseline?: string; + fill?: string | string[] | number | number[] | CanvasGradient | CanvasPattern; + fillGradientType?: number; + fontFamily?: string; + fontSize?: number | string; + fontStyle?: string; + fontVariant?: string; + fontWeight?: string; + letterSpacing?: number; + lineHeight?: number; lineJoin?: string; miterLimit?: number; + padding?: number; + stroke?: string | number; + strokeThickness?: number; + styleID?: number; + textBaseline?: string; + wordWrap?: boolean; + wordWrapWidth?: number; } export class Text extends Sprite { + static getFontStyle(style: TextStyle): string; + static calculateFontProperties(style: string): any; + + constructor(text?: string, style?: TextStyle); + + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; + resolution: number; + protected _text: string; + protected _style: TextStyle; + protected _styleListener: Function; + protected _font: string; + protected localStyleID: number; + static fontPropertiesCache: any; static fontPropertiesCanvas: HTMLCanvasElement; static fontPropertiesContext: CanvasRenderingContext2D; - protected _text: string; - protected _style: TextStyle; - - protected updateText(): void; - protected updateTexture(): void; - protected determineFontProperties(fontStyle: TextStyle): TextStyle; - protected wordWrap(text: string): boolean; - - constructor(text?: string, style?: TextStyle, resolution?: number); - - canvas: HTMLCanvasElement; - context: CanvasRenderingContext2D; - dirty: boolean; - resolution: number; - text: string; - style: TextStyle; - width: number; height: number; + style: TextStyle; + text: string; + + protected updateText(respectDirty?: boolean): void; + protected drawLetterSpacing(text: string, x: number, y: number, isStroke?: boolean): void; + protected updateTexture(): void; + renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + protected wordWrap(text: string): string; + protected _calculateBounds(): void; + protected _onStyleChange: () => void; + protected _generateFillStyle(style: string | number | CanvasGradient, lines: number): string | number | CanvasGradient; + destroy(options?: IDestroyOptions | boolean): void; + dirty: boolean; } - //textures + // textures - export class BaseTexture extends EventEmitter { + export class BaseRenderTexture extends BaseTexture { - static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: number): BaseTexture; - static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): BaseTexture; + constructor(width?: number, height?: number, scaleMode?: number, resolution?: number); - protected _glTextures: any; + height: number; + width: number; + realHeight: number; + realWidth: number; + resolution: number; + scaleMode: number; + hasLoaded: boolean; + protected _glRenderTargets: { [n: number]: WebGLTexture; }; + protected _canvasRenderTarget: { [n: number]: WebGLTexture; }; + valid: boolean; - protected _sourceLoaded(): void; + resize(width: number, height: number): void; + destroy(): void; - constructor(source: HTMLImageElement | HTMLCanvasElement, scaleMode?: number, resolution?: number); + once(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + on(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; - uuid: number; + } + export class BaseTexture extends utils.EventEmitter { + + constructor(source?: HTMLImageElement | HTMLCanvasElement, scaleMode?: number, resolution?: number); + + protected uuid: number; + protected touched: number; resolution: number; width: number; height: number; @@ -981,90 +1384,104 @@ declare namespace PIXI { scaleMode: number; hasLoaded: boolean; isLoading: boolean; - source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; + wrapMode: number; + source: HTMLImageElement | HTMLCanvasElement; + origSource: HTMLImageElement; + imageType: string; + sourceScale: number; premultipliedAlpha: boolean; imageUrl: string; - isPowerOfTwo: boolean; + protected isPowerOfTwo: boolean; mipmap: boolean; + wrap: boolean; + protected _glTextures: any; + protected _enabled: number; + protected _id: number; update(): void; + protected _updateImageType(): void; + protected _loadSvgSource(): void; + protected _loadSvgSourceUsingDataUri(dataUri: string): void; + protected _loadSvgSourceUsingXhr(): void; + protected _loadSvgSourceUsingString(svgString: string): void; loadSource(source: HTMLImageElement | HTMLCanvasElement): void; + protected _sourceLoaded(): void; destroy(): void; dispose(): void; updateSourceImage(newSrc: string): void; - on(event: 'dispose', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - on(event: 'error', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - on(event: 'loaded', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - on(event: 'update', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - on(event: string, fn: Function, context?: any): EventEmitter; + static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: number, sourceScale?: number): BaseTexture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): BaseTexture; - once(event: 'dispose', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - once(event: 'error', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - once(event: 'loaded', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - once(event: 'update', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; + on(event: "update", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + on(event: "loaded", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + on(event: "error", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + on(event: "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + once(event: "update", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + once(event: "loaded", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + once(event: "error", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + once(event: "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; } export class RenderTexture extends Texture { - protected renderWebGL(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; - protected renderCanvas(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; + constructor(baseRenderTexture: BaseRenderTexture, frame?: Rectangle); - constructor(renderer: CanvasRenderer | WebGLRenderer, width?: number, height?: number, scaleMode?: number, resolution?: number); - - width: number; - height: number; - resolution: number; - renderer: CanvasRenderer | WebGLRenderer; + protected legacyRenderer: any; valid: boolean; - render(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; - resize(width: number, height: number, updateBase?: boolean): void; - clear(): void; - destroy(): void; - getImage(): HTMLImageElement; - getPixels(): number[]; - getPixel(x: number, y: number): number[]; - getBase64(): string; - getCanvas(): HTMLCanvasElement; + resize(width: number, height: number, doNotResizeBaseTexture?: boolean): void; + + static create(width?: number, height?: number, scaleMode?: number, resolution?: number): RenderTexture; } - export class Texture extends BaseTexture { + export class Texture extends utils.EventEmitter { - static fromImage(imageUrl: string, crossOrigin?: boolean, scaleMode?: number): Texture; + constructor(baseTexture: BaseTexture, frame?: Rectangle, orig?: Rectangle, trim?: Rectangle, rotate?: number); + + noFrame: boolean; + baseTexture: BaseTexture; + protected _frame: Rectangle; + trim: Rectangle; + valid: boolean; + requiresUpdate: boolean; + protected _uvs: TextureUvs; + orig: Rectangle; + protected _updateID: number; + transform: any; + + update(): void; + protected onBaseTextureLoaded(baseTexture: BaseTexture): void; + protected onBaseTextureUpdated(baseTexture: BaseTexture): void; + destroy(destroyBase?: boolean): void; + clone(): Texture; + protected _updateUvs(): void; + + static fromImage(imageUrl: string, crossOrigin?: boolean, scaleMode?: number, sourceScale?: number): Texture; static fromFrame(frameId: string): Texture; static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): Texture; static fromVideo(video: HTMLVideoElement | string, scaleMode?: number): Texture; static fromVideoUrl(videoUrl: string, scaleMode?: number): Texture; + static from(source: number | string | BaseTexture | HTMLCanvasElement | HTMLVideoElement): Texture; static addTextureToCache(texture: Texture, id: string): void; static removeTextureFromCache(id: string): Texture; - static EMPTY: Texture; - - protected _frame: Rectangle; - protected _uvs: TextureUvs; - - protected onBaseTextureUpdated(baseTexture: BaseTexture): void; - protected onBaseTextureLoaded(baseTexture: BaseTexture): void; - protected _updateUvs(): void; - - constructor(baseTexture: BaseTexture, frame?: Rectangle, crop?: Rectangle, trim?: Rectangle, rotate?: boolean); - - noFrame: boolean; - baseTexture: BaseTexture; - trim: Rectangle; - valid: boolean; - requiresUpdate: boolean; - width: number; - height: number; - crop: Rectangle; - rotate: boolean; frame: Rectangle; + protected _rotate: boolean; + rotate: number; + width: number; + height: number; - update(): void; - destroy(destroyBase?: boolean): void; - clone(): Texture; + static EMPTY: Texture; + + on(event: "update", fn: (texture: Texture) => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + once(event: "update", fn: (texture: Texture) => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + off(event: string, fn: Function, context?: any): utils.EventEmitter; } export class TextureUvs { @@ -1078,645 +1495,43 @@ declare namespace PIXI { x3: number; y3: number; - set(frame: Rectangle, baseFrame: Rectangle, rotate: boolean): void; + uvsUint32: Uint32Array; + + protected set(frame: Rectangle, baseFrame: Rectangle, rotate: number): void; } export class VideoBaseTexture extends BaseTexture { - static fromVideo(video: HTMLVideoElement, scaleMode?: number): VideoBaseTexture; - static fromUrl(videoSrc: string | any | string[] | any[]): VideoBaseTexture; - - protected _loaded: boolean; - protected _onUpdate(): void; - protected _onPlayStart(): void; - protected _onPlayStop(): void; - protected _onCanPlay(): void; - constructor(source: HTMLVideoElement, scaleMode?: number); autoUpdate: boolean; + autoPlay: boolean; + protected _isAutoUpdating: boolean; + update(): void; + protected _onCanPlay(): void; + protected _onPlayStart(): void; + protected _onPlayStop(): void; destroy(): void; + protected _isSourcePlaying(): boolean; + protected _isSourceReady(): boolean; + + static fromVideo(video: HTMLVideoElement, scaleMode?: number): VideoBaseTexture; + static fromUrl(videoSrc: string | any | string[] | any[]): VideoBaseTexture; + static fromUrls(videoSrc: string | any | string[] | any[]): VideoBaseTexture; } - //utils + // ticker - export class utils { - - static uuid(): number; - static hex2rgb(hex: number, out?: number[]): number[]; - static hex2string(hex: number): string; - static rgb2hex(rgb: Number[]): number; - static canUseNewCanvasBlendModel(): boolean; - static getNextPowerOfTwo(number: number): number; - static isPowerOfTwo(width: number, height: number): boolean; - static getResolutionOfUrl(url: string): number; - static sayHello(type: string): void; - static isWebGLSupported(): boolean; - static sign(n: number): number; - static TextureCache: any; - static BaseTextureCache: any; - - } - - ////////////////////////////////////////////////////////////////////////////// - ////////////////////////////EXTRAS//////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export module extras { - - export interface BitmapTextStyle { - - font?: string | { - - name?: string; - size?: number; - - }; - align?: string; - tint?: number; - - } - export class BitmapText extends Container { - - static fonts: any; - - protected _glyphs: Sprite[]; - protected _font: string | { - tint: number; - align: string; - name: string; - size: number; - }; - protected _text: string; - - protected updateText(): void; - - constructor(text: string, style?: BitmapTextStyle); - - textWidth: number; - textHeight: number; - maxWidth: number; - maxLineHeight: number; - dirty: boolean; - - tint: number; - align: string; - font: string | { - tint: number; - align: string; - name: string; - size: number; - }; - text: string; - - } - export class MovieClip extends Sprite { - - static fromFrames(frame: string[]): MovieClip; - static fromImages(images: string[]): MovieClip; - - protected _textures: Texture[]; - protected _durations: number[]; - protected _currentTime: number; - - protected update(deltaTime: number): void; - - constructor(textures: Texture[]); - - animationSpeed: number; - loop: boolean; - onComplete: () => void; - currentFrame: number; - playing: boolean; - - totalFrames: number; - textures: Texture[]; - - stop(): void; - play(): void; - gotoAndStop(frameName: number): void; - gotoAndPlay(frameName: number): void; - destroy(): void; - - } - export class TilingSprite extends Sprite { - - //This is really unclean but is the only way :( - //See http://stackoverflow.com/questions/29593905/typescript-declaration-extending-class-with-static-method/29595798#29595798 - //Thanks bas! - static fromFrame(frameId: string): Sprite; - static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; - - static fromFrame(frameId: string, width?: number, height?: number): TilingSprite; - static fromImage(imageId: string, width?: number, height?: number, crossorigin?: boolean, scaleMode?: number): TilingSprite; - - protected _tileScaleOffset: Point; - protected _tilingTexture: boolean; - protected _refreshTexture: boolean; - protected _uvs: TextureUvs[]; - - constructor(texture: Texture, width: number, height: number); - - tileScale: Point; - tilePosition: Point; - - width: number; - height: number; - originalTexture: Texture; - - getBounds(): Rectangle; - generateTilingTexture(renderer: WebGLRenderer | CanvasRenderer, texture: Texture, forcePowerOfTwo?: boolean): Texture; - containsPoint(point: Point): boolean; - destroy(): void; - - } - - } - - ////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////FILTERS//////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - namespace filters { - - export class AsciiFilter extends AbstractFilter { - size: number; - } - export class BloomFilter extends AbstractFilter { - - blur: number; - blurX: number; - blurY: number; - - } - export class BlurFilter extends AbstractFilter { - - protected blurXFilter: BlurXFilter; - protected blurYFilter: BlurYFilter; - - blur: number; - passes: number; - blurX: number; - blurY: number; - - } - export class BlurXFilter extends AbstractFilter { - - passes: number; - strength: number; - blur: number; - - } - export class BlurYFilter extends AbstractFilter { - - passes: number; - strength: number; - blur: number; - - } - export class SmartBlurFilter extends AbstractFilter { - - } - export class ColorMatrixFilter extends AbstractFilter { - - protected _loadMatrix(matrix: number[], multiply: boolean): void; - protected _multiply(out: number[], a: number[], b: number[]): void; - protected _colorMatrix(matrix: number[]): void; - - matrix: number[]; - - brightness(b: number, multiply?: boolean): void; - greyscale(scale: number, multiply?: boolean): void; - blackAndWhite(multiply?: boolean): void; - hue(rotation: number, multiply?: boolean): void; - contrast(amount: number, multiply?: boolean): void; - saturate(amount: number, multiply?: boolean): void; - desaturate(multiply?: boolean): void; - negative(multiply?: boolean): void; - sepia(multiply?: boolean): void; - technicolor(multiply?: boolean): void; - polaroid(multiply?: boolean): void; - toBGR(multiply?: boolean): void; - kodachrome(multiply?: boolean): void; - browni(multiply?: boolean): void; - vintage(multiply?: boolean): void; - colorTone(desaturation: number, toned: number, lightColor: string, darkColor: string, multiply?: boolean): void; - night(intensity: number, multiply?: boolean): void; - predator(amount: number, multiply?: boolean): void; - lsd(multiply?: boolean): void; - reset(): void; - - } - export class ColorStepFilter extends AbstractFilter { - - step: number; - - } - export class ConvolutionFilter extends AbstractFilter { - - constructor(matrix: number[], width: number, height: number); - - matrix: number[]; - width: number; - height: number; - - } - export class CrossHatchFilter extends AbstractFilter { - - } - export class DisplacementFilter extends AbstractFilter { - - constructor(sprite: Sprite, scale?: number); - - map: Texture; - - scale: Point; - - } - export class DotScreenFilter extends AbstractFilter { - - scale: number; - angle: number; - - } - export class BlurYTintFilter extends AbstractFilter { - - blur: number; - - } - export class DropShadowFilter extends AbstractFilter { - - blur: number; - blurX: number; - blurY: number; - color: number; - alpha: number; - distance: number; - angle: number; - - } - export class GrayFilter extends AbstractFilter { - - gray: number; - - } - export class InvertFilter extends AbstractFilter { - - invert: number; - - } - export class NoiseFilter extends AbstractFilter { - - noise: number; - - } - export class PixelateFilter extends AbstractFilter { - - size: Point; - - } - export class RGBSplitFilter extends AbstractFilter { - - red: number; - green: number; - blue: number; - - } - export class SepiaFilter extends AbstractFilter { - - sepia: number; - - } - export class ShockwaveFilter extends AbstractFilter { - - center: number[]; - params: any; - time: number; - - } - export class TiltShiftAxisFilter extends AbstractFilter { - - blur: number; - gradientBlur: number; - start: number; - end: number; - - updateDelta(): void; - - } - export class TiltShiftFilter extends AbstractFilter { - - blur: number; - gradientBlur: number; - start: number; - end: number; - - } - export class TiltShiftXFilter extends AbstractFilter { - - updateDelta(): void; - - } - export class TiltShiftYFilter extends AbstractFilter { - - updateDelta(): void; - - } - export class TwistFilter extends AbstractFilter { - - offset: Point; - radius: number; - angle: number; - - } - export class FXAAFilter extends AbstractFilter { - - applyFilter(renderer: WebGLRenderer, input: RenderTarget, output: RenderTarget): void; - - } - } - - ////////////////////////////////////////////////////////////////////////////// - ////////////////////////////INTERACTION/////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export module interaction { - - export interface InteractionEvent { - - stopped: boolean; - target: any; - type: string; - data: InteractionData; - stopPropagation(): void; - - } - - export class InteractionData { - - global: Point; - target: DisplayObject; - originalEvent: Event; - identifier: number; - - getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; - - } - - export class InteractionManager { - - protected interactionDOMElement: HTMLElement; - protected eventsAdded: boolean; - protected _tempPoint: Point; - - protected setTargetElement(element: HTMLElement, resolution: number): void; - protected addEvents(): void; - protected removeEvents(): void; - protected dispatchEvent(displayObject: DisplayObject, eventString: string, eventData: any): void; - protected onMouseDown: (event: Event) => void; - protected processMouseDown: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseUp: (event: Event) => void; - protected processMouseUp: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseMove: (event: Event) => void; - protected processMouseMove: (displayObject: DisplayObject, hit: boolean) => void; - protected onMouseOut: (event: Event) => void; - protected processMouseOverOut: (displayObject: DisplayObject, hit: boolean) => void; - protected onTouchStart: (event: Event) => void; - protected processTouchStart: (DisplayObject: DisplayObject, hit: boolean) => void; - protected onTouchEnd: (event: Event) => void; - protected processTouchEnd: (displayObject: DisplayObject, hit: boolean) => void; - protected onTouchMove: (event: Event) => void; - protected processTouchMove: (displayObject: DisplayObject, hit: boolean) => void; - protected getTouchData(touchEvent: InteractionData): InteractionData; - protected returnTouchData(touchData: InteractionData): void; - - constructor(renderer: CanvasRenderer | WebGLRenderer, options?: { autoPreventDefault?: boolean; interactionFrequence?: number; }); - - renderer: CanvasRenderer | WebGLRenderer; - autoPreventDefault: boolean; - interactionFrequency: number; - mouse: InteractionData; - eventData: { - stopped: boolean; - target: any; - type: any; - data: InteractionData; - }; - interactiveDataPool: InteractionData[]; - last: number; - currentCursorStyle: string; - resolution: number; - update(deltaTime: number): void; - - mapPositionToPoint(point: Point, x: number, y: number): void; - processInteractive(point: Point, displayObject: DisplayObject, func: (displayObject: DisplayObject, hit: boolean) => void, hitTest: boolean, interactive: boolean): boolean; - destroy(): void; - - } - - export interface InteractiveTarget { - - interactive: boolean; - buttonMode: boolean; - interactiveChildren: boolean; - defaultCursor: string; - hitArea: HitArea; - - } - - } - - ////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////LOADER///////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - //https://github.com/englercj/resource-loader/blob/master/src/Loader.js - - export module loaders { - export interface LoaderOptions { - - crossOrigin?: boolean; - loadType?: number; - xhrType?: string; - - } - export interface ResourceDictionary { - - [index: string]: PIXI.loaders.Resource; - } - export class Loader extends EventEmitter { - - constructor(baseUrl?: string, concurrency?: number); - - baseUrl: string; - progress: number; - loading: boolean; - resources: ResourceDictionary; - - add(name: string, url: string, options?: LoaderOptions, cb?: () => void): Loader; - add(url: string, options?: LoaderOptions, cb?: () => void): Loader; - //todo I am not sure of object literal notional (or its options) so just allowing any but would love to improve this - add(obj: any, options?: LoaderOptions, cb?: () => void): Loader; - - on(event: 'complete', fn: (loader: loaders.Loader, object: any) => void, context?: any): EventEmitter; - on(event: 'error', fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; - on(event: 'load', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; - on(event: 'progress', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; - on(event: 'start', fn: (loader: loaders.Loader) => void, context?: any): EventEmitter; - on(event: string, fn: Function, context?: any): EventEmitter; - - once(event: 'complete', fn: (loader: loaders.Loader, object: any) => void, context?: any): EventEmitter; - once(event: 'error', fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; - once(event: 'load', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; - once(event: 'progress', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; - once(event: 'start', fn: (loader: loaders.Loader) => void, context?: any): EventEmitter; - once(event: string, fn: Function, context?: any): EventEmitter; - - before(fn: Function): Loader; - pre(fn: Function): Loader; - - after(fn: Function): Loader; - use(fn: Function): Loader; - - reset(): void; - - load(cb?: (loader: loaders.Loader, object: any) => void): Loader; - - } - export class Resource extends EventEmitter { - - static LOAD_TYPE: { - XHR: number; - IMAGE: number; - AUDIO: number; - VIDEO: number; - }; - - static XHR_READ_STATE: { - UNSENT: number; - OPENED: number; - HEADERS_RECIEVED: number; - LOADING: number; - DONE: number; - }; - - static XHR_RESPONSE_TYPE: { - DEFAULT: number; - BUFFER: number; - BLOB: number; - DOCUMENT: number; - JSON: number; - TEXT: number; - }; - - constructor(name?: string, url?: string | string[], options?: LoaderOptions); - - name: string; - texture: Texture; - textures: Texture[]; - url: string; - data: any; - crossOrigin: string; - loadType: number; - xhrType: string; - error: Error; - xhr: XMLHttpRequest; - - complete(): void; - load(cb?: () => void): void; - - } - } - - ////////////////////////////////////////////////////////////////////////////// - ///////////////////////////////MESH/////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////// - - export module mesh { - - export class Mesh extends Container { - - static DRAW_MODES: { - TRIANGLE_MESH: number; - TRIANGLES: number; - }; - - constructor(texture: Texture, vertices?: number[], uvs?: number[], indices?: number[], drawMode?: number); - - texture: Texture; - uvs: number[]; - vertices: number[]; - indices: number[]; - dirty: boolean; - blendMode: number; - canvasPadding: number; - drawMode: number; - shader: Shader | AbstractFilter; - - getBounds(matrix?: Matrix): Rectangle; - containsPoint(point: Point): boolean; - - protected _texture: Texture; - - protected _renderCanvasTriangleMesh(context: CanvasRenderingContext2D): void; - protected _renderCanvasTriangles(context: CanvasRenderingContext2D): void; - protected _renderCanvasDrawTriangle(context: CanvasRenderingContext2D, vertices: number, uvs: number, index0: number, index1: number, index2: number): void; - protected renderMeshFlat(Mesh: Mesh): void; - protected _onTextureUpdate(): void; - - } - export class Rope extends Mesh { - - protected _ready: boolean; - - protected getTextureUvs(): TextureUvs; - - constructor(texture: Texture, points: Point[]); - - points: Point[]; - colors: number[]; - - refresh(): void; - - } - export class Plane extends Mesh { - - segmentsX: number; - segmentsY: number; - - constructor(texture: Texture, segmentsX?: number, segmentsY?: number); - - } - - - export class MeshRenderer extends ObjectRenderer { - - protected _initWebGL(mesh: Mesh): void; - - indices: number[]; - - constructor(renderer: WebGLRenderer); - - render(mesh: Mesh): void; - flush(): void; - start(): void; - destroy(): void; - - } - - export interface MeshShader extends Shader { } - - } - - namespace ticker { + module ticker { export var shared: Ticker; export class Ticker { protected _tick(time: number): void; - protected _emitter: EventEmitter; + protected _emitter: utils.EventEmitter; protected _requestId: number; protected _maxElapsedMS: number; @@ -1744,4 +1559,1078 @@ declare namespace PIXI { } } -} \ No newline at end of file + + // shader + + export class Shader extends glCore.GLShader { } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////EXTRACT/////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module extract { + + export class CanvasExtract { + + protected renderer: CanvasRenderer; + + constructor(renderer: CanvasRenderer); + + image(target?: DisplayObject | RenderTexture): HTMLImageElement; + base64(target?: DisplayObject | RenderTexture): string; + canvas(target?: DisplayObject | RenderTexture): HTMLCanvasElement; + pixels(renderTexture?: DisplayObject | RenderTexture): number[]; + + destroy(): void; + + } + export class WebGLExtract { + protected renderer: CanvasRenderer; + + constructor(renderer: CanvasRenderer); + + image(target?: DisplayObject | RenderTexture): HTMLImageElement; + base64(target?: DisplayObject | RenderTexture): string; + canvas(target?: DisplayObject | RenderTexture): HTMLCanvasElement; + pixels(renderTexture?: DisplayObject | RenderTexture): number[]; + + destroy(): void; + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////EXTRAS//////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module extras { + + export interface IBitmapTextStyle { + + font?: string | { + + name?: string; + size?: number; + + }; + align?: string; + tint?: number; + + } + export class BitmapText extends Container { + + constructor(text: string, style?: IBitmapTextStyle); + + textWidth: number; + textHeight: number; + protected _glyphs: Sprite[]; + protected _font: string | { + name?: string; + size?: number; + }; + font: string | { + name?: string; + size?: number; + }; + protected _text: string; + maxWidth: number; + maxLineHeight: number; + dirty: boolean; + tint: number; + align: string; + text: string; + anchor: PIXI.Point | number; + + protected updateText(): void; + updateTransform(): void; + getLocalBounds(): Rectangle; + validate(): void; + + static fonts: any; + + } + export class AnimatedSprite extends Sprite { + + constructor(textures: Texture[] | { texture: Texture, time?: number }[]); + + protected _textures: Texture[]; + protected _durations: number[]; + textures: Texture[] | { texture: Texture, time?: number }[]; + animationSpeed: number; + loop: boolean; + onComplete: () => void; + onFrameChange: (currentFrame: number) => void; + protected _currentTime: number; + playing: boolean; + totalFrames: number; + currentFrame: number; + stop(): void; + play(): void; + gotoAndStop(frameNumber: number): void; + gotoAndPlay(frameNumber: number): void; + protected update(deltaTime: number): void; + destroy(): void; + + static fromFrames(frame: string[]): AnimatedSprite; + static fromImages(images: string[]): AnimatedSprite; + + } + export class TextureTransform { + + constructor(texture: Texture, clampMargin?: number); + + protected _texture: Texture; + protected mapCoord: Matrix; + protected uClampFrame: Float32Array; + protected uClampOffset: Float32Array; + protected _lastTextureID: number; + + clampOffset: number; + clampMargin: number; + + texture: Texture; + + update(forceUpdate?: boolean): void; + + } + export class TilingSprite extends Sprite { + + constructor(texture: Texture, width?: number, height?: number); + + tileTransform: TransformStatic; + protected _width: number; + protected _height: number; + protected _canvasPattern: CanvasPattern; + uvTransform: TextureTransform; + + clampMargin: number; + tileScale: Point | ObservablePoint; + tilePosition: Point | ObservablePoint; + + protected _onTextureUpdate(): void; + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + protected _calculateBounds(): void; + getLocalBounds(rect?: Rectangle): Rectangle; + containsPoint(point: Point): boolean; + destroy(): void; + + static from(source: number | string | BaseTexture | HTMLCanvasElement | HTMLVideoElement, width?: number, height?: number): TilingSprite; + static fromFrame(frameId: string, width?: number, height?: number): TilingSprite; + // if you remove the next line, the class will break. https://github.com/pixijs/pixi-typescript/issues/96 + static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + static fromImage(imageId: string, width?: number, height?: number, crossorigin?: boolean, scaleMode?: number): TilingSprite; + + width: number; + height: number; + + } + export class TilingSpriteRenderer extends ObjectRenderer { + + constructor(renderer: WebGLRenderer); + + render(ts: TilingSprite): void; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////FILTERS/////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module filters { + + export class FXAAFilter extends Filter { } + export class BlurFilter extends Filter { + + constructor(strength?: number, quality?: number, resolution?: number); + + blurXFilter: BlurXFilter; + blurYFilter: BlurYFilter; + resolution: number; + padding: number; + passes: number; + blur: number; + blurX: number; + blurY: number; + quality: number; + + } + export class BlurXFilter extends Filter { + + constructor(strength?: number, quality?: number, resolution?: number); + + protected _quality: number; + + quality: number; + passes: number; + resolution: number; + strength: number; + firstRun: boolean; + blur: number; + + } + export class BlurYFilter extends Filter { + + constructor(strength?: number, quality?: number, resolution?: number); + + protected _quality: number; + + quality: number; + passes: number; + resolution: number; + strength: number; + firstRun: boolean; + blur: number; + + } + export class ColorMatrixFilter extends Filter { + + constructor(); + + protected _loadMatrix(matrix: number[], multiply?: boolean): void; + protected _multiply(out: number[], a: number[], b: number[]): void; + protected _colorMatrix(matrix: number[]): void; + + matrix: number[]; + + brightness(b: number, multiply?: boolean): void; + greyscale(scale: number, multiply?: boolean): void; + blackAndWhite(multiply?: boolean): void; + hue(rotation: number, multiply?: boolean): void; + contrast(amount: number, multiply?: boolean): void; + saturate(amount: number, multiply?: boolean): void; + desaturate(multiply?: boolean): void; + negative(multiply?: boolean): void; + sepia(multiply?: boolean): void; + technicolor(multiply?: boolean): void; + polaroid(multiply?: boolean): void; + toBGR(multiply?: boolean): void; + kodachrome(multiply?: boolean): void; + browni(multiply?: boolean): void; + vintage(multiply?: boolean): void; + colorTone(desaturation: number, toned: number, lightColor: string, darkColor: string, multiply?: boolean): void; + night(intensity: number, multiply?: boolean): void; + predator(amount: number, multiply?: boolean): void; + lsd(multiply?: boolean): void; + reset(): void; + + } + export class DisplacementFilter extends Filter { + + constructor(sprite: Sprite, scale?: number); + + scale: Point; + map: Texture; + + } + export class VoidFilter extends Filter { + glShaderKey: string; + } + + // pixi-filters.d.ts todo + // https://github.com/pixijs/pixi-filters/ + export class NoiseFilter extends Filter { + + noise: number; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////INTERACTION/////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module interaction { + + export interface InteractionEvent { + + stopped: boolean; + target: DisplayObject; + currentTarget: DisplayObject; + type: string; + data: InteractionData; + stopPropagation(): void; + + } + export class InteractionData { + + global: Point; + + protected _target: DisplayObject; + target: DisplayObject; + targetProxy: DisplayObject; + originalEvent: Event; + + getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; + + } + export class InteractionManager extends utils.EventEmitter { + + constructor(renderer: SystemRenderer, options?: { autoPreventDefault?: boolean; interactionFrequency?: number; }); + + renderer: SystemRenderer; + autoPreventDefault: boolean; + interactionFrequency: number; + mouse: InteractionData; + pointer: InteractionData; + eventData: { + stopped: boolean; + target: any; + type: any; + data: InteractionData; + stopPropagination(): void; + }; + interactiveDataPool: InteractionData[]; + protected interactionDOMElement: HTMLElement; + protected moveWhenInside: boolean; + protected eventsAdded: boolean; + mouseOverRenderer: boolean; + supportsTouchEvents: boolean; + supportsPointerEvents: boolean; + normalizeTouchEvents: boolean; + normalizeMouseEvents: boolean; + + protected onMouseUp: (event: MouseEvent) => void; + protected processMouseUp: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseDown: (event: MouseEvent) => void; + protected processMouseDown: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseMove: (event: MouseEvent) => void; + protected processMouseMove: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseOut: (event: MouseEvent) => void; + protected processMouseOverOut: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseOver: (event: MouseEvent) => void; + + protected onPointerUp: (event: PointerEvent) => void; + protected processPointerUp: (displayObject: DisplayObject, hit: boolean) => void; + protected onPointerDown: (event: PointerEvent) => void; + protected processPointerDown: (displayObject: DisplayObject, hit: boolean) => void; + protected onPointerMove: (event: PointerEvent) => void; + protected processPointerMove: (displayObject: DisplayObject, hit: boolean) => void; + protected onPointerOut: (event: PointerEvent) => void; + protected processPointerOut: (displayObject: DisplayObject, hit: boolean) => void; + protected onPointerOver: (event: PointerEvent) => void; + + protected onTouchStart: (event: TouchEvent) => void; + protected processTouchStart: (DisplayObject: DisplayObject, hit: boolean) => void; + protected onTouchEnd: (event: TouchEvent) => void; + protected processTouchEnd: (displayObject: DisplayObject, hit: boolean) => void; + protected onTouchMove: (event: TouchEvent) => void; + protected processTouchMove: (displayObject: DisplayObject, hit: boolean) => void; + defaultCursorStyle: string; + currentCursorStyle: string; + protected _tempPoint: Point; + resolution: number; + protected setTargetElement(element: HTMLElement, resolution: number): void; + protected addEvents(): void; + protected removeEvents(): void; + update(deltaTime: number): void; + protected dispatchEvent(displayObject: DisplayObject, eventString: string, eventData: any): void; + mapPositionToPoint(point: Point, x: number, y: number): void; + protected processInteractive(point: Point, displayObject: DisplayObject, func: (displayObject: DisplayObject, hit: boolean) => void, hitTest: boolean, interactive: boolean): boolean; + protected _startInteractionProcess(): void; + protected _queueAdd(displayObject: DisplayObject, order: number): void; + protected _finishInteractionProcess(func: Function): void; + protected getTouchData(touchEvent: InteractionData): InteractionData; + protected returnTouchData(touchData: InteractionData): void; + protected normalizeToPointerData(Event: Event): void; + + destroy(): void; + + } + export interface InteractiveTarget { + + interactive: boolean; + interactiveChildren: boolean; + hitArea: IHitArea; + buttonMode: boolean; + defaultCursor: string; + + } + export interface InteractiveTargetProxy extends InteractiveTarget { + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////LOADER///////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + // extends + // https://github.com/englercj/resource-loader/ + // 1.6.4 + + export module loaders { + + export interface ILoaderOptions { + + crossOrigin?: boolean | string; + loadType?: number; + xhrType?: string; + metaData?: any; + + } + export interface IResourceDictionary { + + [index: string]: PIXI.loaders.Resource; + + } + export class Loader extends utils.EventEmitter { + + protected static _pixiMiddleware: Function[]; + static addPixiMiddleware(fn: Function): void; + + constructor(baseUrl?: string, concurrency?: number); + + baseUrl: string; + progress: number; + loading: boolean; + resources: IResourceDictionary; + + add(name: string, url: string, options?: ILoaderOptions, cb?: () => void): Loader; + add(url: string, options?: ILoaderOptions, cb?: () => void): Loader; + // todo I am not sure of object literal notional (or its options) so just allowing any but would love to improve this + add(obj: any, options?: ILoaderOptions, cb?: () => void): Loader; + + on(event: "complete", fn: (loader: loaders.Loader, object: any) => void, context?: any): utils.EventEmitter; + on(event: "error", fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; + on(event: "load", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; + on(event: "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; + on(event: "start", fn: (loader: loaders.Loader) => void, context?: any): utils.EventEmitter; + on(event: string, fn: Function, context?: any): utils.EventEmitter; + + once(event: "complete", fn: (loader: loaders.Loader, object: any) => void, context?: any): utils.EventEmitter; + once(event: "error", fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; + once(event: "load", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; + once(event: "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): utils.EventEmitter; + once(event: "start", fn: (loader: loaders.Loader) => void, context?: any): utils.EventEmitter; + once(event: string, fn: Function, context?: any): utils.EventEmitter; + + before(fn: Function): Loader; + pre(fn: Function): Loader; + + after(fn: Function): Loader; + use(fn: Function): Loader; + + reset(): void; + + load(cb?: (loader: loaders.Loader, object: any) => void): Loader; + + } + export interface ITextureDictionary { + [index: string]: PIXI.Texture; + } + + export class Resource extends utils.EventEmitter { + + static LOAD_TYPE: { + XHR: number; + IMAGE: number; + AUDIO: number; + VIDEO: number; + }; + + static XHR_READ_STATE: { + UNSENT: number; + OPENED: number; + HEADERS_RECIEVED: number; + LOADING: number; + DONE: number; + }; + + static XHR_RESPONSE_TYPE: { + DEFAULT: number; + BUFFER: number; + BLOB: number; + DOCUMENT: number; + JSON: number; + TEXT: number; + }; + + constructor(name?: string, url?: string | string[], options?: ILoaderOptions); + + protected _loadSourceElement(type: string): void; + isLoading: boolean; + isComplete: boolean; + + isJson: boolean; + isXml: boolean; + isImage: boolean; + isAudio: boolean; + isVideo: boolean; + + name: string; + texture: Texture; + textures: ITextureDictionary; + url: string; + data: any; + crossOrigin: boolean | string; + loadType: number; + xhrType: string; + error: Error; + xhr: XMLHttpRequest; + SVGMetadataElement: any; + + metadata: any; + spineAtlas: any; + spineData: any; + + complete(): void; + load(cb?: () => void): void; + abort(message: string): void; + + } + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////MESH/////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module mesh { + + export class Mesh extends Container { + + constructor(texture: Texture, vertices?: Float32Array, uvs?: Float32Array, indices?: Uint16Array, drawMode?: number); + + protected _texture: Texture; + uvs: Float32Array; + vertices: Float32Array; + indices: Uint16Array; + dirty: number; + indexDirty: number; + dirtyVertex: boolean; + protected _geometryVersion: number; + blendMode: number; + canvasPadding: number; + drawMode: number; + texture: Texture; + shader: glCore.GLShader; + tintRgb: Float32Array; + protected _glDatas: { [n: number]: any; }; + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + protected _onTextureUpdate(): void; + protected _calculateBounds(): void; + containsPoint(point: Point): boolean; + tint: number; + + static DRAW_MODES: { + TRIANGLE_MESH: number; + TRIANGLES: number; + }; + + } + + export class CanvasMeshRenderer { + + constructor(renderer: CanvasRenderer); + + renderer: CanvasRenderer; + + render(mesh: Mesh): void; + protected _renderTriangleMesh(mesh: Mesh): void; + protected _renderTriangles(mesh: Mesh): void; + protected _renderDrawTriangle(mesh: Mesh, index0: number, index1: number, index2: number): void; + protected renderMeshFlat(mesh: Mesh): void; + + destroy(): void; + + } + + export class MeshRenderer extends ObjectRenderer { + + constructor(renderer: WebGLRenderer); + + shader: Shader; + render(mesh: Mesh): void; + + } + + export class Plane extends Mesh { + + constructor(texture: Texture, verticesX?: number, verticesY?: number); + protected _ready: boolean; + verticesX: number; + verticesY: number; + drawMode: number; + + refresh(): void; + + protected _onTexureUpdate(): void; + + } + + export class NineSlicePlane extends Plane { + + constructor(texture: Texture, leftWidth?: number, topHeight?: number, rightWidth?: number, bottomHeight?: number); + + width: number; + height: number; + leftWidth: number; + rightWidth: number; + topHeight: number; + bottomHeight: number; + + protected _leftWidth: number; + protected _rightWidth: number; + protected _topHeight: number; + protected _bottomHeight: number; + protected _height: number; + protected _width: number; + protected _origHeight: number; + protected _origWidth: number; + protected _uvh: number; + protected _uvw: number; + + updateHorizontalVertices(): void; + updateVerticalVertices(): void; + protected drawSegment(context: CanvasRenderingContext2D | WebGLRenderingContext, textureSource: any, w: number, h: number, x1: number, y1: number, x2: number, y2: number): void; + + } + + export class Rope extends Mesh { + + constructor(texture: Texture, points: Point[]); + + points: Point[]; + colors: number[]; + protected _ready: boolean; + refresh(): void; + + protected _onTextureUpdate(): void; + updateTransform(): void; + + } + } + + ////////////////////////////////////////////////////////////////////////////// + /////////////////////////////PARTICLES//////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module particles { + + export interface IParticleContainerProperties { + + scale?: boolean; + position?: boolean; + rotation?: boolean; + uvs?: boolean; + alpha?: boolean; + + } + export class ParticleContainer extends Container { + + constructor(size?: number, properties?: IParticleContainerProperties, batchSize?: number); + + protected _properties: boolean[]; + protected _maxSize: number; + protected _batchSize: number; + protected _glBuffers: { [n: number]: WebGLBuffer; }; + protected _bufferToUpdate: number; + interactiveChildren: boolean; + blendMode: number; + roundPixels: boolean; + baseTexture: BaseTexture; + + setProperties(properties: IParticleContainerProperties): void; + protected onChildrenChange: (smallestChildIndex?: number) => void; + + destroy(options?: IDestroyOptions | boolean): void; + + } + export class ParticleBuffer { + + constructor(gl: WebGLRenderingContext, properties: any, dynamicPropertyFlags: any[], size: number); + + gl: WebGLRenderingContext; + vertSize: number; + vertByteSize: number; + size: number; + dynamicProperties: any[]; + staticProperties: any[]; + staticStride: number; + staticBuffer: any; + staticData: any; + dynamicStride: number; + dynamicBuffer: any; + dynamicData: any; + + bind(): void; + destroy(): void; + + } + export interface IParticleRendererProperty { + attribute: number; + size: number; + uploadFunction: (children: PIXI.DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number) => void; + offset: number; + } + export class ParticleRenderer extends ObjectRenderer { + + constructor(renderer: WebGLRenderer); + + shader: glCore.GLShader; + indexBuffer: WebGLBuffer; + properties: IParticleRendererProperty[]; + protected tempMatrix: Matrix; + + start(): void; + generateBuffers(container: ParticleContainer): ParticleBuffer[]; + uploadVertices(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + uploadPosition(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + uploadRotation(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + uploadUvs(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + uploadAlpha(children: DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; + destroy(): void; + + indices: Uint16Array; + + } + export interface IParticleShader extends glCore.GLShader { } + + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////PREPARE/////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module prepare { + + interface addHook { + (item: any, queue: any[]): boolean; + } + interface uploadHook { + (prepare: UploadHookSource, item: any): boolean + } + export abstract class BasePrepare{ + + constructor(renderer: SystemRenderer); + + limiter: CountLimiter | TimeLimiter; + protected renderer: SystemRenderer; + protected uploadHookHelper: UploadHookSource; + protected queue: any[]; + protected addHooks: addHook[]; + protected uploadHooks: uploadHook[]; + protected completes: Function[]; + protected ticking: boolean; + protected delayedTick: () => void; + + upload(item: Function | DisplayObject | Container, done?: () => void): void; + protected tick(): void; + protected prepareItems(): void; + register(addHook?: addHook, uploadHook?: uploadHook): BasePrepare; + add(item: DisplayObject | Container | any): BasePrepare; + destroy(): void; + + } + export class CanvasPrepare extends BasePrepare { + + constructor(renderer: CanvasRenderer); + + protected canvas: HTMLCanvasElement; + protected ctx: CanvasRenderingContext2D; + + } + export class WebGLPrepare extends BasePrepare { + + constructor(renderer: WebGLRenderer); + + } + export class CountLimiter { + + constructor(maxItemsPerFrame: number); + + protected maxItemsPerFrame: number; + protected itemsLeft: number; + + } + export class TimeLimiter { + + constructor(maxMilliseconds: number); + + protected maxMilliseconds: number; + protected frameStart: number; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + /////////////////////////////pixi-gl-core///////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + // pixi-gl-core https://github.com/pixijs/pixi-gl-core + // sharedArrayBuffer as a type is not available yet. + // need to fully define what an `Attrib` is. + export module glCore { + + export interface IContextOptions { + /** + * Boolean that indicates if the canvas contains an alpha buffer. + */ + alpha?: boolean; + /** + * Boolean that indicates that the drawing buffer has a depth buffer of at least 16 bits. + */ + depth?: boolean; + /** + * Boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits. + */ + stencil?: boolean; + /** + * Boolean that indicates whether or not to perform anti-aliasing. + */ + antialias?: boolean; + /** + * Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. + */ + premultipliedAlpha?: boolean; + /** + * If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author. + */ + preserveDrawingBuffer?: boolean; + /** + * Boolean that indicates if a context will be created if the system performance is low. + */ + failIfMajorPerformanceCaveat?: boolean; + } + export function createContext(view: HTMLCanvasElement, options?: IContextOptions): WebGLRenderingContext; + export function setVertexAttribArrays(gl: WebGLRenderingContext, attribs: IAttrib[], state?: WebGLState): WebGLRenderingContext; + export class GLBuffer { + + static EMPTY_ARRAY_BUFFER: ArrayBuffer; + + constructor(gl: WebGLRenderingContext, type: number, data: ArrayBuffer | ArrayBufferView | any, drawType: number); + + protected _updateID: number; + gl: WebGLRenderingContext; + buffer: WebGLBuffer; + type: number; + drawType: number; + data: ArrayBuffer | ArrayBufferView | any; + + upload(data: ArrayBuffer | ArrayBufferView | any, offset: number, dontBind: boolean): void; + bind(): void; + + static createVertexBuffer(gl: WebGLRenderingContext, data: ArrayBuffer | ArrayBufferView | any, drawType: number): WebGLBuffer; + static createIndexBuffer(gl: WebGLRenderingContext, data: ArrayBuffer | ArrayBufferView | any, drawType: number): WebGLBuffer; + static create(gl: WebGLRenderingContext, type: number, data: ArrayBuffer | ArrayBufferView | any, drawType: number): WebGLBuffer; + + destroy(): void; + + } + export class GLFramebuffer { + + constructor(gl: WebGLRenderingContext, width: number, height: number); + + gl: WebGLRenderingContext; + frameBuffer: WebGLFramebuffer; + stencil: WebGLRenderbuffer; + texture: GLTexture; + width: number; + height: number; + + enableTexture(texture: GLTexture): void; + enableStencil(): void; + clear(r: number, g: number, b: number, a: number): void; + bind(): void; + unbind(): void; + resize(width: number, height: number): void; + destroy(): void; + + static createRGBA(gl: WebGLRenderingContext, width: number, height: number, data: ArrayBuffer | ArrayBufferView | any): GLFramebuffer; + static createFloat32(gl: WebGLRenderingContext, width: number, height: number, data: ArrayBuffer | ArrayBufferView | any): GLFramebuffer; + + } + export class GLShader { + + constructor(gl: WebGLRenderingContext, vertexSrc: string | string[], fragmentSrc: string | string[]); + + gl: WebGLRenderingContext; + program: WebGLProgram; + uniforms: any; + + bind(): void; + destroy(): void; + + } + export class GLTexture { + + constructor(gl: WebGLRenderingContext, width: number, height: number, format: number, type: number); + + gl: WebGLRenderingContext; + texture: WebGLTexture; + mipmap: boolean; + premultiplyAlpha: boolean; + width: number; + height: number; + format: number; + type: number; + + upload(source: HTMLImageElement | ImageData | HTMLVideoElement): void; + uploadData(data: number, width: number, height: number): void; + bind(): void; + unbind(): void; + minFilter(linear: boolean): void; + magFilter(linear: boolean): void; + enableMipmap(): void; + enableLinearScaling(): void; + enableNearestScaling(): void; + enableWrapClamp(): void; + enableWrapRepeat(): void; + enableWrapMirrorRepeat(): void; + destroy(): void; + + static fromSource(gl: WebGLRenderingContext, source: HTMLImageElement | ImageData | HTMLVideoElement, premultipleAlpha?: boolean): GLTexture; + static fromData(gl: WebGLRenderingContext, data: number[], width: number, height: number): GLTexture; + + } + export interface IAttrib { + + attribute: { + location: boolean; + size: number; + }; + normalized: boolean; + stride: number; + start: number; + buffer: ArrayBuffer; + + } + export interface IWebGLRenderingContextAttribute { + + buffer: WebGLBuffer; + attribute: any; + type: number; + normalized: boolean; + stride: number; + start: number; + + } + export interface IAttribState { + tempAttribState: IAttrib[]; + attribState: IAttrib[]; + } + + export class VertexArrayObject { + + static FORCE_NATIVE: boolean; + + constructor(gl: WebGLRenderingContext, state: WebGLState); + + protected nativeVaoExtension: any; + protected nativeState: IAttribState; + protected nativeVao: VertexArrayObject; + gl: WebGLRenderingContext; + attributes: IAttrib[]; + indexBuffer: GLBuffer; + dirty: boolean; + + bind(): VertexArrayObject; + unbind(): VertexArrayObject; + activate(): VertexArrayObject; + addAttribute(buffer: GLBuffer, attribute: IAttrib, type: number, normalized: boolean, stride: number, start: number): VertexArrayObject; + addIndex(buffer: GLBuffer, options?: any): VertexArrayObject; + clear(): VertexArrayObject; + draw(type: number, size: number, start: number): VertexArrayObject; + destroy(): void; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////UTILS////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export interface IDecomposedDataUri { + mediaType: string; + subType: string; + encoding: string; + data: any; + } + + export module utils { + + export function uid(): number; + export function hex2rgb(hex: number, out?: number[]): number[]; + export function hex2string(hex: number): string; + export function rgb2hex(rgb: Number[]): number; + export function canUseNewCanvasBlendModes(): boolean; + export function getResolutionOfUrl(url: string): number; + export function getSvgSize(svgString: string): any; + export function decomposeDataUri(dataUri: string): IDecomposedDataUri; + export function getUrlFileExtension(url: string): string; + export function sayHello(type: string): void; + export function skipHello(): void; + export function isWebGLSupported(): boolean; + export function sign(n: number): number; + export function removeItems(arr: T[], startIdx: number, removeCount: number): void; + export var TextureCache: any; + export var BaseTextureCache: any; + + //https://github.com/kaimallea/isMobile + export module isMobile { + export var apple: { + phone: boolean; + ipod: boolean; + tablet: boolean; + device: boolean; + }; + export var android: { + phone: boolean; + tablet: boolean; + device: boolean; + } + export var amazon: { + phone: boolean; + table: boolean; + device: boolean; + } + export var windows: { + phone: boolean; + tablet: boolean; + device: boolean; + } + export var seven_inch: boolean; + export var other: { + blackberry_10: boolean; + blackberry: boolean; + opera: boolean; + firefox: boolean; + chrome: boolean; + device: boolean; + } + export var any: boolean; + export var phone: boolean; + export var tablet: boolean; + } + + // https://github.com/primus/eventemitter3 + export class EventEmitter { + + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + on(event: string, fn: Function, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + removeListener(event: string, fn: Function, context?: any, once?: boolean): EventEmitter; + removeAllListeners(event: string): EventEmitter; + eventNames(): string[]; + + off(event: string, fn: Function, context?: any, once?: boolean): EventEmitter; + addListener(event: string, fn: Function, context?: any): EventEmitter; + + } + + } + +} + +declare module pixi { + export var gl: typeof PIXI.glCore; +} + +declare module "pixi.js" { + export = PIXI; +} diff --git a/pixi.js/pixi.js-tests.ts b/pixi.js/pixi.js-tests.ts index 329560d6f7..44f663af9a 100644 --- a/pixi.js/pixi.js-tests.ts +++ b/pixi.js/pixi.js-tests.ts @@ -209,7 +209,7 @@ namespace basics { private animate = (): void => { - this.filter.uniforms.customUniform.value += 0.04; + this.filter.uniforms['customUniform'].value += 0.04; this.renderer.render(this.stage); requestAnimationFrame(this.animate); @@ -218,9 +218,9 @@ namespace basics { } - export class CustomizedFilter extends PIXI.AbstractFilter { + export class CustomizedFilter extends PIXI.Filter { - constructor(fragmentSource: string | string[]) { + constructor(fragmentSource: string) { super(null, fragmentSource, { customUniform: { type: '1f', @@ -337,7 +337,7 @@ namespace basics { }; - this.renderTexture = new PIXI.RenderTexture(this.renderer, 300, 200, PIXI.SCALE_MODES.LINEAR, 0.1); + this.renderTexture = PIXI.RenderTexture.create(300, 200, PIXI.SCALE_MODES.LINEAR, 0.1); this.sprite = new PIXI.Sprite(this.renderTexture); this.sprite.x = 450; @@ -354,7 +354,7 @@ namespace basics { private animate = (): void => { - this.renderTexture.render(this.container); + this.renderer.render(this.container, this.renderTexture) requestAnimationFrame(this.animate); @@ -374,7 +374,7 @@ namespace basics { private stage: PIXI.Container; - private movie: PIXI.extras.MovieClip; + private movie: PIXI.extras.AnimatedSprite; constructor() { @@ -398,11 +398,11 @@ namespace basics { } - // create a MovieClip (brings back memories from the days of Flash, right ?) - this.movie = new PIXI.extras.MovieClip(frames); + // create a AnimatedSprite (brings back memories from the days of Flash, right ?) + this.movie = new PIXI.extras.AnimatedSprite(frames); /* - * A MovieClip inherits all the properties of a PIXI sprite + * A AnimatedSprite inherits all the properties of a PIXI sprite * so you can change its position, its anchor, mask it, etc */ this.movie.position.set(300); @@ -460,8 +460,11 @@ namespace basics { this.stage.addChild(this.basicText); var style: PIXI.TextStyle = { - font: '36px Arial bold italic', - fill: PIXI.utils.hex2string(0xF7EDCA), + fontSize: 36, + fontFamily: 'Arial', + fontWeight: 'bold', + fontStyle: 'italic', + fill: '#F7EDCA', stroke: '#4a1850', strokeThickness: 5, dropShadow: true, @@ -783,7 +786,7 @@ namespace demos { private stage: PIXI.Container; - private sprites: PIXI.ParticleContainer; + private sprites: PIXI.particles.ParticleContainer; private maggots: BatchDude[]; @@ -799,7 +802,7 @@ namespace demos { // create the root of the scene graph this.stage = new PIXI.Container(); - this.sprites = new PIXI.ParticleContainer(10000, { + this.sprites = new PIXI.particles.ParticleContainer(10000, { scale: true, position: true, @@ -1706,7 +1709,7 @@ namespace demos { this.stage.on('click', this.onClick); this.stage.on('tap', this.onClick); - this.help = new PIXI.Text('Click to turn masking on / off.', { font: 'bold 12pt Arial', fill: 'white' }); + this.help = new PIXI.Text('Click to turn masking on / off.', { fontFamily: 'Arial', fontSize: 12, fontWeight: 'bold', fill: 'white' }); this.help.position.y = this.renderer.height - 26; this.help.position.x = 10; this.stage.addChild(this.help); @@ -1763,7 +1766,7 @@ namespace demos { namespace demos { - export class MovieClipDemo { + export class AnimatedSpriteDemo { private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; @@ -1801,8 +1804,8 @@ namespace demos { for (i = 0; i < 50; i++) { - // create an explosion MovieClip - var explosion = new PIXI.extras.MovieClip(explosionTextures); + // create an explosion AnimatedSprite + var explosion = new PIXI.extras.AnimatedSprite(explosionTextures); explosion.position.x = Math.random() * 800; explosion.position.y = Math.random() * 600; @@ -1862,8 +1865,8 @@ namespace demos { this.stage = new PIXI.Container(); // create two render textures... these dynamic textures will be used to draw the scene into itself - this.renderTexture = new PIXI.RenderTexture(this.renderer, this.renderer.width, this.renderer.height); - this.renderTexture2 = new PIXI.RenderTexture(this.renderer, this.renderer.width, this.renderer.height); + this.renderTexture = PIXI.RenderTexture.create(this.renderer.width, this.renderer.height); + this.renderTexture2 = PIXI.RenderTexture.create(this.renderer.width, this.renderer.height); this.currentTexture = this.renderTexture; // create a new sprite that uses the render texture we created above @@ -1946,7 +1949,7 @@ namespace demos { // render the stage to the texture // the 'true' clears the texture before the content is rendered - this.renderTexture2.render(this.stage, null, false); + this.renderer.render(this.stage, this.renderTexture2, false); // and finally render the stage this.renderer.render(this.stage); @@ -2087,11 +2090,11 @@ namespace demos { this.stage.addChild(this.background); // create some white text using the Snippet webfont - this.textSample = new PIXI.Text('Pixi.js can has\n multiline text!', { font: '35px Snippet', fill: 'white', align: 'left' }); + this.textSample = new PIXI.Text('Pixi.js can has\n multiline text!', { fontSize: 35, fontFamily: 'Snippet', fill: 'white', align: 'left' }); this.textSample.position.set(20); // create a text object with a nice stroke - this.spinningText = new PIXI.Text('I\'m fun!', { font: 'bold 60px Arial', fill: '#cc00ff', align: 'center', stroke: '#FFFFFF', strokeThickness: 6 }); + this.spinningText = new PIXI.Text('I\'m fun!', { fontWeight: 'bold', fontSize: 60, fontFamily: 'Arial', fill: '#cc00ff', align: 'center', stroke: '#FFFFFF', strokeThickness: 6 }); // setting the anchor point to 0.5 will center align the text... great for spinning! this.spinningText.anchor.set(0.5); @@ -2099,7 +2102,7 @@ namespace demos { this.spinningText.position.y = 200; // create a text object that will be updated... - this.countingText = new PIXI.Text('COUNT 4EVAR: 0', { font: 'bold italic 60px Arvo', fill: '#3e1707', align: 'center', stroke: '#a4410e', strokeThickness: 7 }); + this.countingText = new PIXI.Text('COUNT 4EVAR: 0', { fontWeight: 'bold', fontStyle: 'italic', fontSize: 60, fontFamily: 'Arvo', fill: '#3e1707', align: 'center', stroke: '#a4410e', strokeThickness: 7 }); this.countingText.position.x = 310; this.countingText.position.y = 320; @@ -2704,7 +2707,7 @@ namespace filters { this.stage.on('tap', this.onClick); - this.help = new PIXI.Text('Click to turn filters on / off.', { font: 'bold 12pt Arial', fill: 'white' }); + this.help = new PIXI.Text('Click to turn filters on / off.', { fontWeight: 'bold', fontSize: 12, fontFamily: 'Arial', fill: 'white' }); this.help.position.y = this.renderer.height - 25; this.help.position.x = 10; diff --git a/pixi.js/v3/pixi.js-tests.ts b/pixi.js/v3/pixi.js-tests.ts new file mode 100644 index 0000000000..f54da3fb00 --- /dev/null +++ b/pixi.js/v3/pixi.js-tests.ts @@ -0,0 +1,2761 @@ +/// +namespace basics { + + export class Basics { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bunny: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // create a texture from an image path + var texture: PIXI.Texture = PIXI.Texture.fromImage("../../_assets/basics/bunny.png"); + + // create a new Sprite using the texture + this.bunny = new PIXI.Sprite(texture); + + // center the sprite's anchor point + this.bunny.anchor.x = 0.5; + this.bunny.anchor.y = 0.5; + + // move the sprite to the center of the screen + this.bunny.position.x = 200; + this.bunny.position.y = 150; + + //add it to the stage + this.stage.addChild(this.bunny); + + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.bunny.rotation += 0.1; + + this.renderer.render(this.stage); + + } + + } + +} + +namespace basics { + + export class Click { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private sprite: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); + this.sprite.position.set(230, 264); + this.sprite.interactive = true; + this.sprite.on('mousedown', this.onDown, this); + this.sprite.on('touchstart', this.onDown, this); + + //add it to the stage + this.stage.addChild(this.sprite); + + //start animatng + this.animate(); + + } + + private onDown = (eventData: PIXI.interaction.InteractionData): void => { + + this.sprite.scale.x += 0.3; + this.sprite.scale.y += 0.3; + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +namespace basics { + + export class Container { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private container: PIXI.Container; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.container = new PIXI.Container(); + + this.stage.addChild(this.container); + + for (var j = 0; j < 5; j++) { + + for (var i = 0; i < 5; i++) { + + var bunny: PIXI.Sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); + bunny.x = 40 * i; + bunny.y = 40 * j; + this.container.addChild(bunny); + + }; + + }; + + /* + * All the bunnies are added to the container with the addChild method + * when you do this, all the bunnies become children of the container, and when a container moves, + * so do all its children. + * This gives you a lot of flexibility and makes it easier to position elements on the screen + */ + this.container.x = 100; + this.container.y = 60; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +namespace basics { + + export class CustomFilter { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private background: PIXI.Sprite; + + private filter: CustomizedFilter; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.background = PIXI.Sprite.fromImage('../../_assets/bkg-grass.jpg'); + this.background.scale.set(1.3, 1); + this.stage.addChild(this.background); + + + PIXI.loader.add('shader', '../../_assets/basics/shader.frag'); + PIXI.loader.once('complete', this.onLoaded, this); + PIXI.loader.load(); + + } + + private onLoaded(loader: PIXI.loaders.Loader, res: any) { + + var fragmentSrc = res.shader.data; + + this.filter = new CustomizedFilter(fragmentSrc); + this.background.filters = [this.filter]; + + this.animate(); + + + } + + private animate = (): void => { + + this.filter.uniforms.customUniform.value += 0.04; + + this.renderer.render(this.stage); + requestAnimationFrame(this.animate); + + } + + } + + export class CustomizedFilter extends PIXI.AbstractFilter { + + constructor(fragmentSource: string | string[]) { + super(null, fragmentSource, { + customUniform: { + type: '1f', + value: 0 + } + }) + } + + } + +} + +namespace basics { + + export class Graphics { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private graphics: PIXI.Graphics; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + this.graphics = new PIXI.Graphics(); + + // draw a shape + this.graphics.moveTo(50, 50); + this.graphics.lineTo(250, 50); + this.graphics.lineTo(100, 100); + this.graphics.lineTo(50, 50); + this.graphics.endFill(); + + // set a fill and a line style again and draw a rectangle + this.graphics.lineStyle(2, 0x0000FF, 1); + this.graphics.beginFill(0xFF700B, 1); + this.graphics.drawRect(50, 250, 120, 120); + + // draw a rounded rectangle + this.graphics.lineStyle(2, 0xFF00FF, 1); + this.graphics.beginFill(0xFF00BB, 0.25); + this.graphics.drawRoundedRect(150, 450, 300, 100, 15); + this.graphics.endFill(); + + // draw a circle, set the lineStyle to zero so the circle doesn't have an outline + this.graphics.lineStyle(0); + this.graphics.beginFill(0xFFFF0B, 0.5); + this.graphics.drawCircle(470, 90, 60); + this.graphics.endFill(); + + this.stage.addChild(this.graphics); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +namespace basics { + + export class RenderTexture { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private container: PIXI.Container; + + private renderTexture: PIXI.RenderTexture; + + private sprite: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.container = new PIXI.Container(); + + this.stage.addChild(this.container); + + for (var j = 0; j < 5; j++) { + + for (var i = 0; i < 5; i++) { + + var bunny: PIXI.Sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); + bunny.x = 40 * i; + bunny.y = 40 * j; + bunny.rotation = Math.random() * (Math.PI * 2); + this.container.addChild(bunny); + + }; + + }; + + this.renderTexture = new PIXI.RenderTexture(this.renderer, 300, 200, PIXI.SCALE_MODES.LINEAR, 0.1); + + this.sprite = new PIXI.Sprite(this.renderTexture); + this.sprite.x = 450; + this.sprite.y = 60; + this.stage.addChild(this.sprite); + + this.container.x = 100; + this.container.y = 60; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + this.renderTexture.render(this.container); + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +namespace basics { + + export class SpriteSheet { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private movie: PIXI.extras.MovieClip; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + PIXI.loader.add('../../_assets/basics/fighter.json').load((loader: PIXI.loaders.Loader, object: any): void => { + + // create an array of textures from an image path + var frames: PIXI.Texture[] = []; + + for (var i = 0; i < 30; i++) { + + var val = i < 10 ? '0' + i : i; + + // magically works since the spritesheet was loaded with the pixi loader + frames.push(PIXI.Texture.fromFrame('rollSequence00' + val + '.png')); + } + + + // create a MovieClip (brings back memories from the days of Flash, right ?) + this.movie = new PIXI.extras.MovieClip(frames); + + /* + * A MovieClip inherits all the properties of a PIXI sprite + * so you can change its position, its anchor, mask it, etc + */ + this.movie.position.set(300); + this.movie.anchor.set(0.5); + this.movie.animationSpeed = 0.5; + this.movie.play(); + + this.stage.addChild(this.movie); + + this.animate(); + + }); + + } + + private animate = (): void => { + + this.movie.rotation += 0.01; + + //render the stage container + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +namespace basics { + + export class Text { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private basicText: PIXI.Text; + + private richText: PIXI.Text; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.basicText = new PIXI.Text('Basic Text in Pixi'); + this.basicText.x = 30; + this.basicText.y = 90; + + this.stage.addChild(this.basicText); + + var style: PIXI.TextStyle = { + font: '36px Arial bold italic', + fill: PIXI.utils.hex2string(0xF7EDCA), + stroke: '#4a1850', + strokeThickness: 5, + dropShadow: true, + dropShadowColor: '#000000', + dropShadowAngle: Math.PI / 6, + dropShadowDistance: 6, + wordWrap: true, + wordWrapWidth: 440 + }; + + this.richText = new PIXI.Text('Rich Text with a lot of options and across multiple lines', style); + this.richText.x = 30; + this.richText.y = 180; + + this.stage.addChild(this.richText); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +namespace basics { + + export class TexturedMesh { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private strip: PIXI.mesh.Rope; + + private graphics: PIXI.Graphics; + + private count: number; + + private points: PIXI.Point[]; + + private ropeLength: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.count = 0; + + this.ropeLength = 918 / 20; + this.ropeLength = 45; + + this.points = []; + + for (var i = 0; i < 25; i++) { + this.points.push(new PIXI.Point(i * this.ropeLength, 0)); + }; + + this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage('../../_assets/snake.png'), this.points); + this.strip.position.x = -40; + this.strip.position.y = 300; + this.stage.addChild(this.strip); + + this.graphics = new PIXI.Graphics(); + this.graphics.x = this.strip.x; + this.graphics.y = this.strip.y; + this.stage.addChild(this.graphics); + + //start animating + this.animate(); + + } + + private animate = (): void => { + + this.count += 0.1; + + //make the snake + for (var i = 0; i < this.points.length; i++) { + + this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; + + this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; + + }; + + //render the stage + this.renderer.render(this.stage); + + this.renderPoints(); + + requestAnimationFrame(this.animate); + + } + + private renderPoints(): void { + + this.graphics.clear(); + + this.graphics.lineStyle(2, 0xffc2c2); + this.graphics.moveTo(this.points[0].x, this.points[0].y); + + for (var i = 1; i < this.points.length; i++) { + this.graphics.lineTo(this.points[i].x, this.points[i].y); + }; + + for (var i = 1; i < this.points.length; i++) { + this.graphics.beginFill(0xff0022); + this.graphics.drawCircle(this.points[i].x, this.points[i].y, 10); + this.graphics.endFill(); + }; + + } + + } + +} + +namespace basics { + + export class TilingSprite { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private texture: PIXI.Texture; + + private tilingSprite: PIXI.extras.TilingSprite; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + //create a texture from an image path + this.texture = PIXI.Texture.fromImage('../../_assets/p2.jpeg'); + + /* create a tiling sprite ... + * requires a texture, a width and a height + * in WebGL the image size should preferably be a power of two + */ + this.tilingSprite = new PIXI.extras.TilingSprite(this.texture, this.renderer.width, this.renderer.height); + this.stage.addChild(this.tilingSprite); + + this.count = 0; + + this.animate(); + + } + + private animate = (): void => { + + this.count += 0.005; + + this.tilingSprite.tileScale.x = 2 + Math.sin(this.count); + this.tilingSprite.tileScale.y = 2 + Math.cos(this.count); + + this.tilingSprite.tilePosition.x += 1; + this.tilingSprite.tilePosition.y += 1; + + // render the root container + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +namespace basics { + + export class Video { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private texture: PIXI.Texture; + + private videoSprite: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + //create a video texture from a path + this.texture = PIXI.Texture.fromVideo('../../_assets/testVideo.mp4'); + + //create a new sprite using the video texture (yes it's that easy) + this.videoSprite = new PIXI.Sprite(this.texture); + this.videoSprite.width = this.renderer.width; + this.videoSprite.height = this.renderer.height; + this.stage.addChild(this.videoSprite); + + this.stage.addChild(this.videoSprite); + + this.animate(); + + } + + private animate = (): void => { + + //render the stage + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +namespace demos { + + export class AlphaMask { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private background: PIXI.Container; + + private cells: PIXI.Sprite; + + private mask: PIXI.Sprite; + + private target: PIXI.Point; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + this.background = PIXI.Sprite.fromImage('../../_assets/bkg.jpg'); + this.stage.addChild(this.background); + + this.cells = PIXI.Sprite.fromImage('../../_assets/cells.png'); + this.cells.scale.set(1.5, 1.5); + + this.mask = PIXI.Sprite.fromImage('../../_assets/flowerTop.png'); + this.mask.anchor.set(0.5); + this.mask.position.x = 310; + this.mask.position.y = 190; + + this.cells.mask = this.mask; + + this.stage.addChild(this.mask); + + this.stage.addChild(this.cells); + + this.target = new PIXI.Point(); + + this.reset(); + + this.animate(); + + } + + private reset(): void { + + this.target.x = Math.floor(Math.random() * 550); + this.target.y = Math.floor(Math.random() * 300); + + } + + private animate = (): void => { + + this.mask.position.x += (this.target.x - this.mask.x) * 0.1; + this.mask.position.y += (this.target.y - this.mask.y) * 0.1; + + if (Math.abs(this.mask.x - this.target.x) < 1) { + this.reset(); + } + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +namespace demos { + + export class Batch { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private sprites: PIXI.ParticleContainer; + + private maggots: BatchDude[]; + + private tick: number; + + private dudeBounds: PIXI.Rectangle; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.sprites = new PIXI.ParticleContainer(10000, { + + scale: true, + position: true, + rotation: true, + uvs: true, + alpha: true + + }); + this.stage.addChild(this.sprites); + + // create an array to store all the sprites + this.maggots = []; + + var totalSprites = this.renderer instanceof PIXI.WebGLRenderer ? 10000 : 100; + + for (var i = 0; i < totalSprites; i++) { + + // create a new Sprite + var dude = new BatchDude(PIXI.Texture.fromImage('../../_assets/tinyMaggot.png')); + + dude.tint = Math.random() * 0xE8D4CD; + + // set the anchor point so the texture is centerd on the sprite + dude.anchor.set(0.5); + + // different maggots, different sizes + dude.scale.set(0.8 + Math.random() * 0.3); + + // scatter them all + dude.x = Math.random() * this.renderer.width; + dude.y = Math.random() * this.renderer.height; + + dude.tint = Math.random() * 0x808080; + + // create a random direction in radians + dude.direction = Math.random() * Math.PI * 2; + + // this number will be used to modify the direction of the sprite over time + dude.turningSpeed = Math.random() - 0.8; + + // create a random speed between 0 - 2, and these maggots are slooww + dude.speed = (2 + Math.random() * 2) * 0.2; + + dude.offset = Math.random() * 100; + + // finally we push the dude into the maggots array so it it can be easily accessed later + this.maggots.push(dude); + + this.sprites.addChild(dude); + + } + + // create a bounding box box for the little maggots + var dudeBoundsPadding = 100; + this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, + -dudeBoundsPadding, + this.renderer.width + dudeBoundsPadding * 2, + this.renderer.height + dudeBoundsPadding * 2); + + this.tick = 0; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // iterate through the sprites and update their position + for (var i = 0; i < this.maggots.length; i++) { + + var dude = this.maggots[i]; + dude.scale.y = 0.95 + Math.sin(this.tick + dude.offset) * 0.05; + dude.direction += dude.turningSpeed * 0.01; + dude.position.x += Math.sin(dude.direction) * (dude.speed * dude.scale.y); + dude.position.y += Math.cos(dude.direction) * (dude.speed * dude.scale.y); + dude.rotation = -dude.direction + Math.PI; + + // wrap the maggots + if (dude.position.x < this.dudeBounds.x) { + dude.position.x += this.dudeBounds.width; + } + else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + dude.position.x -= this.dudeBounds.width; + } + + if (dude.position.y < this.dudeBounds.y) { + dude.position.y += this.dudeBounds.height; + } + else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + dude.position.y -= this.dudeBounds.height; + } + } + + // increment the ticker + this.tick += 0.1; + + // time to render the stage ! + this.renderer.render(this.stage); + + // request another animation frame... + requestAnimationFrame(this.animate); + + } + + } + + export class BatchDude extends PIXI.Sprite { + + direction: number; + speed: number; + turningSpeed: number; + offset: number; + + constructor(texture: PIXI.Texture) { + + super(texture); + + } + + } + +} + +namespace demos { + + export class BlendModes { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private background: PIXI.Sprite; + + private dudeArray: BlendModesDude[]; + + private totalDudes: number; + + private dudeBounds: PIXI.Rectangle; + + private tick: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // create a new background sprite + this.background = PIXI.Sprite.fromImage('../../_assets/BGrotate.jpg'); + this.stage.addChild(this.background); + + // create an array to store a reference to the dudes + this.dudeArray = []; + + this.totalDudes = 20; + + for (var i = 0; i < this.totalDudes; i++) { + + // create a new Sprite that uses the image name that we just generated as its source + var dude = new BlendModesDude(PIXI.Texture.fromImage('../../_assets/flowerTop.png')); + + dude.anchor.set(0.5); + + // set a random scale for the dude + dude.scale.set(0.8 + Math.random() * 0.3); + + // finally let's set the dude to be at a random position... + dude.position.x = Math.floor(Math.random() * this.renderer.width); + dude.position.y = Math.floor(Math.random() * this.renderer.height); + + // The important bit of this example, this is how you change the default blend mode of the sprite + dude.blendMode = PIXI.BLEND_MODES.ADD; + + // create some extra properties that will control movement + dude.direction = Math.random() * Math.PI * 2; + + // this number will be used to modify the direction of the dude over time + dude.turningSpeed = Math.random() - 0.8; + + // create a random speed for the dude between 0 - 2 + dude.speed = 2 + Math.random() * 2; + + // finally we push the dude into the dudeArray so it it can be easily accessed later + this.dudeArray.push(dude); + + this.stage.addChild(dude); + + } + + // create a bounding box box for the little maggots + var dudeBoundsPadding = 100; + this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, + -dudeBoundsPadding, + this.renderer.width + dudeBoundsPadding * 2, + this.renderer.height + dudeBoundsPadding * 2); + + this.tick = 0; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // iterate through the dudes and update the positions + for (var i = 0; i < this.dudeArray.length; i++) { + + var dude = this.dudeArray[i]; + dude.direction += dude.turningSpeed * 0.01; + dude.position.x += Math.sin(dude.direction) * dude.speed; + dude.position.y += Math.cos(dude.direction) * dude.speed; + dude.rotation = -dude.direction - Math.PI / 2; + + // wrap the dudes by testing their bounds... + if (dude.position.x < this.dudeBounds.x) { + dude.position.x += this.dudeBounds.width; + } + else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + dude.position.x -= this.dudeBounds.width; + } + + if (dude.position.y < this.dudeBounds.y) { + dude.position.y += this.dudeBounds.height; + } + else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + dude.position.y -= this.dudeBounds.height; + } + } + + // increment the ticker + this.tick += 0.1; + + // time to render the stage ! + this.renderer.render(this.stage); + + // request another animation frame... + requestAnimationFrame(this.animate); + + } + + } + + export class BlendModesDude extends PIXI.Sprite { + + direction: number; + speed: number; + turningSpeed: number; + offset: number; + + constructor(texture: PIXI.Texture) { + + super(texture); + + } + + } + +} + +namespace demos { + + export class CacheAsBitmap { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private aliens: PIXI.Sprite[]; + + private alienContainer: PIXI.Container; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // load resources + PIXI.loader + .add('spritesheet', '../../_assets/monsters.json') + .load(this.onAssetsLoaded); + + // holder to store aliens + this.aliens = []; + + this.count = 0; + + // create an empty container + this.alienContainer = new PIXI.Container(); + this.alienContainer.position.x = 400; + this.alienContainer.position.y = 300; + + // make the stage interactive + this.stage.interactive = true; + + this.stage.addChild(this.alienContainer); + + this.stage.on('click', this.onClick); + this.stage.on('tap', this.onClick); + + } + + private onClick = (event: PIXI.interaction.InteractionEvent): void => { + + this.alienContainer.cacheAsBitmap = !this.alienContainer.cacheAsBitmap; + + //feel free to play with what's below + //var sprite = new PIXI.Sprite(this.alienContainer.generateTexture()); + //this.stage.addChild(sprite); + //sprite.position.x = Math.random() * 800; + //sprite.position.y = Math.random() * 600; + + } + + private onAssetsLoaded = (): void => { + + // add a bunch of aliens with textures from image paths + + var alienFrames = ['eggHead.png', 'flowerTop.png', 'helmlok.png', 'skully.png']; + + for (var i = 0; i < 100; i++) { + + var frameName = alienFrames[i % 4]; + + // create an alien using the frame name.. + var alien = PIXI.Sprite.fromFrame(frameName); + alien.tint = Math.random() * 0xFFFFFF; + + /* + * fun fact for the day :) + * another way of doing the above would be + * var texture = PIXI.Texture.fromFrame(frameName); + * var alien = new PIXI.Sprite(texture); + */ + alien.position.x = Math.random() * 800 - 400; + alien.position.y = Math.random() * 600 - 300; + alien.anchor.x = 0.5; + alien.anchor.y = 0.5; + this.aliens.push(alien); + this.alienContainer.addChild(alien); + + } + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // let's rotate the aliens a little bit + for (var i = 0; i < 100; i++) { + var alien = this.aliens[i]; + alien.rotation += 0.1; + } + + this.count += 0.01; + + this.alienContainer.scale.x = Math.sin(this.count); + this.alienContainer.scale.y = Math.sin(this.count); + + this.alienContainer.rotation += 0.01; + + // render the stage + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +namespace demos { + + export class DraggableBunny extends PIXI.Sprite { + + //todo I dont know what event.data is at this time + private data: any; + + private dragging: boolean; + + constructor(texture?: PIXI.Texture) { + + super(texture); + + // enable the bunny to be interactive... this will allow it to respond to mouse and touch events + this.interactive = true; + + // this button mode will mean the hand cursor appears when you roll over the bunny with your mouse + this.buttonMode = true; + + // center the bunny's anchor point + this.anchor.set(0.5); + + // make it a bit bigger, so it's easier to grab + this.scale.set(3); + + // setup events + this + // events for drag start + .on('mousedown', this.onDragStart) + .on('touchstart', this.onDragStart) + // events for drag end + .on('mouseup', this.onDragEnd) + .on('mouseupoutside', this.onDragEnd) + .on('touchend', this.onDragEnd) + .on('touchendoutside', this.onDragEnd) + // events for drag move + .on('mousemove', this.onDragMove) + .on('touchmove', this.onDragMove); + + } + + private onDragStart = (event: PIXI.interaction.InteractionEvent): void => { + + // store a reference to the data + // the reason for this is because of multitouch + // we want to track the movement of this particular touch + this.data = event.data; + this.alpha = 0.5; + this.dragging = true; + + } + + private onDragEnd = (event: PIXI.interaction.InteractionEvent): void => { + + //set interactiondata to null + this.data = null; + this.alpha = 1; + this.dragging = false; + + } + + private onDragMove = (event: PIXI.interaction.InteractionEvent): void => { + + if (this.dragging) { + var newPosition = this.data.getLocalPosition(this.parent); + this.position.x = newPosition.x; + this.position.y = newPosition.y; + } + + } + + } + + export class Dragging { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private texture: PIXI.Texture; + + private data: PIXI.interaction.InteractionData; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + //create a texture from an image + this.texture = PIXI.Texture.fromImage('../../_assets/bunny.png'); + + for (var i = 0; i < 10; i++) { + this.createBunny(Math.floor(Math.random() * 800), Math.floor(Math.random() * 600)); + } + + // start animating + this.animate(); + + } + + private createBunny(x: number, y: number): void { + + // create our little bunny friend.. + var bunny = new DraggableBunny(this.texture); + + // move the sprite to its designated position + bunny.position.x = x; + bunny.position.y = y; + + // add it to the stage + this.stage.addChild(bunny); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +namespace demos { + + export class GraphicsDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private thing: PIXI.Graphics; + + private graphics: PIXI.Graphics; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + this.graphics = new PIXI.Graphics(); + + // set a fill and line style + this.graphics.beginFill(0xFF3300); + this.graphics.lineStyle(10, 0xffd900, 1); + + // draw a shape + this.graphics.moveTo(50, 50); + this.graphics.lineTo(250, 50); + this.graphics.lineTo(100, 100); + this.graphics.lineTo(250, 220); + this.graphics.lineTo(50, 220); + this.graphics.lineTo(50, 50); + this.graphics.endFill(); + + // set a fill and line style again + this.graphics.lineStyle(10, 0xFF0000, 0.8); + this.graphics.beginFill(0xFF700B, 1); + + // draw a second shape + this.graphics.moveTo(210, 300); + this.graphics.lineTo(450, 320); + this.graphics.lineTo(570, 350); + this.graphics.quadraticCurveTo(600, 0, 480, 100); + this.graphics.lineTo(330, 120); + this.graphics.lineTo(410, 200); + this.graphics.lineTo(210, 300); + this.graphics.endFill(); + + // draw a rectangle + this.graphics.lineStyle(2, 0x0000FF, 1); + this.graphics.drawRect(50, 250, 100, 100); + + // draw a circle + this.graphics.lineStyle(0); + this.graphics.beginFill(0xFFFF0B, 0.5); + this.graphics.drawCircle(470, 200, 100); + this.graphics.endFill(); + + this.graphics.lineStyle(20, 0x33FF00); + this.graphics.moveTo(30, 30); + this.graphics.lineTo(600, 300); + + this.stage.addChild(this.graphics); + + // let's create a moving shape + this.thing = new PIXI.Graphics(); + this.stage.addChild(this.thing); + this.thing.position.x = 620 / 2; + this.thing.position.y = 380 / 2; + + this.count = 0; + + // Just click on the stage to draw random lines + this.stage.on('click', this.onClick); + this.stage.on('tap', this.onClick); + + // start animating + this.animate(); + + } + + private onClick = (event: PIXI.interaction.InteractionEvent): void => { + + this.graphics.lineStyle(Math.random() * 30, Math.random() * 0xFFFFFF, 1); + this.graphics.moveTo(Math.random() * 620, Math.random() * 380); + this.graphics.bezierCurveTo(Math.random() * 620, Math.random() * 380, + Math.random() * 620, Math.random() * 380, + Math.random() * 620, Math.random() * 380); + } + + private animate = (): void => { + + this.thing.clear(); + + this.count += 0.1; + + this.thing.clear(); + this.thing.lineStyle(10, 0xff0000, 1); + this.thing.beginFill(0xffFF00, 0.5); + + this.thing.moveTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + this.thing.lineTo(120 + Math.cos(this.count) * 20, -100 + Math.sin(this.count) * 20); + this.thing.lineTo(120 + Math.sin(this.count) * 20, 100 + Math.cos(this.count) * 20); + this.thing.lineTo(-120 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); + this.thing.lineTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + + this.thing.rotation = this.count * 0.1; + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + } + + } + +} + +namespace demos { + + export class Interactivity { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private background: PIXI.Sprite; + + private buttons: InteractivityButton[]; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // create a background... + this.background = PIXI.Sprite.fromImage('../../_assets/button_test_BG.jpg'); + this.background.width = this.renderer.width; + this.background.height = this.renderer.height; + + // add background to stage... + this.stage.addChild(this.background); + + this.buttons = []; + + var buttonPositions = [ + 175, 75, + 655, 75, + 410, 325, + 150, 465, + 685, 445 + ]; + + function noop(): void { + console.log('click'); + } + + // create some textures from an image path + var textureButton = PIXI.Texture.fromImage('../../_assets/button.png'); + var textureButtonDown = PIXI.Texture.fromImage('../../_assets/buttonDown.png'); + var textureButtonOver = PIXI.Texture.fromImage('../../_assets/buttonOver.png'); + + for (var i = 0; i < 5; i++) { + + var button = new InteractivityButton(textureButton, textureButtonDown, textureButtonOver); + + button.position.x = buttonPositions[i * 2]; + button.position.y = buttonPositions[i * 2 + 1]; + + button.tap = noop; + button.click = noop; + + // add it to the stage + this.stage.addChild(button); + + // add button to array + this.buttons.push(button); + + } + + // set some silly values... + this.buttons[0].scale.set(1.2); + + this.buttons[2].rotation = Math.PI / 10; + + this.buttons[3].scale.set(0.8); + + this.buttons[4].scale.set(0.8, 1.2); + this.buttons[4].rotation = Math.PI; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + + export class InteractivityButton extends PIXI.Sprite { + + private textureButton: PIXI.Texture; + private textureButtonDown: PIXI.Texture; + private textureButtonOver: PIXI.Texture; + + tap: Function; + click: Function; + + isdown: boolean; + isOver: boolean; + + constructor(textureButton: PIXI.Texture, textureButtonDown: PIXI.Texture, textureButtonOver: PIXI.Texture) { + + super(textureButton); + + // create some textures from an image path + this.textureButton = textureButton; + this.textureButtonDown = textureButtonDown; + this.textureButtonOver = textureButtonOver; + + this.buttonMode = true; + this.anchor.set(0.5); + + // make the button interactive... + this.interactive = true; + + this + // set the mousedown and touchstart callback... + .on('mousedown', this.onButtonDown) + .on('touchstart', this.onButtonDown) + + // set the mouseup and touchend callback... + .on('mouseup', this.onButtonUp) + .on('touchend', this.onButtonUp) + .on('mouseupoutside', this.onButtonUp) + .on('touchendoutside', this.onButtonUp) + + // set the mouseover callback... + .on('mouseover', this.onButtonOver) + + // set the mouseout callback... + .on('mouseout', this.onButtonOut) + + // you can also listen to click and tap events : + //.on('click', this.noop) + + } + + private onButtonDown = (event: PIXI.interaction.InteractionEvent): void => { + + this.isdown = true; + this.texture = this.textureButtonDown; + this.alpha = 1; + + } + + private onButtonUp = (event: PIXI.interaction.InteractionEvent): void => { + + this.isdown = false; + + if (this.isOver) { + this.texture = this.textureButtonOver; + } + else { + this.texture = this.textureButton; + } + } + + private onButtonOver = (event: PIXI.interaction.InteractionEvent): void => { + + this.isOver = true; + + if (this.isdown) { + return; + } + + this.texture = this.textureButtonOver; + + } + + private onButtonOut = (event: PIXI.interaction.InteractionEvent): void => { + + this.isOver = false; + + if (this.isdown) { + return; + } + + this.texture = this.textureButton; + } + + } + +} + +namespace demos { + + export class Masking { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bg: PIXI.Sprite; + + private container: PIXI.Container; + + private bgFront: PIXI.Sprite; + + private light1: PIXI.Sprite; + + private light2: PIXI.Sprite; + + private panda: PIXI.Sprite; + + private thing: PIXI.Graphics; + + private count: number; + + private help: PIXI.Text; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb, antialias: true }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + this.bg = PIXI.Sprite.fromImage('../../_assets/BGrotate.jpg'); + this.bg.anchor.x = 0.5; + this.bg.anchor.y = 0.5; + + this.bg.position.x = this.renderer.width / 2; + this.bg.position.y = this.renderer.height / 2; + + this.stage.addChild(this.bg); + + this.container = new PIXI.Container(); + this.container.position.x = this.renderer.width / 2; + this.container.position.y = this.renderer.height / 2; + + // add a bunch of sprites + + this.bgFront = PIXI.Sprite.fromImage('../../_assets/SceneRotate.jpg'); + this.bgFront.anchor.x = 0.5; + this.bgFront.anchor.y = 0.5; + + this.container.addChild(this.bgFront); + + this.light2 = PIXI.Sprite.fromImage('../../_assets/LightRotate2.png'); + this.light2.anchor.x = 0.5; + this.light2.anchor.y = 0.5; + this.container.addChild(this.light2); + + this.light1 = PIXI.Sprite.fromImage('../../_assets/LightRotate1.png'); + this.light1.anchor.x = 0.5; + this.light1.anchor.y = 0.5; + this.container.addChild(this.light1); + + this.panda = PIXI.Sprite.fromImage('../../_assets/panda.png'); + this.panda.anchor.x = 0.5; + this.panda.anchor.y = 0.5; + + this.container.addChild(this.panda); + + this.stage.addChild(this.container); + + // let's create a moving shape + this.thing = new PIXI.Graphics(); + this.stage.addChild(this.thing); + this.thing.position.x = this.renderer.width / 2; + this.thing.position.y = this.renderer.height / 2; + this.thing.lineStyle(0); + + this.container.mask = this.thing; + + this.count = 0; + + this.stage.on('click', this.onClick); + this.stage.on('tap', this.onClick); + + this.help = new PIXI.Text('Click to turn masking on / off.', { font: 'bold 12pt Arial', fill: 'white' }); + this.help.position.y = this.renderer.height - 26; + this.help.position.x = 10; + this.stage.addChild(this.help); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + this.bg.rotation += 0.01; + this.bgFront.rotation -= 0.01; + + this.light1.rotation += 0.02; + this.light2.rotation += 0.01; + + this.panda.scale.x = 1 + Math.sin(this.count) * 0.04; + this.panda.scale.y = 1 + Math.cos(this.count) * 0.04; + + this.count += 0.1; + + this.thing.clear(); + + this.thing.beginFill(0x8bc5ff, 0.4); + this.thing.moveTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + this.thing.lineTo(-320 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); + this.thing.lineTo(120 + Math.cos(this.count) * 20, -100 + Math.sin(this.count) * 20); + this.thing.lineTo(120 + Math.sin(this.count) * 20, 100 + Math.cos(this.count) * 20); + this.thing.lineTo(-120 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); + this.thing.lineTo(-120 + Math.sin(this.count) * 20, -300 + Math.cos(this.count) * 20); + this.thing.lineTo(-320 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + this.thing.rotation = this.count * 0.1; + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + private onClick = (event: PIXI.interaction.InteractionEvent): void => { + + if (!this.container.mask) { + this.container.mask = this.thing; + } + else { + this.container.mask = null; + } + } + + } + +} + +namespace demos { + + export class MovieClipDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + PIXI.loader + .add('spritesheet', '../../_assets/mc.json') + .load(this.onAssetsLoaded); + + // start animating + this.animate(); + + } + + private onAssetsLoaded = (loader: PIXI.loaders.Loader): void => { + + // create an array to store the textures + var explosionTextures: PIXI.Texture[] = []; + var i: number; + + for (i = 0; i < 26; i++) { + + var texture = PIXI.Texture.fromFrame('Explosion_Sequence_A ' + (i + 1) + '.png'); + explosionTextures.push(texture); + + } + + for (i = 0; i < 50; i++) { + + // create an explosion MovieClip + var explosion = new PIXI.extras.MovieClip(explosionTextures); + + explosion.position.x = Math.random() * 800; + explosion.position.y = Math.random() * 600; + explosion.anchor.x = 0.5; + explosion.anchor.y = 0.5; + + explosion.rotation = Math.random() * Math.PI; + + explosion.scale.set(0.75 + Math.random() * 0.5); + + explosion.gotoAndPlay(Math.random() * 27); + + this.stage.addChild(explosion); + + } + + // start animating + this.animate(); + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +namespace demos { + + export class RenderTextureDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private renderTexture: PIXI.RenderTexture; + private renderTexture2: PIXI.RenderTexture; + private currentTexture: PIXI.RenderTexture; + + private outputSprite: PIXI.Sprite; + private stuffContainer: PIXI.Container; + private items: PIXI.Sprite[]; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // create two render textures... these dynamic textures will be used to draw the scene into itself + this.renderTexture = new PIXI.RenderTexture(this.renderer, this.renderer.width, this.renderer.height); + this.renderTexture2 = new PIXI.RenderTexture(this.renderer, this.renderer.width, this.renderer.height); + this.currentTexture = this.renderTexture; + + // create a new sprite that uses the render texture we created above + this.outputSprite = new PIXI.Sprite(this.currentTexture); + + // align the sprite + this.outputSprite.position.x = 400; + this.outputSprite.position.y = 300; + this.outputSprite.anchor.set(0.5); + + // add to stage + this.stage.addChild(this.outputSprite); + + this.stuffContainer = new PIXI.Container(); + + this.stuffContainer.position.x = 400; + this.stuffContainer.position.y = 300; + + this.stage.addChild(this.stuffContainer); + + // create an array of image ids.. + var fruits = [ + '../../_assets/spinObj_01.png', + '../../_assets/spinObj_02.png', + '../../_assets/spinObj_03.png', + '../../_assets/spinObj_04.png', + '../../_assets/spinObj_05.png', + '../../_assets/spinObj_06.png', + '../../_assets/spinObj_07.png', + '../../_assets/spinObj_08.png' + ]; + + // create an array of items + this.items = []; + + // now create some items and randomly position them in the stuff container + for (var i = 0; i < 20; i++) { + + var item = PIXI.Sprite.fromImage(fruits[i % fruits.length]); + item.position.x = Math.random() * 400 - 200; + item.position.y = Math.random() * 400 - 200; + + item.anchor.set(0.5); + + this.stuffContainer.addChild(item); + + this.items.push(item); + + } + + // used for spinning! + this.count = 0; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + for (var i = 0; i < this.items.length; i++) { + // rotate each item + var item = this.items[i]; + item.rotation += 0.1; + } + + this.count += 0.01; + + // swap the buffers ... + var temp = this.renderTexture; + this.renderTexture = this.renderTexture2; + this.renderTexture2 = temp; + + // set the new texture + this.outputSprite.texture = this.renderTexture; + + // twist this up! + this.stuffContainer.rotation -= 0.01; + this.outputSprite.scale.set(1 + Math.sin(this.count) * 0.2); + + // render the stage to the texture + // the 'true' clears the texture before the content is rendered + this.renderTexture2.render(this.stage, null, false); + + // and finally render the stage + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +namespace demos { + + export class StripDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private count: number; + + private points: PIXI.Point[]; + + private strip: PIXI.mesh.Rope; + + private snakeContainer: PIXI.Container; + + private ropeLength: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.count = 0; + + // build a rope! + this.ropeLength = 918 / 20; + + this.points = []; + + for (var i = 0; i < 20; i++) { + this.points.push(new PIXI.Point(i * this.ropeLength, 0)); + } + + this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage('../../_assets/snake.png'), this.points); + this.strip.x = -459; + + this.snakeContainer = new PIXI.Container(); + this.snakeContainer.position.x = 400; + this.snakeContainer.position.y = 300; + + this.snakeContainer.scale.set(800 / 1100); + this.stage.addChild(this.snakeContainer); + + this.snakeContainer.addChild(this.strip); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + this.count += 0.1; + + // make the snake + for (var i = 0; i < this.points.length; i++) { + + this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; + + this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; + + } + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +namespace demos { + + export class TextDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bitmapFontText: PIXI.extras.BitmapText; + + private background: PIXI.Sprite; + + private textSample: PIXI.Text; + + private spinningText: PIXI.Text; + + private countingText: PIXI.Text; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + PIXI.loader + .add('desyrel', '../../_assets/desyrel.xml') + .load(this.onAssetsLoaded); + + // start animating + this.animate(); + + } + + private onAssetsLoaded = (): void => { + + this.bitmapFontText = new PIXI.extras.BitmapText('bitmap fonts are\n now supported!', { font: '35px Desyrel', align: 'right' }); + + this.bitmapFontText.position.x = 600 - this.bitmapFontText.textWidth; + this.bitmapFontText.position.y = 20; + + this.stage.addChild(this.bitmapFontText); + + // add a shiny background... + this.background = PIXI.Sprite.fromImage('../../_assets/textDemoBG.jpg'); + this.stage.addChild(this.background); + + // create some white text using the Snippet webfont + this.textSample = new PIXI.Text('Pixi.js can has\n multiline text!', { font: '35px Snippet', fill: 'white', align: 'left' }); + this.textSample.position.set(20); + + // create a text object with a nice stroke + this.spinningText = new PIXI.Text('I\'m fun!', { font: 'bold 60px Arial', fill: '#cc00ff', align: 'center', stroke: '#FFFFFF', strokeThickness: 6 }); + + // setting the anchor point to 0.5 will center align the text... great for spinning! + this.spinningText.anchor.set(0.5); + this.spinningText.position.x = 310; + this.spinningText.position.y = 200; + + // create a text object that will be updated... + this.countingText = new PIXI.Text('COUNT 4EVAR: 0', { font: 'bold italic 60px Arvo', fill: '#3e1707', align: 'center', stroke: '#a4410e', strokeThickness: 7 }); + + this.countingText.position.x = 310; + this.countingText.position.y = 320; + this.countingText.anchor.x = 0.5; + + this.stage.addChild(this.textSample); + this.stage.addChild(this.spinningText); + this.stage.addChild(this.countingText); + + this.count = 0; + + } + + private animate = (): void => { + + + this.renderer.render(this.stage); + + this.count += 0.05; + + // update the text with a new string + this.countingText.text = 'COUNT 4EVAR: ' + Math.floor(this.count); + + // let's spin the spinning text + this.spinningText.rotation += 0.03; + + requestAnimationFrame(this.animate); + } + + } + +} + +namespace demos { + + export class TextureSwap { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bol: boolean; + + private texture: PIXI.Texture; + private secondTexture: PIXI.Texture; + + private dude: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.bol = false; + + //an image path + this.texture = PIXI.Texture.fromImage('../../_assets/flowerTop.png'); + + // create a second texture + this.secondTexture = PIXI.Texture.fromImage('../../_assets/eggHead.png'); + + // create a new Sprite using the texture + this.dude = new PIXI.Sprite(this.texture); + + // center the sprites anchor point + this.dude.anchor.set(0.5); + + // move the sprite to the center of the screen + this.dude.position.x = this.renderer.width / 2; + this.dude.position.y = this.renderer.height / 2; + + this.stage.addChild(this.dude); + + // make the sprite interactive + this.dude.interactive = true; + + this.dude.on('click', (): void => { + this.bol = !this.bol; + + if (this.bol) { + this.dude.texture = this.secondTexture; + } + else { + this.dude.texture = this.texture; + } + }); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // just for fun, let's rotate mr rabbit a little + this.dude.rotation += 0.1; + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +namespace demos { + + export class Tinting { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private totalDudes: number = 10; + private aliens: TintingDude[]; + + private dudeBounds: PIXI.Rectangle; + + private tick: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // holder to store the aliens + this.aliens = []; + + this.tick = 0; + + for (var i = 0; i < this.totalDudes; i++) { + + // create a new Sprite that uses the image name that we just generated as its source + var dude = new TintingDude(); + + // set the anchor point so the texture is centerd on the sprite + dude.anchor.set(0.5); + + // set a random scale for the dude - no point them all being the same size! + dude.scale.set(0.8 + Math.random() * 0.3); + + // finally lets set the dude to be at a random position.. + dude.position.x = Math.random() * this.renderer.width; + dude.position.y = Math.random() * this.renderer.height; + + dude.tint = Math.random() * 0xFFFFFF; + + // create some extra properties that will control movement : + // create a random direction in radians. This is a number between 0 and PI*2 which is the equivalent of 0 - 360 degrees + dude.direction = Math.random() * Math.PI * 2; + + // this number will be used to modify the direction of the dude over time + dude.turningSpeed = Math.random() - 0.8; + + // create a random speed for the dude between 0 - 2 + dude.speed = 2 + Math.random() * 2; + + // finally we push the dude into the aliens array so it it can be easily accessed later + this.aliens.push(dude); + + this.stage.addChild(dude); + + } + + // create a bounding box for the little dudes + var dudeBoundsPadding = 100; + this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, + -dudeBoundsPadding, + this.renderer.width + dudeBoundsPadding * 2, + this.renderer.height + dudeBoundsPadding * 2); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // iterate through the dudes and update their position + for (var i = 0; i < this.aliens.length; i++) { + + var dude = this.aliens[i]; + dude.direction += dude.turningSpeed * 0.01; + dude.position.x += Math.sin(dude.direction) * dude.speed; + dude.position.y += Math.cos(dude.direction) * dude.speed; + dude.rotation = -dude.direction - Math.PI / 2; + + // wrap the dudes by testing their bounds... + if (dude.position.x < this.dudeBounds.x) { + dude.position.x += this.dudeBounds.width; + } + else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + dude.position.x -= this.dudeBounds.width; + } + + if (dude.position.y < this.dudeBounds.y) { + dude.position.y += this.dudeBounds.height; + } + else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + dude.position.y -= this.dudeBounds.height; + } + + } + + // increment the ticker + this.tick += 0.1; + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + + export class TintingDude extends PIXI.Sprite { + + direction: number; + speed: number; + turningSpeed: number; + + constructor() { + super(PIXI.Texture.fromImage('../../_assets/eggHead.png')); + } + + } + +} + +namespace demos { + + export class TransparentBackground { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bunny: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb, transparent: true }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // create a new Sprite from an image path. + this.bunny = PIXI.Sprite.fromImage('../../_assets/bunny.png'); + + // center the sprite's anchor point + this.bunny.anchor.set(0.5); + + // move the sprite to the center of the screen + this.bunny.position.x = 200; + this.bunny.position.y = 150; + + this.stage.addChild(this.bunny); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // just for fun, let's rotate mr rabbit a little + this.bunny.rotation += 0.1; + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +namespace filters { + + export class Blur { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bg: PIXI.Sprite; + + private littleDudes: PIXI.Sprite; + private littleRobot: PIXI.Sprite; + + private blurFilter1: PIXI.filters.BlurFilter; + private blurFilter2: PIXI.filters.BlurFilter; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.bg = PIXI.Sprite.fromImage('../../_assets/depth_blur_BG.jpg'); + this.bg.width = this.renderer.width; + this.bg.height = this.renderer.height; + this.stage.addChild(this.bg); + + this.littleDudes = PIXI.Sprite.fromImage('../../_assets/depth_blur_dudes.jpg'); + this.littleDudes.position.x = (this.renderer.width / 2) - 315; + this.littleDudes.position.y = 200; + this.stage.addChild(this.littleDudes); + + this.littleRobot = PIXI.Sprite.fromImage('../../_assets/depth_blur_moby.jpg'); + this.littleRobot.position.x = (this.renderer.width / 2) - 200; + this.littleRobot.position.y = 100; + this.stage.addChild(this.littleRobot); + + this.blurFilter1 = new PIXI.filters.BlurFilter(); + this.blurFilter2 = new PIXI.filters.BlurFilter(); + + this.littleDudes.filters = [this.blurFilter1]; + this.littleRobot.filters = [this.blurFilter2]; + + this.count = 0; + + //nimate + this.animate(); + + } + + private animate = (): void => { + + this.count += 0.005; + + var blurAmount = Math.cos(this.count); + var blurAmount2 = Math.sin(this.count); + + this.blurFilter1.blur = 20 * (blurAmount); + this.blurFilter2.blur = 20 * (blurAmount2); + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +namespace filters { + + export class DisplacementMap { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private container: PIXI.Container; + + private padding: number; + + private bounds: PIXI.Rectangle; + + private maggots: DisplacementMapDude[]; + + private displacementSprite: PIXI.Sprite; + + private displacementFilter: PIXI.filters.DisplacementFilter; + + private ring: PIXI.Sprite; + + private bg: PIXI.Sprite; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + this.container = new PIXI.Container(); + this.stage.addChild(this.container); + + this.padding = 100; + + this.bounds = new PIXI.Rectangle(-this.padding, -this.padding, this.renderer.width + this.padding * 2, this.renderer.height + this.padding * 2); + this.maggots = []; + + for (var i = 0; i < 20; i++) { + + var maggot = new DisplacementMapDude(); + maggot.anchor.set(0.5); + this.container.addChild(maggot); + + maggot.direction = Math.random() * Math.PI * 2; + maggot.speed = 1; + maggot.turnSpeed = Math.random() - 0.8; + + maggot.position.x = Math.random() * this.bounds.width; + maggot.position.y = Math.random() * this.bounds.height; + + maggot.scale.set(1 + Math.random() * 0.3); + maggot.original = maggot.scale.clone(); + this.maggots.push(maggot); + + } + + this.displacementSprite = PIXI.Sprite.fromImage('../../_assets/displace.png'); + this.displacementFilter = new PIXI.filters.DisplacementFilter(this.displacementSprite); + + this.stage.addChild(this.displacementSprite); + + this.container.filters = [this.displacementFilter]; + + this.displacementFilter.scale.x = 110; + this.displacementFilter.scale.y = 110; + + this.ring = PIXI.Sprite.fromImage('../../_assets/ring.png'); + + this.ring.anchor.set(0.5); + + this.ring.visible = false; + + this.stage.addChild(this.ring); + + this.bg = PIXI.Sprite.fromImage('../../_assets/bkg-grass.jpg'); + this.bg.width = this.renderer.width; + this.bg.height = this.renderer.height; + + this.bg.alpha = 0.4; + + this.container.addChild(this.bg); + + this.stage + .on('mousemove', this.onPointerMove) + .on('touchmove', this.onPointerMove); + + this.count = 0; + + this.animate(); + + } + + private onPointerMove = (eventData: PIXI.interaction.InteractionEvent): void => { + + this.ring.visible = true; + + this.displacementSprite.x = eventData.data.global.x - 100; + this.displacementSprite.y = eventData.data.global.y - this.displacementSprite.height / 2; + + this.ring.position.x = eventData.data.global.x - 25; + this.ring.position.y = eventData.data.global.y; + + }; + + private animate = (): void => { + + this.count += 0.05; + + for (var i = 0; i < this.maggots.length; i++) { + var maggot = this.maggots[i]; + + maggot.direction += maggot.turnSpeed * 0.01; + maggot.position.x += Math.sin(maggot.direction) * maggot.speed; + maggot.position.y += Math.cos(maggot.direction) * maggot.speed; + + maggot.rotation = -maggot.direction - Math.PI / 2; + + maggot.scale.x = maggot.original.x + Math.sin(this.count) * 0.2; + + // wrap the maggots around as the crawl + if (maggot.position.x < this.bounds.x) { + maggot.position.x += this.bounds.width; + } + else if (maggot.position.x > this.bounds.x + this.bounds.width) { + maggot.position.x -= this.bounds.width; + } + + if (maggot.position.y < this.bounds.y) { + maggot.position.y += this.bounds.height; + } + else if (maggot.position.y > this.bounds.y + this.bounds.height) { + maggot.position.y -= this.bounds.height; + } + } + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + }; + + } + + export class DisplacementMapDude extends PIXI.Sprite { + + direction: number; + speed: number; + turnSpeed: number; + original: PIXI.Point; + + constructor() { + + super(PIXI.Texture.fromImage('../../_assets/maggot.png')); + + } + + } + +} + +namespace filters { + + export class Filter { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private background: PIXI.Sprite; + + private filter: PIXI.filters.ColorMatrixFilter; + + private container: PIXI.Container; + + private bgFront: PIXI.Sprite; + private light2: PIXI.Sprite; + private light1: PIXI.Sprite; + private panda: PIXI.Sprite; + + private count: number; + private switchy: boolean; + + private help: PIXI.Text; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + // create a texture from an image path + var texture: PIXI.Texture = PIXI.Texture.fromImage("../../_assets/basics/bunny.png"); + + this.background = PIXI.Sprite.fromImage('_assets/BGrotate.jpg'); + this.background.anchor.set(0.5); + + this.background.position.x = this.renderer.width / 2; + this.background.position.y = this.renderer.height / 2; + + this.filter = new PIXI.filters.ColorMatrixFilter(); + + this.container = new PIXI.Container(); + this.container.position.x = this.renderer.width / 2; + this.container.position.y = this.renderer.height / 2; + + this.bgFront = PIXI.Sprite.fromImage('../../_assets/SceneRotate.jpg'); + this.bgFront.anchor.set(0.5); + + this.container.addChild(this.bgFront); + + this.light2 = PIXI.Sprite.fromImage('../../_assets/LightRotate2.png'); + this.light2.anchor.set(0.5); + this.container.addChild(this.light2); + + this.light1 = PIXI.Sprite.fromImage('../../_assets/LightRotate1.png'); + this.light1.anchor.set(0.5); + this.container.addChild(this.light1); + + this.panda = PIXI.Sprite.fromImage('../../_assets/panda.png'); + this.panda.anchor.set(0.5); + + this.container.addChild(this.panda); + + this.stage.addChild(this.container); + + this.stage.filters = [this.filter]; + + this.count = 0; + this.switchy = false; + + this.stage.on('click', this.onClick); + this.stage.on('tap', this.onClick); + + + this.help = new PIXI.Text('Click to turn filters on / off.', { font: 'bold 12pt Arial', fill: 'white' }); + this.help.position.y = this.renderer.height - 25; + this.help.position.x = 10; + + this.stage.addChild(this.help); + + //nimate + this.animate(); + + } + + private onClick = (): void => { + + this.switchy = !this.switchy; + + if (!this.switchy) { + this.stage.filters = [this.filter]; + } + else { + this.stage.filters = null; + } + + } + + private animate = (): void => { + + this.background.rotation += 0.01; + this.bgFront.rotation -= 0.01; + + this.light1.rotation += 0.02; + this.light2.rotation += 0.01; + + this.panda.scale.x = 1 + Math.sin(this.count) * 0.04; + this.panda.scale.y = 1 + Math.cos(this.count) * 0.04; + + this.count += 0.1; + + var matrix = this.filter.matrix; + + matrix[1] = Math.sin(this.count) * 3; + matrix[2] = Math.cos(this.count); + matrix[3] = Math.cos(this.count) * 1.5; + matrix[4] = Math.sin(this.count / 3) * 2; + matrix[5] = Math.sin(this.count / 2); + matrix[6] = Math.sin(this.count / 4); + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} diff --git a/pixi.js/v3/pixi.js.d.ts b/pixi.js/v3/pixi.js.d.ts new file mode 100644 index 0000000000..3de0f3f296 --- /dev/null +++ b/pixi.js/v3/pixi.js.d.ts @@ -0,0 +1,1748 @@ +// Type definitions for Pixi.js 3.0.9 dev +// Project: https://github.com/GoodBoyDigital/pixi.js/ +// Definitions by: clark-stevenson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class PIXI { + + static VERSION: string; + static PI_2: number; + static RAD_TO_DEG: number; + static DEG_TO_RAD: number; + static TARGET_FPMS: number; + static RENDERER_TYPE: { + UNKNOWN: number; + WEBGL: number; + CANVAS: number; + }; + static BLEND_MODES: { + NORMAL: number; + ADD: number; + MULTIPLY: number; + SCREEN: number; + OVERLAY: number; + DARKEN: number; + LIGHTEN: number; + COLOR_DODGE: number; + COLOR_BURN: number; + HARD_LIGHT: number; + SOFT_LIGHT: number; + DIFFERENCE: number; + EXCLUSION: number; + HUE: number; + SATURATION: number; + COLOR: number; + LUMINOSITY: number; + + }; + static DRAW_MODES: { + POINTS: number; + LINES: number; + LINE_LOOP: number; + LINE_STRIP: number; + TRIANGLES: number; + TRIANGLE_STRIP: number; + TRIANGLE_FAN: number; + }; + static SCALE_MODES: { + DEFAULT: number; + LINEAR: number; + NEAREST: number; + }; + static RETINA_PREFIX: string; + static RESOLUTION: number; + static FILTER_RESOLUTION: number; + static DEFAULT_RENDER_OPTIONS: { + view: HTMLCanvasElement; + resolution: number; + antialias: boolean; + forceFXAA: boolean; + autoResize: boolean; + transparent: boolean; + backgroundColor: number; + clearBeforeRender: boolean; + preserveDrawingBuffer: boolean; + roundPixels: boolean; + }; + static SHAPES: { + POLY: number; + RECT: number; + CIRC: number; + ELIP: number; + RREC: number; + }; + static SPRITE_BATCH_SIZE: number; + +} + +declare namespace PIXI { + + export function autoDetectRenderer(width: number, height: number, options?: PIXI.RendererOptions, noWebGL?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; + export var loader: PIXI.loaders.Loader; + + //https://github.com/primus/eventemitter3 + export class EventEmitter { + + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + on(event: string, fn: Function, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + removeListener(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + + off(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; + addListener(event: string, fn: Function, context?: any): EventEmitter; + + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////CORE////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + //display + + export class DisplayObject extends EventEmitter implements interaction.InteractiveTarget { + + //begin extras.cacheAsBitmap see https://github.com/pixijs/pixi-typescript/commit/1207b7f4752d79a088d6a9a465a3ec799906b1db + protected _originalRenderWebGL: WebGLRenderer; + protected _originalRenderCanvas: CanvasRenderer; + protected _originalUpdateTransform: boolean; + protected _originalHitTest: any; + protected _cachedSprite: any; + protected _originalDestroy: any; + + cacheAsBitmap: boolean; + + protected _renderCachedWebGL(renderer: WebGLRenderer): void; + protected _initCachedDisplayObject(renderer: WebGLRenderer): void; + protected _renderCachedCanvas(renderer: CanvasRenderer): void; + protected _initCachedDisplayObjectCanvas(renderer: CanvasRenderer): void; + protected _getCachedBounds(): Rectangle; + protected _destroyCachedDisplayObject(): void; + protected _cacheAsBitmapDestroy(): void; + //end extras.cacheAsBitmap + + protected _sr: number; + protected _cr: number; + protected _bounds: Rectangle; + protected _currentBounds: Rectangle; + protected _mask: Rectangle; + protected _cachedObject: any; + + updateTransform(): void; + + position: Point; + scale: Point; + pivot: Point; + rotation: number; + renderable: boolean; + alpha: number; + visible: boolean; + parent: Container; + worldAlpha: number; + worldTransform: Matrix; + filterArea: Rectangle; + + x: number; + y: number; + worldVisible: boolean; + mask: Graphics | Sprite; + filters: AbstractFilter[]; + name: string; + + getBounds(matrix?: Matrix): Rectangle; + getLocalBounds(): Rectangle; + toGlobal(position: Point): Point; + toLocal(position: Point, from?: DisplayObject): Point; + generateTexture(renderer: CanvasRenderer | WebGLRenderer, scaleMode: number, resolution: number): Texture; + setParent(container: Container): Container; + setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, pivotX?: number, pivotY?: number): DisplayObject; + destroy(): void; + getChildByName(name: string): DisplayObject; + getGlobalPosition(point: Point): Point; + + interactive: boolean; + buttonMode: boolean; + interactiveChildren: boolean; + defaultCursor: string; + hitArea: HitArea; + + on(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; + + once(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + + } + + export class Container extends DisplayObject { + + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + + protected onChildrenChange: () => void; + + children: DisplayObject[]; + + width: number; + height: number; + + addChild(...child: DisplayObject[]): DisplayObject; + addChildAt(child: DisplayObject, index: number): DisplayObject; + swapChildren(child: DisplayObject, child2: DisplayObject): void; + getChildIndex(child: DisplayObject): number; + setChildIndex(child: DisplayObject, index: number): void; + getChildAt(index: number): DisplayObject; + removeChild(child: DisplayObject): DisplayObject; + removeChildAt(index: number): DisplayObject; + removeChildren(beginIndex?: number, endIndex?: number): DisplayObject[]; + destroy(destroyChildren?: boolean): void; + generateTexture(renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer, resolution?: number, scaleMode?: number): Texture; + + renderWebGL(renderer: WebGLRenderer): void; + renderCanvas(renderer: CanvasRenderer): void; + + once(event: 'added', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + once(event: 'removed', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + on(event: 'added', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; + on(event: 'removed', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; + + } + + //graphics + + export class GraphicsData { + + constructor(lineWidth: number, lineColor: number, lineAlpha: number, fillColor: number, fillAlpha: number, fill: boolean, shape: Circle | Rectangle | Ellipse | Polygon); + + lineWidth: number; + lineColor: number; + lineAlpha: number; + fillColor: number; + fillAlpha: number; + fill: boolean; + shape: Circle | Rectangle | Ellipse | Polygon; + type: number; + + clone(): GraphicsData; + + protected _lineTint: number; + protected _fillTint: number; + + } + export class Graphics extends Container { + + protected boundsDirty: boolean; + protected dirty: boolean; + protected glDirty: boolean; + + fillAlpha: number; + lineWidth: number; + lineColor: number; + tint: number; + blendMode: number; + isMask: boolean; + boundsPadding: number; + + clone(): Graphics; + lineStyle(lineWidth?: number, color?: number, alpha?: number): Graphics; + moveTo(x: number, y: number): Graphics; + lineTo(x: number, y: number): Graphics; + quadraticCurveTo(cpX: number, cpY: number, toX: number, toY: number): Graphics; + bezierCurveTo(cpX: number, cpY: number, cpX2: number, cpY2: number, toX: number, toY: number): Graphics; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics; + arc(cx: number, cy: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): Graphics; + beginFill(color: number, alpha?: number): Graphics; + endFill(): Graphics; + drawRect(x: number, y: number, width: number, height: number): Graphics; + drawRoundedRect(x: number, y: number, width: number, height: number, radius: number): Graphics; + drawCircle(x: number, y: number, radius: number): Graphics; + drawEllipse(x: number, y: number, width: number, height: number): Graphics; + drawPolygon(path: number[] | Point[]): Graphics; + clear(): Graphics; + //todo + generateTexture(renderer: WebGLRenderer | CanvasRenderer, resolution?: number, scaleMode?: number): Texture; + getBounds(matrix?: Matrix): Rectangle; + containsPoint(point: Point): boolean; + updateLocalBounds(): void; + drawShape(shape: Circle | Rectangle | Ellipse | Polygon): GraphicsData; + + } + export interface GraphicsRenderer extends ObjectRenderer { + //yikes todo + } + export interface WebGLGraphicsData { + //yikes todo! + } + + //math + + export class Point { + + x: number; + y: number; + + constructor(x?: number, y?: number); + + clone(): Point; + copy(p: Point): void; + equals(p: Point): boolean; + set(x?: number, y?: number): void; + + } + export class Matrix { + + a: number; + b: number; + c: number; + d: number; + tx: number; + ty: number; + + fromArray(array: number[]): void; + toArray(transpose?: boolean, out?: number[]): number[]; + apply(pos: Point, newPos?: Point): Point; + applyInverse(pos: Point, newPos?: Point): Point; + translate(x: number, y: number): Matrix; + scale(x: number, y: number): Matrix; + rotate(angle: number): Matrix; + append(matrix: Matrix): Matrix; + prepend(matrix: Matrix): Matrix; + invert(): Matrix; + identity(): Matrix; + clone(): Matrix; + copy(matrix: Matrix): Matrix; + set(a: number, b: number, c: number, d: number, tx: number, ty: number): Matrix; + setTransform(a: number, b: number, c: number, d: number, sr: number, cr: number, cy: number, sy: number, nsx: number, cs: number): PIXI.Matrix; + + static IDENTITY: Matrix; + static TEMP_MATRIX: Matrix; + + } + + export interface HitArea { + + contains(x: number, y: number): boolean; + + } + + export class Circle implements HitArea { + + constructor(x?: number, y?: number, radius?: number); + + x: number; + y: number; + radius: number; + type: number; + + clone(): Circle; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; + + } + export class Ellipse implements HitArea { + + constructor(x?: number, y?: number, width?: number, height?: number); + + x: number; + y: number; + width: number; + height: number; + type: number; + + clone(): Ellipse; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; + + } + export class Polygon implements HitArea { + + constructor(points: Point[]); + constructor(points: number[]); + constructor(...points: Point[]); + constructor(...points: number[]); + + closed: boolean; + points: number[]; + type: number; + + clone(): Polygon; + contains(x: number, y: number): boolean; + + + } + export class Rectangle implements HitArea { + + constructor(x?: number, y?: number, width?: number, height?: number); + + x: number; + y: number; + width: number; + height: number; + type: number; + + static EMPTY: Rectangle; + + clone(): Rectangle; + contains(x: number, y: number): boolean; + + } + export class RoundedRectangle implements HitArea { + + constructor(x?: number, y?: number, width?: number, height?: number, radius?: number); + + x: number; + y: number; + width: number; + height: number; + radius: number; + type: number; + + static EMPTY: Rectangle; + + clone(): Rectangle; + contains(x: number, y: number): boolean; + + } + + //particles + + export interface ParticleContainerProperties { + + scale?: boolean; + position?: boolean; + rotation?: boolean; + uvs?: boolean; + alpha?: boolean; + + } + export class ParticleContainer extends Container { + + constructor(size?: number, properties?: ParticleContainerProperties, batchSize?: number); + + protected _maxSize: number; + protected _batchSize: number; + protected _properties: boolean[]; + protected _buffers: WebGLBuffer[]; + protected _bufferToUpdate: number; + + protected onChildrenChange: (smallestChildIndex?: number) => void; + + interactiveChildren: boolean; + blendMode: number; + roundPixels: boolean; + + setProperties(properties: ParticleContainerProperties): void; + + } + export interface ParticleBuffer { + + gl: WebGLRenderingContext; + vertSize: number; + vertByteSize: number; + size: number; + dynamicProperties: any[]; + staticProperties: any[]; + + staticStride: number; + staticBuffer: any; + staticData: any; + dynamicStride: number; + dynamicBuffer: any; + dynamicData: any; + + initBuffers(): void; + bind(): void; + destroy(): void; + + } + export interface ParticleRenderer { + + } + export interface ParticleShader { + + } + + //renderers + + export interface RendererOptions { + + view?: HTMLCanvasElement; + transparent?: boolean; + antialias?: boolean; + autoResize?: boolean; + resolution?: number; + clearBeforeRendering?: boolean; + preserveDrawingBuffer?: boolean; + forceFXAA?: boolean; + roundPixels?: boolean; + backgroundColor?: number; + + } + export class SystemRenderer extends EventEmitter { + + protected _backgroundColor: number; + protected _backgroundColorRgb: number[]; + protected _backgroundColorString: string; + protected _tempDisplayObjectParent: any; + protected _lastObjectRendered: DisplayObject; + + constructor(system: string, width?: number, height?: number, options?: RendererOptions); + + type: number; + width: number; + height: number; + view: HTMLCanvasElement; + resolution: number; + transparent: boolean; + autoResize: boolean; + blendModes: any; //todo? + preserveDrawingBuffer: boolean; + clearBeforeRender: boolean; + roundPixels: boolean; + backgroundColor: number; + + render(object: DisplayObject): void; + resize(width: number, height: number): void; + destroy(removeView?: boolean): void; + + } + export class CanvasRenderer extends SystemRenderer { + + protected renderDisplayObject(displayObject: DisplayObject, context: CanvasRenderingContext2D): void; + protected _mapBlendModes(): void; + + constructor(width?: number, height?: number, options?: RendererOptions); + + context: CanvasRenderingContext2D; + refresh: boolean; + maskManager: CanvasMaskManager; + roundPixels: boolean; + smoothProperty: string; + + render(object: DisplayObject): void; + resize(w: number, h: number): void; + + } + export class CanvasBuffer { + + protected clear(): void; + + constructor(width: number, height: number); + + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; + + width: number; + height: number; + + resize(width: number, height: number): void; + destroy(): void; + + } + export class CanvasGraphics { + + static renderGraphicsMask(graphics: Graphics, context: CanvasRenderingContext2D): void; + static updateGraphicsTint(graphics: Graphics): void; + + static renderGraphics(graphics: Graphics, context: CanvasRenderingContext2D): void; + + } + export class CanvasMaskManager { + + pushMask(maskData: any, renderer: WebGLRenderer | CanvasRenderer): void; + popMask(renderer: WebGLRenderer | CanvasRenderer): void; + destroy(): void; + + } + export class CanvasTinter { + + static getTintedTexture(sprite: DisplayObject, color: number): HTMLCanvasElement; + static tintWithMultiply(texture: Texture, color: number, canvas: HTMLDivElement): void; + static tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + static tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + static roundColor(color: number): number; + static cacheStepsPerColorChannel: number; + static convertTintToImage: boolean; + static vanUseMultiply: boolean; + static tintMethod: Function; + + } + export class WebGLRenderer extends SystemRenderer { + + protected _useFXAA: boolean; + protected _FXAAFilter: filters.FXAAFilter; + protected _contextOptions: { + alpha: boolean; + antiAlias: boolean; + premultipliedAlpha: boolean; + stencil: boolean; + preseveDrawingBuffer: boolean; + }; + protected _renderTargetStack: RenderTarget[]; + + protected _initContext(): void; + protected _createContext(): void; + protected handleContextLost: (event: WebGLContextEvent) => void; + protected _mapGlModes(): void; + protected _managedTextures: Texture[]; + + constructor(width?: number, height?: number, options?: RendererOptions); + + drawCount: number; + shaderManager: ShaderManager; + maskManager: MaskManager; + stencilManager: StencilManager; + filterManager: FilterManager; + blendModeManager: BlendModeManager; + currentRenderTarget: RenderTarget; + currentRenderer: ObjectRenderer; + + render(object: DisplayObject): void; + renderDisplayObject(displayObject: DisplayObject, renderTarget: RenderTarget, clear: boolean): void; + setObjectRenderer(objectRenderer: ObjectRenderer): void; + setRenderTarget(renderTarget: RenderTarget): void; + updateTexture(texture: BaseTexture | Texture): BaseTexture | Texture; + destroyTexture(texture: BaseTexture | Texture, _skipRemove?: boolean): void; + + } + export class AbstractFilter { + + protected vertexSrc: string[]; + protected fragmentSrc: string[]; + + constructor(vertexSrc?: string | string[], fragmentSrc?: string | string[], uniforms?: any); + + uniforms: any; + + padding: number; + + getShader(renderer: WebGLRenderer): Shader; + applyFilter(renderer: WebGLRenderer, input: RenderTarget, output: RenderTarget, clear?: boolean): void; + syncUniform(uniform: WebGLUniformLocation): void; + + } + export class SpriteMaskFilter extends AbstractFilter { + + constructor(sprite: Sprite); + + maskSprite: Sprite; + maskMatrix: Matrix; + + applyFilter(renderer: WebGLRenderbuffer, input: RenderTarget, output: RenderTarget): void; + map: Texture; + offset: Point; + + } + export class BlendModeManager extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + setBlendMode(blendMode: number): boolean; + + } + + export class FilterManager extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + filterStack: any[]; + renderer: WebGLRenderer; + texturePool: any[]; + + onContextChange: () => void; + setFilterStack(filterStack: any[]): void; + pushFilter(target: RenderTarget, filters: any[]): void; + popFilter(): AbstractFilter; + getRenderTarget(clear?: boolean): RenderTarget; + protected returnRenderTarget(renderTarget: RenderTarget): void; + applyFilter(shader: Shader | AbstractFilter, inputTarget: RenderTarget, outputTarget: RenderTarget, clear?: boolean): void; + calculateMappedMatrix(filterArea: Rectangle, sprite: Sprite, outputMatrix?: Matrix): Matrix; + capFilterArea(filterArea: Rectangle): void; + resize(width: number, height: number): void; + destroy(): void; + + } + + export class MaskManager extends WebGLManager { + + stencilStack: StencilMaskStack; + reverse: boolean; + count: number; + alphaMaskPool: any[]; + + pushMask(target: RenderTarget, maskData: any): void; + popMask(target: RenderTarget, maskData: any): void; + pushSpriteMask(target: RenderTarget, maskData: any): void; + popSpriteMask(): void; + pushStencilMask(target: RenderTarget, maskData: any): void; + popStencilMask(target: RenderTarget, maskData: any): void; + + } + export class ShaderManager extends WebGLManager { + + protected _currentId: number; + protected currentShader: Shader; + + constructor(renderer: WebGLRenderer); + + maxAttibs: number; + attribState: any[]; + tempAttribState: any[]; + stack: any[]; + + setAttribs(attribs: any[]): void; + setShader(shader: Shader): boolean; + destroy(): void; + + } + export class StencilManager extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + setMaskStack(stencilMaskStack: StencilMaskStack): void; + pushStencil(graphics: Graphics, webGLData: WebGLGraphicsData): void; + bindGraphics(graphics: Graphics, webGLData: WebGLGraphicsData): void; + popStencil(graphics: Graphics, webGLData: WebGLGraphicsData): void; + destroy(): void; + pushMask(maskData: any[]): void; + popMask(maskData: any[]): void; + + } + export class WebGLManager { + + protected onContextChange: () => void; + + constructor(renderer: WebGLRenderer); + + renderer: WebGLRenderer; + + destroy(): void; + + } + export class Shader { + + protected attributes: any; + protected textureCount: number; + protected uniforms: any; + + protected _glCompile(type: any, src: any): Shader; + + constructor(shaderManager: ShaderManager, vertexSrc: string, fragmentSrc: string, uniforms: any, attributes: any); + + uuid: number; + gl: WebGLRenderingContext; + shaderManager: ShaderManager; + program: WebGLProgram; + vertexSrc: string; + fragmentSrc: string; + + init(): void; + cacheUniformLocations(keys: string[]): void; + cacheAttributeLocations(keys: string[]): void; + compile(): WebGLProgram; + syncUniform(uniform: any): void; + syncUniforms(): void; + initSampler2D(uniform: any): void; + destroy(): void; + + } + export class ComplexPrimitiveShader extends Shader { + + constructor(shaderManager: ShaderManager); + + } + export class PrimitiveShader extends Shader { + + constructor(shaderManager: ShaderManager); + + } + export class TextureShader extends Shader { + + constructor(shaderManager: ShaderManager, vertexSrc?: string, fragmentSrc?: string, customUniforms?: any, customAttributes?: any); + + } + export interface StencilMaskStack { + + stencilStack: any[]; + reverse: boolean; + count: number; + + } + export class ObjectRenderer extends WebGLManager { + + start(): void; + stop(): void; + flush(): void; + render(object?: any): void; + + } + export class RenderTarget { + + constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: number, resolution: number, root: boolean); + + gl: WebGLRenderingContext; + frameBuffer: WebGLFramebuffer; + texture: Texture; + size: Rectangle; + resolution: number; + projectionMatrix: Matrix; + transform: Matrix; + frame: Rectangle; + stencilBuffer: WebGLRenderbuffer; + stencilMaskStack: StencilMaskStack; + filterStack: any[]; + scaleMode: number; + root: boolean; + + clear(bind?: boolean): void; + attachStencilBuffer(): void; + activate(): void; + calculateProjection(protectionFrame: Matrix): void; + resize(width: number, height: number): void; + destroy(): void; + + } + export interface Quad { + + gl: WebGLRenderingContext; + vertices: number[]; + uvs: number[]; + colors: number[]; + indices: number[]; + vertexBuffer: WebGLBuffer; + indexBuffer: WebGLBuffer; + + map(rect: Rectangle, rect2: Rectangle): void; + upload(): void; + destroy(): void; + + } + + //sprites + + export class Sprite extends Container { + + static fromFrame(frameId: string): Sprite; + static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + + protected _texture: Texture; + protected _width: number; + protected _height: number; + protected cachedTint: number; + + protected _onTextureUpdate(): void; + + constructor(texture?: Texture); + + anchor: Point; + tint: number; + blendMode: number; + shader: Shader | AbstractFilter; + texture: Texture; + + width: number; + height: number; + + getBounds(matrix?: Matrix): Rectangle; + getLocalBounds(): Rectangle; + containsPoint(point: Point): boolean; + destroy(destroyTexture?: boolean, destroyBaseTexture?: boolean): void; + + } + export class SpriteRenderer extends ObjectRenderer { + + protected renderBatch(texture: Texture, size: number, startIndex: number): void; + + vertSize: number; + vertByteSize: number; + size: number; + vertices: number[]; + positions: number[]; + colors: number[]; + indices: number[]; + currentBatchSize: number; + sprites: Sprite[]; + shader: Shader | AbstractFilter; + + render(sprite: Sprite): void; + flush(): void; + start(): void; + destroy(): void; + + } + + //text + + export interface TextStyle { + + font?: string; + fill?: string | number; + align?: string; + stroke?: string | number; + strokeThickness?: number; + wordWrap?: boolean; + wordWrapWidth?: number; + lineHeight?: number; + dropShadow?: boolean; + dropShadowColor?: string | number; + dropShadowAngle?: number; + dropShadowDistance?: number; + padding?: number; + textBaseline?: string; + lineJoin?: string; + miterLimit?: number; + + } + export class Text extends Sprite { + + static fontPropertiesCache: any; + static fontPropertiesCanvas: HTMLCanvasElement; + static fontPropertiesContext: CanvasRenderingContext2D; + + protected _text: string; + protected _style: TextStyle; + + protected updateText(): void; + protected updateTexture(): void; + protected determineFontProperties(fontStyle: TextStyle): TextStyle; + protected wordWrap(text: string): boolean; + + constructor(text?: string, style?: TextStyle, resolution?: number); + + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; + dirty: boolean; + resolution: number; + text: string; + style: TextStyle; + + width: number; + height: number; + + } + + //textures + + export class BaseTexture extends EventEmitter { + + static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: number): BaseTexture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): BaseTexture; + + protected _glTextures: any; + + protected _sourceLoaded(): void; + + constructor(source: HTMLImageElement | HTMLCanvasElement, scaleMode?: number, resolution?: number); + + uuid: number; + resolution: number; + width: number; + height: number; + realWidth: number; + realHeight: number; + scaleMode: number; + hasLoaded: boolean; + isLoading: boolean; + source: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; + premultipliedAlpha: boolean; + imageUrl: string; + isPowerOfTwo: boolean; + mipmap: boolean; + + update(): void; + loadSource(source: HTMLImageElement | HTMLCanvasElement): void; + destroy(): void; + dispose(): void; + updateSourceImage(newSrc: string): void; + + on(event: 'dispose', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + on(event: 'error', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + on(event: 'loaded', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + on(event: 'update', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; + + once(event: 'dispose', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + once(event: 'error', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + once(event: 'loaded', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + once(event: 'update', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + + } + export class RenderTexture extends Texture { + + protected renderWebGL(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; + protected renderCanvas(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; + + constructor(renderer: CanvasRenderer | WebGLRenderer, width?: number, height?: number, scaleMode?: number, resolution?: number); + + width: number; + height: number; + resolution: number; + renderer: CanvasRenderer | WebGLRenderer; + valid: boolean; + + render(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; + resize(width: number, height: number, updateBase?: boolean): void; + clear(): void; + destroy(): void; + getImage(): HTMLImageElement; + getPixels(): number[]; + getPixel(x: number, y: number): number[]; + getBase64(): string; + getCanvas(): HTMLCanvasElement; + + } + export class Texture extends BaseTexture { + + static fromImage(imageUrl: string, crossOrigin?: boolean, scaleMode?: number): Texture; + static fromFrame(frameId: string): Texture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): Texture; + static fromVideo(video: HTMLVideoElement | string, scaleMode?: number): Texture; + static fromVideoUrl(videoUrl: string, scaleMode?: number): Texture; + static addTextureToCache(texture: Texture, id: string): void; + static removeTextureFromCache(id: string): Texture; + static EMPTY: Texture; + + protected _frame: Rectangle; + protected _uvs: TextureUvs; + + protected onBaseTextureUpdated(baseTexture: BaseTexture): void; + protected onBaseTextureLoaded(baseTexture: BaseTexture): void; + protected _updateUvs(): void; + + constructor(baseTexture: BaseTexture, frame?: Rectangle, crop?: Rectangle, trim?: Rectangle, rotate?: boolean); + + noFrame: boolean; + baseTexture: BaseTexture; + trim: Rectangle; + valid: boolean; + requiresUpdate: boolean; + width: number; + height: number; + crop: Rectangle; + rotate: boolean; + + frame: Rectangle; + + update(): void; + destroy(destroyBase?: boolean): void; + clone(): Texture; + + } + export class TextureUvs { + + x0: number; + y0: number; + x1: number; + y1: number; + x2: number; + y2: number; + x3: number; + y3: number; + + set(frame: Rectangle, baseFrame: Rectangle, rotate: boolean): void; + + } + export class VideoBaseTexture extends BaseTexture { + + static fromVideo(video: HTMLVideoElement, scaleMode?: number): VideoBaseTexture; + static fromUrl(videoSrc: string | any | string[] | any[]): VideoBaseTexture; + + protected _loaded: boolean; + protected _onUpdate(): void; + protected _onPlayStart(): void; + protected _onPlayStop(): void; + protected _onCanPlay(): void; + + constructor(source: HTMLVideoElement, scaleMode?: number); + + autoUpdate: boolean; + + destroy(): void; + + } + + //utils + + export class utils { + + static uuid(): number; + static hex2rgb(hex: number, out?: number[]): number[]; + static hex2string(hex: number): string; + static rgb2hex(rgb: Number[]): number; + static canUseNewCanvasBlendModel(): boolean; + static getNextPowerOfTwo(number: number): number; + static isPowerOfTwo(width: number, height: number): boolean; + static getResolutionOfUrl(url: string): number; + static sayHello(type: string): void; + static isWebGLSupported(): boolean; + static sign(n: number): number; + static TextureCache: any; + static BaseTextureCache: any; + + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////EXTRAS//////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module extras { + + export interface BitmapTextStyle { + + font?: string | { + + name?: string; + size?: number; + + }; + align?: string; + tint?: number; + + } + export class BitmapText extends Container { + + static fonts: any; + + protected _glyphs: Sprite[]; + protected _font: string | { + tint: number; + align: string; + name: string; + size: number; + }; + protected _text: string; + + protected updateText(): void; + + constructor(text: string, style?: BitmapTextStyle); + + textWidth: number; + textHeight: number; + maxWidth: number; + maxLineHeight: number; + dirty: boolean; + + tint: number; + align: string; + font: string | { + tint: number; + align: string; + name: string; + size: number; + }; + text: string; + + } + export class MovieClip extends Sprite { + + static fromFrames(frame: string[]): MovieClip; + static fromImages(images: string[]): MovieClip; + + protected _textures: Texture[]; + protected _durations: number[]; + protected _currentTime: number; + + protected update(deltaTime: number): void; + + constructor(textures: Texture[]); + + animationSpeed: number; + loop: boolean; + onComplete: () => void; + currentFrame: number; + playing: boolean; + + totalFrames: number; + textures: Texture[]; + + stop(): void; + play(): void; + gotoAndStop(frameName: number): void; + gotoAndPlay(frameName: number): void; + destroy(): void; + + } + export class TilingSprite extends Sprite { + + //This is really unclean but is the only way :( + //See http://stackoverflow.com/questions/29593905/typescript-declaration-extending-class-with-static-method/29595798#29595798 + //Thanks bas! + static fromFrame(frameId: string): Sprite; + static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + + static fromFrame(frameId: string, width?: number, height?: number): TilingSprite; + static fromImage(imageId: string, width?: number, height?: number, crossorigin?: boolean, scaleMode?: number): TilingSprite; + + protected _tileScaleOffset: Point; + protected _tilingTexture: boolean; + protected _refreshTexture: boolean; + protected _uvs: TextureUvs[]; + + constructor(texture: Texture, width: number, height: number); + + tileScale: Point; + tilePosition: Point; + + width: number; + height: number; + originalTexture: Texture; + + getBounds(): Rectangle; + generateTilingTexture(renderer: WebGLRenderer | CanvasRenderer, texture: Texture, forcePowerOfTwo?: boolean): Texture; + containsPoint(point: Point): boolean; + destroy(): void; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////FILTERS//////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + namespace filters { + + export class AsciiFilter extends AbstractFilter { + size: number; + } + export class BloomFilter extends AbstractFilter { + + blur: number; + blurX: number; + blurY: number; + + } + export class BlurFilter extends AbstractFilter { + + protected blurXFilter: BlurXFilter; + protected blurYFilter: BlurYFilter; + + blur: number; + passes: number; + blurX: number; + blurY: number; + + } + export class BlurXFilter extends AbstractFilter { + + passes: number; + strength: number; + blur: number; + + } + export class BlurYFilter extends AbstractFilter { + + passes: number; + strength: number; + blur: number; + + } + export class SmartBlurFilter extends AbstractFilter { + + } + export class ColorMatrixFilter extends AbstractFilter { + + protected _loadMatrix(matrix: number[], multiply: boolean): void; + protected _multiply(out: number[], a: number[], b: number[]): void; + protected _colorMatrix(matrix: number[]): void; + + matrix: number[]; + + brightness(b: number, multiply?: boolean): void; + greyscale(scale: number, multiply?: boolean): void; + blackAndWhite(multiply?: boolean): void; + hue(rotation: number, multiply?: boolean): void; + contrast(amount: number, multiply?: boolean): void; + saturate(amount: number, multiply?: boolean): void; + desaturate(multiply?: boolean): void; + negative(multiply?: boolean): void; + sepia(multiply?: boolean): void; + technicolor(multiply?: boolean): void; + polaroid(multiply?: boolean): void; + toBGR(multiply?: boolean): void; + kodachrome(multiply?: boolean): void; + browni(multiply?: boolean): void; + vintage(multiply?: boolean): void; + colorTone(desaturation: number, toned: number, lightColor: string, darkColor: string, multiply?: boolean): void; + night(intensity: number, multiply?: boolean): void; + predator(amount: number, multiply?: boolean): void; + lsd(multiply?: boolean): void; + reset(): void; + + } + export class ColorStepFilter extends AbstractFilter { + + step: number; + + } + export class ConvolutionFilter extends AbstractFilter { + + constructor(matrix: number[], width: number, height: number); + + matrix: number[]; + width: number; + height: number; + + } + export class CrossHatchFilter extends AbstractFilter { + + } + export class DisplacementFilter extends AbstractFilter { + + constructor(sprite: Sprite, scale?: number); + + map: Texture; + + scale: Point; + + } + export class DotScreenFilter extends AbstractFilter { + + scale: number; + angle: number; + + } + export class BlurYTintFilter extends AbstractFilter { + + blur: number; + + } + export class DropShadowFilter extends AbstractFilter { + + blur: number; + blurX: number; + blurY: number; + color: number; + alpha: number; + distance: number; + angle: number; + + } + export class GrayFilter extends AbstractFilter { + + gray: number; + + } + export class InvertFilter extends AbstractFilter { + + invert: number; + + } + export class NoiseFilter extends AbstractFilter { + + noise: number; + + } + export class PixelateFilter extends AbstractFilter { + + size: Point; + + } + export class RGBSplitFilter extends AbstractFilter { + + red: number; + green: number; + blue: number; + + } + export class SepiaFilter extends AbstractFilter { + + sepia: number; + + } + export class ShockwaveFilter extends AbstractFilter { + + center: number[]; + params: any; + time: number; + + } + export class TiltShiftAxisFilter extends AbstractFilter { + + blur: number; + gradientBlur: number; + start: number; + end: number; + + updateDelta(): void; + + } + export class TiltShiftFilter extends AbstractFilter { + + blur: number; + gradientBlur: number; + start: number; + end: number; + + } + export class TiltShiftXFilter extends AbstractFilter { + + updateDelta(): void; + + } + export class TiltShiftYFilter extends AbstractFilter { + + updateDelta(): void; + + } + export class TwistFilter extends AbstractFilter { + + offset: Point; + radius: number; + angle: number; + + } + export class FXAAFilter extends AbstractFilter { + + applyFilter(renderer: WebGLRenderer, input: RenderTarget, output: RenderTarget): void; + + } + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////INTERACTION/////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module interaction { + + export interface InteractionEvent { + + stopped: boolean; + target: any; + type: string; + data: InteractionData; + stopPropagation(): void; + + } + + export class InteractionData { + + global: Point; + target: DisplayObject; + originalEvent: Event; + identifier: number; + + getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; + + } + + export class InteractionManager { + + protected interactionDOMElement: HTMLElement; + protected eventsAdded: boolean; + protected _tempPoint: Point; + + protected setTargetElement(element: HTMLElement, resolution: number): void; + protected addEvents(): void; + protected removeEvents(): void; + protected dispatchEvent(displayObject: DisplayObject, eventString: string, eventData: any): void; + protected onMouseDown: (event: Event) => void; + protected processMouseDown: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseUp: (event: Event) => void; + protected processMouseUp: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseMove: (event: Event) => void; + protected processMouseMove: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseOut: (event: Event) => void; + protected processMouseOverOut: (displayObject: DisplayObject, hit: boolean) => void; + protected onTouchStart: (event: Event) => void; + protected processTouchStart: (DisplayObject: DisplayObject, hit: boolean) => void; + protected onTouchEnd: (event: Event) => void; + protected processTouchEnd: (displayObject: DisplayObject, hit: boolean) => void; + protected onTouchMove: (event: Event) => void; + protected processTouchMove: (displayObject: DisplayObject, hit: boolean) => void; + protected getTouchData(touchEvent: InteractionData): InteractionData; + protected returnTouchData(touchData: InteractionData): void; + + constructor(renderer: CanvasRenderer | WebGLRenderer, options?: { autoPreventDefault?: boolean; interactionFrequence?: number; }); + + renderer: CanvasRenderer | WebGLRenderer; + autoPreventDefault: boolean; + interactionFrequency: number; + mouse: InteractionData; + eventData: { + stopped: boolean; + target: any; + type: any; + data: InteractionData; + }; + interactiveDataPool: InteractionData[]; + last: number; + currentCursorStyle: string; + resolution: number; + update(deltaTime: number): void; + + mapPositionToPoint(point: Point, x: number, y: number): void; + processInteractive(point: Point, displayObject: DisplayObject, func: (displayObject: DisplayObject, hit: boolean) => void, hitTest: boolean, interactive: boolean): boolean; + destroy(): void; + + } + + export interface InteractiveTarget { + + interactive: boolean; + buttonMode: boolean; + interactiveChildren: boolean; + defaultCursor: string; + hitArea: HitArea; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////LOADER///////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + //https://github.com/englercj/resource-loader/blob/master/src/Loader.js + + export module loaders { + export interface LoaderOptions { + + crossOrigin?: boolean; + loadType?: number; + xhrType?: string; + + } + export interface ResourceDictionary { + + [index: string]: PIXI.loaders.Resource; + } + export class Loader extends EventEmitter { + + constructor(baseUrl?: string, concurrency?: number); + + baseUrl: string; + progress: number; + loading: boolean; + resources: ResourceDictionary; + + add(name: string, url: string, options?: LoaderOptions, cb?: () => void): Loader; + add(url: string, options?: LoaderOptions, cb?: () => void): Loader; + //todo I am not sure of object literal notional (or its options) so just allowing any but would love to improve this + add(obj: any, options?: LoaderOptions, cb?: () => void): Loader; + + on(event: 'complete', fn: (loader: loaders.Loader, object: any) => void, context?: any): EventEmitter; + on(event: 'error', fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + on(event: 'load', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + on(event: 'progress', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + on(event: 'start', fn: (loader: loaders.Loader) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; + + once(event: 'complete', fn: (loader: loaders.Loader, object: any) => void, context?: any): EventEmitter; + once(event: 'error', fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + once(event: 'load', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + once(event: 'progress', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + once(event: 'start', fn: (loader: loaders.Loader) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + + before(fn: Function): Loader; + pre(fn: Function): Loader; + + after(fn: Function): Loader; + use(fn: Function): Loader; + + reset(): void; + + load(cb?: (loader: loaders.Loader, object: any) => void): Loader; + + } + export class Resource extends EventEmitter { + + static LOAD_TYPE: { + XHR: number; + IMAGE: number; + AUDIO: number; + VIDEO: number; + }; + + static XHR_READ_STATE: { + UNSENT: number; + OPENED: number; + HEADERS_RECIEVED: number; + LOADING: number; + DONE: number; + }; + + static XHR_RESPONSE_TYPE: { + DEFAULT: number; + BUFFER: number; + BLOB: number; + DOCUMENT: number; + JSON: number; + TEXT: number; + }; + + constructor(name?: string, url?: string | string[], options?: LoaderOptions); + + name: string; + texture: Texture; + textures: Texture[]; + url: string; + data: any; + crossOrigin: string; + loadType: number; + xhrType: string; + error: Error; + xhr: XMLHttpRequest; + + complete(): void; + load(cb?: () => void): void; + + } + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////MESH/////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module mesh { + + export class Mesh extends Container { + + static DRAW_MODES: { + TRIANGLE_MESH: number; + TRIANGLES: number; + }; + + constructor(texture: Texture, vertices?: number[], uvs?: number[], indices?: number[], drawMode?: number); + + texture: Texture; + uvs: number[]; + vertices: number[]; + indices: number[]; + dirty: boolean; + blendMode: number; + canvasPadding: number; + drawMode: number; + shader: Shader | AbstractFilter; + + getBounds(matrix?: Matrix): Rectangle; + containsPoint(point: Point): boolean; + + protected _texture: Texture; + + protected _renderCanvasTriangleMesh(context: CanvasRenderingContext2D): void; + protected _renderCanvasTriangles(context: CanvasRenderingContext2D): void; + protected _renderCanvasDrawTriangle(context: CanvasRenderingContext2D, vertices: number, uvs: number, index0: number, index1: number, index2: number): void; + protected renderMeshFlat(Mesh: Mesh): void; + protected _onTextureUpdate(): void; + + } + export class Rope extends Mesh { + + protected _ready: boolean; + + protected getTextureUvs(): TextureUvs; + + constructor(texture: Texture, points: Point[]); + + points: Point[]; + colors: number[]; + + refresh(): void; + + } + export class Plane extends Mesh { + + segmentsX: number; + segmentsY: number; + + constructor(texture: Texture, segmentsX?: number, segmentsY?: number); + + } + + + export class MeshRenderer extends ObjectRenderer { + + protected _initWebGL(mesh: Mesh): void; + + indices: number[]; + + constructor(renderer: WebGLRenderer); + + render(mesh: Mesh): void; + flush(): void; + start(): void; + destroy(): void; + + } + + export interface MeshShader extends Shader { } + + } + + namespace ticker { + + export var shared: Ticker; + + export class Ticker { + + protected _tick(time: number): void; + protected _emitter: EventEmitter; + protected _requestId: number; + protected _maxElapsedMS: number; + + protected _requestIfNeeded(): void; + protected _cancelIfNeeded(): void; + protected _startIfPossible(): void; + + autoStart: boolean; + deltaTime: number; + elapsedMS: number; + lastTime: number; + speed: number; + started: boolean; + + FPS: number; + minFPS: number; + + add(fn: (deltaTime: number) => void, context?: any): Ticker; + addOnce(fn: (deltaTime: number) => void, context?: any): Ticker; + remove(fn: (deltaTime: number) => void, context?: any): Ticker; + start(): void; + stop(): void; + update(): void; + + } + + } +} + +declare module 'pixi.js' { + export = PIXI; +} diff --git a/plugapi/index.d.ts b/plugapi/index.d.ts new file mode 100644 index 0000000000..794fa01d46 --- /dev/null +++ b/plugapi/index.d.ts @@ -0,0 +1,416 @@ +// Type definitions for plugapi +// Project: https://www.npmjs.com/package/plugapi +// Definitions by: Brice Theurillat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare namespace PlugAPI { + + export interface PlugLogin { + email: string; + password: string; + } + + export interface Notification { + action: string; + id: number; + timestamp: string; + value: string; + } + + export interface RawChatMessage { + cid: string; + message: string; + sub: number; + uid: number; + un: string; + } + + export interface Media { + author: string; + format: number; + image: string; + cid: string; + duration: number; + title: string; + id: number; + } + + export interface Score { + positive: number; + listeners: number; + grabs: number; + negative: number; + skipped: number; + } + + export interface LastPlay { + dj: User.DJ; + media: Media; + score: Score; + } + + export interface FollowJoinData { + r: number; + un: string; + id: string; + } + + export interface LogObject { + log: () => void; + } + + export namespace User { + interface Default { + username: string; + language: string; + avatarID: string; + } + + interface Extended extends Default { + status: number; + fans: number; + listenerPoints: number; + id: string; + curatorPoints: number; + djPoints: number; + } + + interface Update extends Extended { + dateJoined: string; + } + + interface Room extends Default { + sub: number; + level: number; + joined: string; + id: number; + badge: string; + role: number; + gRole: number; + slug: string; + } + + interface User extends Room { + silver: boolean; + guest: boolean; + } + + interface DJ extends Room { + blurp: any; + grab: boolean; + status: number; + vote: number; + } + + interface Audience extends DJ { + ignores: any[]; + notifications: Notification[]; + pp: number; + pw: number; + xp: number; + } + } + + export namespace Enum { + interface RoomRole { + NONE: number; + RESIDENTDJ: number; + BOUNCER: number; + MANAGER: number; + COHOST: number; + HOST: number; + } + + interface GlobalRole { + NONE: number; + VOLUNTEER: number; + AMBASSADOR: number; + LEADER: number; + ADMIN: number; + } + + interface Status { + OFFLINE: number; + ONLINE: number; + } + + interface Ban { + HOUR: "h"; + DAY: "d"; + PERMA: "f"; + } + + interface BanReason { + SPAMMING_TROLLING: number; + VERBAL_ABUSE: number; + OFFENSIVE_MEDIA: number; + INAPPROPRIATE_GENRE: number; + NEGATIVE_ATTITUDE: number; + } + + interface Mute { + SHORT: "s"; + MEDIUM: "m"; + LONG: "l"; + } + + interface MuteReason { + VIOLATING_COMMUNITY_RULES: number; + VERBAL_ABUSE: number; + SPAMMING_TROLLING: number; + OFFENSIVE_LANGUAGE: number; + NEGATIVE_ATTITUDE: number; + } + + interface Events { + ADVANCE: "advance"; + BAN: "ban"; + BOOTH_LOCKED: "boothLocked"; + CHAT: "chat"; + CHAT_COMMAND: "command"; + CHAT_DELETE: "chatDelete"; + CHAT_LEVEL_UPDATE: "roomMinChatLevelUpdate"; + COMMAND: "command"; + DJ_LIST_CYCLE: "djListCycle"; + DJ_LIST_UPDATE: "djListUpdate"; + DJ_LIST_LOCKED: "djListLocked"; + EARN: "earn"; + FOLLOW_JOIN: "followJoin"; + FLOOD_CHAT: "floodChat"; + FRIEND_REQUEST: "friendRequest"; + GIFTED: "gifted"; + GRAB: "grab"; + KILL_SESSION: "killSession"; + MAINT_MODE: "plugMaintenance"; + MAINT_MODE_ALERT: "plugMaintenanceAlert"; + MODERATE_ADD_DJ: "modAddDJ"; + MODERATE_ADD_WAITLIST: "modAddWaitList"; + MODERATE_AMBASSADOR: "modAmbassador"; + MODERATE_BAN: "modBan"; + MODERATE_MOVE_DJ: "modMoveDJ"; + MODERATE_MUTE: "modMute"; + MODERATE_REMOVE_DJ: "modRemoveDJ"; + MODERATE_REMOVE_WAITLIST: "modRemoveWaitList"; + MODERATE_SKIP: "modSkip"; + MODERATE_STAFF: "modStaff"; + NOTIFY: "notify"; + PDJ_MESSAGE: "pdjMessage"; + PDJ_UPDATE: "pdjUpdate"; + PING: "ping"; + PLAYLIST_CYCLE: "playlistCycle"; + REQUEST_DURATION: "requestDuration"; + REQUEST_DURATION_RETRY: "requestDurationRetry"; + ROOM_CHANGE: "roomChanged"; + ROOM_DESCRIPTION_UPDATE: "roomDescriptionUpdate"; + ROOM_JOIN: "roomJoin"; + ROOM_NAME_UPDATE: "roomNameUpdate"; + ROOM_VOTE_SKIP: "roomVoteSkip"; + ROOM_WELCOME_UPDATE: "roomWelcomeUpdate"; + SESSION_CLOSE: "sessionClose"; + SKIP: "skip"; + STROBE_TOGGLE: "strobeToggle"; + USER_COUNTER_UPDATE: "userCounterUpdate"; + USER_FOLLOW: "userFollow"; + USER_JOIN: "userJoin"; + USER_LEAVE: "userLeave"; + USER_UPDATE: "userUpdate"; + VOTE: "vote"; + } + } + + export namespace Event { + interface BoothCycle { + moderator: string; + cycle: boolean; + } + + interface BoothLocked { + m: string; + c: boolean; + ml: string; + f: boolean; + } + + interface Chat { + raw: RawChatMessage; + id: string; + from: User.User; + message: string; + mentions: any[]; + muted: boolean; + type: string; + } + + interface ChatDelete { + mi: number; + chatID: string; + } + + type Grab = number; + + interface Advance { + media: Media; + startTime: string; + historyID: string; + djs: User.DJ[]; + currentDJ: User.DJ; + playlistID: number; + lastPlay: LastPlay; + } + + interface DJListUpdate { + djs: User.DJ[]; + remove: string; + } + + interface Emote { + fromID: string; + message: string; + from: string; + type: string; + chatID: string; + } + + interface FollowJoin { + data: FollowJoinData; + type: string; + } + + interface ModAddDJ { + moderator: string; + username: string; + } + + interface ModBan { + moderator: string; + username: string; + duration: number; + ref: string; + reason: string; + } + + interface ModMoveDJ { + moderator: string; + index: number; + old: number; + userID: string; + } + + interface ModRemoveDJ { + moderator: string; + username: string; + userID: string; + } + + interface ModSkip { + mi: number; + m: string; + } + + interface RoomMinChatLevelUpdate { + level: number; + id: number; + user: User.User; + } + + type RoomJoin = string; + + type UserJoin = User.User; + + type UserLeave = User.User; + + interface UserUpdate { + username: string; + status: number; + fans: number; + listenerPoints: number; + dateJoined: string; + language: string; + avatarID: string; + id: string; + curatorPoints: number; + djPoints: number; + } + + interface Vote { + i: number; + v: number; + } + + interface Command extends Event.Chat { + command: string; + args: string[]; + respond: (...args: any[]) => any; + respondTimeout: (...args: any[]) => any; + havePermission: (...args: any[]) => boolean; + isFrom: (...args: any[]) => boolean; + } + } + + export var ROOM_ROLE: Enum.RoomRole; + export var GLOBAL_ROLES: Enum.GlobalRole; + export var STATUS: Enum.Status; + export var BAN: Enum.Ban; + export var BAN_REASON: Enum.BanReason; + export var MUTE: Enum.Mute; + export var MUTE_REASON: Enum.MuteReason; + export var events: Enum.Events; +} + +declare class PlugAPI { + constructor(login: PlugAPI.PlugLogin, callback?: (error: Error, bot: PlugAPI) => void); + constructor(login: PlugAPI.PlugLogin, callback?: (bot: PlugAPI) => void); + deleteAllChat: boolean; + multiLine: boolean; + multiLineLimit: number; + + connect(room: string): void; + changeDJCycle(enabled: boolean, callback?: () => void): boolean; + changeRoom(room: string, callback?: () => void): void; + close(): void; + getAdmins(): PlugAPI.User.Extended[]; + getAmbassadors(): PlugAPI.User.Extended[]; + getAudience(): PlugAPI.User.Audience[]; + getDJ(): PlugAPI.User.DJ; + getDJs(): PlugAPI.User.DJ[]; + getHost(): PlugAPI.User.Extended; + getMedia(): PlugAPI.Media; + getRoomScore(): PlugAPI.Score; + getSelf(): PlugAPI.User.Audience; + getStaff(): PlugAPI.User.Extended[]; + getTimeElapsed(): number; + getTimeRemaining(): number; + getUser(userID: number): PlugAPI.User.DJ; + getUsers(): PlugAPI.User.DJ[]; + getWaitList(): PlugAPI.User.Extended; + getWaitListPosition(userID: number): number; + havePermission(userID: number, permission: number, global?: boolean): boolean; + joinBooth(callback?: () => void): boolean; + leaveBooth(callback?: () => void): boolean; + selfSkip(callback?: () => void): boolean; + sendChat(msg: string, timeout?: number): void; + setLogger(logObject: PlugAPI.LogObject): boolean; + + on(event: "boothCycle", callback: (data: PlugAPI.Event.BoothCycle) => void): void; + on(event: "boothLocked", callback: (data: PlugAPI.Event.BoothLocked) => void): void; + on(event: "chat", callback: (data: PlugAPI.Event.Chat) => void): void; + on(event: "chatDelete", callback: (data: PlugAPI.Event.ChatDelete) => void): void; + on(event: "grab", callback: (data: PlugAPI.Event.Grab) => void): void; + on(event: "advance", callback: (data: PlugAPI.Event.Advance) => void): void; + on(event: "djListUpdate", callback: (data: PlugAPI.Event.DJListUpdate) => void): void; + on(event: "emote", callback: (data: PlugAPI.Event.Emote) => void): void; + on(event: "followJoin", callback: (data: PlugAPI.Event.FollowJoin) => void): void; + on(event: "modAddDJ", callback: (data: PlugAPI.Event.ModAddDJ) => void): void; + on(event: "modBan", callback: (data: PlugAPI.Event.ModBan) => void): void; + on(event: "modMoveDJ", callback: (data: PlugAPI.Event.ModMoveDJ) => void): void; + on(event: "modRemoveDJ", callback: (data: PlugAPI.Event.ModRemoveDJ) => void): void; + on(event: "modSkip", callback: (data: PlugAPI.Event.ModSkip) => void): void; + on(event: "roomMinChatLevelUpdate", callback: (data: PlugAPI.Event.RoomMinChatLevelUpdate) => void): void; + on(event: "roomJoin", callback: (data: PlugAPI.Event.RoomJoin) => void): void; + on(event: "userJoin", callback: (data: PlugAPI.Event.UserJoin) => void): void; + on(event: "userLeave", callback: (data: PlugAPI.Event.UserLeave) => void): void; + on(event: "userUpdate", callback: (data: PlugAPI.Event.UserUpdate) => void): void; + on(event: "vote", callback: (data: PlugAPI.Event.Vote) => void): void; + on(event: "command", callback: (data: PlugAPI.Event.Command) => void): void; + on(event: string, callback: (data: any) => void): void; +} +export = PlugAPI; diff --git a/plugapi/plugapi-tests.ts b/plugapi/plugapi-tests.ts new file mode 100644 index 0000000000..d9a0845997 --- /dev/null +++ b/plugapi/plugapi-tests.ts @@ -0,0 +1,33 @@ +import PlugAPI = require("plugapi"); + +new PlugAPI({ + email: "", + password: "" +}, function (err, bot) { + if (!err) { + const ROOM = "roomslug"; + bot.connect(ROOM); // The part after https://plug.dj + + bot.on(PlugAPI.events.ROOM_JOIN, function (room) { + console.log("Joined " + room); + }); + + bot.on("chat", function (data) { + if (data.type == "emote") { + console.log(data.from + data.message); + } else { + console.log(data.from + "> " + data.message); + } + }); + + bot.on("error", function () { + bot.connect(ROOM); + }); + + bot.deleteAllChat = false; + bot.multiLine = true; + bot.multiLineLimit = 5; + } else { + console.log("Error initializing plugAPI: " + err); + } +}); diff --git a/plugapi/tsconfig.json b/plugapi/tsconfig.json new file mode 100644 index 0000000000..36b84a69c2 --- /dev/null +++ b/plugapi/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "plugapi-tests.ts" + ] +} diff --git a/plugapi/tslint.json b/plugapi/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/plugapi/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/pouchdb-mapreduce/index.d.ts b/pouchdb-mapreduce/index.d.ts index fdcd1fee74..76acbab156 100644 --- a/pouchdb-mapreduce/index.d.ts +++ b/pouchdb-mapreduce/index.d.ts @@ -20,7 +20,7 @@ declare namespace PouchDB { } } -declare module 'pouchdb-adapter-mapreduce' { +declare module 'pouchdb-mapreduce' { const plugin: PouchDB.Plugin; export = plugin; } diff --git a/pouchdb-upsert/pouchdb-upsert.d.ts b/pouchdb-upsert/index.d.ts similarity index 100% rename from pouchdb-upsert/pouchdb-upsert.d.ts rename to pouchdb-upsert/index.d.ts diff --git a/pouchdb-upsert/pouchdb-upsert-tests.ts b/pouchdb-upsert/pouchdb-upsert-tests.ts index fa4eb83af3..5ed17266b1 100644 --- a/pouchdb-upsert/pouchdb-upsert-tests.ts +++ b/pouchdb-upsert/pouchdb-upsert-tests.ts @@ -1,5 +1,3 @@ -/// - import * as pouchdbUpsert from 'pouchdb-upsert'; PouchDB.plugin(pouchdbUpsert); diff --git a/pouchdb-upsert/tsconfig.json b/pouchdb-upsert/tsconfig.json index a88f26d221..a0719c3eaf 100644 --- a/pouchdb-upsert/tsconfig.json +++ b/pouchdb-upsert/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "pouchdb-upsert.d.ts", + "index.d.ts", "pouchdb-upsert-tests.ts" ] } \ No newline at end of file diff --git a/promise-polyfill/index.d.ts b/promise-polyfill/index.d.ts new file mode 100644 index 0000000000..703f7a6a8c --- /dev/null +++ b/promise-polyfill/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for promise v6.0.2 +// Project: https://www.npmjs.com/package/promise-polyfill +// Definitions by: Steve Jenkins +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default Promise; \ No newline at end of file diff --git a/promise-polyfill/promise-polyfill-tests.ts b/promise-polyfill/promise-polyfill-tests.ts new file mode 100644 index 0000000000..280a2bebdf --- /dev/null +++ b/promise-polyfill/promise-polyfill-tests.ts @@ -0,0 +1,18 @@ +const prom1 = new Promise((resolve, reject) => { + resolve(12); +}); + +const prom2 = new Promise((resolve, reject) => { + reject('an error'); +}).then((val) => { + console.log(val); + return val; +}).catch((err) => { + console.error(err); +}); + +Promise.all([prom1, prom2]) +.then(result => { + console.log(result); +}, (exception) => console.error(exception)) +.catch((ex) => console.error(ex)); \ No newline at end of file diff --git a/promise-polyfill/tsconfig.json b/promise-polyfill/tsconfig.json new file mode 100644 index 0000000000..d411c896d5 --- /dev/null +++ b/promise-polyfill/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "promise-polyfill-tests.ts" + ] +} \ No newline at end of file diff --git a/query-string/index.d.ts b/query-string/index.d.ts index 2f002c2966..fbd2d3638d 100644 --- a/query-string/index.d.ts +++ b/query-string/index.d.ts @@ -3,28 +3,29 @@ // Definitions by: Sam Verschueren // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +declare module "query-string" { type value = string | boolean | number; - + interface StringifyOptions { strict?: boolean; encode?: boolean; } -/** - * Parse a query string into an object. - * Leading ? or # are ignored, so you can pass location.search or location.hash directly. - * @param str - */ - export declare function parse(str: string): { [key: string]: string | string[] }; + /** + * Parse a query string into an object. + * Leading ? or # are ignored, so you can pass location.search or location.hash directly. + * @param str + */ + export function parse(str: string): { [key: string]: string | string[] }; -/** - * Stringify an object into a query string, sorting the keys. - * - * @param obj - */ - export declare function stringify(obj: { [key: string]: value | value[] }, options?: StringifyOptions): string; + /** + * Stringify an object into a query string, sorting the keys. + * + * @param obj + */ + export function stringify(obj: { [key: string]: value | value[] }, options?: StringifyOptions): string; -/** - * Extract a query string from a URL that can be passed into .parse(). - * - * @param str - */ -export declare function extract(str: string): string; + /** + * Extract a query string from a URL that can be passed into .parse(). + * + * @param str + */ + export function extract(str: string): string; +} diff --git a/quill/index.d.ts b/quill/index.d.ts index 1a159d4407..cf7440f428 100644 --- a/quill/index.d.ts +++ b/quill/index.d.ts @@ -27,7 +27,7 @@ declare namespace Quill { placeholder?: string, readOnly?: boolean, theme?: string, - formats?: string[] + formats?: string[] } export interface BoundsStatic { diff --git a/qunit/qunit-tests-1.16.ts b/qunit/qunit-tests-1.16.ts index 88734488c6..93081b15f3 100644 --- a/qunit/qunit-tests-1.16.ts +++ b/qunit/qunit-tests-1.16.ts @@ -1,5 +1,3 @@ - - QUnit.test("assert.async() test", function (assert) { var done = assert.async(); var input = []; @@ -1666,4 +1664,4 @@ QUnit.extend(QUnit.assert, { var expected = "String matching /" + regex.toString() + "/"; this.push(success, actual, expected, message); } -}); \ No newline at end of file +}); diff --git a/qunit/qunit-tests.ts b/qunit/qunit-tests.ts index 6a739b8213..f6b645875f 100644 --- a/qunit/qunit-tests.ts +++ b/qunit/qunit-tests.ts @@ -551,4 +551,4 @@ QUnit.module( "module", { }); QUnit.test( "test with beforeEach and afterEach", function( assert ) { assert.expect( 2 ); -}); \ No newline at end of file +}); diff --git a/qunit/tsconfig.json b/qunit/tsconfig.json index 4a3678001b..6bbbd55474 100644 --- a/qunit/tsconfig.json +++ b/qunit/tsconfig.json @@ -16,4 +16,4 @@ "index.d.ts", "qunit-tests.ts" ] -} \ No newline at end of file +} diff --git a/random-seed/index.d.ts b/random-seed/index.d.ts new file mode 100644 index 0000000000..cdd63a140c --- /dev/null +++ b/random-seed/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for random-seed 0.3.0 +// Project: https://github.com/skratchdot/random-seed/ +// Definitions by: Endel Dreyer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface RandomSeed { + range (range: number): number; + random (): number; + floatBetween (min: number, max: number): number; + intBetween (min: number, max: number): number; + + string (count: number): string; + seed (seed: string): void; + + cleanString (inStr: string): string; + hashString (inStr: string): string; + + addEntropy (...args: any[]): void; + initState (): void; + + done (): void; +} + +export function create (seed?: string): RandomSeed; diff --git a/random-seed/random-seed-tests.ts b/random-seed/random-seed-tests.ts new file mode 100644 index 0000000000..9eb399eff5 --- /dev/null +++ b/random-seed/random-seed-tests.ts @@ -0,0 +1,17 @@ +import { RandomSeed, create } from "random-seed"; + +// these generators produce different numbers +let rand1: RandomSeed = create(); // method 1 + +// these generators will produce +// the same sequence of numbers +let seed = 'My Secret String Value'; +let rand2 = create(seed); + +// API +rand1.addEntropy(); +rand1.random(); +rand1.range(100); +rand1.intBetween(0, 10); +rand1.floatBetween(0, 1); +rand1.seed("new seed"); diff --git a/random-seed/tsconfig.json b/random-seed/tsconfig.json new file mode 100644 index 0000000000..19bb011f0d --- /dev/null +++ b/random-seed/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "random-seed-tests.ts" + ] +} diff --git a/random-seed/tslint.json b/random-seed/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/random-seed/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/raven-js/ravenjs-tests.ts b/raven-js/ravenjs-tests.ts index d35e89c448..9608e41322 100644 --- a/raven-js/ravenjs-tests.ts +++ b/raven-js/ravenjs-tests.ts @@ -47,6 +47,8 @@ Raven.setUserContext({ Raven.captureMessage('Broken!'); Raven.captureMessage('Broken!', {tags: { key: "value" }}); +Raven.showReportDialog(options); + Raven.setTagsContext({ key: "value" }); Raven.setExtraContext({ foo: "bar" }); diff --git a/rc-tooltip/rc-tooltip.d.ts b/rc-tooltip/index.d.ts similarity index 100% rename from rc-tooltip/rc-tooltip.d.ts rename to rc-tooltip/index.d.ts diff --git a/rc-tooltip/tsconfig.json b/rc-tooltip/tsconfig.json index 3ad29fc103..2f9aa65a4b 100644 --- a/rc-tooltip/tsconfig.json +++ b/rc-tooltip/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "rc-tooltip.d.ts", + "index.d.ts", "rc-tooltip-tests.tsx" ] } \ No newline at end of file diff --git a/react-autosuggest/react-autosuggest.d.ts b/react-autosuggest/index.d.ts similarity index 70% rename from react-autosuggest/react-autosuggest.d.ts rename to react-autosuggest/index.d.ts index cfec62d047..739509bdef 100644 --- a/react-autosuggest/react-autosuggest.d.ts +++ b/react-autosuggest/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-autosuggest v3.7.3 // Project: http://react-autosuggest.js.org/ -// Definitions by: Nicolas Schmitt +// Definitions by: Nicolas Schmitt , Philip Ottesen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -16,14 +16,24 @@ declare namespace ReactAutosuggest { valueBeforeUpDown?: string; } + interface ChangeEvent { + newValue: string; + method: 'down' | 'up' | 'escape' | 'enter' | 'click' | 'type'; + } + + interface BlurEvent { + focusedSuggestion: any; + } + interface InputProps extends React.HTMLAttributes { value: string; - onChange: (event: React.FormEvent, params?: {newValue: string, method: string}) => void; + onChange: (event: React.FormEvent, params?: ChangeEvent) => void; + onBlur?: (event: React.FormEvent, params?: BlurEvent) => void; } interface ExplicitSuggestionSelectedEventData { - method: string; - sectionIndex: number; + method: 'click' | 'enter'; + sectionIndex: number | null; suggestion: TSuggestion; suggestionValue: string; } @@ -32,15 +42,15 @@ declare namespace ReactAutosuggest { } interface Theme { - container: string; - containerOpen: string; - input: string; - sectionContainer: string; - sectionSuggestionsContainer: string; - sectionTitle: string; - suggestion: string; - suggestionFocused: string; - suggestionsContainer: string; + container?: string; + containerOpen?: string; + input?: string; + sectionContainer?: string; + sectionSuggestionsContainer?: string; + sectionTitle?: string; + suggestion?: string; + suggestionFocused?: string; + suggestionsContainer?: string; } interface AutosuggestProps extends React.Props { @@ -49,6 +59,7 @@ declare namespace ReactAutosuggest { getSuggestionValue: (suggestion: any) => string; renderSuggestion: (suggestion: any, inputValues: InputValues) => JSX.Element; inputProps: InputProps; + alwaysRenderSuggestions?: boolean; shouldRenderSuggestions?: (value: string) => boolean; multiSection?: boolean; renderSectionTitle?: (section: any, inputValues: InputValues) => JSX.Element; diff --git a/react-autosuggest/react-autosuggest-tests.tsx b/react-autosuggest/react-autosuggest-tests.tsx index 5a107fe525..d3d4278829 100644 --- a/react-autosuggest/react-autosuggest-tests.tsx +++ b/react-autosuggest/react-autosuggest-tests.tsx @@ -55,12 +55,21 @@ export class ReactAutosuggestBasicTest extends React.Component { onChange: this.onChange.bind(this) }; + const theme = { + input: 'themed-input-class', + container: 'themed-container-class', + suggestionFocused: 'active' + } + return ; + alwaysRenderSuggestions={true} + inputProps={inputProps} + theme={theme} + />; } protected onSuggestionsSelected(event: React.FormEvent, data: ReactAutosuggest.ExplicitSuggestionSelectedEventData): void { @@ -306,7 +315,7 @@ export class ReactAutosuggestCustomTest extends React.Component { { parts.map((part, index) => { - const className = part.highlight ? 'highlight' : null; + const className = part.highlight ? 'highlight' : undefined; return {part.text}; }) diff --git a/react-autosuggest/tsconfig.json b/react-autosuggest/tsconfig.json index 3f2805e714..07f6b45bf7 100644 --- a/react-autosuggest/tsconfig.json +++ b/react-autosuggest/tsconfig.json @@ -3,7 +3,7 @@ "module": "commonjs", "target": "es6", "noImplicitAny": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-autosuggest.d.ts", + "index.d.ts", "react-autosuggest-tests.tsx" ] } \ No newline at end of file diff --git a/react-big-calendar/react-big-calendar.d.ts b/react-big-calendar/index.d.ts similarity index 100% rename from react-big-calendar/react-big-calendar.d.ts rename to react-big-calendar/index.d.ts diff --git a/react-big-calendar/tsconfig.json b/react-big-calendar/tsconfig.json index ef22e3c080..219b769f52 100644 --- a/react-big-calendar/tsconfig.json +++ b/react-big-calendar/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-big-calendar.d.ts", + "index.d.ts", "react-big-calendar-tests.tsx" ] } \ No newline at end of file diff --git a/react-bootstrap-table/index.d.ts b/react-bootstrap-table/index.d.ts index 8cfa2c2d4b..cc902fe4c2 100644 --- a/react-bootstrap-table/index.d.ts +++ b/react-bootstrap-table/index.d.ts @@ -121,8 +121,8 @@ export interface BootstrapTableProps extends Props { headerStyle?: any; bodyStyle?: any; ignoreSinglePage?: boolean; - } + export type SelectRowMode = 'none' | 'radio' | 'checkbox'; export interface SelectRow { diff --git a/react-bootstrap/index.d.ts b/react-bootstrap/index.d.ts index 2ec9eed50d..d60b8f18c7 100644 --- a/react-bootstrap/index.d.ts +++ b/react-bootstrap/index.d.ts @@ -535,6 +535,14 @@ declare namespace ReactBootstrap { type NavbarText = React.ClassicComponent; const NavbarText: React.ClassicComponentClass; + // + interface NavbarFormProps extends React.HTMLProps { + componentClass?: React.ReactType; + pullRight?: boolean; + } + type NavbarForm = React.ClassicComponent; + const NavbarForm: React.ClassicComponentClass; + // interface NavbarProps extends React.HTMLProps { brand?: any; // TODO: Add more specific type @@ -560,6 +568,7 @@ declare namespace ReactBootstrap { Toggle: typeof NavbarToggle; Link: typeof NavbarLink; Text: typeof NavbarText; + Form: typeof NavbarForm; } type Navbar = React.ClassicComponent; var Navbar: NavbarClass; @@ -862,6 +871,7 @@ declare namespace ReactBootstrap { hover?: boolean; responsive?: boolean; striped?: boolean; + fill?: boolean; } type Table = React.ClassicComponent; var Table: React.ClassicComponentClass; diff --git a/react-bootstrap/react-bootstrap-tests.tsx b/react-bootstrap/react-bootstrap-tests.tsx index 65ecbca247..e04a993be7 100644 --- a/react-bootstrap/react-bootstrap-tests.tsx +++ b/react-bootstrap/react-bootstrap-tests.tsx @@ -274,6 +274,29 @@ export class ReactBootstrapTest extends Component { +
+ + Some default panel content here. + + + + + + + + + + + + + + + +
ABC
Item 1Item 2
+ Some more panel content here. +
+
+
@@ -522,6 +545,13 @@ export class ReactBootstrapTest extends Component { Signed in as: Mark Otto + + + + + {' '} + + Have a great day! diff --git a/react-breadcrumbs/react-breadcrumbs.d.ts b/react-breadcrumbs/index.d.ts similarity index 100% rename from react-breadcrumbs/react-breadcrumbs.d.ts rename to react-breadcrumbs/index.d.ts diff --git a/react-breadcrumbs/tsconfig.json b/react-breadcrumbs/tsconfig.json index 5fc6650176..79fc7c00c4 100644 --- a/react-breadcrumbs/tsconfig.json +++ b/react-breadcrumbs/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-breadcrumbs.d.ts", + "index.d.ts", "react-breadcrumbs-tests.tsx" ] } \ No newline at end of file diff --git a/react-calendar-timeline/react-calendar-timeline.d.ts b/react-calendar-timeline/index.d.ts similarity index 100% rename from react-calendar-timeline/react-calendar-timeline.d.ts rename to react-calendar-timeline/index.d.ts diff --git a/react-calendar-timeline/tsconfig.json b/react-calendar-timeline/tsconfig.json index 4bd69bf193..7e2c69e149 100644 --- a/react-calendar-timeline/tsconfig.json +++ b/react-calendar-timeline/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-calendar-timeline.d.ts", + "index.d.ts", "react-calendar-timeline-tests.tsx" ] } \ No newline at end of file diff --git a/react-codemirror/react-codemirror.d.ts b/react-codemirror/index.d.ts similarity index 100% rename from react-codemirror/react-codemirror.d.ts rename to react-codemirror/index.d.ts diff --git a/react-codemirror/tsconfig.json b/react-codemirror/tsconfig.json index 2c0e4d2ad5..1a0d6a5a8b 100644 --- a/react-codemirror/tsconfig.json +++ b/react-codemirror/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-codemirror.d.ts", + "index.d.ts", "react-codemirror-tests.tsx" ] } \ No newline at end of file diff --git a/react-data-grid/index.d.ts b/react-data-grid/index.d.ts index c76ab540b8..7c438468e9 100644 --- a/react-data-grid/index.d.ts +++ b/react-data-grid/index.d.ts @@ -6,6 +6,12 @@ /// declare namespace AdazzleReactDataGrid { + + interface SelectionParams { + rowIdx: number, + row: any + } + interface GridProps { /** * Gets the data to render in each row. Required. @@ -170,6 +176,20 @@ declare namespace AdazzleReactDataGrid { * @default 0 */ rowScrollTimeout?: number + /** + * Options object for selecting rows + */ + rowSelection?: { + showCheckbox?: boolean + enableShiftSelect?: boolean + onRowsSelected?: (rows: Array) => void, + onRowsDeselected?: (rows: Array) => void, + selectBy?: { + indexes?: Array; + keys?: { rowKey: string, values: Array }; + isSelectedKey?: string; + } + } } /** @@ -393,6 +413,7 @@ declare namespace AdazzleReactDataGrid { // Various events export import RowUpdateEvent = AdazzleReactDataGrid.RowUpdateEvent; + export import SelectionParams = AdazzleReactDataGrid.SelectionParams; export import CellDragEvent = AdazzleReactDataGrid.CellDragEvent; export import DragHandleDoubleClickEvent = AdazzleReactDataGrid.DragHandleDoubleClickEvent; export import CellCopyPasteEvent = AdazzleReactDataGrid.CellCopyPasteEvent; diff --git a/react-data-grid/react-data-grid-tests.tsx b/react-data-grid/react-data-grid-tests.tsx index 4c2598c87c..bff860ee02 100644 --- a/react-data-grid/react-data-grid-tests.tsx +++ b/react-data-grid/react-data-grid-tests.tsx @@ -243,7 +243,19 @@ class Example extends React.Component { return this.state.rows.length; } + onRowsSelected(rows: Array) { + var selectedIndexes = this.state.selectedIndexes as Array; + + this.setState({selectedIndexes: selectedIndexes.concat(rows.map(r => r.rowIdx))}); + } + onRowsDeselected(rows: Array) { + var rowIndexes = rows.map(r => r.rowIdx); + var selectedIndexes = this.state.selectedIndexes as Array; + this.setState({selectedIndexes: selectedIndexes.filter(i => rowIndexes.indexOf(i) === -1 )}); + } + render() { + let selectedRows = ['id1', 'id2']; return ( { rowHeight={50} minHeight={600} rowScrollTimeout={200} + rowSelection={{ + showCheckbox: true, + enableShiftSelect: true, + onRowsSelected: this.onRowsSelected, + onRowsDeselected: this.onRowsDeselected, + selectBy: { + keys: {rowKey: 'id', values: selectedRows} + } + }} /> ); diff --git a/react-datepicker/react-datepicker.d.ts b/react-datepicker/index.d.ts similarity index 100% rename from react-datepicker/react-datepicker.d.ts rename to react-datepicker/index.d.ts diff --git a/react-datepicker/tsconfig.json b/react-datepicker/tsconfig.json index 60fcd89c5f..8f2905ef26 100644 --- a/react-datepicker/tsconfig.json +++ b/react-datepicker/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-datepicker.d.ts", + "index.d.ts", "react-datepicker-tests.tsx" ] } \ No newline at end of file diff --git a/react-day-picker/index.d.ts b/react-day-picker/index.d.ts index 3e64d2f71a..c3eb4a3170 100644 --- a/react-day-picker/index.d.ts +++ b/react-day-picker/index.d.ts @@ -65,6 +65,7 @@ declare namespace ReactDayPicker { numberOfMonths?: number; renderDay?: (date: Date) => number | string | JSX.Element; enableOutsideDays?: boolean; + firstDayOfWeek?:number; canChangeMonth?: boolean; disabledDays?: (date: Date) => boolean; fixedWeeks?: boolean; @@ -74,10 +75,10 @@ declare namespace ReactDayPicker { localeUtils?: LocaleUtils; locale?: string; captionElement?: React.ReactElement; - onDayClick?: (e: React.SyntheticEvent<{}>, day: Date, modifiers: string[]) => any; - onDayTouchTap?: (e: React.SyntheticEvent<{}>, day: Date, modifiers: string[]) => any; - onDayMouseEnter?: (e: React.SyntheticEvent<{}>, day: Date, modifiers: string[]) => any; - onDayMouseLeave?: (e: React.SyntheticEvent<{}>, day: Date, modifiers: string[]) => any; + onDayClick?: (e: React.SyntheticEvent<{}>, day: Date, modifiers: DayModifiers) => any; + onDayTouchTap?: (e: React.SyntheticEvent<{}>, day: Date, modifiers: DayModifiers) => any; + onDayMouseEnter?: (e: React.SyntheticEvent<{}>, day: Date, modifiers: DayModifiers) => any; + onDayMouseLeave?: (e: React.SyntheticEvent<{}>, day: Date, modifiers: DayModifiers) => any; onDayTouchEnd?: (e: React.SyntheticEvent<{}>, day: Date, modifiers: DayModifiers) => any; onDayTouchStart?: (e: React.SyntheticEvent<{}>, day: Date, modifiers: DayModifiers) => any; navbarElement?: React.ReactElement; diff --git a/react-dnd-html5-backend/react-dnd-html5-backend.d.ts b/react-dnd-html5-backend/index.d.ts similarity index 100% rename from react-dnd-html5-backend/react-dnd-html5-backend.d.ts rename to react-dnd-html5-backend/index.d.ts diff --git a/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts b/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts index 6a94717e92..670790c46a 100644 --- a/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts +++ b/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts @@ -1,4 +1,3 @@ -/// "use strict"; // Test adapted from the ReactDnD chess game tutorial: diff --git a/react-dnd-html5-backend/tsconfig.json b/react-dnd-html5-backend/tsconfig.json index b7ef8e9789..68c26e2605 100644 --- a/react-dnd-html5-backend/tsconfig.json +++ b/react-dnd-html5-backend/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "react-dnd-html5-backend.d.ts", + "index.d.ts", "react-dnd-html5-backend-tests.ts" ] } \ No newline at end of file diff --git a/react-dom/index.d.ts b/react-dom/index.d.ts index e242d65a90..0878cc0256 100644 --- a/react-dom/index.d.ts +++ b/react-dom/index.d.ts @@ -7,7 +7,7 @@ export as namespace ReactDOM; export = ReactDOM; import { ReactInstance, Component, ComponentState, - ReactElement, SFCElement, CElement, + ReactElement, SFCElement, CElement, DOMAttributes, DOMElement } from 'react'; declare namespace ReactDOM { diff --git a/react-easy-chart/index.d.ts b/react-easy-chart/index.d.ts new file mode 100644 index 0000000000..8728ad0eaf --- /dev/null +++ b/react-easy-chart/index.d.ts @@ -0,0 +1,277 @@ +// Type definitions for react-easy-chart v0.1.12 +// Project: https://github.com/rma-consulting/react-easy-chart +// Definitions by: Dave Leaver +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "react-easy-chart" { + + interface BarData { + x: number | Date | string; + y: number; + color?: string + } + interface BarChartProps { + /** Whether to show axis labels */ + axes?: boolean; + + /** Labels for each of the axis */ + axisLabels?: { x?: string, y?: string, y2?: string }; + + /** The width of an individual bar in pixels */ + barWidth?: number; + + clickHandler?: (data: BarData, mouseEvent: MouseEvent) => any; + + /** Whether to automatically color the bars */ + colorBars?: boolean; + + data: Array; + + /** A d3 time formatting pattern to be applied to format the x axis values */ + datePattern?: string; + + /** Whether to show horizontal grid lines on the chart */ + grid?: boolean; + + /** Height of the chart in pixels */ + height?: number; + + /** Interpolation method if you add a line to this chart (via lineData) */ + interpolate?: string; + + lineData?: Array; + + /** css margins */ + margin?: { top?: number, right?: number, bottom?: number, left?: number }; + + mouseMoveHandler?: (data: BarData, mouseEvent: MouseEvent) => any; + + mouseOutHandler?: (data: BarData, mouseEvent: MouseEvent) => any; + + mouseOverHandler?: (data: BarData, mouseEvent: MouseEvent) => any; + + /** The d3 time format to be used for the x axis (when xType is 'time') */ + tickTimeDisplayFormat?: string; + + /** Width of the chart in pixels */ + width?: number; + + /** The range that the x axis should show (otherwise automatically calculated) */ + xDomainRange?: Array | Array | Array; + + /** The amount of ticks to be shown on the x axis */ + xTickNumber?: number; + + /** What data type the x axis is */ + xType?: 'time' | 'text' | 'linear'; + + /** What data type the second y axis is */ + y2Type?: 'time' | 'text' | 'linear'; + + /** Whether to show the axis on the right (default false: left) */ + yAxisOrientRight?: boolean; + + /** The range that the y axis should show (otherwise automatically calculated) */ + yDomainRange?: Array; + + /** The amount of ticks to be shown on the y axis */ + yTickNumber?: number; + } + class BarChart extends React.Component { + } + + interface PieData { + key: string; + value: number; + color?: string; + } + interface PieChartProps { + clickHandler?: (data: PieData, mouseEvent: MouseEvent) => any; + + data: Array<{ key: string, value: number, color?: string }>; + + /** Size in pixels of the inner hole (diameter) */ + innerHoleSize?: number; + + /** Whether to add labels the to pie segments */ + labels?: boolean; + + mouseMoveHandler?: (data: PieData, mouseEvent: MouseEvent) => any; + + mouseOutHandler?: (data: PieData, mouseEvent: MouseEvent) => any; + + mouseOverHandler?: (data: PieData, mouseEvent: MouseEvent) => any; + + /** Padding around the chart in pixels */ + padding?: number; + + /** Size in pixels in each dimension */ + size?: number; + + styles?: { [cssSelector: string]: React.CSSProperties }; + } + class PieChart extends React.Component { + } + + interface LineData { + x: number | Date | string; + y: number | Date | string; + } + interface LineChartProps { + /** Whether to show axis labels */ + axes?: boolean; + + /** Labels for each of the axis */ + axisLabels?: { x?: string, y?: string }; + + clickHandler?: (data: LineData, mouseEvent: MouseEvent) => any; + + data: Array>; + + /** Whether to show circles on the data points */ + dataPoints?: boolean; + + /** Whether to show horizontal grid lines on the chart */ + grid?: boolean; + + /** Height of the chart in pixels */ + height?: number; + + /** Smoothing option for the lines */ + interpolate?: 'linear' | 'linear-closed' | 'step' | 'step-before' | 'step-after' | 'basis' | 'basis-open' | 'basis-closed' | 'bundle' | 'cardinal' | 'cardinal-open' | 'cardinal-closed' | 'monotone'; + + lineColors?: Array; + + /** css margins */ + margin?: { top?: number, right?: number, bottom?: number, left?: number }; + + mouseMoveHandler?: (data: LineData, mouseEvent: MouseEvent) => any; + + mouseOutHandler?: (data: LineData, mouseEvent: MouseEvent) => any; + + mouseOverHandler?: (data: LineData, mouseEvent: MouseEvent) => any; + + /** The d3 time format to be used for the x axis (when xType is 'time') */ + tickTimeDisplayFormat?: string; + + /** Whether to show vertical grid lines on the chart */ + verticalGrid?: boolean; + + /** Width of the chart in pixels */ + width?: number; + + /** The range that the x axis should show (otherwise automatically calculated) */ + xDomainRange?: Array | Array | Array; + + /** The amount of ticks to be shown on the x axis */ + xTicks?: number; + + /** What data type the x axis is */ + xType?: 'time' | 'text' | 'linear'; + + /** Whether to show the axis on the right (default false: left) */ + yAxisOrientRight?: boolean; + + /** The range that the y axis should show (otherwise automatically calculated) */ + yDomainRange?: Array | Array; + + /** The amount of ticks to be shown on the y axis */ + yTicks?: number; + + /** What data type the x axis is */ + yType?: 'time' | 'text' | 'linear'; + } + class LineChart extends React.Component { + } + + interface AreaChartProps extends LineChartProps { + /** Make the gradient area a solid fill rather than a gradient */ + noAreaGradient?: boolean; + } + class AreaChart extends React.Component { + } + + interface ScatterplotData { + type: string | number; + x: number | Date | string; + y: number | Date | string; + z?: number; + } + interface ScatterplotChartProps { + /** Whether to show axis labels */ + axes?: boolean; + + /** Labels for each of the axis */ + axisLabels?: { x?: string, y?: string }; + + clickHandler?: (data: ScatterplotData, mouseEvent: MouseEvent) => any; + + /** Allows styling of individual types of points */ + config?: Array<{ type: string, color: string, stroke: string }>; + + data: Array; + + /** Radius of the dots on the chart */ + dotRadius?: number; + + /** Whether to show horizontal grid lines on the chart */ + grid?: boolean; + + /** Height of the chart in pixels */ + height?: number; + + /** css margins */ + margin?: { top?: number, right?: number, bottom?: number, left?: number }; + + mouseMoveHandler?: (data: ScatterplotData, mouseEvent: MouseEvent) => any; + + mouseOutHandler?: (data: ScatterplotData, mouseEvent: MouseEvent) => any; + + mouseOverHandler?: (data: ScatterplotData, mouseEvent: MouseEvent) => any; + + /** Whether to show vertical grid lines on the chart */ + verticalGrid?: boolean; + + /** Width of the chart in pixels */ + width?: number; + + /** The range that the x axis should show (otherwise automatically calculated) */ + xDomainRange?: Array | Array | Array; + + /** What data type the x axis is */ + xType?: 'time' | 'text' | 'linear'; + + /** Whether to show the axis on the right (default false: left) */ + yAxisOrientRight?: boolean; + + /** The range that the y axis should show (otherwise automatically calculated) */ + yDomainRange?: Array | Array | Array; + + /** What data type the x axis is */ + yType?: 'time' | 'text' | 'linear'; + } + class ScatterplotChart extends React.Component { + } + + interface LegendProps { + /** Override the color of the items */ + config?: Array<{ color: string }>; + + data: Array; + + dataId: string; + + /** change list items to inline-block (default block) */ + horizontal?: boolean; + + /** Override the css styles of individual components, see http://rma-consulting.github.io/react-easy-chart/legend/index.html */ + styles?: { [cssSelector: string]: React.CSSProperties }; + } + class Legend extends React.Component { + + } + +} + diff --git a/react-easy-chart/react-easy-chart-tests.tsx b/react-easy-chart/react-easy-chart-tests.tsx new file mode 100644 index 0000000000..65ab377ccc --- /dev/null +++ b/react-easy-chart/react-easy-chart-tests.tsx @@ -0,0 +1,2021 @@ +import * as React from 'react'; +import { AreaChart, BarChart, Legend, LineChart, PieChart, ScatterplotChart } from 'react-easy-chart'; + +class BarChartData extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartHeightAndWidth extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartColorBars extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartMargin extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartOverridingBarColors extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartAxes extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartAxesLabels extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartYAxisOrientation extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartYAxesType extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartYAxesType2 extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartDatePattern extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartBarWidth extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartDomainRange extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartTickDisplayFormat extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartNumberOfTicks extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartGrid extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartBarAndLine extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class BarChartMouseHandlers extends React.Component<{}, {}> { + mouseOverHandler(d: any, e: any) { + } + + mouseMoveHandler(e: any) { + } + + mouseOutHandler() { + } + + render(): any { + return ( + this.setState({ dataDisplay: `The value on the ${d.x} is ${d.y}` })} + mouseOverHandler={this.mouseOverHandler} + mouseOutHandler={this.mouseOutHandler} + mouseMoveHandler={this.mouseMoveHandler} + yDomainRange={[0, 100]} + /> + ); + } +} + + +class PieChartData extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class PieChartColor extends React.Component<{}, {}> { + render(): any { + return ( + + + ); + } +} + +class PieChartSize extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class PieChartDonut extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class PieChartPadding extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class PieChartLabels extends React.Component<{}, {}> { + render(): any { + return ( +
rt_text': { + fontSize: '1em', + fill: '#fff' + } + }} + /> + ); + } +} + +class PieChartStyle extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class PieChartMouseHandlers extends React.Component<{}, {}> { + mouseOverHandler(d: any, e: any) { } + mouseMoveHandler(e: any) { } + mouseOutHandler() { } + render(): any { + return ( + this.setState({})} + mouseOverHandler={this.mouseOverHandler} + mouseOutHandler={this.mouseOutHandler.bind(this)} + mouseMoveHandler={this.mouseMoveHandler.bind(this)} + padding={10} + /> + ); + } +} + + +class LineChartData extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartData2 extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartHeightAndWidth extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartMargin extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartAxes extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartAxesLabels extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartYAxisOrientation extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartInterpolate extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartXType extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartXTypeTime extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartYTypeText extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartYTypeTime extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartGrid extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartVerticalGrid extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartDomainRange extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartTickDisplayFormat extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartNumberOfTicks extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartLineColors extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartDataPoints extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LineChartMouseEvents extends React.Component<{}, {}> { + mouseOverHandler(d: any, e: any) { } + mouseMoveHandler(e: any) { } + mouseOutHandler() { } + render(): any { + return ( + { } } + mouseOverHandler={this.mouseOverHandler} + mouseOutHandler={this.mouseOutHandler} + mouseMoveHandler={this.mouseMoveHandler} + width={700} + height={350} + interpolate={'cardinal'} + data={[ + [ + { x: 10, y: 25 }, + { x: 20, y: 10 }, + { x: 30, y: 25 }, + { x: 40, y: 10 }, + { x: 50, y: 12 }, + { x: 60, y: 25 } + ], [ + { x: 10, y: 40 }, + { x: 20, y: 30 }, + { x: 30, y: 25 }, + { x: 40, y: 60 }, + { x: 50, y: 22 }, + { x: 60, y: 9 } + ] + ]} + /> + ); + } +} + + +class AreaChartData extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartData2 extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartHeightAndWidth extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartMargin extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartAxes extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartAxesLabels extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartYAxisOrientation extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartInterpolate extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartAxisType extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartAxisTypeXTime extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartYTypeText extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartGrid extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartVerticalGrid extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartDomainRange extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartTickDisplayFormat extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartTickNumbers extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartDataPoints extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class AreaChartMouseHandlers extends React.Component<{}, {}> { + mouseOverHandler(d: any, e: any) { } + mouseMoveHandler(e: any) { } + mouseOutHandler() { } + render(): any { + return ( + { } } + mouseOverHandler={this.mouseOverHandler} + mouseOutHandler={this.mouseOutHandler} + mouseMoveHandler={this.mouseMoveHandler} + tickTimeDisplayFormat={'%d %m'} + interpolate={'cardinal'} + width={750} + height={250} + data={[ + [ + { x: '1-Jan-15', y: 20 }, + { x: '1-Feb-15', y: 10 }, + { x: '1-Mar-15', y: 33 }, + { x: '1-Apr-15', y: 45 }, + { x: '1-May-15', y: 15 } + ], [ + { x: '1-Jan-15', y: 10 }, + { x: '1-Feb-15', y: 15 }, + { x: '1-Mar-15', y: 13 }, + { x: '1-Apr-15', y: 15 }, + { x: '1-May-15', y: 10 } + ] + ]} + /> + ); + } +} + + +const data = [ + { + type: 'One', + x: 1, + y: 5 + }, + { + type: 'Two', + x: 3, + y: 1 + }, + { + type: 'Three', + x: 0, + y: 6 + }, + { + type: 'Four', + x: 5, + y: 2 + }, + { + type: 'Five', + x: 4, + y: 4 + }, + { + type: 'Six', + x: 5, + y: 9 + }, + { + type: 'Seven', + x: 9, + y: 1 + }, + { + type: 'Eight', + x: 5, + y: 6 + }, + { + type: 'Nine', + x: 3, + y: 9 + }, + { + type: 'Ten', + x: 7, + y: 9 + } +]; + +class ScatterplotData extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class ScatterplotHeightAndWidth extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class ScatterplotMargin extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class ScatterplotAxes extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class ScatterplotYAxisOrientation extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class ScatterplotAxesLabels extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class ScatterplotDotRadius extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class ScatterplotConfig extends React.Component<{}, {}> { + config = [ + { + type: 'One', + color: '#ff0000', + stroke: 'blue' + }, + { + type: 'Two', + color: '#00ff00', + stroke: 'blue' + }, + { + type: 'Three', + color: '#ffffff', + stroke: 'black' + } + ]; + render(): any { + return ( + + ); + } +} + +class ScatterplotGrid extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class ScatterplotVerticalGrid extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class ScatterplotAxisType extends React.Component<{}, {}> { + + typedData = [ + { + type: 1, + x: 'Tue', + y: 10 + }, + { + type: 1, + x: 'Wed', + y: 20 + }, + { + type: 2, + x: 'Tue', + y: 30 + }, + { + type: 3, + x: 'Thu', + y: 40 + } + ]; + render(): any { + return ( + + + ); + } +} + +class ScatterplotDomainRange extends React.Component<{}, {}> { + + typedData = [ + { + type: 1, + x: '1-Jan-15', + y: 10 + }, + { + type: 1, + x: '2-Jan-15', + y: 20 + }, + { + type: 2, + x: '1-Jan-15', + y: 30 + }, + { + type: 2, + x: '2-Jan-15', + y: 30 + }, + { + type: 3, + x: '3-Jan-15', + y: 40 + } + ]; + + render(): any { + return ( + + ); + } +} + +class ScatterplotMouseEvents extends React.Component<{}, {}> { + mouseOverHandler(d: any, e: any) { } + mouseMoveHandler(e: any) { } + mouseOutHandler() { } + render(): any { + return ( + + { } } + /> + ); + } +} + + +const pieData = [ + { key: 'Cats', value: 100 }, + { key: 'Dogs', value: 200 }, + { key: 'Other', value: 50 } +]; + +class LegendData extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +class LegendHorizontal extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + +const pieDataCustom = [ + { key: 'Cats', value: 100, color: '#aaac84' }, + { key: 'Dogs', value: 200, color: '#dce7c5' }, + { key: 'Other', value: 50, color: '#e3a51a' } +]; + +const config = [ + { color: '#aaac84' }, + { color: '#dce7c5' }, + { color: '#e3a51a' } +]; + +class LegendConfig extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} + + +/* default component styles */ +const defaultStyles = { + '.legend': { + 'list-style': 'none', + margin: 0, + padding: 0 + }, + '.legend li': { + display: 'block', + lineHeight: '24px', + marginRight: '24px', + marginBottom: '6px', + paddingLeft: '24px', + position: 'relative' + }, + '.legend li.horizontal': { + display: 'inline-block' + }, + '.legend .icon': { + width: '12px', + height: '12px', + background: 'red', + borderRadius: '6px', + position: 'absolute', + left: '0', + top: '50%', + marginTop: '-6px' + } +}; + +/* example override */ +const customStyle = { + '.legend': { + backgroundColor: '#f9f9f9', + border: '1px solid #e5e5e5', + borderRadius: '12px', + fontSize: '0.8em', + maxWidth: '300px', + padding: '12px' + } +}; + +class LegendStyles extends React.Component<{}, {}> { + render(): any { + return ( + + ); + } +} \ No newline at end of file diff --git a/rails-actioncable/tsconfig.json b/react-easy-chart/tsconfig.json similarity index 79% rename from rails-actioncable/tsconfig.json rename to react-easy-chart/tsconfig.json index 01da174ddf..fa7efaac28 100644 --- a/rails-actioncable/tsconfig.json +++ b/react-easy-chart/tsconfig.json @@ -5,15 +5,16 @@ "noImplicitAny": true, "strictNullChecks": false, "baseUrl": "../", + "jsx": "react", "typeRoots": [ "../" ], - "types": [], + "types": ["react"], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", - "rails-actioncable-tests.ts" + "react-easy-chart-tests.tsx" ] } \ No newline at end of file diff --git a/react-file-input/react-file-input.d.ts b/react-file-input/index.d.ts similarity index 100% rename from react-file-input/react-file-input.d.ts rename to react-file-input/index.d.ts diff --git a/react-file-input/tsconfig.json b/react-file-input/tsconfig.json index 6e2b25f0d2..25521dc631 100644 --- a/react-file-input/tsconfig.json +++ b/react-file-input/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-file-input.d.ts", + "index.d.ts", "react-file-input-tests.tsx" ] } \ No newline at end of file diff --git a/react-file-reader-input/react-file-reader-input.d.ts b/react-file-reader-input/index.d.ts similarity index 100% rename from react-file-reader-input/react-file-reader-input.d.ts rename to react-file-reader-input/index.d.ts diff --git a/react-file-reader-input/tsconfig.json b/react-file-reader-input/tsconfig.json index ec09339b0e..968de91e87 100644 --- a/react-file-reader-input/tsconfig.json +++ b/react-file-reader-input/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-file-reader-input.d.ts", + "index.d.ts", "react-file-reader-input-tests.tsx" ] } \ No newline at end of file diff --git a/react-flexr/react-flexr.d.ts b/react-flexr/index.d.ts similarity index 100% rename from react-flexr/react-flexr.d.ts rename to react-flexr/index.d.ts diff --git a/react-flexr/tsconfig.json b/react-flexr/tsconfig.json index 658fa94b63..4ae2aa3a91 100644 --- a/react-flexr/tsconfig.json +++ b/react-flexr/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-flexr.d.ts", + "index.d.ts", "react-flexr-tests.tsx" ] } \ No newline at end of file diff --git a/react-fontawesome/react-fontawesome.d.ts b/react-fontawesome/index.d.ts similarity index 100% rename from react-fontawesome/react-fontawesome.d.ts rename to react-fontawesome/index.d.ts diff --git a/react-fontawesome/tsconfig.json b/react-fontawesome/tsconfig.json index 9d1784f8a7..136824e9bc 100644 --- a/react-fontawesome/tsconfig.json +++ b/react-fontawesome/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-fontawesome.d.ts", + "index.d.ts", "react-fontawesome-tests.tsx" ] } \ No newline at end of file diff --git a/react-imageloader/react-imageloader.d.ts b/react-imageloader/index.d.ts similarity index 100% rename from react-imageloader/react-imageloader.d.ts rename to react-imageloader/index.d.ts diff --git a/react-imageloader/tsconfig.json b/react-imageloader/tsconfig.json index ce35e9adb2..457ffae645 100644 --- a/react-imageloader/tsconfig.json +++ b/react-imageloader/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-imageloader.d.ts", + "index.d.ts", "react-imageloader-tests.tsx" ] } \ No newline at end of file diff --git a/react-intl/index.d.ts b/react-intl/index.d.ts index 76df84469e..1d6412defa 100644 --- a/react-intl/index.d.ts +++ b/react-intl/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for react-intl 2.0.0 +// Type definitions for react-intl 2.1.5 // Project: http://formatjs.io/react/ -// Definitions by: Bruno Grieder , Christian Droulers +// Definitions by: Bruno Grieder , Christian Droulers , Fedor Nezhivoi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -12,7 +12,7 @@ declare namespace ReactIntl { pluralRuleFunction?: (n: number, ord: boolean) => string; } - function injectIntl(clazz: T): T; + function injectIntl(component: React.ComponentClass | React.StatelessComponent): React.ComponentClass; function addLocaleData(data: Locale[] | Locale): void; @@ -34,14 +34,14 @@ declare namespace ReactIntl { formats?: any; } - interface InjectedIntlProps { - formatDate?: (date: Date, options?: FormattedDate.PropsBase) => string; - formatTime?: (date: Date, options?: FormattedTime.PropsBase) => string; - formatRelative?: (value: number, options?: FormattedRelative.PropsBase) => string; - formatNumber?: (value: number, options?: FormattedNumber.PropsBase) => string; - formatPlural?: (value: number, options?: FormattedPlural.PropsBase) => string; - formatMessage?: (messageDescriptor: FormattedMessage.MessageDescriptor, values?: Object) => string; - formatHTMLMessage?: (messageDescriptor: FormattedMessage.MessageDescriptor, values?: Object) => string; + interface InjectedIntl { + formatDate: (date: Date, options?: FormattedDate.PropsBase) => string; + formatTime: (date: Date, options?: FormattedTime.PropsBase) => string; + formatRelative: (value: number, options?: FormattedRelative.PropsBase) => string; + formatNumber: (value: number, options?: FormattedNumber.PropsBase) => string; + formatPlural: (value: number, options?: FormattedPlural.PropsBase) => string; + formatMessage: (messageDescriptor: FormattedMessage.MessageDescriptor, values?: Object) => string; + formatHTMLMessage: (messageDescriptor: FormattedMessage.MessageDescriptor, values?: Object) => string; } namespace IntlComponent { diff --git a/react-intl/react-intl-tests.tsx b/react-intl/react-intl-tests.tsx index f140dd95d1..cd484c17b4 100644 --- a/react-intl/react-intl-tests.tsx +++ b/react-intl/react-intl-tests.tsx @@ -1,5 +1,6 @@ /** * Created by Bruno Grieder and Christian Droulers + * Updated by Fedor Nezhivoi */ /// @@ -9,7 +10,7 @@ import * as reactMixin from "react-mixin" import { IntlProvider, -InjectedIntlProps, +InjectedIntl, addLocaleData, hasLocaleData, injectIntl, @@ -29,22 +30,23 @@ import reactIntlEn = require("react-intl/locale-data/en"); addLocaleData(reactIntlEn); console.log(hasLocaleData("en")); -interface SomeComponentProps extends InjectedIntlProps { - +interface SomeComponentProps { + intl: InjectedIntl } -class SomeComponent extends React.Component { +class SomeComponent extends React.Component { static propTypes: React.ValidationMap = { intl: intlShape.isRequired }; public render(): React.ReactElement<{}> { - const formattedDate = this.props.formatDate(new Date(), { format: "short" }); - const formattedTime = this.props.formatTime(new Date(), { format: "short" }); - const formattedRelative = this.props.formatRelative(new Date().getTime(), { format: "short" }); - const formattedNumber = this.props.formatNumber(123, { format: "short" }); - const formattedPlural = this.props.formatPlural(1, { one: "hai!" }); - const formattedMessage = this.props.formatMessage({ id: "hello", defaultMessage: "Hello {name}!" }, { name: "Roger" }); - const formattedHTMLMessage = this.props.formatHTMLMessage({ id: "hello", defaultMessage: "Hello {name}!" }, { name: "Roger" }); + const intl = this.props.intl; + const formattedDate = intl.formatDate(new Date(), { format: "short" }); + const formattedTime = intl.formatTime(new Date(), { format: "short" }); + const formattedRelative = intl.formatRelative(new Date().getTime(), { format: "short" }); + const formattedNumber = intl.formatNumber(123, { format: "short" }); + const formattedPlural = intl.formatPlural(1, { one: "hai!" }); + const formattedMessage = intl.formatMessage({ id: "hello", defaultMessage: "Hello {name}!" }, { name: "Roger" }); + const formattedHTMLMessage = intl.formatHTMLMessage({ id: "hello", defaultMessage: "Hello {name}!" }, { name: "Roger" }); return
{ } } +const SomeComponentWithIntl = injectIntl(SomeComponent); + class TestApp extends React.Component<{}, {}> { public render(): React.ReactElement<{}> { const definedMessages = defineMessages({ @@ -153,14 +157,16 @@ class TestApp extends React.Component<{}, {}> { const messages = { "hello": "Hello, {name}!" - } - return ( - - ) + }; + return ( + + + + ); } } export default { TestApp, - SomeComponent: injectIntl(SomeComponent) + SomeComponent: SomeComponentWithIntl } diff --git a/react-is-deprecated/react-is-deprecated.d.ts b/react-is-deprecated/index.d.ts similarity index 100% rename from react-is-deprecated/react-is-deprecated.d.ts rename to react-is-deprecated/index.d.ts diff --git a/react-is-deprecated/tsconfig.json b/react-is-deprecated/tsconfig.json index f9d5739a14..c5cf1213a3 100644 --- a/react-is-deprecated/tsconfig.json +++ b/react-is-deprecated/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-is-deprecated.d.ts", + "index.d.ts", "react-is-deprecated-tests.ts" ] } \ No newline at end of file diff --git a/react-json-tree/index.d.ts b/react-json-tree/index.d.ts index 2721604f3b..dd20fdb6e6 100644 --- a/react-json-tree/index.d.ts +++ b/react-json-tree/index.d.ts @@ -15,7 +15,7 @@ export interface JSONTreeProps extends Props { invertTheme?: boolean; keyPath?: [string | number]; sortObjectKeys?: Function | boolean; - shouldExpandNode?: (keyName: string, data: [any] | {}, level: number) => boolean; + shouldExpandNode?: (keyPath: (string | number)[], data: [any] | {}, level: number) => boolean; getItemString?: (type: string, data: [any] | {}, itemType: string, itemString: string) => JSX.Element; labelRenderer?: (raw: [string, string]) => JSX.Element; valueRenderer?: (raw: string) => JSX.Element; diff --git a/react-jsonschema-form/react-jsonschema-form.d.ts b/react-jsonschema-form/index.d.ts similarity index 100% rename from react-jsonschema-form/react-jsonschema-form.d.ts rename to react-jsonschema-form/index.d.ts diff --git a/react-jsonschema-form/tsconfig.json b/react-jsonschema-form/tsconfig.json index b70a03d4ba..f1b6bb257d 100644 --- a/react-jsonschema-form/tsconfig.json +++ b/react-jsonschema-form/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-jsonschema-form.d.ts", + "index.d.ts", "react-jsonschema-form-tests.tsx" ] } \ No newline at end of file diff --git a/react-measure/react-measure.d.ts b/react-measure/index.d.ts similarity index 100% rename from react-measure/react-measure.d.ts rename to react-measure/index.d.ts diff --git a/react-measure/tsconfig.json b/react-measure/tsconfig.json index 0a0e3ad58e..99338af61d 100644 --- a/react-measure/tsconfig.json +++ b/react-measure/tsconfig.json @@ -15,7 +15,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "react-measure.d.ts", + "index.d.ts", "react-measure-tests.tsx" ] } \ No newline at end of file diff --git a/react-modal/react-modal.d.ts b/react-modal/index.d.ts similarity index 100% rename from react-modal/react-modal.d.ts rename to react-modal/index.d.ts diff --git a/react-modal/tsconfig.json b/react-modal/tsconfig.json index 87f956ff88..61490f70b7 100644 --- a/react-modal/tsconfig.json +++ b/react-modal/tsconfig.json @@ -14,7 +14,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "react-modal.d.ts", + "index.d.ts", "react-modal-tests.tsx" ] } \ No newline at end of file diff --git a/react-motion-slider/react-motion-slider.d.ts b/react-motion-slider/index.d.ts similarity index 100% rename from react-motion-slider/react-motion-slider.d.ts rename to react-motion-slider/index.d.ts diff --git a/react-motion-slider/tsconfig.json b/react-motion-slider/tsconfig.json index 09a7065508..d93775736c 100644 --- a/react-motion-slider/tsconfig.json +++ b/react-motion-slider/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-motion-slider.d.ts", + "index.d.ts", "react-motion-slider-tests.tsx" ] } \ No newline at end of file diff --git a/react-native-sortable-list/tsconfig.json b/react-native-sortable-list/tsconfig.json index 1f709abb74..9e533f6495 100644 --- a/react-native-sortable-list/tsconfig.json +++ b/react-native-sortable-list/tsconfig.json @@ -17,4 +17,4 @@ "index.d.ts", "react-native-sortable-list-tests.tsx" ] -} \ No newline at end of file +} diff --git a/react-overlays/index.d.ts b/react-overlays/index.d.ts new file mode 100644 index 0000000000..e826dc83eb --- /dev/null +++ b/react-overlays/index.d.ts @@ -0,0 +1,222 @@ +// Type definitions for React Overlays v0.6.10 +// Project: https://github.com/react-bootstrap/react-overlays +// Definitions by: Aaron Beall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "react-overlays" { + import * as React from "react"; + import * as ReactBootstrap from "react-bootstrap"; + + // + interface AffixProps { + /** + * Pixels to offset from top of screen when calculating position + */ + offsetTop?: number; + + /** + * When affixed, pixels to offset from top of viewport + */ + viewportOffsetTop?: number; + + /** + * Pixels to offset from bottom of screen when calculating position + */ + offsetBottom?: number; + + /** + * CSS class or classes to apply when at top + */ + topClassName?: string; + + /** + * Style to apply when at top + */ + topStyle?: React.CSSProperties; + + /** + * CSS class or classes to apply when affixed + */ + affixClassName?: string; + + /** + * Style to apply when affixed + */ + affixStyle?: React.CSSProperties; + + /** + * CSS class or classes to apply when at bottom + */ + bottomClassName?: string; + + /** + * Style to apply when at bottom + */ + bottomStyle?: React.CSSProperties; + + /** + * Callback fired when the right before the `affixStyle` and `affixStyle` props are rendered + */ + onAffix?: () => void; + /** + * Callback fired after the component `affixStyle` and `affixClassName` props have been rendered. + */ + onAffixed?: () => void; + + /** + * Callback fired when the right before the `topStyle` and `topClassName` props are rendered + */ + onAffixTop?: () => void; + + /** + * Callback fired after the component `topStyle` and `topClassName` props have been rendered. + */ + onAffixedTop?: () => void; + + /** + * Callback fired when the right before the `bottomStyle` and `bottomClassName` props are rendered + */ + onAffixBottom?: () => void; + + /** + * Callback fired after the component `bottomStyle` and `bottomClassName` props have been rendered. + */ + onAffixedBottom?: () => void; + } + class Affix extends React.Component { } + + // + interface AutoAffixProps extends AffixProps { + + /** + * The logical container node or component for determining offset from bottom + * of viewport, or a function that returns it + */ + container?: React.ReactInstance | (() => React.ReactInstance); + + /** + * Automatically set width when affixed + */ + autoWidth?: boolean; + } + class AutoAffix extends React.Component { } + + // + type Modal = ReactBootstrap.Modal; // Provided already through react-bootstrap + + // + type Overlay = ReactBootstrap.Overlay; // Provided already through react-bootstrap + + // + type Portal = ReactBootstrap.Portal; // Provided already through react-bootstrap + + // + type Position = ReactBootstrap.Position; // Provided already through react-bootstrap + + // + interface TransitionProps { + className?: string; + + /** + * Show the component; triggers the enter or exit animation + */ + in?: boolean; + + /** + * Unmount the component (remove it from the DOM) when it is not shown + */ + unmountOnExit?: boolean; + + /** + * Run the enter animation when the component mounts, if it is initially + * shown + */ + transitionAppear?: boolean; + + /** + * A Timeout for the animation, in milliseconds, to ensure that a node doesn't + * transition indefinately if the browser transitionEnd events are + * canceled or interrupted. + * + * By default this is set to a high number (5 seconds) as a failsafe. You should consider + * setting this to the duration of your animation (or a bit above it). + */ + timeout?: number; + + /** + * CSS class or classes applied when the component is exited + */ + exitedClassName?: string; + + /** + * CSS class or classes applied while the component is exiting + */ + exitingClassName?: string; + + /** + * CSS class or classes applied when the component is entered + */ + enteredClassName?: string; + + /** + * CSS class or classes applied while the component is entering + */ + enteringClassName?: string; + + /** + * Callback fired before the "entering" classes are applied + */ + onEnter?: (element: Element) => void; + + /** + * Callback fired after the "entering" classes are applied + */ + onEntering?: (element: Element) => void; + + /** + * Callback fired after the "enter" classes are applied + */ + onEntered?: (element: Element) => void; + + /** + * Callback fired before the "exiting" classes are applied + */ + onExit?: (element: Element) => void; + + /** + * Callback fired after the "exiting" classes are applied + */ + onExiting?: (element: Element) => void; + + /** + * Callback fired after the "exited" classes are applied + */ + onExited?: (element: Element) => void; + } + class Transition extends React.Component { } +} + +declare module "react-overlays/lib/RootCloseWrapper" { + import * as React from "react"; + + // + interface RootCloseWrapperProps { + onRootClose?: () => void; + children?: React.ReactNode; + + /** + * Disable the the RootCloseWrapper, preventing it from triggering + * `onRootClose`. + */ + disabled?: boolean; + + /** + * Choose which document mouse event to bind to + */ + event?: 'click' | 'mousedown'; + } + class RootCloseWrapper extends React.Component { } + + namespace RootCloseWrapper { } // module export workaround: https://github.com/Microsoft/TypeScript/issues/5073 + export = RootCloseWrapper; +} diff --git a/react-overlays/react-overlays-tests.tsx b/react-overlays/react-overlays-tests.tsx new file mode 100644 index 0000000000..6beee70ea7 --- /dev/null +++ b/react-overlays/react-overlays-tests.tsx @@ -0,0 +1,44 @@ +import * as React from "react"; + +import {Transition, Portal, Modal, Position, Overlay, Affix, AutoAffix} from "react-overlays"; +import * as RootCloseWrapper from "react-overlays/lib/RootCloseWrapper"; + +function testTransition() { + return ( + +
Test
+
+ ); +} + + +class TestAffix extends React.Component<{}, {}> { + render(): JSX.Element { + return ( +
+ +
Test
+
+
+ ); + } +} + +class TestRootCloseWrapper extends React.Component<{}, {}> { + handleRootClose = () => { }; + render() { + return ( + +
Test
+
+ ); + } +} diff --git a/react-overlays/tsconfig.json b/react-overlays/tsconfig.json new file mode 100644 index 0000000000..ab93e191ad --- /dev/null +++ b/react-overlays/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-overlays-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-redux-i18n/index.d.ts b/react-redux-i18n/index.d.ts index aa47bb2723..d7851b23dc 100644 --- a/react-redux-i18n/index.d.ts +++ b/react-redux-i18n/index.d.ts @@ -20,6 +20,10 @@ declare module 'react-redux-i18n' { type TranslationObjects = { [lang: string]: SubTranslationObject }; + type DispatchCallback = { + (dispatch?: redux.Dispatch, getState?: () => S): any; + } + type I18nState = { translations: TranslationObjects; locale: string; @@ -55,8 +59,8 @@ declare module 'react-redux-i18n' { /** * Redux Actions */ - export function loadTranslations(translationsObject: TranslationObjects): void; + export function loadTranslations(translationsObject: TranslationObjects): DispatchCallback; - export function setLocale(locale: string): void; + export function setLocale(locale: string): DispatchCallback; } diff --git a/react-relay/react-relay.d.ts b/react-relay/index.d.ts similarity index 98% rename from react-relay/react-relay.d.ts rename to react-relay/index.d.ts index 5aad6d4e4e..3731f9ca5d 100644 --- a/react-relay/react-relay.d.ts +++ b/react-relay/index.d.ts @@ -52,7 +52,7 @@ declare module "react-relay" { } class DefaultNetworkLayer implements RelayNetworkLayer { - constructor(host: string, options: any) + constructor(host: string, options?: any) supports(...options: string[]): boolean } diff --git a/react-relay/tsconfig.json b/react-relay/tsconfig.json index c3b3c4e209..c3fca33dab 100644 --- a/react-relay/tsconfig.json +++ b/react-relay/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-relay.d.ts", + "index.d.ts", "react-relay-test.tsx" ] } \ No newline at end of file diff --git a/react-responsive/react-responsive.d.ts b/react-responsive/index.d.ts similarity index 100% rename from react-responsive/react-responsive.d.ts rename to react-responsive/index.d.ts diff --git a/react-responsive/tsconfig.json b/react-responsive/tsconfig.json index a15be69b1e..2b46a3f997 100644 --- a/react-responsive/tsconfig.json +++ b/react-responsive/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-responsive.d.ts", + "index.d.ts", "react-responsive-tests.tsx" ] } \ No newline at end of file diff --git a/react-router/index.d.ts b/react-router/index.d.ts index 1dbb3f8682..da7ea7f16e 100644 --- a/react-router/index.d.ts +++ b/react-router/index.d.ts @@ -47,9 +47,11 @@ export type PlainRoute = Router.PlainRoute; export type EnterHook = Router.EnterHook; export type LeaveHook = Router.LeaveHook; export type ParseQueryString = Router.ParseQueryString; +export type LocationDescriptor = Router.LocationDescriptor; export type RedirectFunction = Router.RedirectFunction; export type RouteComponent = Router.RouteComponent; export type RouteComponentProps = Router.RouteComponentProps; +export type RouteConfig = Router.RouteConfig; export type RouteHook = Router.RouteHook; export type StringifyQuery = Router.StringifyQuery; export type RouterListener = Router.RouterListener; diff --git a/react-router/lib/Link.d.ts b/react-router/lib/Link.d.ts index 58e9f85bcf..7b41e61dc2 100644 --- a/react-router/lib/Link.d.ts +++ b/react-router/lib/Link.d.ts @@ -1,6 +1,5 @@ import * as React from 'react'; import Router from './Router'; -import * as H from 'history'; declare const Link: Link; type Link = Link.Link; @@ -12,9 +11,7 @@ declare namespace Link { activeStyle?: React.CSSProperties; activeClassName?: string; onlyActiveOnIndex?: boolean; - to: Router.RoutePattern | H.LocationDescriptor; - query?: H.Query; - state?: H.LocationState; + to: Router.RoutePattern | Router.LocationDescriptor | ((...args: any[]) => Router.LocationDescriptor); } interface Link extends React.ComponentClass {} diff --git a/react-router/lib/Router.d.ts b/react-router/lib/Router.d.ts index 5a4cfacb15..a9c5417f47 100644 --- a/react-router/lib/Router.d.ts +++ b/react-router/lib/Router.d.ts @@ -2,8 +2,8 @@ import * as React from 'react'; import RouterContext from './RouterContext'; import { QueryString, Query, - Location, LocationDescriptor, LocationState, - History, + Location, LocationDescriptor, LocationState as HLocationState, + History, Href, Pathname, Path } from 'history'; declare const Router: Router; @@ -33,13 +33,19 @@ declare namespace Router { type RouterListener = (error: Error, nextState: RouterState) => void; + type LocationDescriptor = { + pathname?: Pathname + query?: Query + hash?: Href + state?: HLocationState + } interface RedirectFunction { (location: LocationDescriptor): void; /** * @deprecated `replaceState(state, pathname, query) is deprecated; Use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated */ - (state: LocationState, pathname: Pathname | Path, query?: Query): void; + (state: HLocationState, pathname: Pathname | Path, query?: Query): void; } interface RouterState { @@ -87,7 +93,7 @@ declare namespace Router { interface RouterOnContext extends History { setRouteLeaveHook(route: PlainRoute, hook?: RouteHook): () => void; - isActive(pathOrLoc: LocationDescriptor, indexOnly?: boolean): boolean; + isActive(pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean): boolean; } // Wrap a component using withRouter(Component) to provide a router object @@ -97,14 +103,14 @@ declare namespace Router { // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md interface InjectedRouter { - push: (pathOrLoc: History.LocationDescriptor) => void - replace: (pathOrLoc: History.LocationDescriptor) => void + push: (pathOrLoc: Path | LocationDescriptor) => void + replace: (pathOrLoc: Path | LocationDescriptor) => void go: (n: number) => void goBack: () => void goForward: () => void setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void createPath(path: History.Path, query?: History.Query): History.Path createHref(path: History.Path, query?: History.Query): History.Href - isActive: (pathOrLoc: History.LocationDescriptor, indexOnly?: boolean) => boolean + isActive: (pathOrLoc: Path | LocationDescriptor, indexOnly?: boolean) => boolean } } diff --git a/react-scrollbar/react-scrollbar.d.ts b/react-scrollbar/index.d.ts similarity index 100% rename from react-scrollbar/react-scrollbar.d.ts rename to react-scrollbar/index.d.ts diff --git a/react-scrollbar/tsconfig.json b/react-scrollbar/tsconfig.json index 1f4f102561..940cf56fbd 100644 --- a/react-scrollbar/tsconfig.json +++ b/react-scrollbar/tsconfig.json @@ -14,7 +14,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "react-scrollbar.d.ts", + "index.d.ts", "react-scrollbar-tests.tsx" ] } \ No newline at end of file diff --git a/react-slick/react-slick.d.ts b/react-slick/index.d.ts similarity index 100% rename from react-slick/react-slick.d.ts rename to react-slick/index.d.ts diff --git a/react-slick/tsconfig.json b/react-slick/tsconfig.json index f29388a78f..1a32f8f96a 100644 --- a/react-slick/tsconfig.json +++ b/react-slick/tsconfig.json @@ -14,7 +14,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "react-slick.d.ts", + "index.d.ts", "react-slick-test.tsx" ] } \ No newline at end of file diff --git a/react-sortable-hoc/react-sortable-hoc.d.ts b/react-sortable-hoc/index.d.ts similarity index 100% rename from react-sortable-hoc/react-sortable-hoc.d.ts rename to react-sortable-hoc/index.d.ts diff --git a/react-sortable-hoc/tsconfig.json b/react-sortable-hoc/tsconfig.json index 595b57b362..9873b4d2be 100644 --- a/react-sortable-hoc/tsconfig.json +++ b/react-sortable-hoc/tsconfig.json @@ -14,7 +14,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "react-sortable-hoc.d.ts", + "index.d.ts", "react-sortable-hoc-tests.tsx" ] } \ No newline at end of file diff --git a/react-split-pane/react-split-pane.d.ts b/react-split-pane/index.d.ts similarity index 100% rename from react-split-pane/react-split-pane.d.ts rename to react-split-pane/index.d.ts diff --git a/react-split-pane/tsconfig.json b/react-split-pane/tsconfig.json index e6db5fa417..f476a14fd6 100644 --- a/react-split-pane/tsconfig.json +++ b/react-split-pane/tsconfig.json @@ -14,7 +14,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "react-split-pane.d.ts", + "index.d.ts", "react-split-pane-tests.tsx" ] } \ No newline at end of file diff --git a/react-swipeable/react-swipeable.d.ts b/react-swipeable/index.d.ts similarity index 100% rename from react-swipeable/react-swipeable.d.ts rename to react-swipeable/index.d.ts diff --git a/react-swipeable/tsconfig.json b/react-swipeable/tsconfig.json index 02fd1d28d5..0ae8b22d4e 100644 --- a/react-swipeable/tsconfig.json +++ b/react-swipeable/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-swipeable.d.ts", + "index.d.ts", "react-swipeable-tests.tsx" ] } \ No newline at end of file diff --git a/react-textarea-autosize/react-textarea-autosize.d.ts b/react-textarea-autosize/index.d.ts similarity index 100% rename from react-textarea-autosize/react-textarea-autosize.d.ts rename to react-textarea-autosize/index.d.ts diff --git a/react-textarea-autosize/tsconfig.json b/react-textarea-autosize/tsconfig.json index 5f7456c652..90f12412d1 100644 --- a/react-textarea-autosize/tsconfig.json +++ b/react-textarea-autosize/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-textarea-autosize.d.ts", + "index.d.ts", "react-textarea-autosize-tests.tsx" ] } \ No newline at end of file diff --git a/react-user-tour/react-user-tour.d.ts b/react-user-tour/index.d.ts similarity index 100% rename from react-user-tour/react-user-tour.d.ts rename to react-user-tour/index.d.ts diff --git a/react-user-tour/tsconfig.json b/react-user-tour/tsconfig.json index 6ba3336beb..2a7f80fd83 100644 --- a/react-user-tour/tsconfig.json +++ b/react-user-tour/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "react-user-tour.d.ts", + "index.d.ts", "react-user-tour-tests.tsx" ] } \ No newline at end of file diff --git a/react-virtualized/index.d.ts b/react-virtualized/index.d.ts index f00215ffd2..345dcc79db 100644 --- a/react-virtualized/index.d.ts +++ b/react-virtualized/index.d.ts @@ -118,6 +118,23 @@ declare module "react-virtualized" { type ScrollSyncProps = any; export class ScrollSync extends React.Component { } - type WindowScrollerProps = any; - export class WindowScroller extends React.Component { } + export module WindowScroller { + export type OnResizeArg = { + height: number; + } + export type OnScrollArg = { + scrollTop: number; + } + export type RenderCallbackArg = { + height: number; + scrollTop: number; + isScrolling: boolean; + } + export type Props = { + onScroll?: (arg: OnScrollArg) => void; + onResize?: (arg: OnResizeArg) => void; + // TODO `children` should be typed here + }; + } + export class WindowScroller extends React.Component { } } diff --git a/react-virtualized/react-virtualized-tests.tsx b/react-virtualized/react-virtualized-tests.tsx index 1cb9d97c1b..6c799746fd 100644 --- a/react-virtualized/react-virtualized-tests.tsx +++ b/react-virtualized/react-virtualized-tests.tsx @@ -291,9 +291,11 @@ function ScrollSyncTest() { } function WindowScrollerTest() { + const onScroll = function({scrollTop}: WindowScroller.OnScrollArg) {}; + const onResize = function({height}: WindowScroller.OnResizeArg) {}; ReactDOM.render( - - {({ height, isScrolling, scrollTop }) => ( + + {({ height, isScrolling, scrollTop }: WindowScroller.RenderCallbackArg) => ( , document.getElementById('example') ); + // test that onScroll & onResize are optional + ReactDOM.render( + , + document.getElementById('example') + ); } diff --git a/react/index.d.ts b/react/index.d.ts index fa960ad671..1929a7853c 100644 --- a/react/index.d.ts +++ b/react/index.d.ts @@ -2563,41 +2563,41 @@ declare global { circle: React.SVGProps; clipPath: React.SVGProps; defs: React.SVGProps; - desc: React.SVGProps; + desc: React.SVGProps; ellipse: React.SVGProps; - feBlend: React.SVGProps; - feColorMatrix: React.SVGProps; - feComponentTransfer: React.SVGProps; - feComposite: React.SVGProps; - feConvolveMatrix: React.SVGProps; - feDiffuseLighting: React.SVGProps; - feDisplacementMap: React.SVGProps; - feDistantLight: React.SVGProps; - feFlood: React.SVGProps; - feFuncA: React.SVGProps; - feFuncB: React.SVGProps; - feFuncG: React.SVGProps; - feFuncR: React.SVGProps; - feGaussianBlur: React.SVGProps; - feImage: React.SVGProps; - feMerge: React.SVGProps; - feMergeNode: React.SVGProps; - feMorphology: React.SVGProps; - feOffset: React.SVGProps; - fePointLight: React.SVGProps; - feSpecularLighting: React.SVGProps; - feSpotLight: React.SVGProps; - feTile: React.SVGProps; - feTurbulence: React.SVGProps; - filter: React.SVGProps; - foreignObject: React.SVGProps; + feBlend: React.SVGProps; + feColorMatrix: React.SVGProps; + feComponentTransfer: React.SVGProps; + feComposite: React.SVGProps; + feConvolveMatrix: React.SVGProps; + feDiffuseLighting: React.SVGProps; + feDisplacementMap: React.SVGProps; + feDistantLight: React.SVGProps; + feFlood: React.SVGProps; + feFuncA: React.SVGProps; + feFuncB: React.SVGProps; + feFuncG: React.SVGProps; + feFuncR: React.SVGProps; + feGaussianBlur: React.SVGProps; + feImage: React.SVGProps; + feMerge: React.SVGProps; + feMergeNode: React.SVGProps; + feMorphology: React.SVGProps; + feOffset: React.SVGProps; + fePointLight: React.SVGProps; + feSpecularLighting: React.SVGProps; + feSpotLight: React.SVGProps; + feTile: React.SVGProps; + feTurbulence: React.SVGProps; + filter: React.SVGProps; + foreignObject: React.SVGProps; g: React.SVGProps; image: React.SVGProps; line: React.SVGProps; linearGradient: React.SVGProps; - marker: React.SVGProps; + marker: React.SVGProps; mask: React.SVGProps; - metadata: React.SVGProps; + metadata: React.SVGProps; path: React.SVGProps; pattern: React.SVGProps; polygon: React.SVGProps; @@ -2605,13 +2605,13 @@ declare global { radialGradient: React.SVGProps; rect: React.SVGProps; stop: React.SVGProps; - switch: React.SVGProps; + switch: React.SVGProps; symbol: React.SVGProps; text: React.SVGProps; - textPath: React.SVGProps; + textPath: React.SVGProps; tspan: React.SVGProps; use: React.SVGProps; - view: React.SVGProps; + view: React.SVGProps; } } } diff --git a/redis/index.d.ts b/redis/index.d.ts index f1b4b6e11b..0c2e107646 100644 --- a/redis/index.d.ts +++ b/redis/index.d.ts @@ -385,6 +385,9 @@ export interface RedisClient extends NodeJS.EventEmitter { hscan(args: any[], callback?: ResCallbackT): boolean; zscan(...args: any[]): boolean; zscan(args: any[], callback?: ResCallbackT): boolean; + + // Extras + duplicate(options?:any[], callback?:ResCallbackT): RedisClient; } export interface Multi { diff --git a/redis/redis-tests.ts b/redis/redis-tests.ts index 1002c03031..d98979f256 100644 --- a/redis/redis-tests.ts +++ b/redis/redis-tests.ts @@ -110,4 +110,6 @@ client.multi(commandArr).exec(); client.monitor(resCallback); // Send command -client.send_command(str, args, resCallback); \ No newline at end of file +client.send_command(str, args, resCallback); +// Duplicate +client.duplicate(); \ No newline at end of file diff --git a/redux-actions/index.d.ts b/redux-actions/index.d.ts index 5247e21704..7d4a6ea622 100644 --- a/redux-actions/index.d.ts +++ b/redux-actions/index.d.ts @@ -44,6 +44,11 @@ declare namespace ReduxActions { metaCreator: (...args: any[]) => Meta ): (...args: any[]) => ActionMeta; + export function handleAction( + actionType: { toString: () => string }, + reducer: Reducer | ReducerMap + ): Reducer; + export function handleAction( actionType: { toString(): string }, reducer: Reducer | ReducerMap @@ -54,6 +59,11 @@ declare namespace ReduxActions { reducer: ReducerMeta | ReducerMap ): Reducer; + export function handleActions( + reducerMap: ReducerMap, + initialState?: StateAndPayload + ): Reducer; + export function handleActions( reducerMap: ReducerMap, initialState?: State diff --git a/redux-bootstrap/redux-bootstrap.d.ts b/redux-bootstrap/index.d.ts similarity index 100% rename from redux-bootstrap/redux-bootstrap.d.ts rename to redux-bootstrap/index.d.ts diff --git a/redux-bootstrap/tsconfig.json b/redux-bootstrap/tsconfig.json index e5e83c285f..264ed2e6be 100644 --- a/redux-bootstrap/tsconfig.json +++ b/redux-bootstrap/tsconfig.json @@ -15,7 +15,7 @@ "jsx": "react" }, "files": [ - "redux-bootstrap.d.ts", + "index.d.ts", "redux-bootstrap-tests.tsx" ] } \ No newline at end of file diff --git a/redux-devtools/index.d.ts b/redux-devtools/index.d.ts index 414e0b6573..5be4b746df 100644 --- a/redux-devtools/index.d.ts +++ b/redux-devtools/index.d.ts @@ -9,7 +9,7 @@ import * as React from 'react'; import { GenericStoreEnhancer } from 'redux'; -interface IDevTools { +export interface IDevTools { new (): JSX.ElementClass; instrument(): GenericStoreEnhancer } diff --git a/redux-mock-store/redux-mock-store.d.ts b/redux-mock-store/index.d.ts similarity index 100% rename from redux-mock-store/redux-mock-store.d.ts rename to redux-mock-store/index.d.ts diff --git a/redux-mock-store/tsconfig.json b/redux-mock-store/tsconfig.json index 9e015629bd..1e0540ee2f 100644 --- a/redux-mock-store/tsconfig.json +++ b/redux-mock-store/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "redux-mock-store.d.ts", + "index.d.ts", "redux-mock-store-tests.ts" ] } \ No newline at end of file diff --git a/redux-optimistic-ui/redux-optimistic-ui.d.ts b/redux-optimistic-ui/index.d.ts similarity index 100% rename from redux-optimistic-ui/redux-optimistic-ui.d.ts rename to redux-optimistic-ui/index.d.ts diff --git a/redux-optimistic-ui/tsconfig.json b/redux-optimistic-ui/tsconfig.json index 8de339b93a..0f4499bc00 100644 --- a/redux-optimistic-ui/tsconfig.json +++ b/redux-optimistic-ui/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "redux-optimistic-ui.d.ts", + "index.d.ts", "redux-optimistic-ui-tests.ts" ] } \ No newline at end of file diff --git a/redux-promise-middleware/redux-promise-middleware.d.ts b/redux-promise-middleware/index.d.ts similarity index 100% rename from redux-promise-middleware/redux-promise-middleware.d.ts rename to redux-promise-middleware/index.d.ts diff --git a/redux-promise-middleware/tsconfig.json b/redux-promise-middleware/tsconfig.json index 380792b821..4b98cbafa9 100644 --- a/redux-promise-middleware/tsconfig.json +++ b/redux-promise-middleware/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "redux-promise-middleware.d.ts", + "index.d.ts", "redux-promise-middleware-tests.ts" ] } \ No newline at end of file diff --git a/redux-storage/redux-storage.d.ts b/redux-storage/index.d.ts similarity index 100% rename from redux-storage/redux-storage.d.ts rename to redux-storage/index.d.ts diff --git a/redux-storage/tsconfig.json b/redux-storage/tsconfig.json index 2559181263..08ffc4fd8c 100644 --- a/redux-storage/tsconfig.json +++ b/redux-storage/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "redux-storage.d.ts", + "index.d.ts", "redux-storage-tests.ts" ] } \ No newline at end of file diff --git a/redux-ui/redux-ui.d.ts b/redux-ui/index.d.ts similarity index 100% rename from redux-ui/redux-ui.d.ts rename to redux-ui/index.d.ts diff --git a/redux-ui/tsconfig.json b/redux-ui/tsconfig.json index 7bfc0fc3b7..b79ee9a548 100644 --- a/redux-ui/tsconfig.json +++ b/redux-ui/tsconfig.json @@ -15,7 +15,7 @@ "experimentalDecorators": true }, "files": [ - "redux-ui.d.ts", + "index.d.ts", "redux-ui-tests.ts" ] } \ No newline at end of file diff --git a/request/index.d.ts b/request/index.d.ts index f842e37400..0dff82cfa3 100644 --- a/request/index.d.ts +++ b/request/index.d.ts @@ -84,6 +84,8 @@ declare namespace request { aws?: AWSOptions; hawk?: HawkOptions; qs?: any; + qsStringifyOptions?: any; + qsParseOptions?: any; json?: any; multipart?: RequestPart[] | Multipart; agent?: http.Agent | https.Agent; diff --git a/resemblejs/index.d.ts b/resemblejs/index.d.ts index 7b1801ad35..166beb186b 100644 --- a/resemblejs/index.d.ts +++ b/resemblejs/index.d.ts @@ -3,18 +3,19 @@ // Definitions by: Tim Perry // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace Resemble { - interface ResembleStatic { - /** - * Retrieve basic analysis for a single image (add compareTo to compare with another). - */ - (image: string|ImageData): ResembleAnalysis; +export = Resemble; +export as namespace resemble; - /** - * Set the resemblance image output style - */ - outputSettings(settings: OutputSettings): ResembleStatic; - } +/** + * Retrieve basic analysis for a single image (add compareTo to compare with another). + */ +declare function Resemble(image: string | ImageData): Resemble.ResembleAnalysis; + +declare namespace Resemble { + /** + * Set the resemblance image output style + */ + function outputSettings(settings: OutputSettings): typeof Resemble; interface OutputSettings { errorColor: { @@ -36,7 +37,7 @@ declare namespace Resemble { /** * Compare this image to another image, to get resemblance data */ - compareTo(fileData: string|ImageData): ResembleComparison; + compareTo(fileData: string | ImageData): ResembleComparison; } interface ResembleAnalysisResult { @@ -93,5 +94,3 @@ declare namespace Resemble { analysisTime: number; } } - -declare var resemble: Resemble.ResembleStatic; diff --git a/response-time/index.d.ts b/response-time/index.d.ts index 8ab91c86ec..5f3e86e6bb 100644 --- a/response-time/index.d.ts +++ b/response-time/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for response-time 2.2.0 +// Type definitions for response-time 2.3.2 // Project: https://github.com/expressjs/response-time -// Definitions by: Uros Smolnik +// Definitions by: Uros Smolnik , TonyYang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + /* =================== USAGE =================== import responseTime = require('response-time'); @@ -11,27 +12,32 @@ =============================================== */ +/// -import express = require('express'); +import http = require("http"); + + +export = responseTime; /** * Response time header for node.js * Returns middleware that adds a X-Response-Time header to responses. */ -declare function responseTime(options?: { - /** - * The fixed number of digits to include in the output, which is always in milliseconds, defaults to 3 (ex: 2.300ms). - */ - digits?: number; - /** - * The name of the header to set, defaults to X-Response-Time. - */ - header?: string; - /** - * Boolean to indicate if units of measurement suffix should be added to the output, defaults to true (ex: 2.300ms vs 2.300). - */ - suffix?: boolean; -}): express.RequestHandler; +declare function responseTime(options?: responseTime.ResponseTimeOptions): + (request: http.IncomingMessage, response: http.ServerResponse, callback: (err: any) => void) => any; +declare function responseTime(fn: responseTime.ResponseTimeFunction): + (request: http.IncomingMessage, response: http.ServerResponse, callback: (err: any) => void) => any; -export = responseTime; + +declare namespace responseTime { + export interface ResponseTimeOptions { + digits?: number; + header?: string; + suffix?: boolean; + } + + export interface ResponseTimeFunction { + (request: http.IncomingMessage, response: http.ServerResponse, time: number ): any; + } +} diff --git a/response-time/response-time-tests.ts b/response-time/response-time-tests.ts index 8c5e9595dd..b6a9b4a2af 100644 --- a/response-time/response-time-tests.ts +++ b/response-time/response-time-tests.ts @@ -1,11 +1,41 @@ - -import express = require('express'); import responseTime = require('response-time'); -var app = express(); -app.use(responseTime()); -app.use(responseTime({ - digits: 3, - header: 'X-Response-Time', - suffix: true -})); + +//////////////////////////////////////////////////////////////////////////////////// +// expressconnect tests https://github.com/expressjs/response-time#expressconnect // +//////////////////////////////////////////////////////////////////////////////////// +import express = require('express') +namespace express_connect_tests { + const app = express() + app.use(responseTime()) +} + + +////////////////////////////////////////////////////////////////////////////////////////////// +// vanilla http server tests https://github.com/expressjs/response-time#vanilla-http-server // +////////////////////////////////////////////////////////////////////////////////////////////// +import http = require('http') +namespace vanilla_http_server_tests { + // create "middleware" + var _responseTime = responseTime() + http.createServer(function (req, res) { + _responseTime(req, res, function (err) { + if (err) return console.log(err); + + // respond to request + res.setHeader('content-type', 'text/plain') + res.end('hello, world!') + }) + }) +} + + +////////////////////////////////////////////////////////////////////////////////////////////////// +// response time metrics tests https://github.com/expressjs/response-time#response-time-metrics // +////////////////////////////////////////////////////////////////////////////////////////////////// +namespace response_time_metrics_tests { + const app = express() + app.use(responseTime(function (req, res, time) { + let num: number = time; + })); +} diff --git a/restangular/index.d.ts b/restangular/index.d.ts index da0bc085de..20a0bff82c 100644 --- a/restangular/index.d.ts +++ b/restangular/index.d.ts @@ -93,6 +93,15 @@ declare namespace restangular { extendModel(route: string, extender: (model: IElement) => any): void; extendCollection(route: string, extender: (collection: ICollection) => any): void; } + + interface IScopedService extends IService { + one(id: number): IElement; + one(id: string): IElement; + post(elementToPost: any, queryParams?: any, headers?: any): IPromise; + post(elementToPost: T, queryParams?: any, headers?: any): IPromise; + getList(queryParams?: any, headers?: any): ICollectionPromise; + getList(queryParams?: any, headers?: any): ICollectionPromise; + } interface IScopedService extends IService { one(id: number): IElement; diff --git a/restify/index.d.ts b/restify/index.d.ts index a1fd5e18d9..2a99479d7c 100644 --- a/restify/index.d.ts +++ b/restify/index.d.ts @@ -468,22 +468,22 @@ interface ClientOptions { } interface Client { - get: (opts: string | { path?: string;[name: string]: any }, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - head: (opts: string | { path?: string;[name: string]: any }, callback?: (err: any, req: Request, res: Response) => any) => any; - post: (opts: string | { path?: string;[name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - put: (opts: string | { path?: string;[name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - patch: (opts: string | { path?: string;[name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - del: (opts: string | { path?: string;[name: string]: any }, callback?: (err: any, req: Request, res: Response) => any) => any; + get: (opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + head: (opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response) => any) => any; + post: (opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + put: (opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + patch: (opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + del: (opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response) => any) => any; basicAuth: (username: string, password: string) => any; } interface HttpClient extends Client { - get: (opts?: string | { path?: string;[name: string]: any }, callback?: Function) => any; - head: (opts?: string | { path?: string;[name: string]: any }, callback?: Function) => any; - post: (opts?: string | { path?: string;[name: string]: any }, callback?: Function) => any; - put: (opts?: string | { path?: string;[name: string]: any }, callback?: Function) => any; - patch: (opts?: string | { path?: string;[name: string]: any }, callback?: Function) => any; - del: (opts?: string | { path?: string;[name: string]: any }, callback?: Function) => any; + get: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + head: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + post: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + put: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + patch: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + del: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; } interface ThrottleOptions { diff --git a/restler/restler.d.ts b/restler/index.d.ts similarity index 100% rename from restler/restler.d.ts rename to restler/index.d.ts diff --git a/restler/restler-tests.ts b/restler/restler-tests.ts index 8c53455d08..5cb11d71c1 100644 --- a/restler/restler-tests.ts +++ b/restler/restler-tests.ts @@ -1,5 +1,3 @@ -/// - import rest = require("restler"); rest.get("http://google.com").on("complete", function(result) { diff --git a/restler/tsconfig.json b/restler/tsconfig.json index 4d717eca0b..0944a4d389 100644 --- a/restler/tsconfig.json +++ b/restler/tsconfig.json @@ -13,7 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "restler.d.ts", + "index.d.ts", "restler-tests.ts" ] } \ No newline at end of file diff --git a/rethinkdb/index.d.ts b/rethinkdb/index.d.ts index 1489edc4ec..355e57c94b 100644 --- a/rethinkdb/index.d.ts +++ b/rethinkdb/index.d.ts @@ -1,240 +1,516 @@ -// Type definitions for Rethinkdb 1.10.0 +// Type definitions for RethinkDB 2.3 // Project: http://rethinkdb.com/ -// Definitions by: Sean Hess +// Definitions by: Alex Gorbatchev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Reference: http://www.rethinkdb.com/api/#js -// TODO: Document manipulation and below +// +// Reference: https://rethinkdb.com/api/javascript/ +// +// Notes: +// - Currently missing control structures and geospatial commands. Please help out! +// +// Testing: +// $ tsc --noImplicitAny --module commonjs -p rethinkdb/ -/// +/// -export declare function connect(host: ConnectionOptions, cb?: (err: Error, conn: Connection) => void): Promise; +/** + * https://rethinkdb.com/api/javascript/ + */ +declare module "rethinkdb" { + /** + * Create a new connection to the database server. + * + * See: https://rethinkdb.com/api/javascript/connect/ + */ + export function connect(opts: ConnectionOptions, cb: (err: ReqlDriverError, conn: Connection) => void): void; + export function connect(host: string, cb: (err: ReqlDriverError, conn: Connection) => void): void; + export function connect(opts: ConnectionOptions): Promise; + export function connect(host: string): Promise; -export declare function dbCreate(name: string): Operation; -export declare function dbDrop(name: string): Operation; -export declare function dbList(): Operation; + export function dbCreate(name: string): Operation; + export function dbDrop(name: string): Operation; + export function dbList(): Operation; -export declare function db(name: string): Db; -export declare function table(name: string, options?: { useOutdated: boolean }): Table; + export function db(name: string): Db; + export function table(name: string, options?: { useOutdated: boolean }): Table; -export declare function asc(property: string): Sort; -export declare function desc(property: string): Sort; + export function asc(property: string): Sort; + export function desc(property: string): Sort; -export declare var count: Aggregator; -export declare function sum(prop: string): Aggregator; -export declare function avg(prop: string): Aggregator; + export var count: Aggregator; + export function sum(prop: string): Aggregator; + export function avg(prop: string): Aggregator; -export declare function row(name: string): Expression; -export declare function expr(stuff: any): Expression; + export const row: Row; + export function expr(stuff: any): Expression; -export declare function now(): Time; + export function now(): Expression