diff --git a/README.md b/README.md index bbf2a6f16e..746d9d9f3e 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,8 @@ Also see the [definitelytyped.org](http://definitelytyped.org) website, although This section tracks the health of the repository and publishing process. It may be helpful for contributors experiencing any issues with their PRs and packages. -* All packages are type-checking/linting cleanly: [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) -* All packages are being published to npm in under 10,000 seconds: [![Publish Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) +* All packages are [type-checking/linting](https://github.com/Microsoft/dtslint) cleanly: [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) +* All packages are being [published to npm](https://github.com/Microsoft/types-publisher) in under an hour: [![Publish Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) * [typescript-bot](https://github.com/typescript-bot) has been active on DefinitelyTyped [![Activity Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) If anything here seems wrong, or any of the above are failing, please raise an issue in [the DefinitelyTyped Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped). @@ -229,7 +229,7 @@ It depends, but most pull requests will be merged within a week. PRs that have b #### My PR is merged; when will the `@types` NPM package be updated? -NPM packages should update within a few hours. If it's been more than 24 hours, ping @RyanCavanaugh and @andy-ms on the PR to investigate. +NPM packages should update within a few minutes. If it's been more than an hour, mention the PR number on [the DefinitelyTyped Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped) and the current maintainer will get the correct team member to investigate. #### I'm writing a definition that depends on another definition. Should I use `` or an import? @@ -327,14 +327,60 @@ If the standard is still a draft, it belongs here. Use a name beginning with `dom-` and include a link to the standard as the "Project" link in the header. When it graduates draft mode, we may remove it from DefinitelyTyped and deprecate the associated `@types` package. -#### I want to update a package to a new major version +#### How do DefinitelyTyped package versions relate to versions of the corresponding library? -If you intend to continue updating the older version of the package, you may create a new subfolder with the current version e.g. `v2`, and copy existing files to it. If so, you will need to: +_NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)_ + +Each DefinitelyTyped package is versioned when published to NPM. +The [types-publisher](https://github.com/Microsoft/types-publisher) (the tool that publishes `@types` packages to npm) will set the declaration package's version by using the `major.minor` version number listed in the first line of its `index.d.ts` file. +For example, here are the first few lines of [Node's type declarations](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1253faabf5e0d2c5470db6ea87795d7f96fef7e2/types/node/index.d.ts) for version `10.12.x` at the time of writing: + +```js +// Type definitions for Node.js 10.12 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +``` + +Because `10.12` is at the end the first line, the npm version of the `@types/node` package will also be `10.12.x`. +Note that the first-line comment in the `index.d.ts` file should only contain the `major.minor` version (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`). +This is because only the major and minor release numbers are aligned between library packages and type declaration packages. +The patch release number of the type declaration package (e.g. `.0` in `10.12.0`) is initialized to zero by DefinitelyTyped and is incremented each time a new `@types/node` package is published to NPM for the same major/minor version of the corresponding library. + +Sometimes type declaration package versions and library package versions can get out of sync. +Below are a few common reasons why, in order of how much they inconvenience users of a library. +Only the last case is typically problematic. + +* As noted above, the patch version of the type declaration package is unrelated to the library patch version. + This allows DefinitelyTyped to safely update type declarations for the same major/minor version of a library. +* If updating a package for new functionality, don't forget to update the version number to line up with that version of the library. + If users make sure versions correspond between JavaScript packages and their respective `@types` packages, then `npm update` should typically just work. +* It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. + So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the type declaration package for a new library release. + If you're impacted by this, you can be the change you want to see in the world and you can be that helpful community member! + +:exclamation: If you're updating type declarations for a library, always set the `major.minor` version in the first line of `index.d.ts` to match the library version that you're documenting! :exclamation: + +#### If a library is updated to a new major version with breaking changes, how should I update its type declaration package? + +[Semantic versioning](https://semver.org/) requires that versions with breaking changes must increment the major version number. +For example, a library that removes a publicly exported function after its `3.5.8` release must bump its version to `4.0.0` in its next release. +Furthermore, when the library's `4.0.0` release is out, its DefinitelyTyped type declaration package should also be updated to `4.0.0`, including any breaking changes to the library's API. + +Many libraries have a large installed base of developers (including maintainers of other packages using that library as a dependency) who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version. +In the meantime, users of old library versions still may want to update type declarations for older versions. + +If you intend to continue updating the older version of a library's type declarations, you may create a new subfolder (e.g. `/v2/`) named for the current (soon to be "old") version, and copy existing files from the current version to it. + +Because the root folder should always contain the type declarations for the latest ("new") version, you'll need to make a few changes to the files in your old-version subdirectory to ensure that relative path references point to the subdirectory, not the root. 1. Update the relative paths in `tsconfig.json` as well as `tslint.json`. 2. Add path mapping rules to ensure that tests are running against the intended version. -For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: +For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`. +Because many users still consumed the older `2.x` version, a maintainer who wanted to update the type declarations for this library to `3.x` added a `v2` folder inside the history repository that contains type declarations for the older version. +At the time of writing, the [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1253faabf5e0d2c5470db6ea87795d7f96fef7e2/types/history/v2/tsconfig.json) looks roughly like: ```json { @@ -352,10 +398,11 @@ For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi } ``` -If there are other packages on DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this for packages depending on packages depending on the old version. +If there are other packages in DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. +You will also need to do this recursively for packages depending on packages depending on the old version. -For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`; -transitively `react-router-bootstrap` (which depends on `react-router`) also adds a path mapping in its [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json). +For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/v2/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`. +Transitively, `react-router-bootstrap` (which depends on `react-router`) also needed to add the same path mapping (`"history": [ "history/v2" ]`) in its `tsconfig.json` until its `react-router` dependency was updated to the latest version. Also, `/// ` will not work with path mapping, so dependencies must use `import`. diff --git a/notNeededPackages.json b/notNeededPackages.json index 701978da24..e3483b3c4b 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -564,12 +564,24 @@ "sourceRepoURL": "https://www.npmjs.com/package/fast-simplex-noise", "asOfVersion": "3.0.0" }, + { + "libraryName": "fastify-cors", + "typingsPackageName": "fastify-cors", + "sourceRepoURL": "https://github.com/fastify/fastify-cors", + "asOfVersion": "2.1.0" + }, { "libraryName": "Fastify-JWT", "typingsPackageName": "fastify-jwt", "sourceRepoURL": "https://github.com/fastify/fastify-jwt", "asOfVersion": "0.8.1" }, + { + "libraryName": "fastify-static", + "typingsPackageName": "fastify-static", + "sourceRepoURL": "https://github.com/fastify/fastify-static", + "asOfVersion": "2.2.0" + }, { "libraryName": "fecha", "typingsPackageName": "fecha", diff --git a/types/acl/index.d.ts b/types/acl/index.d.ts index 3f4df31aa2..931452dc52 100644 --- a/types/acl/index.d.ts +++ b/types/acl/index.d.ts @@ -1,150 +1,179 @@ -// Type definitions for node_acl 0.4.8 +// Type definitions for acl 0.4 // Project: https://github.com/optimalbits/node_acl // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// -/// import http = require('http'); -import Promise = require("bluebird"); -import express = require("express"); +import Promise = require('bluebird'); +import express = require('express'); +import redis = require('redis'); +import mongo = require('mongodb'); -type strings = string|string[]; -type Value = string|number; -type Values = Value|Value[]; +export = AclStatic; + +declare const AclStatic: AclStatic; + +type strings = string | string[]; +type Value = string | number; +type Values = Value | Value[]; type Action = () => any; -type Callback = (err: Error) => any; +type Callback = (err?: Error) => any; type AnyCallback = (err: Error, obj: any) => any; type AllowedCallback = (err: Error, allowed: boolean) => any; type GetUserId = (req: http.IncomingMessage, res: http.ServerResponse) => Value; interface AclStatic { - new (backend: Backend, logger: Logger, options: Option): Acl; - new (backend: Backend, logger: Logger): Acl; - new (backend: Backend): Acl; - memoryBackend: MemoryBackendStatic; + new ( + backend: AclStatic.Backend, + logger?: AclStatic.Logger, + options?: AclStatic.Option + ): AclStatic.Acl; + readonly memoryBackend: AclStatic.MemoryBackendStatic; + readonly mongodbBackend: AclStatic.MongodbBackendStatic; + readonly redisBackend: AclStatic.RedisBackendStatic; } -interface Logger { - debug: (msg: string) => any; -} - -interface Acl { - addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise; - removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise; - userRoles: (userId: Value, cb?: (err: Error, roles: string[]) => any) => Promise; - roleUsers: (role: Value, cb?: (err: Error, users: Values) => any) => Promise; - hasRole: (userId: Value, role: string, cb?: (err: Error, isInRole: boolean) => any) => Promise; - addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise; - removeRole: (role: string, cb?: Callback) => Promise; - removeResource: (resource: string, cb?: Callback) => Promise; - allow: { - (roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise; - (aclSets: AclSet | AclSet[]): Promise; +declare namespace AclStatic { + interface Logger { + debug: (msg: string) => any; } - removeAllow: (role: string, resources: strings, permissions: strings, cb?: Callback) => Promise; - removePermissions: (role: string, resources: strings, permissions: strings, cb?: Function) => Promise; - allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise; - isAllowed: (userId: Value, resources: strings, permissions: strings, cb?: AllowedCallback) => Promise; - areAnyRolesAllowed: (roles: strings, resource: strings, permissions: strings, cb?: AllowedCallback) => Promise; - whatResources: { - (roles: strings, cb?: AnyCallback): Promise; - (roles: strings, permissions: strings, cb?: AnyCallback): Promise; + + interface Acl { + addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise; + removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise; + userRoles: (userId: Value, cb?: (err: Error, roles: string[]) => any) => Promise; + roleUsers: (role: Value, cb?: (err: Error, users: Values) => any) => Promise; + hasRole: ( + userId: Value, + role: string, + cb?: (err: Error, isInRole: boolean) => any + ) => Promise; + addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise; + removeRole: (role: string, cb?: Callback) => Promise; + removeResource: (resource: string, cb?: Callback) => Promise; + allow: { + (roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise; + (aclSets: AclSet | AclSet[]): Promise; + }; + removeAllow: ( + role: string, + resources: strings, + permissions: strings, + cb?: Callback + ) => Promise; + removePermissions: ( + role: string, + resources: strings, + permissions: strings, + cb?: Callback + ) => Promise; + allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise; + isAllowed: ( + userId: Value, + resources: strings, + permissions: strings, + cb?: AllowedCallback + ) => Promise; + areAnyRolesAllowed: ( + roles: strings, + resource: strings, + permissions: strings, + cb?: AllowedCallback + ) => Promise; + whatResources: { + (roles: strings, cb?: AnyCallback): Promise; + (roles: strings, permissions: strings, cb?: AnyCallback): Promise; + }; + permittedResources: (roles: strings, permissions: strings, cb?: Callback) => Promise; + middleware: ( + numPathComponents?: number, + userId?: Value | GetUserId, + actions?: strings + ) => express.RequestHandler; + } + + interface Option { + buckets?: BucketsOption; + } + + interface BucketsOption { + meta?: string; + parents?: string; + permissions?: string; + resources?: string; + roles?: string; + users?: string; + } + + interface AclSet { + roles: strings; + allows: AclAllow[]; + } + + interface AclAllow { + resources: strings; + permissions: strings; + } + + interface MemoryBackend extends Backend {} + interface MemoryBackendStatic { + new (): MemoryBackend; + } + + // + // For internal use + // + interface Backend { + begin: () => T; + end: (transaction: T, cb?: Action) => void; + clean: (cb?: Action) => void; + get: (bucket: string, key: Value, cb?: Action) => void; + union: (bucket: string, keys: Value[], cb?: Action) => void; + add: (transaction: T, bucket: string, key: Value, values: Values) => void; + del: (transaction: T, bucket: string, keys: Value[]) => void; + remove: (transaction: T, bucket: string, key: Value, values: Values) => void; + + endAsync: (transaction: T, cb?: (err: Error | null) => void) => Promise; + getAsync: ( + bucket: string, + key: Value, + cb?: (err: Error | null, value: any) => void + ) => Promise; + cleanAsync: (cb?: (error?: Error) => void) => Promise; + unionAsync: ( + bucket: string, + keys: Value[], + cb?: (error: Error | undefined, results: any[]) => void + ) => Promise; + } + + interface Contract { + (args: IArguments): Contract | NoOp; + debug: boolean; + fulfilled: boolean; + args: any[]; + checkedParams: string[]; + params: (...types: string[]) => Contract | NoOp; + end: () => void; + } + + interface NoOp { + params: (...types: string[]) => NoOp; + end: () => void; + } + + // for redis backend + interface RedisBackend extends Backend {} + interface RedisBackendStatic { + new (redis: redis.RedisClient, prefix?: string): RedisBackend; + } + + // for mongodb backend + interface MongodbBackend extends Backend {} + interface MongodbBackendStatic { + new (db: mongo.Db, prefix?: string, useSingle?: boolean): MongodbBackend; } - permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise; - middleware: (numPathComponents?: number, userId?: Value | GetUserId, actions?: strings) => express.RequestHandler; } - -interface Option { - buckets?: BucketsOption; -} - -interface BucketsOption { - meta?: string; - parents?: string; - permissions?: string; - resources?: string; - roles?: string; - users?: string; -} - -interface AclSet { - roles: strings; - allows: AclAllow[]; -} - -interface AclAllow { - resources: strings; - permissions: strings; -} - -interface MemoryBackend extends Backend { } -interface MemoryBackendStatic { - new (): MemoryBackend; -} - -// -// For internal use -// -interface Backend { - begin: () => T; - end: (transaction: T, cb?: Action) => void; - clean: (cb?: Action) => void; - get: (bucket: string, key: Value, cb?: Action) => void; - union: (bucket: string, keys: Value[], cb?: Action) => void; - add: (transaction: T, bucket: string, key: Value, values: Values) => void; - del: (transaction: T, bucket: string, keys: Value[]) => void; - remove: (transaction: T, bucket: string, key: Value, values: Values) => void; - - endAsync: Function; //TODO: Give more specific function signature - getAsync: Function; - cleanAsync: Function; - unionAsync: Function; -} - -interface Contract { - (args: IArguments): Contract | NoOp; - debug: boolean; - fulfilled: boolean; - args: any[]; - checkedParams: string[]; - params: (...types: string[]) => Contract | NoOp; - end: () => void; -} - -interface NoOp { - params: (...types: string[]) => NoOp; - end: () => void; -} - -// for redis backend -import redis = require('redis'); - -interface AclStatic { - redisBackend: RedisBackendStatic; -} - -interface RedisBackend extends Backend { } -interface RedisBackendStatic { - new (redis: redis.RedisClient, prefix: string): RedisBackend; - new (redis: redis.RedisClient): RedisBackend; -} - -// for mongodb backend -import mongo = require('mongodb'); - -interface AclStatic { - mongodbBackend: MongodbBackendStatic; -} - -interface MongodbBackend extends Backend { } -interface MongodbBackendStatic { - new (db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend; - new (db: mongo.Db, prefix: string): MongodbBackend; - new (db: mongo.Db): MongodbBackend; -} - -declare var _: AclStatic; -export = _; diff --git a/types/acl/test/index.ts b/types/acl/test/index.ts index bb3e6fa54e..3485ab3662 100644 --- a/types/acl/test/index.ts +++ b/types/acl/test/index.ts @@ -2,15 +2,15 @@ // https://github.com/OptimalBits/node_acl/blob/master/Readme.md import Acl = require('acl'); -var report = (err: Error, value: T) => { - if (err) { - console.error(err); - } - console.info(value); +const report = (err: Error, value: any) => { + if (err) { + console.error(err); + } + console.info(value); }; // Using the memory backend -var acl = new Acl(new Acl.memoryBackend()); +const acl: Acl.Acl = new Acl(new Acl.memoryBackend()); // middleware with no optional parameters acl.middleware(); @@ -18,11 +18,11 @@ acl.middleware(); acl.middleware(1); acl.middleware(1, () => { - return "joed"; + return 'joed'; }); acl.middleware(1, () => { - return 2; + return 2; }); acl.middleware(1, 'joed'); @@ -33,36 +33,36 @@ acl.middleware(3, 'joed', 'post'); acl.allow('guest', 'blogs', 'view'); // allow function accepts arrays as any parameter -acl.allow('member', 'blogs', ['edit','view', 'delete']); +acl.allow('member', 'blogs', ['edit', 'view', 'delete']); acl.addUserRoles('joed', 'guest'); -acl.addRoleParents('baz', ['foo','bar']); +acl.addRoleParents('baz', ['foo', 'bar']); -acl.allow('foo', ['blogs','forums','news'], ['view', 'delete']); +acl.allow('foo', ['blogs', 'forums', 'news'], ['view', 'delete']); -acl.allow('admin', ['blogs','forums'], '*'); +acl.allow('admin', ['blogs', 'forums'], '*'); acl.allow([ { - roles:['guest','special-member'], - allows:[ - {resources:'blogs', permissions:'get'}, - {resources:['forums','news'], permissions:['get','put','delete']} - ] + roles: ['guest', 'special-member'], + allows: [ + { resources: 'blogs', permissions: 'get' }, + { resources: ['forums', 'news'], permissions: ['get', 'put', 'delete'] }, + ], }, { - roles:['gold','silver'], - allows:[ - {resources:'cash', permissions:['sell','exchange']}, - {resources:['account','deposit'], permissions:['put','delete']} - ] - } + roles: ['gold', 'silver'], + allows: [ + { resources: 'cash', permissions: ['sell', 'exchange'] }, + { resources: ['account', 'deposit'], permissions: ['put', 'delete'] }, + ], + }, ]); acl.isAllowed('joed', 'blogs', 'view', (err, res) => { if (res) { - console.log("User joed is allowed to view blogs"); + console.log('User joed is allowed to view blogs'); } }); @@ -78,15 +78,14 @@ acl.whatResources('foo', 'view', (err, res) => { } }); -acl.isAllowed('jsmith', 'blogs', ['edit','view','delete']) -.then((result) => { - console.dir('jsmith is allowed blogs ' + result); - acl.addUserRoles('jsmith', 'member'); -}).then(() => - acl.isAllowed('jsmith', 'blogs', ['edit','view','delete']) -).then((result) => - console.dir('jsmith is allowed blogs ' + result) -).then(() => { - acl.allowedPermissions('james', ['blogs','forums'], report); - acl.allowedPermissions('jsmith', ['blogs','forums'], report); -}); +acl.isAllowed('jsmith', 'blogs', ['edit', 'view', 'delete']) + .then(result => { + console.dir('jsmith is allowed blogs ' + result); + acl.addUserRoles('jsmith', 'member'); + }) + .then(() => acl.isAllowed('jsmith', 'blogs', ['edit', 'view', 'delete'])) + .then(result => console.dir('jsmith is allowed blogs ' + result)) + .then(() => { + acl.allowedPermissions('james', ['blogs', 'forums'], report); + acl.allowedPermissions('jsmith', ['blogs', 'forums'], report); + }); diff --git a/types/acl/test/mongodbBackend.ts b/types/acl/test/mongodbBackend.ts index ae3b1d03c9..449cefa030 100644 --- a/types/acl/test/mongodbBackend.ts +++ b/types/acl/test/mongodbBackend.ts @@ -5,10 +5,10 @@ import mongodb = require('mongodb'); declare var db: mongodb.Db; // Using the mongo db backend -var acl = new Acl(new Acl.mongodbBackend(db, 'acl_', true)); +const acl = new Acl(new Acl.mongodbBackend(db, 'acl_', true)); // guest is allowed to view blogs acl.allow('guest', 'blogs', 'view'); // allow function accepts arrays as any parameter -acl.allow('member', 'blogs', ['edit','view', 'delete']); +acl.allow('member', 'blogs', ['edit', 'view', 'delete']); diff --git a/types/acl/test/redisBackend.ts b/types/acl/test/redisBackend.ts index ec1924cce6..669d28ed6d 100644 --- a/types/acl/test/redisBackend.ts +++ b/types/acl/test/redisBackend.ts @@ -5,10 +5,10 @@ import redis = require('redis'); declare var client: redis.RedisClient; // Using the redis backend -var acl = new Acl(new Acl.redisBackend(client, 'acl_')); +const acl = new Acl(new Acl.redisBackend(client, 'acl_')); // guest is allowed to view blogs acl.allow('guest', 'blogs', 'view'); // allow function accepts arrays as any parameter -acl.allow('member', 'blogs', ['edit','view', 'delete']); +acl.allow('member', 'blogs', ['edit', 'view', 'delete']); diff --git a/types/acl/tslint.json b/types/acl/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/acl/tslint.json +++ b/types/acl/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index 04291996ba..633b681432 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -1687,7 +1687,7 @@ declare namespace algoliasearch { * 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[]; + removeStopWords?: boolean | string[]; /** * List of attributes on which you want to apply word-splitting ("decompounding") for * each of the languages supported (German, Dutch, and Finnish as of 05/2018) diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index b83a41a6df..7470fb08bb 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -294,6 +294,14 @@ foo.then((x) => { x.toFixed(); }); +namespace TestPromiseInterop { + declare const promiseInterop: ng.IPromise; + const ngStringPromise: ng.IPromise = + promiseInterop.then((num) => Promise.resolve(String(num))); + const caughtStringPromise: ng.IPromise = + promiseInterop.catch((reason) => Promise.resolve('oh noes')); +} + // $q signature tests namespace TestQ { interface AbcObject { diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 4a8b26fba9..0c28ddbf27 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -1197,6 +1197,15 @@ declare namespace angular { * the `notifyCallback` method. The promise can not be resolved or rejected from the * `notifyCallback` method. */ + then( + successCallback?: + | ((value: T) => PromiseLike | PromiseLike | TResult1) + | null, + errorCallback?: + | ((reason: any) => PromiseLike | PromiseLike | TResult2) + | null, + notifyCallback?: (state: any) => any + ): IPromise; then( successCallback?: | ((value: T) => IPromise | IPromise | TResult1) @@ -1210,6 +1219,11 @@ declare namespace angular { /** * Shorthand for promise.then(null, errorCallback) */ + catch( + onRejected?: + | ((reason: any) => PromiseLike | PromiseLike | TResult) + | null + ): IPromise; catch( onRejected?: | ((reason: any) => IPromise | IPromise | TResult) diff --git a/types/angular/tsconfig.json b/types/angular/tsconfig.json index 46eeb69c7a..590c9c7798 100644 --- a/types/angular/tsconfig.json +++ b/types/angular/tsconfig.json @@ -11,7 +11,8 @@ "lib": [ "es5", "dom", - "es2015.iterable" + "es2015.iterable", + "es2015.promise" ], "noImplicitAny": false, "noImplicitThis": false, @@ -25,4 +26,4 @@ "noEmit": true, "forceConsistentCasingInFileNames": true } -} \ No newline at end of file +} diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index ba6ebdc5ac..ad063c20b6 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -1,12 +1,14 @@ declare let str: string; declare let strOrNull: string | null; declare let strOrUndefined: string | undefined; +declare let strOrUndefinedOrNull: string | undefined | null; declare let date: Date; declare let anyObj: any; declare let num: number; declare let error: Error; declare let bool: boolean; declare let boolOrUndefined: boolean | undefined; +declare let numOrUndefined: number | undefined; declare let apiGwEvtReqCtx: AWSLambda.APIGatewayEventRequestContext; declare let apiGwEvtReqCtxOpt: AWSLambda.APIGatewayEventRequestContext | null | undefined; declare let apiGwEvt: AWSLambda.APIGatewayEvent; @@ -80,6 +82,11 @@ declare const scheduledEvent: AWSLambda.ScheduledEvent; str = apiGwEvtReqCtx.accountId; str = apiGwEvtReqCtx.apiId; authResponseContextOpt = apiGwEvtReqCtx.authorizer; +numOrUndefined = apiGwEvtReqCtx.connectedAt; +strOrUndefined = apiGwEvtReqCtx.connectionId; +strOrUndefined = apiGwEvtReqCtx.domainName; +strOrUndefined = apiGwEvtReqCtx.eventType; +strOrUndefined = apiGwEvtReqCtx.extendedRequestId; str = apiGwEvtReqCtx.httpMethod; strOrNull = apiGwEvtReqCtx.identity.accessKey; strOrNull = apiGwEvtReqCtx.identity.accountId; @@ -94,11 +101,15 @@ str = apiGwEvtReqCtx.identity.sourceIp; strOrNull = apiGwEvtReqCtx.identity.user; strOrNull = apiGwEvtReqCtx.identity.userAgent; strOrNull = apiGwEvtReqCtx.identity.userArn; +strOrUndefined = apiGwEvtReqCtx.messageDirection; +strOrUndefinedOrNull = apiGwEvtReqCtx.messageId; str = apiGwEvtReqCtx.path; str = apiGwEvtReqCtx.stage; str = apiGwEvtReqCtx.requestId; +strOrUndefined = apiGwEvtReqCtx.requestTime; str = apiGwEvtReqCtx.resourceId; str = apiGwEvtReqCtx.resourcePath; +strOrUndefined = apiGwEvtReqCtx.routeKey; /* API Gateway Event */ strOrNull = apiGwEvt.body; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 52314529bc..3301feebb5 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -25,6 +25,7 @@ // Trevor Leach // James Gregory // Erik Dalén +// Loïk Gaonac'h // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -33,6 +34,11 @@ export interface APIGatewayEventRequestContext { accountId: string; apiId: string; authorizer?: AuthResponseContext | null; + connectedAt: number; + connectionId?: string; + domainName?: string; + eventType?: string; + extendedRequestId?: string; httpMethod: string; identity: { accessKey: string | null; @@ -49,12 +55,16 @@ export interface APIGatewayEventRequestContext { userAgent: string | null; userArn: string | null; }; + messageDirection?: string; + messageId?: string | null; path: string; stage: string; requestId: string; + requestTime?: string; requestTimeEpoch: number; resourceId: string; resourcePath: string; + routeKey?: string; } // API Gateway "event" diff --git a/types/aws-param-store/aws-param-store-tests.ts b/types/aws-param-store/aws-param-store-tests.ts new file mode 100644 index 0000000000..13ad6c0514 --- /dev/null +++ b/types/aws-param-store/aws-param-store-tests.ts @@ -0,0 +1,78 @@ +import { SSM } from 'aws-sdk'; +import { + ParameterQuery, + parameterQuery, + getParameter, + getParameters, + getParametersByPath, + getParameterSync, + getParametersSync, + getParametersByPathSync, +} from 'aws-param-store'; + +declare let bool: boolean; +declare let query: ParameterQuery; +declare let psName: SSM.Types.PSParameterName; +declare let psNames: SSM.Types.ParameterNameList; +declare let options: SSM.Types.ClientConfiguration; +declare let paramResult: SSM.Types.Parameter; +declare let paramsResult: SSM.Types.GetParametersResult; +declare let paramsByPathResult: SSM.Types.ParameterList; +declare let allParamResults: SSM.Types.Parameter | SSM.Types.GetParametersByPathResult | SSM.Types.ParameterList; +declare let promiseParamResult: Promise; +declare let promiseParamsResult: Promise; +declare let promiseParamsByPathResult: Promise; +declare let promiseAllParamResults: Promise; + +query = parameterQuery(); + +query.path(psName); +query.named(psName); +query.named(psNames); +query.decryption(bool); +query.recursive(bool); + +promiseAllParamResults = query.execute(); +allParamResults = query.executeSync(); + +// test chaining +query = query +.path(psName) +.named(psName) +.named(psNames) +.decryption(bool) +.recursive(bool); + +promiseAllParamResults = query +.path(psName) +.named(psName) +.named(psNames) +.decryption(bool) +.recursive(bool) +.execute(); + +allParamResults = query +.path(psName) +.named(psName) +.named(psNames) +.decryption(bool) +.recursive(bool) +.executeSync(); + +promiseParamResult = getParameter(psName); +promiseParamResult = getParameter(psName, options); + +promiseParamsResult = getParameters(psNames); +promiseParamsResult = getParameters(psNames, options); + +promiseParamsByPathResult = getParametersByPath(psNames); +promiseParamsByPathResult = getParametersByPath(psNames, options); + +paramResult = getParameterSync(psName); +paramResult = getParameterSync(psName, options); + +paramsResult = getParametersSync(psNames); +paramsResult = getParametersSync(psNames, options); + +paramsByPathResult = getParametersByPathSync(psNames); +paramsByPathResult = getParametersByPathSync(psNames, options); diff --git a/types/aws-param-store/index.d.ts b/types/aws-param-store/index.d.ts new file mode 100644 index 0000000000..c35edef688 --- /dev/null +++ b/types/aws-param-store/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for aws-param-store 2.1 +// Project: https://github.com/vandium-io/aws-param-store#readme +// Definitions by: Jason Gray +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import { SSM } from 'aws-sdk'; + +export function getParameter( + name: SSM.Types.PSParameterName, + options?: SSM.Types.ClientConfiguration +): Promise; + +export function getParameterSync( + name: SSM.Types.PSParameterName, + options?: SSM.Types.ClientConfiguration +): SSM.Types.Parameter; + +export function getParameters( + names: SSM.Types.ParameterNameList, + options?: SSM.Types.ClientConfiguration +): Promise; + +export function getParametersSync( + names: SSM.Types.ParameterNameList, + options?: SSM.Types.ClientConfiguration +): SSM.Types.GetParametersResult; + +export function getParametersByPath( + path: SSM.Types.ParameterNameList, + options?: SSM.Types.ClientConfiguration +): Promise; + +export function getParametersByPathSync( + path: SSM.Types.ParameterNameList, + options?: SSM.Types.ClientConfiguration +): SSM.Types.ParameterList; + +export interface ParameterQuery { + path(path: SSM.Types.PSParameterName): ParameterQuery; + named(nameOrNames: SSM.Types.PSParameterName | SSM.Types.ParameterNameList): ParameterQuery; + decryption(enabled: boolean): ParameterQuery; + recursive(enabled: boolean): ParameterQuery; + execute(): Promise; + executeSync(): SSM.Types.ParameterList | SSM.Types.Parameter | SSM.Types.GetParametersResult; +} + +export function parameterQuery(options?: SSM.Types.ClientConfiguration): ParameterQuery; diff --git a/types/aws-param-store/package.json b/types/aws-param-store/package.json new file mode 100644 index 0000000000..abb680d4ac --- /dev/null +++ b/types/aws-param-store/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "aws-sdk": "^2.325.0" + } +} diff --git a/types/aws-param-store/tsconfig.json b/types/aws-param-store/tsconfig.json new file mode 100644 index 0000000000..2857e45680 --- /dev/null +++ b/types/aws-param-store/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "aws-param-store-tests.ts" + ] +} diff --git a/types/fastify-cors/tslint.json b/types/aws-param-store/tslint.json similarity index 100% rename from types/fastify-cors/tslint.json rename to types/aws-param-store/tslint.json diff --git a/types/backbone-relational/backbone-relational-tests.ts b/types/backbone-relational/backbone-relational-tests.ts index 6e0135fcd9..c8b94c4029 100644 --- a/types/backbone-relational/backbone-relational-tests.ts +++ b/types/backbone-relational/backbone-relational-tests.ts @@ -1,13 +1,13 @@ -import * as Backbone from 'backbone'; +import * as BackboneRel from 'backbone-relational'; -class House extends Backbone.RelationalModel { +class House extends BackboneRel.Model { // The 'relations' property, on the House's prototype. Initialized separately for each // instance of House. Each relation must define (as a minimum) the 'type', 'key' and // 'relatedModel'. Options include 'includeInJSON', 'createModels' and 'reverseRelation'. relations = [ { - type: Backbone.HasMany, // Use the type, or the string 'HasOne' or 'HasMany'. + type: BackboneRel.HasMany, // Use the type, or the string 'HasOne' or 'HasMany'. key: 'occupants', relatedModel: 'Person', includeInJSON: true, @@ -20,14 +20,14 @@ class House extends Backbone.RelationalModel { } -class Person extends Backbone.RelationalModel { +class Person extends BackboneRel.Model { relations = [ { // Create a (recursive) one-to-one relationship - type: Backbone.HasOne, + type: BackboneRel.HasOne, key: 'user', relatedModel: 'User', reverseRelation: { - type: Backbone.HasOne, + type: BackboneRel.HasOne, key: 'person' } } @@ -39,7 +39,7 @@ class Person extends Backbone.RelationalModel { } } -class User extends Backbone.RelationalModel { +class User extends BackboneRel.Model { } diff --git a/types/backbone-relational/index.d.ts b/types/backbone-relational/index.d.ts index 84406fb60a..f19cfa8daa 100644 --- a/types/backbone-relational/index.d.ts +++ b/types/backbone-relational/index.d.ts @@ -1,15 +1,16 @@ -// Type definitions for Backbone-relational 0.8.5 +// Type definitions for Backbone-relational 0.10.0 // Project: http://backbonerelational.org/ // Definitions by: Eirik Hoem +// Julian Gonggrijp // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// -import * as Backbone from 'backbone'; +import { Events, EventsHash, Model as BModel, Collection } from 'backbone'; -declare module 'backbone' { - class RelationalModel extends Model { +declare module 'backbone-relational' { + class Model extends BModel { /** * Do not use, prefer TypeScript's extend functionality. **/ @@ -47,7 +48,7 @@ declare module 'backbone' { static findOrCreate(attributes:any, options?:any); } - export class Relation extends Model { + export class Relation extends BModel { options:any; instance:any; @@ -60,11 +61,11 @@ declare module 'backbone' { checkPreconditions():boolean; - setRelated(related:Model):void; + setRelated(related:BModel):void; - setRelated(related:Collection):void; + setRelated(related:Collection):void; - getReverseRelations(model:RelationalModel):Relation; + getReverseRelations(model:Model):Relation; destroy():void; } @@ -72,7 +73,7 @@ declare module 'backbone' { export class HasOne extends Relation { collectionType:any; - findRelated(options:any):Model; + findRelated(options:any):BModel; setKeyContents(keyContents:string):void; @@ -82,21 +83,21 @@ declare module 'backbone' { setKeyContents(keyContents:number[]):void; - setKeyContents(keyContents:Collection):void; + setKeyContents(keyContents:Collection):void; - onChange(model:Model, attr:any, options:any):void; + onChange(model:BModel, attr:any, options:any):void; - handleAddition(model:Model, coll:Collection, options:any):void; + handleAddition(model:BModel, coll:Collection, options:any):void; - handleRemoval(model:Model, coll:Collection, options:any):void; + handleRemoval(model:BModel, coll:Collection, options:any):void; - handleReset(coll:Collection, options:any):void; + handleReset(coll:Collection, options:any):void; - tryAddRelated(model:Model, coll:any, options:any):void; + tryAddRelated(model:BModel, coll:any, options:any):void; - addRelated(model:Model, options:any):void; + addRelated(model:BModel, options:any):void; - removeRelated(model:Model, coll:any, options:any):void; + removeRelated(model:BModel, coll:any, options:any):void; } @@ -104,21 +105,21 @@ declare module 'backbone' { export class HasMany extends Relation { collectionType:any; - findRelated(options:any):Model; + findRelated(options:any):BModel; setKeyContents(keyContents:string):void; setKeyContents(keyContents:number):void; - setKeyContents(keyContents:Model):void; + setKeyContents(keyContents:BModel):void; - onChange(model:Model, attr:any, options:any):void; + onChange(model:BModel, attr:any, options:any):void; - tryAddRelated(model:Model, coll:any, options:any):void; + tryAddRelated(model:BModel, coll:any, options:any):void; - addRelated(model:Model, options:any):void; + addRelated(model:BModel, options:any):void; - removeRelated(model:Model, coll:any, options:any):void; + removeRelated(model:BModel, coll:any, options:any):void; } @@ -141,9 +142,9 @@ declare module 'backbone' { removeModelScope(scope):void; - addSubModels(subModelTypes:RelationalModel, superModelType:RelationalModel):void; + addSubModels(subModelTypes:Model, superModelType:Model):void; - setupSuperModel(modelType:RelationalModel):void; + setupSuperModel(modelType:Model):void; addReverseRelation(relation:any):void; @@ -151,30 +152,30 @@ declare module 'backbone' { processOrphanRelations():void; - retroFitRelation(relation:RelationalModel, create:boolean):Collection; + retroFitRelation(relation:Model, create:boolean):Collection; - getCollection(type:RelationalModel, create:boolean):Collection; + getCollection(type:Model, create:boolean):Collection; getObjectByName(name:string):any; resolveIdForItem(type:any, item:any):any; - static find(type:any, item:string):RelationalModel; + static find(type:any, item:string):Model; - static find(type:any, item:number):RelationalModel; + static find(type:any, item:number):Model; - static find(type:any, item:RelationalModel):RelationalModel; + static find(type:any, item:Model):Model; - static find(type:any, item:any):RelationalModel; + static find(type:any, item:any):Model; - register(model:RelationalModel):void; + register(model:Model):void; - checkId(model:RelationalModel, id:any):void; + checkId(model:Model, id:any):void; - update(model:RelationalModel):void; + update(model:Model):void; - unregister(model:RelationalModel, collection:Collection, options:any):void; + unregister(model:Model, collection:Collection, options:any):void; reset():void; diff --git a/types/bunyan-seq/bunyan-seq-tests.ts b/types/bunyan-seq/bunyan-seq-tests.ts new file mode 100644 index 0000000000..beeeb9d8ee --- /dev/null +++ b/types/bunyan-seq/bunyan-seq-tests.ts @@ -0,0 +1,2 @@ +import bunyanSeq = require("bunyan-seq"); +bunyanSeq.createStream({name: 'LoggerComponent', serverUrl: 'http://seq.com'}); diff --git a/types/bunyan-seq/index.d.ts b/types/bunyan-seq/index.d.ts new file mode 100644 index 0000000000..2520c93339 --- /dev/null +++ b/types/bunyan-seq/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for bunyan-blackhole 0.2 +// Project: https://github.com/datalust/bunyan-seq +// Definitions by: Ray Booysen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// +import * as Logger from "bunyan"; +export interface Configuration { + apiKey?: string; + batchSizeLimit?: number; + eventSizeLimit?: number; + level?: string; + maxBatchingTime?: number; + name?: string; + onError?: (e: Error) => void; + reemitErrorEvents?: boolean; + serverUrl?: string; +} + +export function createStream(config: Configuration): Logger.Stream; diff --git a/types/fastify-cors/tsconfig.json b/types/bunyan-seq/tsconfig.json similarity index 93% rename from types/fastify-cors/tsconfig.json rename to types/bunyan-seq/tsconfig.json index 9e696b42e2..bd77368148 100644 --- a/types/fastify-cors/tsconfig.json +++ b/types/bunyan-seq/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "fastify-cors-tests.ts" + "bunyan-seq-tests.ts" ] } diff --git a/types/fastify-static/tslint.json b/types/bunyan-seq/tslint.json similarity index 100% rename from types/fastify-static/tslint.json rename to types/bunyan-seq/tslint.json diff --git a/types/carbon__colors/carbon__colors-tests.ts b/types/carbon__colors/carbon__colors-tests.ts new file mode 100644 index 0000000000..1df2cea931 --- /dev/null +++ b/types/carbon__colors/carbon__colors-tests.ts @@ -0,0 +1,3 @@ +import { rgba } from "@carbon/colors"; + +rgba("TOTORO", 0.4); // $ExpectType string diff --git a/types/carbon__colors/index.d.ts b/types/carbon__colors/index.d.ts new file mode 100644 index 0000000000..33438d7c66 --- /dev/null +++ b/types/carbon__colors/index.d.ts @@ -0,0 +1,491 @@ +// Type definitions for @carbon/colors 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/colors +// Definitions by: Vince Picone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const black: string; + +export const black100: string; + +export const blue: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const blue10: string; + +export const blue100: string; + +export const blue20: string; + +export const blue30: string; + +export const blue40: string; + +export const blue50: string; + +export const blue60: string; + +export const blue70: string; + +export const blue80: string; + +export const blue90: string; + +export const colors: { + black: { + "100": string; + }; + blue: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + coolGray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + cyan: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + gray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + green: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + magenta: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + orange: { + "40": string; + }; + purple: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + red: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + teal: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + warmGray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + white: { + "0": string; + }; + yellow: { + "20": string; + }; +}; + +export const coolGray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const coolGray10: string; + +export const coolGray100: string; + +export const coolGray20: string; + +export const coolGray30: string; + +export const coolGray40: string; + +export const coolGray50: string; + +export const coolGray60: string; + +export const coolGray70: string; + +export const coolGray80: string; + +export const coolGray90: string; + +export const cyan: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const cyan10: string; + +export const cyan100: string; + +export const cyan20: string; + +export const cyan30: string; + +export const cyan40: string; + +export const cyan50: string; + +export const cyan60: string; + +export const cyan70: string; + +export const cyan80: string; + +export const cyan90: string; + +export const gray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const gray10: string; + +export const gray100: string; + +export const gray20: string; + +export const gray30: string; + +export const gray40: string; + +export const gray50: string; + +export const gray60: string; + +export const gray70: string; + +export const gray80: string; + +export const gray90: string; + +export const green: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const green10: string; + +export const green100: string; + +export const green20: string; + +export const green30: string; + +export const green40: string; + +export const green50: string; + +export const green60: string; + +export const green70: string; + +export const green80: string; + +export const green90: string; + +export const magenta: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const magenta10: string; + +export const magenta100: string; + +export const magenta20: string; + +export const magenta30: string; + +export const magenta40: string; + +export const magenta50: string; + +export const magenta60: string; + +export const magenta70: string; + +export const magenta80: string; + +export const magenta90: string; + +export const orange: string; + +export const orange40: string; + +export const purple: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const purple10: string; + +export const purple100: string; + +export const purple20: string; + +export const purple30: string; + +export const purple40: string; + +export const purple50: string; + +export const purple60: string; + +export const purple70: string; + +export const purple80: string; + +export const purple90: string; + +export const red: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const red10: string; + +export const red100: string; + +export const red20: string; + +export const red30: string; + +export const red40: string; + +export const red50: string; + +export const red60: string; + +export const red70: string; + +export const red80: string; + +export const red90: string; + +export const teal: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const teal10: string; + +export const teal100: string; + +export const teal20: string; + +export const teal30: string; + +export const teal40: string; + +export const teal50: string; + +export const teal60: string; + +export const teal70: string; + +export const teal80: string; + +export const teal90: string; + +export const warmGray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const warmGray10: string; + +export const warmGray100: string; + +export const warmGray20: string; + +export const warmGray30: string; + +export const warmGray40: string; + +export const warmGray50: string; + +export const warmGray60: string; + +export const warmGray70: string; + +export const warmGray80: string; + +export const warmGray90: string; + +export const white: string; + +export const white0: string; + +export const yellow: string; + +export const yellow20: string; + +export function rgba(hexcode: string, opacity: number): string; + +export namespace rgba { + const prototype: {}; +} diff --git a/types/carbon__colors/tsconfig.json b/types/carbon__colors/tsconfig.json new file mode 100644 index 0000000000..3b03be1aae --- /dev/null +++ b/types/carbon__colors/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true, + "paths": { + "@carbon/colors": ["carbon__colors"] + } + }, + "files": ["index.d.ts", "carbon__colors-tests.ts"] +} diff --git a/types/carbon__colors/tslint.json b/types/carbon__colors/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__colors/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/carbon__layout/carbon__layout-tests.ts b/types/carbon__layout/carbon__layout-tests.ts new file mode 100644 index 0000000000..ef002f50ae --- /dev/null +++ b/types/carbon__layout/carbon__layout-tests.ts @@ -0,0 +1,20 @@ +import { + rem, + em, + px, + breakpoint, + breakpoints, + breakpointDown, + breakpointUp, + baseFontSize +} from "@carbon/layout"; + +const firstBreakpoint = Object.keys(breakpoints)[0]; + +rem(baseFontSize); // $ExpectType string +em(baseFontSize); // $ExpectType string +px(baseFontSize); // $ExpectType string + +breakpoint(firstBreakpoint); // $ExpectType string +breakpointUp(firstBreakpoint); // $ExpectType string +breakpointDown(firstBreakpoint); // $ExpectType string diff --git a/types/carbon__layout/index.d.ts b/types/carbon__layout/index.d.ts new file mode 100644 index 0000000000..1d7c7b4630 --- /dev/null +++ b/types/carbon__layout/index.d.ts @@ -0,0 +1,80 @@ +// Type definitions for @carbon/layout 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/layout +// Definitions by: Vince Picone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const baseFontSize: number; + +export const breakpoints: { + lg: { + columns: number; + margin: string; + width: string; + }; + max: { + columns: number; + margin: string; + width: string; + }; + md: { + columns: number; + margin: string; + width: string; + }; + sm: { + columns: number; + margin: string; + width: string; + }; + xlg: { + columns: number; + margin: string; + width: string; + }; +}; + +export const miniUnit: number; + +export const spacing: number[]; + +export function breakpoint(...args: any[]): string; + +export function breakpointDown(name: string): string; + +export function breakpointUp(name: string): string; + +export function em(px: number): string; + +export function miniUnits(count: number): string; + +export function px(value: number): string; + +export function rem(px: number): string; + +export namespace breakpoint { + const prototype: {}; +} + +export namespace breakpointDown { + const prototype: {}; +} + +export namespace breakpointUp { + const prototype: {}; +} + +export namespace em { + const prototype: {}; +} + +export namespace miniUnits { + const prototype: {}; +} + +export namespace px { + const prototype: {}; +} + +export namespace rem { + const prototype: {}; +} diff --git a/types/carbon__layout/tsconfig.json b/types/carbon__layout/tsconfig.json new file mode 100644 index 0000000000..10f832a631 --- /dev/null +++ b/types/carbon__layout/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@carbon/layout": ["carbon__layout"] + } + }, + "files": ["index.d.ts", "carbon__layout-tests.ts"] +} diff --git a/types/carbon__layout/tslint.json b/types/carbon__layout/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__layout/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/carbon__motion/carbon__motion-tests.ts b/types/carbon__motion/carbon__motion-tests.ts new file mode 100644 index 0000000000..6bcc820f5d --- /dev/null +++ b/types/carbon__motion/carbon__motion-tests.ts @@ -0,0 +1,8 @@ +import { easings, motion } from "@carbon/motion"; + +const easingNames = Object.keys(easings); + +const firstEasing = easingNames[0]; +const firstMode = Object.keys(firstEasing)[0]; + +motion(firstEasing, firstMode); diff --git a/types/carbon__motion/index.d.ts b/types/carbon__motion/index.d.ts new file mode 100644 index 0000000000..173687d04c --- /dev/null +++ b/types/carbon__motion/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for @carbon/motion 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/motion +// Definitions by: Vince Picone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const easings: { + entrance: { + expressive: string; + productive: string; + }; + exit: { + expressive: string; + productive: string; + }; + standard: { + expressive: string; + productive: string; + }; +}; + +export function motion(name: string, mode: string): string; + +export namespace motion { + const prototype: {}; +} diff --git a/types/carbon__motion/tsconfig.json b/types/carbon__motion/tsconfig.json new file mode 100644 index 0000000000..38245c7c9e --- /dev/null +++ b/types/carbon__motion/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@carbon/motion": ["carbon__motion"] + } + }, + "files": ["index.d.ts", "carbon__motion-tests.ts"] +} diff --git a/types/carbon__motion/tslint.json b/types/carbon__motion/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__motion/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/carbon__themes/carbon__themes-tests.ts b/types/carbon__themes/carbon__themes-tests.ts new file mode 100644 index 0000000000..7515742031 --- /dev/null +++ b/types/carbon__themes/carbon__themes-tests.ts @@ -0,0 +1,59 @@ +import ThemePackage from "@carbon/themes"; + +interface Theme { + active01: string; + activeDanger: string; + activePrimary: string; + activeSecondary: string; + activeTertiary: string; + activeUI: string; + brand01: string; + brand02: string; + brand03: string; + disabled01: string; + disabled02: string; + disabled03: string; + field01: string; + field02: string; + focus: string; + highlight: string; + hoverDanger: string; + hoverField: string; + hoverPrimary: string; + hoverPrimaryText: string; + hoverRow: string; + hoverSecondary: string; + hoverSelectedUI: string; + hoverTertiary: string; + hoverUI: string; + icon01: string; + icon02: string; + interactive01: string; + interactive02: string; + interactive03: string; + inverse01: string; + inverse02: string; + overlay01: string; + selectedUI: string; + support01: string; + support02: string; + support03: string; + support04: string; + text01: string; + text02: string; + text03: string; + text04: string; + ui01: string; + ui02: string; + ui03: string; + ui04: string; + ui05: string; + uiBackground: string; + visitedLink: string; +} + +const getDefaultTheme = (): Theme => { + return ThemePackage.white; +}; + +getDefaultTheme(); diff --git a/types/carbon__themes/index.d.ts b/types/carbon__themes/index.d.ts new file mode 100644 index 0000000000..e10f17f35c --- /dev/null +++ b/types/carbon__themes/index.d.ts @@ -0,0 +1,74 @@ +// Type definitions for @carbon/themes 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/themes +// Definitions by: Vince Picone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default carbon__themes; + +interface Theme { + active01: string; + activeDanger: string; + activePrimary: string; + activeSecondary: string; + activeTertiary: string; + activeUI: string; + brand01: string; + brand02: string; + brand03: string; + disabled01: string; + disabled02: string; + disabled03: string; + field01: string; + field02: string; + focus: string; + highlight: string; + hoverDanger: string; + hoverField: string; + hoverPrimary: string; + hoverPrimaryText: string; + hoverRow: string; + hoverSecondary: string; + hoverSelectedUI: string; + hoverTertiary: string; + hoverUI: string; + icon01: string; + icon02: string; + interactive01: string; + interactive02: string; + interactive03: string; + inverse01: string; + inverse02: string; + overlay01: string; + selectedUI: string; + support01: string; + support02: string; + support03: string; + support04: string; + text01: string; + text02: string; + text03: string; + text04: string; + ui01: string; + ui02: string; + ui03: string; + ui04: string; + ui05: string; + uiBackground: string; + visitedLink: string; +} + +// The default theme is included as a top level export +type ThemePackage = { + white: Theme; + g10: Theme; + g100: Theme; + g90: Theme; + themes: { + g10: Theme; + g100: Theme; + g90: Theme; + white: Theme; + }; +} & Theme; + +declare const carbon__themes: ThemePackage; diff --git a/types/carbon__themes/tsconfig.json b/types/carbon__themes/tsconfig.json new file mode 100644 index 0000000000..490b17648e --- /dev/null +++ b/types/carbon__themes/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@carbon/themes": ["carbon__themes"] + } + }, + "files": ["index.d.ts", "carbon__themes-tests.ts"] +} diff --git a/types/carbon__themes/tslint.json b/types/carbon__themes/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__themes/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/carbon__type/carbon__type-tests.ts b/types/carbon__type/carbon__type-tests.ts new file mode 100644 index 0000000000..a5d4cf7b8b --- /dev/null +++ b/types/carbon__type/carbon__type-tests.ts @@ -0,0 +1,6 @@ +import { fontFamily, fontWeight, getTypeSize, print } from "@carbon/type"; + +fontFamily("mono"); // $ExpectType { fontFamily: string; } +fontWeight("light"); // $ExpectType { fontWeight: number; } +print(fontFamily("mono")); // $ExpectType string +getTypeSize(2); // $ExpectType number diff --git a/types/carbon__type/index.d.ts b/types/carbon__type/index.d.ts new file mode 100644 index 0000000000..7933f2e358 --- /dev/null +++ b/types/carbon__type/index.d.ts @@ -0,0 +1,726 @@ +// Type definitions for @carbon/type 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/type +// Definitions by: Vince Picone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export const bodyLong01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const bodyLong02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const bodyShort01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const bodyShort02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const caption01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const code01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const code02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const display01: { + "@media (min-width: 42rem)": { + fontSize: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const display02: { + "@media (min-width: 42rem)": { + fontSize: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const display03: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const display04: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const expressiveHeading04: { + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const expressiveHeading05: { + "@media (min-width: 42rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const expressiveParagraph01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lg: { + fontSize: string; + lineHeight: string; + }; + lineHeight: string; + max: { + fontSize: string; + lineHeight: string; + }; +}; + +export const fontFamilies: { + mono: string; + sans: string; + sansCondensed: string; + sansHebrew: string; + serif: string; +}; + +export const fontWeights: { + light: number; + regular: number; + semibold: number; +}; + +export const heading01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const heading02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const heading03: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const helperText01: { + fontFamily: string; + fontSize: string; + fontStyle: string; + letterSpacing: string; + lineHeight: string; +}; + +export const label01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const productiveHeading04: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const productiveHeading05: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const quotation01: { + "@media (min-width: 42rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + }; + "@media (min-width: 66rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const quotation02: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const reset: { + body: { + "-moz-osx-font-smoothing": string; + "-webkit-font-smoothing": string; + fontFamily: string; + fontWeight: number; + textRendering: string; + }; + html: { + fontSize: string; + }; + strong: { + fontWeight: number; + }; +}; + +export const scale: number[]; + +export const spacing: { + layout01: string; + layout02: string; + layout03: string; + margin01: string; + margin02: string; + margin03: string; +}; + +export const styles: { + bodyLong01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + bodyLong02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + bodyShort01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + bodyShort02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + caption01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + code01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + code02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + display01: { + "@media (min-width: 42rem)": { + fontSize: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + display02: { + "@media (min-width: 42rem)": { + fontSize: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + display03: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + display04: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + expressiveHeading04: { + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + expressiveHeading05: { + "@media (min-width: 42rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + expressiveParagraph01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lg: { + fontSize: string; + lineHeight: string; + }; + lineHeight: string; + max: { + fontSize: string; + lineHeight: string; + }; + }; + heading01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + heading02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + heading03: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + helperText01: { + fontFamily: string; + fontSize: string; + fontStyle: string; + letterSpacing: string; + lineHeight: string; + }; + label01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + productiveHeading04: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + productiveHeading05: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + quotation01: { + "@media (min-width: 42rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + }; + "@media (min-width: 66rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + quotation02: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; +}; + +export function fontFamily( + name: string +): { + fontFamily: string; +}; + +export function fontWeight( + weight: string +): { + fontWeight: number; +}; + +export function getTypeSize(step: number): number; + +export function print(block: object): string; + +export namespace fontFamily { + const prototype: {}; +} + +export namespace fontWeight { + const prototype: {}; +} + +export namespace getTypeSize { + const prototype: {}; +} + +export namespace print { + const prototype: {}; +} diff --git a/types/carbon__type/tsconfig.json b/types/carbon__type/tsconfig.json new file mode 100644 index 0000000000..7949e7ab22 --- /dev/null +++ b/types/carbon__type/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@carbon/type": ["carbon__type"] + } + }, + "files": ["index.d.ts", "carbon__type-tests.ts"] +} diff --git a/types/carbon__type/tslint.json b/types/carbon__type/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__type/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cassandra-driver/cassandra-driver-tests.ts b/types/cassandra-driver/cassandra-driver-tests.ts index 3e203837b7..b4f850c315 100644 --- a/types/cassandra-driver/cassandra-driver-tests.ts +++ b/types/cassandra-driver/cassandra-driver-tests.ts @@ -102,3 +102,35 @@ const mapper = new cassandra.mapping.Mapper( const videoMapper = mapper.forModel('Video'); videoMapper.insert({ videoId: 'uuid', addedDate: new Date(), userId: 'uuid', name: 'My video', description: 'My desc' }); videoMapper.find({ videoId: 'uuid' }).then(results => results.first()); + +console.log(cassandra.version); + +const metadata = new cassandra.metadata.Metadata(cassandra.defaultOptions(), undefined); +let refreshFinished: Promise = metadata.refreshKeyspaces(); +refreshFinished = metadata.refreshKeyspaces(true); +metadata.refreshKeyspaces(() => {}); +metadata.refreshKeyspaces(true, () => {}); + +const start: cassandra.token.Token = new cassandra.token.Token("x"); +const end: cassandra.token.Token = new cassandra.token.Token("z"); + +const tokenizer: cassandra.token.Tokenizer = { + hash: (value: Buffer | number[]) => new cassandra.token.Token("x"), + parse: (value: string) => new cassandra.token.Token("x"), + minToken: () => new cassandra.token.Token("x"), + split: (start: cassandra.token.Token, end: cassandra.token.Token, numberOfSplits: number) => [], + splitBase: (start: number, end: number, ringEnd: number, ringLength: number, numberOfSplits: number): number[] => [1], + stringify: (token: cassandra.token.Token): string => "asd" +}; + +const range: cassandra.token.TokenRange = new cassandra.token.TokenRange(start, end, tokenizer); + +class MyLoadBalancingPolicy extends cassandra.policies.loadBalancing.LoadBalancingPolicy { + getDistance() { + return cassandra.types.distance.ignored; + } +} + +const myPolicy: cassandra.policies.loadBalancing.LoadBalancingPolicy = new MyLoadBalancingPolicy(); +let existingPolicy: cassandra.policies.loadBalancing.LoadBalancingPolicy = new cassandra.policies.loadBalancing.DCAwareRoundRobinPolicy(); +existingPolicy = new cassandra.policies.loadBalancing.DCAwareRoundRobinPolicy("dc"); diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 02853c66ba..18527ed8c5 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -34,43 +34,29 @@ export namespace policies { } namespace loadBalancing { - let DCAwareRoundRobinPolicy: DCAwareRoundRobinPolicyStatic; - let RoundRobinPolicy: RoundRobinPolicyStatic; - let TokenAwarePolicy: TokenAwarePolicyStatic; - let WhiteListPolicy: WhiteListPolicyStatic; - - interface LoadBalancingPolicy { + class LoadBalancingPolicy { init(client: Client, hosts: HostMap, callback: Callback): void; getDistance(host: Host): types.distance; newQueryPlan(keyspace: string, queryOptions: ExecutionOptions | null, callback: Callback): void; + getOptions(): Map; } - interface DCAwareRoundRobinPolicyStatic { - new (localDc?: string): DCAwareRoundRobinPolicy; - } - - interface DCAwareRoundRobinPolicy extends LoadBalancingPolicy { + class DCAwareRoundRobinPolicy extends LoadBalancingPolicy { + localDc: string; localHostsArray: Host[]; - remoteHostsArray: Host[]; + + constructor(localDc?: string); } - interface RoundRobinPolicyStatic { - new (): RoundRobinPolicy; + class RoundRobinPolicy extends LoadBalancingPolicy {} + + class TokenAwarePolicy extends LoadBalancingPolicy { + constructor(childPolicy: LoadBalancingPolicy); } - interface RoundRobinPolicy extends LoadBalancingPolicy { } - - interface TokenAwarePolicyStatic { - new (childPolicy: LoadBalancingPolicy): TokenAwarePolicy; + class WhiteListPolicy extends LoadBalancingPolicy { + constructor(childPolicy: LoadBalancingPolicy, whiteList: string[]); } - - interface TokenAwarePolicy extends LoadBalancingPolicy { } - - interface WhiteListPolicyStatic { - new (childPolicy: LoadBalancingPolicy, whiteList: string[]): WhiteListPolicy; - } - - interface WhiteListPolicy extends LoadBalancingPolicy { } } namespace reconnection { @@ -499,8 +485,6 @@ export namespace types { } export let Client: ClientStatic; -export let Host: HostStatic; -export let HostMap: HostMapStatic; export let Encoder: EncoderStatic; export interface ClientOptions { @@ -611,14 +595,10 @@ export interface Client extends events.EventEmitter { stream(query: string, params?: any, options?: QueryOptions, callback?: Callback): NodeJS.ReadableStream; } -export interface HostStatic { - new (address: string, protocolVersion: number, options: ClientOptions): Host; -} - export interface Host extends events.EventEmitter { address: string; cassandraVersion: string; - dataCenter: string; + datacenter: string; rack: string; tokens: string[]; @@ -627,10 +607,6 @@ export interface Host extends events.EventEmitter { isUp(): boolean; } -export interface HostMapStatic { - new (): HostMap; -} - export interface HostMap extends events.EventEmitter { length: number; @@ -742,19 +718,10 @@ export namespace errors { } export namespace metadata { - let Aggregate: AggregateStatic; - let Index: IndexStatic; - let MaterializedView: MaterializedViewStatic; let Metadata: MetadataStatic; - let SchemaFunction: SchemaFunctionStatic; - let TableMetadata: TableMetadataStatic; type caching = "all" | "keys_only" | "rows_only" | "none"; - interface AggregateStatic { - new (): Aggregate; - } - interface Aggregate { argumentTypes: Array<{ code: number, info: any }>; finalFunction: string; @@ -766,10 +733,6 @@ export namespace metadata { stateType: string; } - interface ClientStateStatic { - new (): ClientState; - } - interface ClientState { getConnectedHosts(): Host[]; getInFlightQueries(host: Host): number; @@ -822,13 +785,6 @@ export namespace metadata { composites } - interface IndexStatic { - new (name: string, target: string, kind: string | IndexType, options: object): Index; - - fromRows(indexRows: types.Row[]): Index[]; - fromColumnRows(columnRows: types.Row[], columnsByName: { [key: string]: ColumnInfo }): Index[]; - } - interface Index { kind: IndexType; name: string; @@ -840,11 +796,19 @@ export namespace metadata { isKeysKind(): boolean; } - interface MaterializedViewStatic { - new (name: string): MaterializedView; + interface MaterializedView extends DataCollection { } + + interface QueryTrace { + requestType: any; + coordinator: any; + parameters: any; + startedAt: any; + duration: any; + clientAddress: any; + events: Array<{ id: any; activity: any; source: any; elapsed: any; thread: any }>; } - interface MaterializedView extends DataCollection { } + type MetadataCallback = (err: any, retVal: T) => void; interface MetadataStatic { new (options: ClientOptions, controlConnection: any): Metadata; @@ -853,21 +817,34 @@ export namespace metadata { interface Metadata { clearPrepared(): void; - getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: Callback): void; - getAggregates(keyspaceName: string, name: string, callback: Callback): void; - getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: Callback): void; - getFunctions(keyspaceName: string, name: string, callback: Callback): void; - getMaterializedView(keyspaceName: string, name: string, callback: Callback): void; - getReplicas(keyspaceName: string, tokenBuffer: Buffer): any[]; - getTable(keyspaceName: string, name: string, callback: Callback): void; - getTrace(traceId: types.Uuid, callback: Callback): void; - getUdt(keyspaceName: string, name: string, callback: Callback): void; - refreshKeyspace(name: string, callback?: Callback): void; - refreshKeyspaces(callback?: Callback): void; - } - - interface SchemaFunctionStatic { - new (): SchemaFunction; + getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: MetadataCallback): void; + getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>): Promise; + getAggregates(keyspaceName: string, name: string, callback: MetadataCallback): void; + getAggregates(keyspaceName: string, name: string): Promise; + getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: MetadataCallback): void; + getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>): Promise; + getFunctions(keyspaceName: string, name: string, callback: MetadataCallback): void; + getFunctions(keyspaceName: string, name: string): Promise; + getMaterializedView(keyspaceName: string, name: string, callback: MetadataCallback): void; + getMaterializedView(keyspaceName: string, name: string, callback: Callback): Promise; + getReplicas(keyspaceName: string, token: Buffer | token.Token | token.TokenRange): any[]; // TODO + getTable(keyspaceName: string, name: string, callback: MetadataCallback): void; + getTable(keyspaceName: string, name: string): Promise; + getTokenRanges(): Set; + getTokenRangesForHost(keyspaceName: string, host: Host): Set | null; + getTrace(traceId: types.Uuid, consistency: types.consistencies, callback: MetadataCallback): void; + getTrace(traceId: types.Uuid, consistency: types.consistencies, callback: Callback): Promise; + getTrace(traceId: types.Uuid, callback: MetadataCallback): void; + getTrace(traceId: types.Uuid): Promise; + getUdt(keyspaceName: string, name: string, callback: MetadataCallback): void; // TODO + getUdt(keyspaceName: string, name: string): Promise; // TODO + newToken(components: Buffer[] | Buffer | string): token.Token; + newTokenRange(start: token.Token, end: token.Token): token.TokenRange; + refreshKeyspace(name: string, callback: Callback): void; + refreshKeyspace(name: string): Promise; + refreshKeyspaces(waitReconnect: boolean, callback: Callback): void; + refreshKeyspaces(waitReconnect?: boolean): Promise; + refreshKeyspaces(callback: Callback): void; } interface SchemaFunction { @@ -882,10 +859,6 @@ export namespace metadata { signature: string[]; } - interface TableMetadataStatic { - new (name: string): TableMetadata; - } - interface TableMetadata extends DataCollection { indexes: Index[]; indexInterval?: number; @@ -927,6 +900,7 @@ export interface ExecutionOptions { } export let ExecutionOptions: ExecutionOptionsStatic; +export let ExecutionProfile: ExecutionProfileStatic; export namespace mapping { let Mapper: MapperStatic; @@ -1136,3 +1110,41 @@ export namespace metrics { } interface DefaultMetrics extends ClientMetrics {} } + +export namespace token { + interface Tokenizer { + hash(value: Buffer | number[]): Token; + parse(value: string): Token; + minToken(): Token; + split(start: Token, end: Token, numberOfSplits: number): TokenRange[]; + splitBase(start: number, end: number, ringEnd: number, ringLength: number, numberOfSplits: number): number[]; + stringify(token: Token): string; + } + + class Token { + constructor(value: any); + + getType(): { code: number, info: any }; + getValue(): any; + compare(other: Token): number; + equals(other: Token): boolean; + } + + class TokenRange { + start: Token; + end: Token; + + constructor(start: Token, end: Token, tokenizer: Tokenizer); + + splitEvenly(numberOfSplits: number): TokenRange[]; + isEmpty(): boolean; + isWrappedAround(): boolean; + unwrap(): TokenRange[]; + contains(token: Token): boolean; + equals(other: TokenRange): boolean; + compare(other: TokenRange): number; + } +} + +export function defaultOptions(): ClientOptions; +export const version: string; diff --git a/types/color-support/color-support-tests.ts b/types/color-support/color-support-tests.ts new file mode 100644 index 0000000000..45bb6317cf --- /dev/null +++ b/types/color-support/color-support-tests.ts @@ -0,0 +1,48 @@ +import colorSupport = require('color-support'); + +(() => { + const result = colorSupport(); + if (!result) { + console.log('color is not supported'); + } else if (result.has16m) { + console.log('\x1b[38;2;102;194;255m16m colors\x1b[0m'); + } else if (result.has256) { + console.log('\x1b[38;5;119m256 colors\x1b[0m'); + } else if (result.hasBasic) { + console.log('\x1b[31mbasic colors\x1b[0m'); + } else { + console.log('Level: ', result.level); + console.log('this is impossible, but colors are not supported'); + } +})(); + +(() => { + const result = colorSupport({ + alwaysReturn: false, + env: process.env, + ignoreCI: true, + ignoreDumb: true, + ignoreTTY: true, + level: 2, + stream: process.stdout, + term: process.env.TERM, + }, { + has16m: false, + has256: false, + hasBasic: false, + level: 0, + }); + + if (!result) { + console.log('color is not supported'); + } else if (result.has16m) { + console.log('\x1b[38;2;102;194;255m16m colors\x1b[0m'); + } else if (result.has256) { + console.log('\x1b[38;5;119m256 colors\x1b[0m'); + } else if (result.hasBasic) { + console.log('\x1b[31mbasic colors\x1b[0m'); + } else { + console.log('Level: ', result.level); + console.log('this is impossible, but colors are not supported'); + } +})(); diff --git a/types/color-support/index.d.ts b/types/color-support/index.d.ts new file mode 100644 index 0000000000..290a6e29b0 --- /dev/null +++ b/types/color-support/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for color-support 1.1 +// Project: https://github.com/isaacs/color-support#readme +// Definitions by: Guketlev Dmitry +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +type ColorSupportLevel = 0 | 1 | 2 | 3; + +interface ColorSupportOptions { + alwaysReturn?: boolean; + env?: NodeJS.ProcessEnv; + ignoreCI?: boolean; + ignoreDumb?: boolean; + ignoreTTY?: boolean; + level?: ColorSupportLevel; + stream?: NodeJS.WriteStream; + term?: string; +} + +interface ColorSupportResult { + level: ColorSupportLevel; + hasBasic: boolean; + has256: boolean; + has16m: boolean; +} + +type ColorSupport = (options?: ColorSupportOptions, + obj?: ColorSupportResult) => false | ColorSupportResult; + +declare var colorSupport: ColorSupport; + +export = colorSupport; diff --git a/types/color-support/tsconfig.json b/types/color-support/tsconfig.json new file mode 100644 index 0000000000..f1e6de8e28 --- /dev/null +++ b/types/color-support/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "color-support-tests.ts" + ] +} diff --git a/types/color-support/tslint.json b/types/color-support/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-support/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-exclusions-tests.ts b/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-exclusions-tests.ts new file mode 100644 index 0000000000..291622b349 --- /dev/null +++ b/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-exclusions-tests.ts @@ -0,0 +1,70 @@ +import historyApiFallback = require('connect-history-api-fallback-exclusions'); +import express = require('express'); + +const app = express(); +app.use(historyApiFallback()); + +historyApiFallback({ + verbose: true +}); + +historyApiFallback({ + logger: console.log.bind(console) +}); + +historyApiFallback({ + exclusions: [ + '/api/*', + '/health', + ], +}); + +historyApiFallback({ + rewrites: [ + { from: /\/soccer/, to: '/soccer.html' } + ] +}); + +historyApiFallback({ + index: 'default.html' +}); + +historyApiFallback({ + htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'] +}); + +historyApiFallback({ + rewrites: [ + { + from: /^\/libs\/(.*)$/, + to(context) { + return './bower_components' + context.parsedUrl.pathname; + } + } + ] +}); + +historyApiFallback({ + rewrites: [ + { + from: /\/app\/login/, + to: function onMatch(ctx) { + if (ctx.parsedUrl.path && ctx.parsedUrl.path.indexOf('.js')) { + return ctx.parsedUrl.href || ''; + } + return '/app/login/index.html'; + } + } + ] +}); + +historyApiFallback({ + rewrites: [ + { + from: /^\/libs\/(.*)$/, + to(context) { + return `/${context.match[2]}/${context.match[3]}`; + } + } + ] +}); diff --git a/types/connect-history-api-fallback-exclusions/index.d.ts b/types/connect-history-api-fallback-exclusions/index.d.ts new file mode 100644 index 0000000000..c83335203a --- /dev/null +++ b/types/connect-history-api-fallback-exclusions/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for connect-history-api-fallback-exclusions 1.5 +// Project: https://github.com/Wirewheel/connect-history-api-fallback#readme +// Definitions by: Tony Stone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +import { Url } from 'url'; + +import * as core from "express-serve-static-core"; + +declare function historyApiFallback(options?: historyApiFallback.Options): core.RequestHandler; + +declare namespace historyApiFallback { + interface Options { + exclusions?: string[]; + disableDotRule?: true; + htmlAcceptHeaders?: string[]; + index?: string; + logger?: typeof console.log; + rewrites?: Rewrite[]; + verbose?: boolean; + } + + interface Context { + match: RegExpMatchArray; + parsedUrl: Url; + } + type RewriteTo = (context: Context) => string; + + interface Rewrite { + from: RegExp; + to: string | RegExp | RewriteTo; + } +} +export = historyApiFallback; diff --git a/types/connect-history-api-fallback-exclusions/tsconfig.json b/types/connect-history-api-fallback-exclusions/tsconfig.json new file mode 100644 index 0000000000..1fc7fec2ca --- /dev/null +++ b/types/connect-history-api-fallback-exclusions/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "connect-history-api-fallback-exclusions-tests.ts" + ] +} \ No newline at end of file diff --git a/types/connect-history-api-fallback-exclusions/tslint.json b/types/connect-history-api-fallback-exclusions/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/connect-history-api-fallback-exclusions/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/d3-force/d3-force-tests.ts b/types/d3-force/d3-force-tests.ts index 6b73a1dbf4..9bf424c1b6 100644 --- a/types/d3-force/d3-force-tests.ts +++ b/types/d3-force/d3-force-tests.ts @@ -685,6 +685,7 @@ nodeLinkSimulation = nodeLinkSimulation.stop(); // tick() ----------------------------------------------------------------------------- nodeLinkSimulation.tick(); +nodeLinkSimulation.tick(10); // find() ----------------------------------------------------------------------------- diff --git a/types/d3-force/index.d.ts b/types/d3-force/index.d.ts index 35f4d06657..563ca925c3 100644 --- a/types/d3-force/index.d.ts +++ b/types/d3-force/index.d.ts @@ -1,9 +1,12 @@ -// Type definitions for D3JS d3-force module 1.1 +// Type definitions for D3JS d3-force module 1.2 // Project: https://github.com/d3/d3-force/ -// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov +// Definitions by: Tom Wanzek +// Alex Ford +// Boris Yankov +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.1.0 +// Last module patch version validated against: 1.2.0 // ----------------------------------------------------------------------- // Force Simulation @@ -108,13 +111,16 @@ export interface Simulation name.test("DefinitelyTyped:log"))); +log("Enabled?: %s", debug1.enabled("DefinitelyTyped:log")); +log("Name Enabled: %s", debug1.names.some(name => name.test("DefinitelyTyped:log"))); log("Namespace: %s", log.namespace); -var error:debug.IDebugger = debug("DefinitelyTyped:error"); +const error: debug1.Debugger = debug1("DefinitelyTyped:error"); error.log = console.error.bind(console); error("This should be printed to stderr"); -var extendedLog: debug.IDebugger = log.extend('extended'); +const extendedLog: debug1.Debugger = log.extend('extended'); extendedLog("Testing this is also an IDebugger."); -var extendedWithCustomDelimiter: debug.IDebugger = log.extend('with-delim', '.'); -extendedWithCustomDelimiter("Testing this is an IDebugger, too."); \ No newline at end of file +const extendedWithCustomDelimiter: debug1.Debugger = log.extend('with-delim', '.'); +extendedWithCustomDelimiter("Testing this is an IDebugger, too."); diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index 2eca1c8fb8..2067b27222 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -1,40 +1,45 @@ -// Type definitions for debug +// Type definitions for debug 4.1 // Project: https://github.com/visionmedia/debug // Definitions by: Seon-Wook Park // Gal Talmor // John McLaughlin // Brasten Sager +// Nicolas Penin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var debug: debug.IDebug; +declare var debug: debug.Debug & {debug: debug.Debug, default: debug.Debug}; export = debug; export as namespace debug; declare namespace debug { - export interface IDebug { - (namespace: string): debug.IDebugger, - coerce: (val: any) => any, - disable: () => void, - enable: (namespaces: string) => void, - enabled: (namespaces: string) => boolean, + interface Debug { + (namespace: string): Debugger; + coerce: (val: any) => any; + disable: () => void; + enable: (namespaces: string) => void; + enabled: (namespaces: string) => boolean; - names: RegExp[], - skips: RegExp[], + names: RegExp[]; + skips: RegExp[]; - formatters: IFormatters + formatters: Formatters; } - export interface IFormatters { - [formatter: string]: Function + type IDebug = Debug; + + interface Formatters { + [formatter: string]: (v: any) => string; } - export interface IDebugger { + type IDebugger = Debugger; + + interface Debugger { (formatter: any, ...args: any[]): void; enabled: boolean; - log: Function; + log: (v: any) => string; namespace: string; - extend: (namespace: string, delimiter?: string) => debug.IDebugger; + extend: (namespace: string, delimiter?: string) => Debugger; } } diff --git a/types/debug/tslint.json b/types/debug/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/debug/tslint.json +++ b/types/debug/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/elliptic/index.d.ts b/types/elliptic/index.d.ts index fa8e19a2cf..722568a6f6 100644 --- a/types/elliptic/index.d.ts +++ b/types/elliptic/index.d.ts @@ -176,7 +176,7 @@ export class ec { keyPair(options: ec.KeyPairOptions): ec.KeyPair; keyFromPrivate(priv: Buffer | string | ec.KeyPair, enc?: string): ec.KeyPair; - keyFromPublic(pub: Buffer | string | ec.KeyPair, enc?: string): ec.KeyPair; + keyFromPublic(pub: Buffer | string | {x: string, y: string} | ec.KeyPair, enc?: string): ec.KeyPair; genKeyPair(options?: ec.GenKeyPairOptions): ec.KeyPair; sign(msg: BNInput, key: Buffer | ec.KeyPair, enc: string, options?: ec.SignOptions): ec.Signature; sign(msg: BNInput, key: Buffer | ec.KeyPair, options?: ec.SignOptions): ec.Signature; @@ -201,7 +201,7 @@ export namespace ec { } class KeyPair { - static fromPublic(ec: ec, pub: Buffer | string | KeyPair, enc?: string): KeyPair; + static fromPublic(ec: ec, pub: Buffer | string | {x: string, y: string} | KeyPair, enc?: string): KeyPair; static fromPrivate(ec: ec, priv: Buffer | string | KeyPair, enc?: string): KeyPair; ec: ec; diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 58e5938a8f..d9f858d2a7 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -619,7 +619,7 @@ export class EnzymeAdapter { } /** - * Configure enzyme to use the correct adapter for the react verstion + * Configure enzyme to use the correct adapter for the react version * This is enabling the Enzyme configuration with adapters in TS */ export function configure(options: { diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 62a7dcbb91..10045e57e6 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { Text, AccessibilityInfo } from 'react-native'; +import { Text } from 'react-native'; import { Accelerometer, @@ -154,7 +154,6 @@ Audio.setAudioModeAsync({ interruptionModeIOS: 2, interruptionModeAndroid: 1, allowsRecordingIOS: true, - playThroughEarpieceAndroid: false }); Audio.setIsEnabledAsync(true); @@ -233,7 +232,7 @@ Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE === 3; Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY; Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY; async () => { - const result = await Audio.Sound.create({uri: 'uri'}, { + const result = await Audio.Sound.createAsync({uri: 'uri'}, { volume: 0.55, rate: 16.5 }, null, true); @@ -262,13 +261,13 @@ async () => { ); -const barCodeScannedCallback = () => {}; +const barcodeReadCallback = () => {}; () => ( + onBarCodeScanned={barcodeReadCallback} /> ); () => ( @@ -408,7 +407,7 @@ async () => { }; async () => { - const result = await ImageManipulator.manipulate('url', [ + const result = await ImageManipulator.manipulateAsync('url', [ { rotate: 90 }, { resize: { width: 300 } }, { resize: { height: 300 } }, @@ -963,7 +962,7 @@ const userLocationCallback = (event: EventUserLocation) => console.log(event); // #endregion async () => { - const updateEventListener: Updates.UpdateEventListener = ({ type, manifest, message }) => { + const updateEventListener: Updates.UpdateEventListener = ({ type }) => { switch (type) { case Updates.EventType.DOWNLOAD_STARTED: case Updates.EventType.DOWNLOAD_PROGRESS: diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index c206bc12ff..f48d01b75d 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for expo 31.0 +// Type definitions for expo 32.0 // Project: https://github.com/expo/expo-sdk // Definitions by: Konstantin Kai // Martynas Kadiša @@ -15,6 +15,7 @@ // Pavel Ihm // Bartosz Dotryw // Jason Killian +// Satyajit Sahoo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -22,11 +23,21 @@ export * from 'react-native-maps'; export { default as MapView } from 'react-native-maps'; import { EventSubscription } from 'fbemitter'; -import { Component, ComponentClass, ComponentType, Ref } from 'react'; -import { ImageRequireSource, ImageURISource, LinkingStatic as ReactNativeLinkingStatic, StyleProp, ViewProps, ViewStyle } from 'react-native'; +import { Component, ComponentClass, Ref, ComponentType } from 'react'; +import { + ColorPropType, + ImageRequireSource, + ImageURISource, + LinkingStatic as ReactNativeLinkingStatic, + NativeEventEmitter, + ViewProps, + ViewStyle, + Permission, + StyleProp +} from 'react-native'; export type Axis = number; -export type BarCodeScannedCallback = (params: { type: string; data: string; }) => void; +export type BarCodeScannedCallback = (result: { type: string; data: string; }) => void; export type Md5 = string; export type Orientation = 'portrait' | 'landscape'; export type RequireSource = ImageRequireSource; @@ -401,9 +412,6 @@ export namespace Audio { /** an enum selecting how your experience’s audio should interact with the audio from other apps on Android: */ interruptionModeAndroid: InterruptionModeAndroid; - - /** Boolean selecting if audio should go to earpiece (only on Android). */ - playThroughEarpieceAndroid: boolean; } function setIsEnabledAsync(value: boolean): Promise; @@ -420,7 +428,7 @@ export namespace Audio { * - `sound`: The newly created and loaded Sound object. * - `status`: The PlaybackStatus of the Sound object. See the AV documentation for further information. */ - static create( + static createAsync( /** * The source of the sound. The following forms are supported: * @@ -565,7 +573,7 @@ export interface PlaybackStatusToSet { volume?: number; } -export type PlaybackSource = RequireSource | { uri: string, headers?: { [header: string]: string }, overrideFileExtensionAndroid?: string } | Asset; +export type PlaybackSource = RequireSource | { uri: string } | Asset; export class PlaybackObject { /** @@ -769,10 +777,10 @@ export namespace Brightness { * Camera */ export interface PictureOptions { - quality?: number; - base64?: boolean; - exif?: boolean; - onPictureSaved?: (data: PictureResponse) => void; + quality?: number; + base64?: boolean; + exif?: boolean; + onPictureSaved?: (data: PictureResponse) => void; } export interface PictureResponse { @@ -797,24 +805,28 @@ export class CameraObject { } export interface CameraProps extends ViewProps { - autoFocus?: string | number | boolean; - barCodeTypes?: Array; - faceDetectionClassifications?: number; - faceDetectionLandmarks?: number; - faceDetectionMode?: number; - flashMode?: string | number; + zoom?: number; + ratio?: string; /** Distance to plane of sharpest focus. A value between `0` and `1`. `0`: infinity focus, `1`: focus as close as possible. Default: `0`. For Android this is available only for some devices and when `useCamera2Api` is set to `true`. */ focusDepth?: number; - onBarCodeScanned?: BarCodeScannedCallback; + type?: number | string; onCameraReady?: () => void; + useCamera2Api?: boolean; + flashMode?: number | string; + whiteBalance?: number | string; + autoFocus?: string | boolean | number; + pictureSize?: string; + videoStabilizationMode?: number; + onMountError?: (error: { message: string }) => void; + barCodeScannerSettings?: { barCodeTypes?: Array; }; + onBarCodeScanned?: BarCodeScannedCallback; + faceDetectorSettings?: { + mode?: number; + runClassifications?: number; + detectLandmarks?: number; + }; onFacesDetected?: (options: { faces: TrackedFaceFeature[] }) => void; - onMountError?: () => void; - ratio?: string; ref?: Ref; - type?: string | number; - whiteBalance?: string | number; - /** A value between `0` and `1` being a percentage of device's max zoom. `0`: not zoomed, `1`: maximum zoom. Default: `0`. */ - zoom?: number; } export interface CameraConstants { @@ -1540,15 +1552,62 @@ export namespace FacebookAds { setMediaCachePolicy(cachePolicy: MediaCachePolicy): void; } - function withNativeAd(component: Component<{ - icon?: string; - coverImage?: string; - title?: string; - subtitle?: string; - description?: string; - callToActionText?: string; + interface NativeAd { + /** + * The headline the advertiser entered when they created their ad. This is usually the ad's main + * title. + */ + headline?: string; + + /** + * The link description which is additional information that the advertiser may have entered + */ + linkDescription?: string; + + /** + * The name of the Facebook Page or mobile app that represents the business running the ad + */ + advertiserName?: string; + + /** + * The ad's social context, such as, "Over half a million users" + */ socialContext?: string; - }>): Component<{ adsManager: NativeAdsManager }, { ad: any, canRequestAds: boolean }>; + + /** + * The call-to-action phrase of the ad, such as, "Install Now" + */ + callToActionText?: string; + + /** + * The body text, truncated to 90 characters, that contains the text the advertiser entered when + * they created their ad to tell people what the ad promotes + */ + bodyText?: string; + + /** + * The word "ad", translated into the viewer's language + */ + adTranslation?: string; + + /** + * The word "promoted", translated into the viewer's language + */ + promotedTranslation?: string; + + /** + * The word "sponsored", translated into the viewer's language + */ + sponsoredTranslation?: string; + } + + function withNativeAd

(component: Component

): Component< + { + adsManager: NativeAdsManager, + onAdLoaded?: ((ad: NativeAd) => void) | null; + } & P, + { ad: NativeAd | null, canRequestAds: boolean } + >; /** * Banner View @@ -1564,6 +1623,16 @@ export namespace FacebookAds { class BannerView extends Component { } + type AdTriggerViewProps

= { + renderInteractiveComponent?: (props: P) => React.ReactElement

; + } & P; + + class AdTriggerView

extends Component> { } + + class AdIconView extends Component { } + + class AdMediaView extends Component { } + /** * Ad Settings */ @@ -1657,6 +1726,8 @@ export namespace FaceDetector { * FileSystem */ export namespace FileSystem { + type EncodingType = "utf8" | "base64"; + type FileInfo = { exists: true; isDirectory: boolean; @@ -1669,6 +1740,16 @@ export namespace FileSystem { isDirectory: false; }; + interface ReadingOptions { + encoding?: EncodingType; + position?: number; + length?: number; + } + + interface WritingOptions { + encoding?: EncodingType; + } + interface DownloadResult { uri: string; status: number; @@ -1680,8 +1761,8 @@ export namespace FileSystem { const cacheDirectory: string; function getInfoAsync(fileUri: string, options?: { md5?: string, size?: boolean; }): Promise; - function readAsStringAsync(fileUri: string): Promise; - function writeAsStringAsync(fileUri: string, contents: string): Promise; + function readAsStringAsync(fileUri: string, options?: ReadingOptions): Promise; + function writeAsStringAsync(fileUri: string, contents: string, options?: WritingOptions): Promise; function deleteAsync(fileUri: string, options?: { idempotent: boolean; }): Promise; function moveAsync(options: { from: string, to: string; }): Promise; function copyAsync(options: { from: string, to: string; }): Promise; @@ -1742,6 +1823,14 @@ export namespace LocalAuthentication { error: string }; + interface AuthenticationTypeType { + FINGERPRINT: number; + FACIAL_RECOGNITION: number; + } + + /** Determine the auhentication types supported on the device. */ + function supportedAuthenticationTypesAsync(): Promise; + /** Determine whether a face or fingerprint scanner is available on the device. */ function hasHardwareAsync(): Promise; @@ -1887,8 +1976,6 @@ export namespace ImageManipulator { format?: 'jpeg' | 'png'; } - function manipulate(uri: string, actions: Action[], saveOptions?: SaveOptions): Promise; - function manipulateAsync(uri: string, actions: Action[], saveOptions?: SaveOptions): Promise; } @@ -2075,9 +2162,10 @@ export const Linking: LinkingStatic; */ export namespace Location { interface LocationOptions { - enableHighAccuracy?: boolean; + accuracy: number; timeInterval?: number; distanceInterval?: number; + timeout?: number; } interface LocationProps { @@ -2120,6 +2208,20 @@ export namespace Location { name: string; } + interface LocationTaskOptions { + accuracy?: number; + showsBackgroundLocationIndicator?: boolean; + } + + interface Region { + identifier?: string; + latitude: number; + longitude: number; + radius: number; + notifyOnEnter?: boolean; + notifyOnExit?: boolean; + } + type LocationCallback = (data: LocationData) => void; function getCurrentPositionAsync(options: LocationOptions): Promise; @@ -2127,8 +2229,16 @@ export namespace Location { function getProviderStatusAsync(): Promise; function getHeadingAsync(): Promise; function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription; - function geocodeAsync(address: string): Promise; + function geocodeAsync(address: string): Promise; function reverseGeocodeAsync(location: LocationProps): Promise; + function requestPermissionsAsync(): Promise; + function hasServicesEnabledAsync(): Promise; + function startgeocodUpdatesAsync(taskName: string, options: LocationTaskOptions): Promise; + function stopLocationUpdatesAsync(taskName: string): Promise; + function hasStartedLocationUpdatesAsync(taskName: string): Promise; + function startGeofencingAsync(taskName: string, regions: Region[]): Promise; + function stopGeofencingAsync(taskName: string): Promise; + function hasStartedGeofencingAsync(taskName: string): Promise; function setApiKey(key: string): void; } @@ -2166,46 +2276,72 @@ export namespace Notifications { sound?: boolean }; android?: { - sound?: boolean; + channelId?: string; icon?: string; color?: string; - priority?: 'min' | 'low' | 'high' | 'max'; sticky?: boolean; - vibrate?: boolean | number[]; - link?: string; }; } - interface SchedulingOptions { - time: Date | number; - repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; - intervalMs?: number; - } - - interface ChannelAndroid { - name: string; - description?: string; - sound?: boolean; - priority?: 'min' | 'low' | 'default' | 'high' | 'max'; - vibrate?: boolean | number[]; - badge?: boolean; - } - type LocalNotificationId = string | number; - function addListener(listener: (notification: Notification) => any): EventSubscription; + interface Channel { + name: string; + description?: string; + priority?: string; + sound?: boolean; + vibrate?: boolean | number[]; + badge?: boolean; + } + + interface ActionType { + actionId: string; + buttonTitle: string; + isDestructive?: boolean; + isAuthenticationRequired?: boolean; + textInput?: { + submitButtonTitle: string; + placeholder: string; + }; + } + + function createCategoryAsync(categoryId: string, actions: ActionType[]): Promise; + function deleteCategoryAsync(categoryId: string): Promise; function getExpoPushTokenAsync(): Promise; - function presentLocalNotificationAsync(localNotification: LocalNotification): Promise; - function scheduleLocalNotificationAsync( - localNotification: LocalNotification, - schedulingOptions: SchedulingOptions - ): Promise; - function dismissNotificationAsync(localNotificationId: LocalNotificationId): Promise; - function dismissAllNotificationsAsync(): Promise; - function cancelScheduledNotificationAsync(localNotificationId: LocalNotificationId): Promise; - function cancelAllScheduledNotificationsAsync(): Promise; - function createChannelAndroidAsync(id: string, channel: ChannelAndroid): Promise; + function getDevicePushTokenAsync(config: { + gcmSenderId?: string; + }): Promise<{ type: string; data: string }>; + function createChannelAndroidAsync(id: string, channel: Channel): Promise; function deleteChannelAndroidAsync(id: string): Promise; + + /* Shows a notification instantly */ + function presentLocalNotificationAsync( + notification: LocalNotification + ): Promise; + + /** Schedule a notification at a later date */ + function scheduleLocalNotificationAsync( + notification: LocalNotification, + options?: { + time?: Date | number; + repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; + intervalMs?: number; + } + ): Promise; + + /** Dismiss currently shown notification with ID (Android only) */ + function dismissNotificationAsync(notificationId: LocalNotificationId): Promise; + + /** Dismiss all currently shown notifications (Android only) */ + function dismissAllNotificationsAsync(): Promise; + + /** Cancel scheduled notification notification with ID */ + function cancelScheduledNotificationAsync(notificationId: LocalNotificationId): Promise; + + /** Cancel all scheduled notifications */ + function cancelAllScheduledNotificationsAsync(): Promise; + + function addListener(listener: (notification: Notification) => any): EventSubscription; function getBadgeNumberAsync(): Promise; function setBadgeNumberAsync(number: number): Promise; } @@ -2332,11 +2468,14 @@ export namespace Segment { function identify(userId: string): void; function identifyWithTraits(userId: string, traits: object): void; function track(event: string): void; + function alias(newId: string, options?: { [key: string]: any }): Promise; function reset(): void; function trackWithProperties(event: string, properties: object): void; function screen(screenName: string): void; function screenWithProperties(screenName: string, properties: object): void; function flush(): void; + function getEnabledAsync(): void; + function setEnabledAsync(enabled: boolean): void; } /** @@ -2350,7 +2489,7 @@ export namespace Speech { onStart?: () => void; onStopped?: () => void; onDone?: () => void; - onError?: (error: string) => void; + onError?: (error: Error) => void; } function speak(text: string, options?: SpeechOptions): void; @@ -2563,13 +2702,14 @@ export class Svg extends Component<{ width: number, height: number, viewBox?: st * Take Snapshot */ export function takeSnapshotAsync( - view?: (number | React.ReactElement), + node: number | React.ReactElement | React.RefObject, options?: { - width?: number, - height?: number, - format?: 'png' | 'jpg' | 'jpeg' | 'webm', - quality?: number, - result?: 'file' | 'base64' | 'data-uri', + width?: number; + height?: number; + format: 'png' | 'jpg' | 'raw' | 'webm'; + quality: number; + snapshotContentContainer: boolean; + result: "tmpfile" | "base64" | "data-uri" | "zip-base64"; } ): Promise; diff --git a/types/expo/v31/expo-tests.tsx b/types/expo/v31/expo-tests.tsx new file mode 100644 index 0000000000..10045e57e6 --- /dev/null +++ b/types/expo/v31/expo-tests.tsx @@ -0,0 +1,1263 @@ +import * as React from 'react'; +import { Text } from 'react-native'; + +import { + Accelerometer, + AdMobAppEvent, + AdMobBanner, + AdMobInterstitial, + AdMobRewarded, + Amplitude, + AppLoading, + Asset, + Audio, + AuthSession, + BarCodeScanner, + BlurView, + Brightness, + Calendar, + Camera, + CameraObject, + Constants, + Contacts, + DocumentPicker, + EdgeInsets, + EdgePadding, + EventUserLocation, + Facebook, + FacebookAds, + FaceDetector, + FileSystem, + Haptic, + ImageManipulator, + ImagePicker, + IntentLauncherAndroid, + KeepAwake, + KmlMapEvent, + LinearGradient, + Linking, + Location, + MailComposer, + MapEvent, + MapStyleElement, + MapView, + MediaLibrary, + Permissions, + PublisherBanner, + Region, + registerRootComponent, + ScreenOrientation, + SecureStore, + Svg, + Updates +} from 'expo'; + +const reverseGeocode: Promise = Location.reverseGeocodeAsync({ + latitude: 0, + longitude: 0 +}); + +Accelerometer.addListener((obj) => { + obj.x; + obj.y; + obj.z; +}); +Accelerometer.removeAllListeners(); +Accelerometer.setUpdateInterval(1000); + +() => ( + console.log(error)} + style={{ flex: 1 }} + /> +); + +() => ( + console.log(error)} + onAdMobDispatchAppEvent={(event: AdMobAppEvent) => console.log(event)} + style={{ flex: 1 }} + /> +); + +AdMobInterstitial.setAdUnitID('ca-app-pub-3940256099942544/1033173712'); // Test ID, Replace with your-admob-unit-id +AdMobInterstitial.setTestDeviceID('EMULATOR'); +async () => { + await AdMobInterstitial.requestAdAsync(); + await AdMobInterstitial.showAdAsync(); +}; + +AdMobRewarded.setAdUnitID('ca-app-pub-3940256099942544/1033173712'); // Test ID, Replace with your-admob-unit-id +AdMobRewarded.setTestDeviceID('EMULATOR'); +async () => { + await AdMobRewarded.requestAdAsync(); + await AdMobRewarded.showAdAsync(); +}; + +Amplitude.initialize('key'); +Amplitude.setUserId('userId'); +Amplitude.setUserProperties({key: 1}); +Amplitude.clearUserProperties(); +Amplitude.logEvent('name'); +Amplitude.logEventWithProperties('event', {key: 'value'}); +Amplitude.setGroup('type', ['value']); + +const asset = Asset.fromModule(1); +asset.downloadAsync(); +Asset.loadAsync(1); +Asset.loadAsync([1, 2, 3]); +const asset1 = new Asset({ + uri: 'uri', + type: 'type', + name: 'name', + hash: 'hash', + width: 122, + height: 122 +}); + +const url = AuthSession.getRedirectUrl(); +AuthSession.dismiss(); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: 'url2' +}).then(result => { + switch (result.type) { + case 'success': + result.event; + result.params; + break; + case 'error': + result.errorCode; + result.params; + result.event; + break; + case 'dismissed': + case 'cancel': + result.type; + break; + } +}); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: undefined +}); + +Audio.setAudioModeAsync({ + shouldDuckAndroid: false, + playsInSilentModeIOS: true, + interruptionModeIOS: 2, + interruptionModeAndroid: 1, + allowsRecordingIOS: true, +}); +Audio.setIsEnabledAsync(true); + +Audio.INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS === 0; +Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX === 1; +Audio.INTERRUPTION_MODE_IOS_DUCK_OTHERS === 2; + +Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX === 1; +Audio.INTERRUPTION_MODE_ANDROID_DUCK_OTHERS === 2; + +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT === 0; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_THREE_GPP === 1; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4 === 2; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_NB === 3; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_WB === 4; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADIF === 5; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADTS === 6; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_RTP_AVP === 7; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG2TS === 8; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_WEBM === 9; + +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT === 0; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_NB === 1; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_WB === 2; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC === 3; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_HE_AAC === 4; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC_ELD === 5; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_VORBIS === 6; + +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_LINEARPCM === 'lpcm'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AC3 === 'ac-3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_60958AC3 === 'cac3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLEIMA4 === 'ima4'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC === 'aac '; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4CELP === 'celp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4HVXC === 'hvxc'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4TWINVQ === 'twvq'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE3 === 'MAC3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE6 === 'MAC6'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ULAW === 'ulaw'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ALAW === 'alaw'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN === 'QDMC'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN2 === 'QDM2'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QUALCOMM === 'Qclp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER1 === '.mp1'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER2 === '.mp2'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER3 === '.mp3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLELOSSLESS === 'alac'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE === 'aach'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_LD === 'aacl'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD === 'aace'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_SBR === 'aacf'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_V2 === 'aacg'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE_V2 === 'aacp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_SPATIAL === 'aacs'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR === 'samr'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR_WB === 'sawb'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AUDIBLE === 'AUDB'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ILBC === 'ilbc'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_DVIINTELIMA === 0x6d730011; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MICROSOFTGSM === 0x6d730031; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AES3 === 'aes3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ENHANCEDAC3 === 'ec-3'; + +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MIN === 0; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_LOW === 0x20; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MEDIUM === 0x40; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH === 0x60; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MAX === 0x7f; + +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_CONSTANT === 0; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_LONG_TERM_AVERAGE === 1; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE_CONSTRAINED === 2; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE === 3; + +Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY; +Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY; +async () => { + const result = await Audio.Sound.createAsync({uri: 'uri'}, { + volume: 0.55, + rate: 16.5 + }, null, true); + + const sound = result.sound; + const status = result.status; + + if (!status.isLoaded) { + status.error; + } else { + status.didJustFinish; + // etc. + } + + const _status = await sound.getStatusAsync(); + await sound.loadAsync({uri: 'uri'}); +}; + +() => ( + Promise.resolve()} + onFinish={() => {}} + onError={(error) => console.log(error)} /> +); +() => ( + +); + +const barcodeReadCallback = () => {}; +() => ( + +); + +() => ( + +); + +async () => { + await Brightness.setBrightnessAsync(0.65); + await Brightness.setSystemBrightnessAsync(0.75); + const br1 = await Brightness.getBrightnessAsync(); + const br2 = await Brightness.getSystemBrightnessAsync(); +}; + +Camera.Constants.AutoFocus; +Camera.Constants.Type; +Camera.Constants.FlashMode; +Camera.Constants.WhiteBalance; +Camera.Constants.VideoQuality; +Camera.Constants.BarCodeType; +() => { + return( { + if (component) { + component.recordAsync(); + } + }} />); +}; +async (camera: CameraObject) => { + const picture = await camera.takePictureAsync({ + quality: 0.5, + base64: true, + exif: true + }); + + picture.uri; + picture.width; + picture.height; + picture.exif; + picture.base64; + + camera.takePictureAsync({ + quality: 1, + onPictureSaved: pic => { + pic.uri; + pic.width; + pic.height; + pic.exif; + pic.base64; + } + }); +}; + +async () => { + const result = await DocumentPicker.getDocumentAsync(); + + if (result.type === 'success') { + result.name; + result.uri; + result.size; + } +}; + +async () => { + const { type, expires, token } = await Facebook.logInWithReadPermissionsAsync("appId"); +}; + +() => ( + {}} + onError={() => {}} /> +); + +async () => { + const info = await FileSystem.getInfoAsync('file'); + + info.exists; + info.isDirectory; + + if (info.exists) { + info.md5; + info.uri; + info.size; + info.modificationTime; + } + + const string: string = await FileSystem.readAsStringAsync('file'); + await FileSystem.writeAsStringAsync('file', 'content'); + await FileSystem.deleteAsync('file'); + await FileSystem.moveAsync({ from: 'from', to: 'to'}); + await FileSystem.copyAsync({ from: 'from', to: 'to' }); + await FileSystem.makeDirectoryAsync('dir'); + const dirs: string[] = await FileSystem.readDirectoryAsync('dir'); + const result = await FileSystem.downloadAsync('from', 'to'); + + result.headers; + result.status; + result.uri; + result.md5; +}; + +async () => { + // Video test + const result = await ImagePicker.launchImageLibraryAsync({ + mediaTypes: ImagePicker.MediaTypeOptions.Videos, + }); + + if (!result.cancelled) { + result.uri; + result.width; + result.height; + result.duration; + result.type; + } +}; + +async () => { + // Image test + const result = await ImagePicker.launchImageLibraryAsync({ + mediaTypes: ImagePicker.MediaTypeOptions.Images, + base64: true, + aspect: [4, 3], + quality: 1, + exif: true, + }); + + if (!result.cancelled) { + result.uri; + result.width; + result.height; + result.exif; + result.base64; + result.type; + } +}; + +async () => { + const result = await ImageManipulator.manipulateAsync('url', [ + { rotate: 90 }, + { resize: { width: 300 } }, + { resize: { height: 300 } }, + { resize: { height: 300, width: 300 } }, + ], { + compress: 0.75 + }); + + result.height; + result.uri; + result.width; +}; + +async () => { + const result = await ImageManipulator.manipulateAsync('url', [ + { rotate: 360 }, + { resize: { width: 300 } }, + { resize: { height: 300 } }, + { resize: { height: 300, width: 300 } }, + ], { + compress: 0.75 + }); + + result.height; + result.uri; + result.width; +}; + +FaceDetector.Constants.Mode.fast; +FaceDetector.Constants.Mode.accurate; +FaceDetector.Constants.Landmarks.all; +FaceDetector.Constants.Landmarks.none; +FaceDetector.Constants.Classifications.all; +FaceDetector.Constants.Classifications.none; +async () => { + const result = await FaceDetector.detectFaces('url', { + mode: FaceDetector.Constants.Mode.fast, + detectLandmarks: FaceDetector.Constants.Landmarks.all, + runClassifications: FaceDetector.Constants.Classifications.none + }); + + result.faces[0]; +}; + +async () => { + function isBoolean(x: boolean) { + } + function isString(x: string) { + } + // Two examples of members inherited from react-native Linking + // to prove that inheritence is working. + Linking.addEventListener('url', (e) => { + e.url === ''; + }); + isBoolean(await Linking.canOpenURL('expo://')); + + // Extensions added by expo. + + isString(Linking.makeUrl('path')); + isString(Linking.makeUrl('path', { q: 2, u: 'ery', })); + + const { + path, + queryParams, + } = Linking.parse(''); + isString(path); + isString(queryParams['x'] || ''); + + const { + path: path2, + queryParams: queryParams2, + } = await Linking.parseInitialURLAsync(); + isString(path2); + isString(queryParams2['y'] || ''); +}; + +// #region securestore +async () => { + await SecureStore.setItemAsync('some-key', 'some-val', { + keychainService: "some-service", + keychainAccessible: SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY, + }); + const result = await SecureStore.getItemAsync('some-key', { keychainService: "some-service" }); + if (result != null) { + result.slice() === 'some-val'; + } + await SecureStore.deleteItemAsync('some-key', { keychainService: "some-service" }); +}; + +const allSecureStoreKeychainAccessibleValues: number[] = [ + SecureStore.WHEN_UNLOCKED, + SecureStore.AFTER_FIRST_UNLOCK, + SecureStore.ALWAYS, + SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY, + SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY, + SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY, + SecureStore.ALWAYS_THIS_DEVICE_ONLY, +]; +// #endregion + +() => ( + + + + + + + + + STROKED TEXT + + + + + + + + We go up and down, + then up again + + + + + + + + + + + + + + + + + + + + + + +); + +() => ( + +); + +IntentLauncherAndroid.ACTION_ACCESSIBILITY_SETTINGS === 'android.settings.ACCESSIBILITY_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_NOTIFICATION_REDACTION === 'android.settings.ACTION_APP_NOTIFICATION_REDACTION'; +IntentLauncherAndroid.ACTION_CONDITION_PROVIDER_SETTINGS === 'android.settings.ACTION_CONDITION_PROVIDER_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_LISTENER_SETTINGS === 'android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS'; +IntentLauncherAndroid.ACTION_PRINT_SETTINGS === 'android.settings.ACTION_PRINT_SETTINGS'; +IntentLauncherAndroid.ACTION_ADD_ACCOUNT_SETTINGS === 'android.settings.ADD_ACCOUNT_SETTINGS'; +IntentLauncherAndroid.ACTION_AIRPLANE_MODE_SETTINGS === 'android.settings.AIRPLANE_MODE_SETTINGS'; +IntentLauncherAndroid.ACTION_APN_SETTINGS === 'android.settings.APN_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_DETAILS_SETTINGS === 'android.settings.APPLICATION_DETAILS_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_DEVELOPMENT_SETTINGS === 'android.settings.APPLICATION_DEVELOPMENT_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_SETTINGS === 'android.settings.APPLICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_NOTIFICATION_SETTINGS === 'android.settings.APP_NOTIFICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_OPS_SETTINGS === 'android.settings.APP_OPS_SETTINGS'; +IntentLauncherAndroid.ACTION_BATTERY_SAVER_SETTINGS === 'android.settings.BATTERY_SAVER_SETTINGS'; +IntentLauncherAndroid.ACTION_BLUETOOTH_SETTINGS === 'android.settings.BLUETOOTH_SETTINGS'; +IntentLauncherAndroid.ACTION_CAPTIONING_SETTINGS === 'android.settings.CAPTIONING_SETTINGS'; +IntentLauncherAndroid.ACTION_CAST_SETTINGS === 'android.settings.CAST_SETTINGS'; +IntentLauncherAndroid.ACTION_DATA_ROAMING_SETTINGS === 'android.settings.DATA_ROAMING_SETTINGS'; +IntentLauncherAndroid.ACTION_DATE_SETTINGS === 'android.settings.DATE_SETTINGS'; +IntentLauncherAndroid.ACTION_DEVICE_INFO_SETTINGS === 'android.settings.DEVICE_INFO_SETTINGS'; +IntentLauncherAndroid.ACTION_DEVICE_NAME === 'android.settings.DEVICE_NAME'; +IntentLauncherAndroid.ACTION_DISPLAY_SETTINGS === 'android.settings.DISPLAY_SETTINGS'; +IntentLauncherAndroid.ACTION_DREAM_SETTINGS === 'android.settings.DREAM_SETTINGS'; +IntentLauncherAndroid.ACTION_HARD_KEYBOARD_SETTINGS === 'android.settings.HARD_KEYBOARD_SETTINGS'; +IntentLauncherAndroid.ACTION_HOME_SETTINGS === 'android.settings.HOME_SETTINGS'; +IntentLauncherAndroid.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS === 'android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS === 'android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS'; +IntentLauncherAndroid.ACTION_INPUT_METHOD_SETTINGS === 'android.settings.INPUT_METHOD_SETTINGS'; +IntentLauncherAndroid.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS === 'android.settings.INPUT_METHOD_SUBTYPE_SETTINGS'; +IntentLauncherAndroid.ACTION_INTERNAL_STORAGE_SETTINGS === 'android.settings.INTERNAL_STORAGE_SETTINGS'; +IntentLauncherAndroid.ACTION_LOCALE_SETTINGS === 'android.settings.LOCALE_SETTINGS'; +IntentLauncherAndroid.ACTION_LOCATION_SOURCE_SETTINGS === 'android.settings.LOCATION_SOURCE_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS === 'android.settings.MANAGE_ALL_APPLICATIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_APPLICATIONS_SETTINGS === 'android.settings.MANAGE_APPLICATIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_DEFAULT_APPS_SETTINGS === 'android.settings.MANAGE_DEFAULT_APPS_SETTINGS'; +IntentLauncherAndroid.ACTION_MEMORY_CARD_SETTINGS === 'android.settings.MEMORY_CARD_SETTINGS'; +IntentLauncherAndroid.ACTION_MONITORING_CERT_INFO === 'android.settings.MONITORING_CERT_INFO'; +IntentLauncherAndroid.ACTION_NETWORK_OPERATOR_SETTINGS === 'android.settings.NETWORK_OPERATOR_SETTINGS'; +IntentLauncherAndroid.ACTION_NFCSHARING_SETTINGS === 'android.settings.NFCSHARING_SETTINGS'; +IntentLauncherAndroid.ACTION_NFC_PAYMENT_SETTINGS === 'android.settings.NFC_PAYMENT_SETTINGS'; +IntentLauncherAndroid.ACTION_NFC_SETTINGS === 'android.settings.NFC_SETTINGS'; +IntentLauncherAndroid.ACTION_NIGHT_DISPLAY_SETTINGS === 'android.settings.NIGHT_DISPLAY_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS === 'android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_SETTINGS === 'android.settings.NOTIFICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_PAIRING_SETTINGS === 'android.settings.PAIRING_SETTINGS'; +IntentLauncherAndroid.ACTION_PRIVACY_SETTINGS === 'android.settings.PRIVACY_SETTINGS'; +IntentLauncherAndroid.ACTION_QUICK_LAUNCH_SETTINGS === 'android.settings.QUICK_LAUNCH_SETTINGS'; +IntentLauncherAndroid.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS === 'android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS'; +IntentLauncherAndroid.ACTION_SECURITY_SETTINGS === 'android.settings.SECURITY_SETTINGS'; +IntentLauncherAndroid.ACTION_SETTINGS === 'android.settings.SETTINGS'; +IntentLauncherAndroid.ACTION_SHOW_ADMIN_SUPPORT_DETAILS === 'android.settings.SHOW_ADMIN_SUPPORT_DETAILS'; +IntentLauncherAndroid.ACTION_SHOW_INPUT_METHOD_PICKER === 'android.settings.SHOW_INPUT_METHOD_PICKER'; +IntentLauncherAndroid.ACTION_SHOW_REGULATORY_INFO === 'android.settings.SHOW_REGULATORY_INFO'; +IntentLauncherAndroid.ACTION_SHOW_REMOTE_BUGREPORT_DIALOG === 'android.settings.SHOW_REMOTE_BUGREPORT_DIALOG'; +IntentLauncherAndroid.ACTION_SOUND_SETTINGS === 'android.settings.SOUND_SETTINGS'; +IntentLauncherAndroid.ACTION_STORAGE_MANAGER_SETTINGS === 'android.settings.STORAGE_MANAGER_SETTINGS'; +IntentLauncherAndroid.ACTION_SYNC_SETTINGS === 'android.settings.SYNC_SETTINGS'; +IntentLauncherAndroid.ACTION_SYSTEM_UPDATE_SETTINGS === 'android.settings.SYSTEM_UPDATE_SETTINGS'; +IntentLauncherAndroid.ACTION_TETHER_PROVISIONING_UI === 'android.settings.TETHER_PROVISIONING_UI'; +IntentLauncherAndroid.ACTION_TRUSTED_CREDENTIALS_USER === 'android.settings.TRUSTED_CREDENTIALS_USER'; +IntentLauncherAndroid.ACTION_USAGE_ACCESS_SETTINGS === 'android.settings.USAGE_ACCESS_SETTINGS'; +IntentLauncherAndroid.ACTION_USER_DICTIONARY_INSERT === 'android.settings.USER_DICTIONARY_INSERT'; +IntentLauncherAndroid.ACTION_USER_DICTIONARY_SETTINGS === 'android.settings.USER_DICTIONARY_SETTINGS'; +IntentLauncherAndroid.ACTION_USER_SETTINGS === 'android.settings.USER_SETTINGS'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_AIRPLANE_MODE === 'android.settings.VOICE_CONTROL_AIRPLANE_MODE'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE === 'android.settings.VOICE_CONTROL_BATTERY_SAVER_MODE'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE === 'android.settings.VOICE_CONTROL_DO_NOT_DISTURB_MODE'; +IntentLauncherAndroid.ACTION_VOICE_INPUT_SETTINGS === 'android.settings.VOICE_INPUT_SETTINGS'; +IntentLauncherAndroid.ACTION_VPN_SETTINGS === 'android.settings.VPN_SETTINGS'; +IntentLauncherAndroid.ACTION_VR_LISTENER_SETTINGS === 'android.settings.VR_LISTENER_SETTINGS'; +IntentLauncherAndroid.ACTION_WEBVIEW_SETTINGS === 'android.settings.WEBVIEW_SETTINGS'; +IntentLauncherAndroid.ACTION_WIFI_IP_SETTINGS === 'android.settings.WIFI_IP_SETTINGS'; +IntentLauncherAndroid.ACTION_WIFI_SETTINGS === 'android.settings.WIFI_SETTINGS'; +IntentLauncherAndroid.ACTION_WIRELESS_SETTINGS === 'android.settings.WIRELESS_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_AUTOMATION_SETTINGS === 'android.settings.ZEN_MODE_AUTOMATION_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_EVENT_RULE_SETTINGS === 'android.settings.ZEN_MODE_EVENT_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS === 'android.settings.ZEN_MODE_EXTERNAL_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_PRIORITY_SETTINGS === 'android.settings.ZEN_MODE_PRIORITY_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS === 'android.settings.ZEN_MODE_SCHEDULE_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_SETTINGS === 'android.settings.ZEN_MODE_SETTINGS'; + +KeepAwake.activate(); +KeepAwake.deactivate(); + +() => ( + +); + +() => ( + +); + +Permissions.CAMERA === 'camera'; +Permissions.CAMERA_ROLL === 'cameraRoll'; +Permissions.AUDIO_RECORDING === 'audioRecording'; +Permissions.CONTACTS === 'contacts'; +Permissions.NOTIFICATIONS === 'notifications'; +Permissions.SYSTEM_BRIGHTNESS === 'systemBrightness'; +Permissions.USER_FACING_NOTIFICATIONS === 'userFacingNotifications'; +Permissions.REMINDERS === 'reminders'; +async () => { + const result = await Permissions.askAsync(Permissions.CAMERA, Permissions.CONTACTS); + + result.status === 'granted'; + result.status === 'denied'; + result.status === 'undetermined'; + + result.expires === 'never'; +}; + +ScreenOrientation.Orientation.ALL; +ScreenOrientation.allow(ScreenOrientation.Orientation.ALL); + +class __TestEntry__ extends React.Component { + render() { + return( + test + ); + } +} +registerRootComponent(__TestEntry__); + +Calendar.EntityTypes.EVENT === 'event'; +Calendar.EntityTypes.REMINDER === 'reminder'; + +Calendar.CalendarType.LOCAL === 'local'; +Calendar.CalendarType.CALDAV === 'caldav'; +Calendar.CalendarType.EXCHANGE === 'exchange'; +Calendar.CalendarType.SUBSCRIBED === 'subscribed'; +Calendar.CalendarType.BIRTHDAYS === 'birthdays'; + +async () => { + const result = await Calendar.getCalendarsAsync(Calendar.EntityTypes.EVENT); + result.length; + + const calendar = result[0]; + calendar.id === ''; + calendar.title === ''; + calendar.sourceId === ''; + calendar.type === Calendar.CalendarType.BIRTHDAYS; + calendar.color === ''; + calendar.entityType === Calendar.EntityTypes.EVENT; + calendar.allowsModifications === true; + calendar.allowedAvailabilities === ['']; + calendar.isPrimary === true; + calendar.name === ''; + calendar.ownerAccount === ''; + calendar.timeZone === ''; + calendar.allowedReminders === ['']; + calendar.allowedAttendeeTypes === ['']; + calendar.isVisible === false; + calendar.isSynced === false; + calendar.accessLevel === Calendar.CalendarAccessLevel.CONTRIBUTOR; + + if (calendar.source) { + calendar.source.id === ''; + calendar.source.type === ''; + calendar.source.name === ''; + calendar.source.isLocalAccount === false; + } + + const id1 = await Calendar.createCalendarAsync({ + accessLevel: Calendar.CalendarAccessLevel.EDITOR + }); + + id1 === ''; + + const id2 = await Calendar.updateCalendarAsync('1234', { + isVisible: false + }); + + id2 === ''; + + const id3 = await Calendar.updateCalendarAsync('1234', null); + + await Calendar.deleteCalendarAsync('1234'); + + const events = await Calendar.getEventsAsync( + ['123', '124'], + new Date(), + new Date() + ); + + const event1 = events[0]; + + event1.accessLevel === Calendar.EventAccessLevel.CONFIDENTIAL; + event1.alarms === []; + event1.allDay === true; + event1.availability === Calendar.Availability.FREE; + event1.calendarId === ''; + event1.creationDate === ''; + event1.endDate === ''; + event1.endTimeZone === ''; + event1.guestsCanInviteOthers === true; + event1.guestsCanModify === true; + event1.guestsCanSeeGuests === false; + event1.id === ''; + event1.instanceId === ''; + event1.isDetached === false; + + const event2 = await Calendar.getEventAsync('123', { + futureEvents: true + }); + + const eventId1 = await Calendar.createEventAsync('123'); + + const eventId2 = await Calendar.updateEventAsync('1234'); + + await Calendar.deleteEventAsync('1234'); + + const attendees = await Calendar.getAttendeesForEventAsync('123'); + + const aId1 = await Calendar.createAttendeeAsync('123'); + + const aId2 = await Calendar.updateAttendeeAsync('123'); + + await Calendar.deleteAttendeeAsync('123'); + + const reminders = await Calendar.getRemindersAsync(['123']); + + const reminder = await Calendar.getReminderAsync('123'); + + const remId1 = await Calendar.createReminderAsync('123'); + + const remId2 = await Calendar.updateReminderAsync('123'); + + await Calendar.deleteReminderAsync('123'); + + const sources = await Calendar.getSourcesAsync(); + + const source = await Calendar.getSourceAsync('123'); + + Calendar.openEventInCalendar('123'); +}; + +async () => { + const result = await MailComposer.composeAsync({ + subject: 'sss' + }); + + result.status === 'saved'; +}; + +// #region MapView +const initialRegion: Region = { + latitude: 0, + longitude: 0, + latitudeDelta: 0, + longitudeDelta: 0, +}; + +const edgePadding: EdgePadding = { + top: 0, + right: 0, + bottom: 0, + left: 0, +}; + +const edgeInsets: EdgeInsets = { + top: 0, + right: 0, + bottom: 0, + left: 0, +}; + +const mapStyleElements: MapStyleElement[] = [{ + featureType: 'featureType', + elementType: 'elementType', + stylers: [{}, {}], +}]; + +const mapEventCallback = (event: MapEvent) => console.log(event); +const regionCallback = (region: Region) => console.log(region); +const kmlCallback = (kml: KmlMapEvent) => console.log(kml); +const userLocationCallback = (event: EventUserLocation) => console.log(event); + +() => ( + ({})} + onKmlReady={kmlCallback} + onRegionChange={regionCallback} + onRegionChangeComplete={regionCallback} + onPress={mapEventCallback} + onLongPress={mapEventCallback} + onUserLocationChange={userLocationCallback} + onPanDrag={mapEventCallback} + onPoiClick={(event: MapEvent<{ placeId: string, name: string }>) => console.log(event)} + onMarkerPress={(event: MapEvent<{ action: 'marker-press', id: string }>) => console.log(event)} + onMarkerSelect={(event: MapEvent<{ action: 'marker-select', id: string }>) => console.log(event)} + onMarkerDeselect={(event: MapEvent<{ action: 'marker-deselect', id: string }>) => console.log(event)} + onCalloutPress={(event: MapEvent<{ action: 'callout-press' }>) => console.log(event)} + onMarkerDragStart={mapEventCallback} + onMarkerDrag={mapEventCallback} + onMarkerDragEnd={mapEventCallback} + + minZoomLevel={0} + maxZoomLevel={0} + kmlSrc="src" + style={{ flex: 1 }} + /> +); +// #endregion + +async () => { + const updateEventListener: Updates.UpdateEventListener = ({ type }) => { + switch (type) { + case Updates.EventType.DOWNLOAD_STARTED: + case Updates.EventType.DOWNLOAD_PROGRESS: + case Updates.EventType.DOWNLOAD_FINISHED: + case Updates.EventType.NO_UPDATE_AVAILABLE: + case Updates.EventType.ERROR: + return true; + } + }; + + Updates.reload(); + + Updates.reloadFromCache(); + + Updates.addListener(updateEventListener); + + const updateCheckResult = await Updates.checkForUpdateAsync(); + + if (updateCheckResult.isAvailable) { + console.log(updateCheckResult.manifest); + } + + Updates.fetchUpdateAsync({ eventListener: updateEventListener }); + + const bundleFetchResult = await Updates.fetchUpdateAsync(); + + if (bundleFetchResult.isNew) { + console.log(bundleFetchResult.manifest); + } +}; + +async () => { + const asset: MediaLibrary.Asset = await MediaLibrary.createAssetAsync('some-url'); + const getAssetsOptions: MediaLibrary.GetAssetsOptions = { + first: 0, + after: 'lastAssetId', + album: 'albumId', + sortBy: MediaLibrary.SortBy.creationTime, + mediaType: MediaLibrary.MediaType.photo + }; + const assetsList: MediaLibrary.GetAssetsResult = await MediaLibrary.getAssetsAsync(getAssetsOptions); + const endCursor: string = assetsList.endCursor; + const hasNextPage: boolean = assetsList.hasNextPage; + const totalCount: number = assetsList.totalCount; + const asset1: MediaLibrary.Asset = await MediaLibrary.getAssetInfoAsync(asset); + if (await MediaLibrary.deleteAssetsAsync(assetsList.assets)) { + console.log('assets deleted'); + } + const albums: MediaLibrary.Album[] = await MediaLibrary.getAlbumsAsync(); + const album: MediaLibrary.Album | null = await MediaLibrary.getAlbumAsync('albumName'); + const album1: MediaLibrary.Album = await MediaLibrary.createAlbumAsync('albumName', asset1); + if (await MediaLibrary.addAssetsToAlbumAsync([asset, asset1], album1, true)) { + console.log('assets added'); + } + + const moments: MediaLibrary.Album[] = await MediaLibrary.getMomentsAsync(); + + switch (getAssetsOptions.mediaType) { + case MediaLibrary.MediaType.audio: + case MediaLibrary.MediaType.photo: + case MediaLibrary.MediaType.video: + case MediaLibrary.MediaType.unknow: + return true; + } + + switch (getAssetsOptions.sortBy) { + case MediaLibrary.SortBy.default: + case MediaLibrary.SortBy.id: + case MediaLibrary.SortBy.creationTime: + case MediaLibrary.SortBy.modificationTime: + case MediaLibrary.SortBy.mediaType: + case MediaLibrary.SortBy.width: + case MediaLibrary.SortBy.height: + case MediaLibrary.SortBy.duration: + return true; + } +}; + +// #region MediaLibrary +async () => { + const mlAsset: MediaLibrary.Asset = await MediaLibrary.createAssetAsync('localUri'); + const mlAssetResult: MediaLibrary.GetAssetsResult = await MediaLibrary.getAssetsAsync({ + first: 0, + after: '', + album: 'Album', + sortBy: MediaLibrary.SortBy.creationTime, + mediaType: MediaLibrary.MediaType.photo + }); + const mlAsset1: MediaLibrary.Asset = await MediaLibrary.getAssetInfoAsync(mlAsset); + const areDeleted: boolean = await MediaLibrary.deleteAssetsAsync([mlAsset]); + const albums: MediaLibrary.Album[] = await MediaLibrary.getAlbumsAsync(); + const album: MediaLibrary.Album = await MediaLibrary.getAlbumAsync('album'); + const album1: MediaLibrary.Album = await MediaLibrary.createAlbumAsync('album', mlAsset); + const areAddedToAlbum: boolean = await MediaLibrary.addAssetsToAlbumAsync([mlAsset, mlAsset1], 'album'); + const areDeletedFromAlbum: boolean = await MediaLibrary.removeAssetsFromAlbumAsync([mlAsset, mlAsset1], 'album'); + const momuents: MediaLibrary.Album[] = await MediaLibrary.getMomentsAsync(); +}; +//#endregion + +// #region Haptic +Haptic.impact(Haptic.ImpactStyles.Heavy); +Haptic.impact(Haptic.ImpactStyles.Light); +Haptic.impact(Haptic.ImpactStyles.Medium); + +Haptic.notification(Haptic.NotificationType.Error); +Haptic.notification(Haptic.NotificationType.Success); +Haptic.notification(Haptic.NotificationType.Error); + +Haptic.selection(); +// #endregion + +// #region Constants +async () => { + const appOwnerShip = Constants.appOwnership; + const expoVersion = Constants.expoVersion; + const installationId = Constants.installationId; + const deviceId = Constants.deviceId; + const deviceName = Constants.deviceName; + const deviceYearClass = Constants.deviceYearClass; + const isDevice = Constants.isDevice; + const platform = Constants.platform; + const sessionId = Constants.sessionId; + const statusBarHeight = Constants.statusBarHeight; + const systemFonts = Constants.systemFonts; + const manifest = Constants.manifest; + const linkingUri = Constants.linkingUri; + const userAgent: string = await Constants.getWebViewUserAgentAsync(); +}; +// #endregion + +// #region Contacts +Contacts.Fields.ID === 'id'; +Contacts.Fields.Name === 'name'; +Contacts.Fields.FirstName === 'firstName'; +Contacts.Fields.MiddleName === 'middleName'; +Contacts.Fields.LastName === 'lastName'; +Contacts.Fields.NamePrefix === 'namePrefix'; +Contacts.Fields.NameSuffix === 'nameSuffix'; +Contacts.Fields.PhoneticFirstName === 'phoneticFirstName'; +Contacts.Fields.PhoneticMiddleName === 'phoneticMiddleName'; +Contacts.Fields.PhoneticLastName === 'phoneticLastName'; +Contacts.Fields.Birthday === 'birthday'; +Contacts.Fields.Emails === 'emails'; +Contacts.Fields.PhoneNumbers === 'phoneNumbers'; +Contacts.Fields.Addresses === 'addresses'; +Contacts.Fields.InstantMessageAddresses === 'instantMessageAddresses'; +Contacts.Fields.UrlAddresses === 'urlAddresses'; +Contacts.Fields.Company === 'company'; +Contacts.Fields.JobTitle === 'jobTitle'; +Contacts.Fields.Department === 'department'; +Contacts.Fields.ImageAvailable === 'imageAvailable'; +Contacts.Fields.Image === 'image'; +Contacts.Fields.Note === 'note'; +Contacts.Fields.Dates === 'dates'; +Contacts.Fields.Relationships === 'relationships'; +Contacts.Fields.Nickname === 'nickname'; +Contacts.Fields.RawImage === 'rawImage'; +Contacts.Fields.MaidenName === 'maidenName'; +Contacts.Fields.ContactType === 'contactType'; +Contacts.Fields.SocialProfiles === 'socialProfiles'; +Contacts.Fields.NonGregorianBirthday === 'nonGregorianBirthday'; + +const contact: Contacts.Contact = { + [Contacts.Fields.ID]: 'id', + [Contacts.Fields.Name]: 'name', + [Contacts.Fields.FirstName]: 'firstName', + [Contacts.Fields.MiddleName]: 'middleName', + [Contacts.Fields.LastName]: 'lastName', + [Contacts.Fields.NamePrefix]: 'namePrefix', + [Contacts.Fields.NameSuffix]: 'nameSuffix', + [Contacts.Fields.PhoneticFirstName]: 'phoneticFirstName', + [Contacts.Fields.PhoneticMiddleName]: 'phoneticMiddleName', + [Contacts.Fields.PhoneticLastName]: 'phoneticLastName', + [Contacts.Fields.Birthday]: { + day: 1, + month: 1, + year: 2010, + format: Contacts.CalendarFormats.Gregorian, + id: 'id', + label: 'label' + }, + [Contacts.Fields.Emails]: [{ + email: 'email', + isPrimary: true, + id: 'id', + label: 'label' + }], + [Contacts.Fields.PhoneNumbers]: [{ + number: 'number', + isPrimary: true, + digits: 'digits', + countryCode: 'countryCode', + id: 'id', + label: 'label' + }], + [Contacts.Fields.Addresses]: [{ + street: 'street', + city: 'city', + country: 'country', + region: 'region', + neighborhood: 'neighborhood', + postalCode: 'postalCode', + poBox: 'poBox', + isoCountryCode: 'isoCountryCode', + id: 'id', + label: 'label' + }], + [Contacts.Fields.InstantMessageAddresses]: [{ + service: 'service', + username: 'username', + localizedProfile: 'localizedProfile', + id: 'id', + label: 'label' + }], + [Contacts.Fields.UrlAddresses]: [{ + url: 'url', + id: 'id', + label: 'label' + }], + [Contacts.Fields.Company]: 'company', + [Contacts.Fields.JobTitle]: 'jobTitle', + [Contacts.Fields.Department]: 'department', + [Contacts.Fields.ImageAvailable]: true, + [Contacts.Fields.Image]: { + uri: 'uri' + }, + [Contacts.Fields.Note]: 'note', + [Contacts.Fields.Dates]: [{ + day: 1, + month: 1, + year: 2010, + format: Contacts.CalendarFormats.Gregorian, + id: 'id', + label: 'label' + }], + [Contacts.Fields.Relationships]: [{ + name: 'name', + id: 'id', + label: 'label' + }], + [Contacts.Fields.Nickname]: 'nickname', + [Contacts.Fields.RawImage]: { + uri: 'uri' + }, + [Contacts.Fields.MaidenName]: 'maidenName', + [Contacts.Fields.ContactType]: Contacts.ContactTypes.Person, + [Contacts.Fields.SocialProfiles]: [{ + service: 'service', + username: 'username', + localizedProfile: 'localizedProfile', + url: 'url', + userId: 'userId', + id: 'id', + label: 'label' + }], + [Contacts.Fields.NonGregorianBirthday]: { + day: 1, + month: 1, + year: 2010, + format: Contacts.CalendarFormats.Hebrew, + id: 'id', + label: 'label' + } +}; + +async () => { + const response1: Contacts.ContactResponse = await Contacts.getContactsAsync(); + const response2: Contacts.ContactResponse = await Contacts.getContactsAsync({ id: 'contactId' }); + + const response3: Contacts.Contact = await Contacts.getContactByIdAsync('contactId'); + const response4: Contacts.Contact = await Contacts.getContactByIdAsync('contactId', [Contacts.Fields.Name]); + + const response5: string = await Contacts.addContactAsync(contact); + const response6: string = await Contacts.addContactAsync(contact, 'containerId'); + + const response7: string = await Contacts.updateContactAsync(contact); + await Contacts.removeContactAsync('contactId'); + const response8: string = await Contacts.writeContactToFileAsync({ id: 'contactId' }); + await Contacts.presentFormAsync('contactId'); + await Contacts.addExistingGroupToContainerAsync('groupId', 'containerId'); + + const response9: string = await Contacts.createGroupAsync('groupId'); + const response10: string = await Contacts.createGroupAsync('groupId', 'containerId'); + + await Contacts.updateGroupNameAsync('groupName', 'groupId'); + await Contacts.removeGroupAsync('groupId'); + await Contacts.addExistingContactToGroupAsync('contactId', 'groupId'); + await Contacts.removeContactFromGroupAsync('contactId', 'groupId'); + + const response11 = await Contacts.getGroupsAsync({ groupName: 'groupName' }); + response11.forEach((_: Contacts.Group) => _); + + const response12: string = await Contacts.getDefaultContainerIdAsync(); + + const response13 = await Contacts.getContainersAsync({ containerId: 'containerId' }); + response13.forEach((_: Contacts.Container) => _); +}; +// #endregion diff --git a/types/expo/v31/index.d.ts b/types/expo/v31/index.d.ts new file mode 100644 index 0000000000..5f560a8546 --- /dev/null +++ b/types/expo/v31/index.d.ts @@ -0,0 +1,3606 @@ +// Type definitions for expo 31.0 +// Project: https://github.com/expo/expo-sdk +// Definitions by: Konstantin Kai +// Martynas Kadiša +// Jan Aagaard +// Sergio Sánchez +// Fernando Helwanger +// Umidbek Karimov +// Moshe Feuchtwanger +// Michael Prokopchuk +// Tina Roh +// Nathan Phillip Brink +// Martin Olsson +// Levan Basharuli +// Pavel Ihm +// Bartosz Dotryw +// Jason Killian +// Satyajit Sahoo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export * from 'react-native-maps'; +export { default as MapView } from 'react-native-maps'; + +import { EventSubscription } from 'fbemitter'; +import { Component, ComponentClass, Ref, ComponentType } from 'react'; +import { + ColorPropType, + ImageRequireSource, + ImageURISource, + LinkingStatic as ReactNativeLinkingStatic, + NativeEventEmitter, + ViewProps, + ViewStyle, + Permission, + StyleProp +} from 'react-native'; + +export type Axis = number; +export type BarCodeScannedCallback = (result: { type: string; data: string; }) => void; +export type Md5 = string; +export type Orientation = 'portrait' | 'landscape'; +export type RequireSource = ImageRequireSource; +export type ResizeModeContain = 'contain'; +export type ResizeModeCover = 'cover'; +export type ResizeModeStretch = 'stretch'; +export type URISource = ImageURISource; + +export interface HashMap { [key: string]: any; } +export interface StringHashMap { [key: string]: string; } + +/** Access the device accelerometer sensor(s) to respond to changes in acceleration in 3d space. */ +export namespace Accelerometer { + interface AccelerometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + /** + * Subscribe for updates to the accelerometer. + * @param listener A callback that is invoked when an accelerometer update is available. When invoked, the listener is provided a single argumument that is an object containing keys x, y, z. + * @returns An EventSubscription object that you can call remove() on when you would like to unsubscribe the listener. + */ + function addListener(listener: (obj: AccelerometerObject) => any): EventSubscription; + + /** Remove all listeners. */ + function removeAllListeners(): void; + + /** + * Subscribe for updates to the accelerometer. + * @param intervalMs Desired interval in milliseconds between accelerometer updates. + */ + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Admob + */ +export type AdMobBannerSize = + | 'banner' + | 'largeBanner' + | 'mediumRectangle' + | 'fullBanner' + | 'leaderboard' + | 'smartBannerPortrait' + | 'smartBannerLandscape'; +export interface AdMobBannerProperties extends ViewProps { + bannerSize?: AdMobBannerSize; + adUnitID?: string; + testDeviceID?: string; + didFailToReceiveAdWithError?(errorDescription: string): void; + adViewDidReceiveAd?(): void; + adViewWillPresentScreen?(): void; + adViewWillDismissScreen?(): void; + adViewDidDismissScreen?(): void; + adViewWillLeaveApplication?(): void; +} + +export class AdMobBanner extends Component { } +export interface AdMobAppEvent { + name: string; + info: string; +} +export interface PublisherBannerProperties extends AdMobBannerProperties { + onAdMobDispatchAppEvent?(event: AdMobAppEvent): void; +} +export class PublisherBanner extends Component { } + +export type AdMobInterstitialEmptyEvent = + | 'interstitialDidLoad' + | 'interstitialDidOpen' + | 'interstitialDidClose' + | 'interstitialWillLeaveApplication'; +export type AdMobInterstitialEvent = AdMobInterstitialEmptyEvent | 'interstitialDidFailToLoad'; +export namespace AdMobInterstitial { + function setAdUnitID(id: string): void; + function setTestDeviceID(id: string): void; + function requestAdAsync(): Promise; + function showAdAsync(): Promise; + function dismissAdAsync(): Promise; + function getIsReadyAsync(): Promise; + function addEventListener(event: 'interstitialDidFailToLoad', handler: (error: string) => void): void; + function addEventListener(event: AdMobInterstitialEmptyEvent, handler: () => void): void; + function removeEventListener(event: 'interstitialDidFailToLoad', handler: (error: string) => void): void; + function removeEventListener(event: AdMobInterstitialEmptyEvent, handler: () => void): void; + function removeAllListeners(): void; +} + +export type AdMobRewardedEmptyEvent = + | 'rewardedVideoDidLoad' + | 'rewardedVideoDidOpen' + | 'rewardedVideoDidStart' + | 'rewardedVideoDidClose' + | 'rewardedVideoWillLeaveApplication'; +export type AdMobRewardedEvent = AdMobRewardedEmptyEvent | 'rewardedVideoDidRewardUser' | 'rewardedVideoDidFailToLoad'; +export namespace AdMobRewarded { + function setAdUnitID(id: string): void; + function setTestDeviceID(id: string): void; + function requestAdAsync(): Promise; + function showAdAsync(): Promise; + function dismissAdAsync(): Promise; + function getIsReadyAsync(): Promise; + function addEventListener(event: 'rewardedVideoDidRewardUser', handler: (type: string, amount: number) => void): void; + function addEventListener(event: 'rewardedVideoDidFailToLoad', handler: (error: string) => void): void; + function addEventListener(event: AdMobRewardedEmptyEvent, handler: () => void): void; + function removeEventListener(event: 'rewardedVideoDidRewardUser', handler: (type: string, amount: number) => void): void; + function removeEventListener(event: 'rewardedVideoDidFailToLoad', handler: (error: string) => void): void; + function removeEventListener(event: AdMobRewardedEmptyEvent, handler: () => void): void; + function removeAllListeners(): void; +} + +/** + * Provides access to Amplitude mobile analytics which basically lets you log various events to the Cloud. This module wraps Amplitude’s iOS and Android SDKs. + * + * Note: Session tracking may not work correctly when running Experiences in the main Expo app. It will work correctly if you create a standalone app. + */ +export namespace Amplitude { + /** Initializes Amplitude with your Amplitude API key. */ + function initialize(apiKey: string): void; + + /** Assign a user ID to the current user. If you don’t have a system for user IDs you don’t need to call this. */ + function setUserId(userId: string): void; + + /** Set properties for the current user. */ + function setUserProperties(userProperties: HashMap): void; + + /** Clear properties set by `setUserProperties()`. */ + function clearUserProperties(): void; + + /** Log an event to Amplitude. */ + function logEvent(eventName: string): void; + + /** Log an event to Amplitude with custom properties. */ + function logEventWithProperties( + eventName: string, + + /** A map of custom properties. */ + properties: HashMap + ): void; + + /** Add the current user to a group. */ + function setGroup( + /** The group name, e.g. `'sports'`. */ + groupType: string, + + /** An array of group names, e.g. `['tennis', 'soccer']`. */ + groupNames: string[] + ): void; +} + +// #region AppLoading +/** The following props are recommended, but optional for the sake of backwards compatibility (they were introduced in SDK21). If you do not provide any props, you are responsible for coordinating loading assets, handling errors, and updating state to unmount the `AppLoading` component. */ +export interface AppLoadingProps { + /** A `function` that returns a `Promise`. The `Promise` should resolve when the app is done loading data and assets. */ + startAsync?: () => Promise; + + /** Required if you provide `startAsync`. Called when `startAsync` resolves or rejects. This should be used to set state and unmount the `AppLoading` component. */ + onFinish?: () => void; + + /** If `startAsync` throws an error, it is caught and passed into the function provided to `onError`. */ + onError?: (error: Error) => void; +} + +/** + * A React component that tells Expo to keep the app loading screen open if it is the first and only component rendered in your app. When it is removed, the loading screen will disappear and your app will be visible. + * + * This is incredibly useful to let you download and cache fonts, logo and icon images and other assets that you want to be sure the user has on their device for an optimal experience before rendering they start using the app. + */ +export class AppLoading extends Component { } +// #endregion AppLoading + +/** This module provides an interface to Expo’s asset system. An asset is any file that lives alongside the source code of your app that the app needs at runtime. Examples include images, fonts and sounds. Expo’s asset system integrates with React Native’s, so that you can refer to files with require('path/to/file'). This is how you refer to static image files in React Native for use in an Image component, for example. */ +export class Asset { + constructor({ name, type, hash, uri, width, height }: { + name: string; + type: string; + hash: string; + uri: string; + width?: number; + height?: number; + }); + + /** The MD5 hash of the asset’s data. */ + hash: Md5; + + /** The name of the asset file without the extension. Also without the part from @ onward in the filename (used to specify scale factor for images). */ + name: string; + + /** The extension of the asset filename. */ + type: string; + + /** A URI that points to the asset’s data on the remote server. When running the published version of your app, this refers to the the location on Expo’s asset server where Expo has stored your asset. When running the app from XDE during development, this URI points to XDE’s server running on your computer and the asset is served directly from your computer. */ + uri: string; + + /** If the asset has been downloaded (by calling `downloadAsync()`), the `file://` URI pointing to the local file on the device that contains the asset data. */ + localUri: string; + + /** If the asset is an image, the width of the image data divided by the scale factor. The scale factor is the number after `@` in the filename, or `1` if not present. */ + width?: number; + + /** If the asset is an image, the height of the image data divided by the scale factor. The scale factor is the number after `@` in the filename, or `1` if not present. */ + height?: number; + + downloading: boolean; + downloaded: boolean; + downloadCallbacks: Array<{ resolve: () => any, reject: (e?: any) => any }>; + + /** Downloads the asset data to a local file in the device’s cache directory. Once the returned promise is fulfilled without error, the localUri field of this asset points to a local file containing the asset data. The asset is only downloaded if an up-to-date local file for the asset isn’t already present due to an earlier download. */ + downloadAsync(): Promise; + + /** Returns the `Expo.Asset` instance representing an asset given its module. */ + static fromModule(module: RequireSource): Asset; + + /** + * A helper that wraps `Expo.Asset.fromModule(module).downloadAsync` for convenience. + * @param moduleIds An array of `require('path/to/file')`. Can also be just one module without an Array. + */ + static loadAsync(module: RequireSource[] | RequireSource): Promise; +} + +/** + * Provides basic sample playback and recording. + * + * Note that Expo does not yet support backgrounding, so audio is not available to play in the background of your experience. Audio also automatically stops if headphones / bluetooth audio devices are disconnected. + */ +export namespace Audio { + enum InterruptionModeIos { + /** This is the default option. If this option is set, your experience’s audio is mixed with audio playing in background apps. */ + INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS = 0, + + /** If this option is set, your experience’s audio interrupts audio from other apps. */ + INTERRUPTION_MODE_IOS_DO_NOT_MIX = 1, + + /** If this option is set, your experience’s audio lowers the volume ("ducks") of audio from other apps while your audio plays. */ + INTERRUPTION_MODE_IOS_DUCK_OTHERS = 2 + } + + const INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS: 0; + const INTERRUPTION_MODE_IOS_DO_NOT_MIX: 1; + const INTERRUPTION_MODE_IOS_DUCK_OTHERS: 2; + + enum InterruptionModeAndroid { + /** If this option is set, your experience’s audio interrupts audio from other apps. */ + INTERRUPTION_MODE_ANDROID_DO_NOT_MIX = 1, + + /** This is the default option. If this option is set, your experience’s audio lowers the volume ("ducks") of audio from other apps while your audio plays. */ + INTERRUPTION_MODE_ANDROID_DUCK_OTHERS = 2 + } + + const INTERRUPTION_MODE_ANDROID_DO_NOT_MIX: 1; + const INTERRUPTION_MODE_ANDROID_DUCK_OTHERS: 2; + + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT: 0; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_THREE_GPP: 1; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4: 2; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_NB: 3; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_WB: 4; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADIF: 5; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADTS: 6; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_RTP_AVP: 7; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG2TS: 8; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_WEBM: 9; + + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT: 0; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_NB: 1; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_WB: 2; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC: 3; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_HE_AAC: 4; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC_ELD: 5; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_VORBIS: 6; + + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_LINEARPCM: 'lpcm'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AC3: 'ac-3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_60958AC3: 'cac3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLEIMA4: 'ima4'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC: 'aac '; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4CELP: 'celp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4HVXC: 'hvxc'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4TWINVQ: 'twvq'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE3: 'MAC3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE6: 'MAC6'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ULAW: 'ulaw'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ALAW: 'alaw'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN: 'QDMC'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN2: 'QDM2'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QUALCOMM: 'Qclp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER1: '.mp1'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER2: '.mp2'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER3: '.mp3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLELOSSLESS: 'alac'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE: 'aach'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_LD: 'aacl'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD: 'aace'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_SBR: 'aacf'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_V2: 'aacg'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE_V2: 'aacp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_SPATIAL: 'aacs'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR: 'samr'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR_WB: 'sawb'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AUDIBLE: 'AUDB'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ILBC: 'ilbc'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_DVIINTELIMA: 0x6d730011; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MICROSOFTGSM: 0x6d730031; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AES3: 'aes3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ENHANCEDAC3: 'ec-3'; + + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MIN: 0; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_LOW: 0x20; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MEDIUM: 0x40; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH: 0x60; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MAX: 0x7f; + + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_CONSTANT: 0; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_LONG_TERM_AVERAGE: 1; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE_CONSTRAINED: 2; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE: 3; + + type RecordingStatus = { + canRecord: false, + isDoneRecording: false + } | { + canRecord: true, + isRecording: boolean, + durationMillis: number + } | { + canRecord: false, + isDoneRecording: true, + durationMillis: number + }; + + const RECORDING_OPTIONS_PRESET_HIGH_QUALITY: RecordingOptions; + const RECORDING_OPTIONS_PRESET_LOW_QUALITY: RecordingOptions; + + interface RecordingOptions { + android: { + extension: string; + outputFormat: number; + audioEncoder: number; + sampleRate?: number; + numberOfChannels?: number; + bitRate?: number; + maxFileSize?: number; + }; + ios: { + extension: string; + outputFormat?: string | number; + audioQuality: number; + sampleRate: number; + numberOfChannels: number; + bitRate: number; + bitRateStrategy?: number; + bitDepthHint?: number; + linearPCMBitDepth?: number; + linearPCMIsBigEndian?: boolean; + linearPCMIsFloat?: boolean; + }; + } + + interface AudioMode { + /** Boolean selecting if your experience’s audio should play in silent mode on iOS. This value defaults to `false`. */ + playsInSilentModeIOS: boolean; + + /** Boolean selecting if recording is enabled on iOS. This value defaults to `false`. NOTE: when this flag is set to true, playback may be routed to the phone receiver instead of to the speaker. */ + allowsRecordingIOS: boolean; + + /** Enum selecting how your experience’s audio should interact with the audio from other apps on iOS. */ + interruptionModeIOS: InterruptionModeIos; + + /** Boolean selecting if your experience’s audio should automatically be lowered in volume ("duck") if audio from another app interrupts your experience. This value defaults to true. If false, audio from other apps will pause your audio. */ + shouldDuckAndroid: boolean; + + /** an enum selecting how your experience’s audio should interact with the audio from other apps on Android: */ + interruptionModeAndroid: InterruptionModeAndroid; + } + + function setIsEnabledAsync(value: boolean): Promise; + function setAudioModeAsync(mode: AudioMode): Promise; + + /** This class represents a sound corresponding to an Asset or URL. */ + class Sound extends PlaybackObject { + constructor(); + + /** + * Creates and loads a sound from source, with optional `initialStatus`, `onPlaybackStatusUpdate`, and `downloadFirst`. + * + * @returns A `Promise` that is rejected if creation failed, or fulfilled with the following dictionary if creation succeeded: + * - `sound`: The newly created and loaded Sound object. + * - `status`: The PlaybackStatus of the Sound object. See the AV documentation for further information. + */ + static createAsync( + /** + * The source of the sound. The following forms are supported: + * + * - A dictionary of the form `{ uri: 'http://path/to/file' }` with a network URL pointing to an audio file on the web. + * - `require('path/to/file')` for an audio file asset in the source code directory. + * - An `Expo.Asset` object for an audio file asset. + */ + source: PlaybackSource, + + /** The initial intended PlaybackStatusToSet of the sound, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. */ + initialStatus?: PlaybackStatusToSet, + + /** A function taking a single parameter PlaybackStatus. This value defaults to `null` if no parameter is passed. */ + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null, + + /** If set to true, the system will attempt to download the resource to the device before loading. This value defaults to `true`. Note that at the moment, this will only work for `source`s of the form `require('path/to/file')` or `Asset` objects. */ + downloadFirst?: boolean + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } + + class Recording { + constructor(); + + /** Gets the `status` of the `Recording`. */ + getStatusAsync(): Promise; + + /** Sets a function to be called regularly with the `status` of the `Recording`. */ + setOnRecordingStatusUpdate(onRecordingStatusUpdate?: (status: RecordingStatus) => void): void; + + /** Sets the interval with which onRecordingStatusUpdate is called while the recording can record. This value defaults to 500 milliseconds. */ + setProgressUpdateInterval(progressUpdateIntervalMillis: number): void; + + /** Loads the recorder into memory and prepares it for recording. This must be called before calling `startAsync()`. This method can only be called if the `Recording` instance has never yet been prepared. */ + prepareToRecordAsync( + /** Options for the recording, including sample rate, bitrate, channels, format, encoder, and extension. If no options are passed to `prepareToRecordAsync()`, the recorder will be created with options `Expo.Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY`. */ + options?: RecordingOptions + ): Promise; + + /** Begins recording. This method can only be called if the `Recording` has been prepared. */ + startAsync(): Promise; + + /** + * Pauses recording. This method can only be called if the Recording has been prepared. + * + * NOTE: This is only available on Android API version 24 and later. + */ + pauseAsync(): Promise; + + /** Stops the recording and deallocates the recorder from memory. This reverts the Recording instance to an unprepared state, and another Recording instance must be created in order to record again. This method can only be called if the `Recording` has been prepared. */ + stopAndUnloadAsync(): Promise; + + /** + * Gets the local URI of the Recording. Note that this will only succeed once the Recording is prepared to record. + * + * @returns A string with the local URI of the `Recording`, or `null` if the `Recording` is not prepared to record. + */ + getURI(): string | null | undefined; + + /** + * Creates and loads a new `Sound` object to play back the `Recording`. Note that this will only succeed once the `Recording` is done recording (once `stopAndUnloadAsync()` has been called). + * + * @returns A Promise that is rejected if creation failed, or fulfilled with the following dictionary if creation succeeded: + * - `sound`: the newly created and loaded Sound object. + * - `status`: the PlaybackStatus of the Sound object. + */ + createNewLoadedSound( + /** The initial intended `PlaybackStatusToSet` of the sound, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. */ + initialStatus?: PlaybackStatusToSet, + + /** A function taking a single parameter `PlaybackStatus`. This value defaults to `null` if no parameter is passed. */ + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } +} + +/** + * AuthSession + */ +export namespace AuthSession { + type StartAsyncResponse = { + type: 'cancel'; + } | { + type: 'dismissed'; + } | { + type: 'success'; + params: HashMap; + event: HashMap; + } | { + type: 'error'; + params: HashMap; + errorCode: string; + event: HashMap; + }; + + function startAsync(options: { authUrl: string; returnUrl?: string; }): Promise; + function dismiss(): void; + function getRedirectUrl(): string; +} + +// #region AV +/** + * AV + */ +export type PlaybackStatus = { + isLoaded: false; + androidImplementation?: string; + + /** Populated exactly once when an error forces the object to unload. */ + error?: string; +} | { + isLoaded: true; + androidImplementation?: string; + uri: string; + progressUpdateIntervalMillis: number; + durationMillis?: number; + positionMillis: number; + playableDurationMillis?: number; + shouldPlay: boolean; + isPlaying: boolean; + isBuffering: boolean; + rate: number; + shouldCorrectPitch: boolean; + volume: number; + isMuted: boolean; + isLooping: boolean; + + /** True exactly once when the track plays to finish. */ + didJustFinish: boolean; +}; + +export interface PlaybackStatusToSet { + androidImplementation?: string; + isLooping?: boolean; + isMuted?: boolean; + positionMillis?: number; + progressUpdateIntervalMillis?: number; + /** The desired playback rate of the media. This value must be between `0.0` and `32.0`. Only available on Android API version 23 and later and iOS. */ + rate?: number; + shouldCorrectPitch?: boolean; + shouldPlay?: boolean; + /** A number between `0.0` (silence) and `1.0` (maximum volume). */ + volume?: number; +} + +export type PlaybackSource = RequireSource | { uri: string } | Asset; + +export class PlaybackObject { + /** + * Gets the `PlaybackStatus` of the `playbackObject`. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject`. + */ + getStatusAsync(): Promise; + + /** + * Loads the media from source into memory and prepares it for playing. This must be called before calling setStatusAsync() or any of the convenience set status methods. This method can only be called if the playbackObject is in an unloaded state. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once it is loaded, or rejects if loading failed. The `Promise` will also reject if the `playbackObject` was already loaded. See below for details on `PlaybackStatus`. + */ + loadAsync( + /** + * The source of the media. The following forms are supported: + * - A dictionary of the form `{ uri: 'http://path/to/file' }` with a network URL pointing to a media file on the web. + * - `require('path/to/file')` for a media file asset in the source code directory. + * - An `Expo.Asset object` for a media file asset. + */ + source: PlaybackSource, + + /** The initial intended `PlaybackStatusToSet` of the `playbackObject`, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. See below for details on `PlaybackStatusToSet` and the default initial playback status. */ + initialStatus?: PlaybackStatusToSet, + + /** If set to `true`, the system will attempt to download the resource to the device before loading. This value defaults to true. Note that at the moment, this will only work for sources of the form `require('path/to/file')` or `Expo.Asset` objects. */ + downloadFirst?: boolean + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: false })`. */ + pauseAsync(): Promise; + + /** + * This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: true })`. + * + * Playback may not start immediately after calling this function for reasons such as buffering. Make sure to update your UI based on the `isPlaying` and `isBuffering` properties of the `PlaybackStatus`. + */ + playAsync(): Promise; + + /** + * This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: true, positionMillis: millis })`. + * + * Playback may not start immediately after calling this function for reasons such as buffering. Make sure to update your UI based on the isPlaying and `isBuffering` properties of the `PlaybackStatus`. + */ + playFromPositionAsync( + /** The desired position of playback in milliseconds. */ + positionMillis: number, + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis, seekMillisToleranceBefore: toleranceMillisBefore, seekMillisToleranceAfter: toleranceMillisAfter })`. The tolerances are used only on iOS. */ + tolerances?: { + toleranceMillisBefore: number, + toleranceMillisAfter: number + } + ): Promise; + + /** + * Replays the item. When using `playFromPositionAsync(0)` the item is seeked to the position at `0` ms. On iOS this method uses internal implementation of the player and is able to play the item from the beginning immediately. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once the new status has been set successfully, or rejects if setting the new status failed. + */ + replayAsync( + /** The new `PlaybackStatusToSet` of the `playbackObject`, whose values will override the current playback status. */ + status: PlaybackStatusToSet + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ isLooping: value })`. */ + setIsLoopingAsync( + /** A boolean describing if the media should play once (`false`) or loop indefinitely (`true`). */ + isLooping: boolean + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ isMuted: value })`. */ + setIsMutedAsync( + /** A boolean describing if the audio of this media should be muted. */ + isMuted: boolean + ): Promise; + + /** + * Sets a function to be called regularly with the `PlaybackStatus` of the `playbackObject`. See below for details on `PlaybackStatus` and an example use case of this function. + * + * `onPlaybackStatusUpdate` will be called whenever a call to the API for this `playbackObject` completes (such as `setStatusAsync()`, `getStatusAsync()`, or `unloadAsync()`), and will also be called at regular intervals while the media is in the loaded state. Set `progressUpdateIntervalMillis` via `setStatusAsync()` or `setProgressUpdateIntervalAsync()` to modify the interval with which `onPlaybackStatusUpdate` is called while loaded. + */ + setOnPlaybackStatusUpdate( + /** A function taking a single parameter `PlaybackStatus`. */ + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void + ): void; + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis })`. */ + setPositionAsync( + positionMillis: number, + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis, seekMillisToleranceBefore: toleranceMillisBefore, seekMillisToleranceAfter: toleranceMillisAfter })`. The tolerances are used only on iOS. */ + tolerances?: { + toleranceMillisBefore: number, + toleranceMillisAfter: number + } + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ progressUpdateIntervalMillis: millis })`. */ + setProgressUpdateIntervalAsync( + /** The new minimum interval in milliseconds between calls of `onPlaybackStatusUpdate`. */ + progressUpdateIntervalMillis: number + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ rate: value, shouldCorrectPitch: shouldCorrectPitch })`. */ + setRateAsync( + /** The desired playback rate of the media. This value must be between `0.0` and `32.0`. Only available on Android API version 23 and later and iOS. */ + rate: number, + /** A boolean describing if we should correct the pitch for a changed rate. If set to `true`, the pitch of the audio will be corrected (so a rate different than `1.0` will timestretch the audio). */ + shouldCorrectPitch: boolean + ): Promise; + + /** Sets a new `PlaybackStatusToSet` on the `playbackObject`. This method can only be called if the media has been loaded. Return a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once the new status has been set successfully, or rejects if setting the new status failed. */ + setStatusAsync( + /** The new `PlaybackStatusToSet` of the `playbackObject`, whose values will override the current playback status. */ + status: PlaybackStatusToSet + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ volume: value })`. */ + setVolumeAsync( + /** A number between `0.0` (silence) and `1.0` (maximum volume). */ + volume: number + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: false, positionMillis: 0 })`. */ + stopAsync(): Promise; + + /** + * Unloads the media from memory. `loadAsync()` must be called again in order to be able to play the media. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once it is unloaded, or rejects if unloading failed. See below for details on `PlaybackStatus`. + */ + unloadAsync(): Promise; +} +// #endregion + +// #region BarCodeScanner +/** + * BarCodeScanner + */ +export interface BarCodeScannerProps extends ViewProps { + type?: 'front' | 'back'; + torchMode?: 'on' | 'off'; + barCodeTypes?: string[]; + onBarCodeScanned?: BarCodeScannedCallback; +} + +export class BarCodeScanner extends Component { + static Constants: { + TorchMode: { + on: string; + off: string + } + } & CameraConstants; +} +// #endregion + +// #region BlurView +/** + * BlurView + */ +export interface BlurViewProps extends ViewProps { + tint: 'light' | 'default' | 'dark'; + intensity: number; +} +export class BlurView extends Component { } +// #endregion + +/** + * An API to get and set screen brightness. + */ +export namespace Brightness { + /** Sets screen brightness. */ + function setBrightnessAsync( + /** A number between `0` and `1`, representing the desired screen brightness. */ + brightnessValue: number + ): Promise; + + /** + * Gets screen brightness. + * @returns A Promise that is resolved with a number between `0` and `1`, representing the current screen brightness. + */ + function getBrightnessAsync(): Promise; + + /** + * Gets global system screen brightness. + * @returns A Promise that is resolved with a number between `0` and `1`, representing the current system screen brightness. + */ + function getSystemBrightnessAsync(): Promise; + + /** Sets global system screen brightness, requires `WRITE_SETTINGS` permissions on Android. */ + function setSystemBrightnessAsync( + /** A number between `0` and `1`, representing the desired screen brightness. */ + brightnessValue: number + ): Promise; +} + +// #region Camera +/** + * Camera + */ +export interface PictureOptions { + quality?: number; + base64?: boolean; + exif?: boolean; + onPictureSaved?: (data: PictureResponse) => void; +} + +export interface PictureResponse { + uri: string; + width: number; + height: number; + exif: string; + base64: string; +} + +export interface RecordingOptions { + quality?: string | number; + maxDuration?: number; + maxFileSize?: number; +} + +export class CameraObject { + takePictureAsync(options?: PictureOptions): Promise; + recordAsync(options: RecordingOptions): Promise<{ uri: string; }>; + stopRecording(): void; + getSupportedRatiosAsync(): Promise; // Android only +} + +export interface CameraProps extends ViewProps { + zoom?: number; + ratio?: string; + /** Distance to plane of sharpest focus. A value between `0` and `1`. `0`: infinity focus, `1`: focus as close as possible. Default: `0`. For Android this is available only for some devices and when `useCamera2Api` is set to `true`. */ + focusDepth?: number; + type?: number | string; + onCameraReady?: () => void; + useCamera2Api?: boolean; + flashMode?: number | string; + whiteBalance?: number | string; + autoFocus?: string | boolean | number; + pictureSize?: string; + videoStabilizationMode?: number; + onMountError?: (error: { message: string }) => void; + barCodeScannerSettings?: { barCodeTypes?: Array; }; + onBarCodeScanned?: BarCodeScannedCallback; + faceDetectorSettings?: { + mode?: number; + runClassifications?: number; + detectLandmarks?: number; + }; + onFacesDetected?: (options: { faces: TrackedFaceFeature[] }) => void; + ref?: Ref; +} + +export interface CameraConstants { + readonly Type: { + back: string; + front: string; + }; + readonly FlashMode: { + on: string; + off: string; + auto: string; + torch: string; + }; + readonly AutoFocus: { + on: string; + off: string; + }; + readonly WhiteBalance: { + auto: string; + sunny: string; + cloudy: string; + shadow: string; + fluorescent: string; + incandescent: string; + }; + readonly VideoQuality: { + [videoQuality: string]: number; + }; + readonly BarCodeType: { + aztec: string; + codabar: string; + code39: string; + code93: string; + code128: string; + code138: string; + code39mod43: string; + datamatrix: string; + ean13: string; + ean8: string; + interleaved2of5: string; + itf14: string; + maxicode: string; + pdf417: string; + rss14: string; + rssexpanded: string; + upc_a: string; + upc_e: string; + upc_ean: string; + qr: string; + }; +} + +export class Camera extends Component { + static readonly Constants: CameraConstants; +} +// #endregion + +/** + * Constants + */ +export namespace Constants { + const appOwnership: 'expo' | 'standalone' | 'guest'; + const expoVersion: string; + const installationId: string; + const deviceId: string; + const deviceName: string; + const deviceYearClass: number; + const isDevice: boolean; + + interface Platform { + ios?: { + platform: string; + model: string; + userInterfaceIdiom: string; + buildNumber: string; + }; + android?: { + versionCode: string; + }; + } + const platform: Platform; + const sessionId: string; + const statusBarHeight: number; + const systemFonts: string[]; + + interface Manifest { + name: string; + description?: string; + slug?: string; + sdkVersion?: string; + version?: string; + orientation?: Orientation; + primaryColor?: string; + privacy?: 'public' | 'unlisted'; + scheme?: string; + icon?: string; + platforms?: string[]; + githubUrl?: string; + notification?: { + icon?: string, + color?: string, + androidMode?: 'default' | 'collapse', + androidCollapsedTitle?: string + }; + loading?: { + icon?: string, + exponentIconColor?: 'white' | 'blue', + exponentIconGrayscale?: 1 | 0, + backgroundImage?: string, + backgroundColor?: string, + hideExponentText?: boolean + }; + appKey?: string; + androidStatusBar?: { + barStyle?: 'light-content' | 'dark-content', + backgroundColor?: string + }; + androidShowExponentNotificationInShellApp?: boolean; + extra?: { + [propName: string]: any + }; + rnCliPath?: any; + entryPoint?: string; + packagerOpts?: { + hostType?: string, + dev?: boolean, + strict?: boolean, + minify?: boolean, + urlType?: string, + urlRandomness?: string, + lanType?: string, + [propName: string]: any + }; + ignoreNodeModulesValidation?: any; + nodeModulesPath?: string; + ios?: { + bundleIdentifier?: string, + buildNumber?: string, + config?: { + usesNonExemptEncryption?: boolean, + googleSignIn?: { + reservedClientId: string + } + }, + supportsTablet?: boolean, + infoPlist?: any + }; + android?: { + package?: string, + versionCode?: string, + config?: { + fabric?: { + apiKey: string, + buildSecret: string + }, + googleMaps?: { + apiKey: string + }, + googleSignIn?: { + apiKey: string, + certificateHash: string + } + } + }; + facebookScheme?: any; + facebookAppId?: string; + facebookDisplayName?: string; + splash?: { + backgroundColor?: string; + resizeMode?: ResizeModeContain | ResizeModeCover; + image?: string; + }; + assetBundlePatterns?: string[]; + releaseChannel: string; + [propName: string]: any; + } + const manifest: Manifest; + const linkingUri: string; + + function getWebViewUserAgentAsync(): Promise; +} + +/** + * Contacts + */ +export namespace Contacts { + // Constants + + namespace Fields { + type ID = 'id'; + type Name = 'name'; + type FirstName = 'firstName'; + type MiddleName = 'middleName'; + type LastName = 'lastName'; + type NamePrefix = 'namePrefix'; + type NameSuffix = 'nameSuffix'; + type PhoneticFirstName = 'phoneticFirstName'; + type PhoneticMiddleName = 'phoneticMiddleName'; + type PhoneticLastName = 'phoneticLastName'; + type Birthday = 'birthday'; + type Emails = 'emails'; + type PhoneNumbers = 'phoneNumbers'; + type Addresses = 'addresses'; + type InstantMessageAddresses = 'instantMessageAddresses'; + type UrlAddresses = 'urlAddresses'; + type Company = 'company'; + type JobTitle = 'jobTitle'; + type Department = 'department'; + type ImageAvailable = 'imageAvailable'; + type Image = 'image'; + type Note = 'note'; + type Dates = 'dates'; + type Relationships = 'relationships'; + type Nickname = 'nickname'; + type RawImage = 'rawImage'; + type MaidenName = 'maidenName'; + type ContactType = 'contactType'; + type SocialProfiles = 'socialProfiles'; + type NonGregorianBirthday = 'nonGregorianBirthday'; + + const ID: ID; + const Name: Name; + const FirstName: FirstName; + const MiddleName: MiddleName; + const LastName: LastName; + const NamePrefix: NamePrefix; + const NameSuffix: NameSuffix; + const PhoneticFirstName: PhoneticFirstName; + const PhoneticMiddleName: PhoneticMiddleName; + const PhoneticLastName: PhoneticLastName; + const Birthday: Birthday; + const Emails: Emails; + const PhoneNumbers: PhoneNumbers; + const Addresses: Addresses; + const InstantMessageAddresses: InstantMessageAddresses; + const UrlAddresses: UrlAddresses; + const Company: Company; + const JobTitle: JobTitle; + const Department: Department; + const ImageAvailable: ImageAvailable; + const Image: Image; + const Note: Note; + const Dates: Dates; + const Relationships: Relationships; + const Nickname: Nickname; + const RawImage: RawImage; + const MaidenName: MaidenName; + const ContactType: ContactType; + const SocialProfiles: SocialProfiles; + const NonGregorianBirthday: NonGregorianBirthday; + } + + type Field = + | Fields.ID + | Fields.Name + | Fields.FirstName + | Fields.MiddleName + | Fields.LastName + | Fields.NamePrefix + | Fields.NameSuffix + | Fields.PhoneticFirstName + | Fields.PhoneticMiddleName + | Fields.PhoneticLastName + | Fields.Birthday + | Fields.Emails + | Fields.PhoneNumbers + | Fields.Addresses + | Fields.InstantMessageAddresses + | Fields.UrlAddresses + | Fields.Company + | Fields.JobTitle + | Fields.Department + | Fields.ImageAvailable + | Fields.Image + | Fields.Note + | Fields.Dates + | Fields.Relationships + | Fields.Nickname + | Fields.RawImage + | Fields.MaidenName + | Fields.ContactType + | Fields.SocialProfiles + | Fields.NonGregorianBirthday; + + namespace FormTypes { + type New = 'new'; + type Unknown = 'unknown'; + type Default = 'default'; + + const New: New; + const Unknown: Unknown; + const Default: Default; + } + + type FormType = FormTypes.New | FormTypes.Unknown | FormTypes.Default; + + /** + * iOS Only + */ + namespace ContactTypes { + type Person = 'person'; + type Company = 'company'; + + const Person: Person; + const Company: Company; + } + + type ContactType = ContactTypes.Person | ContactTypes.Company; + + namespace SortTypes { + type FirstName = 'firstName'; + type LastName = 'lastName'; + type UserDefault = 'userDefault'; + + const FirstName: FirstName; + const LastName: LastName; + const UserDefault: UserDefault; + } + + type SortType = SortTypes.FirstName | SortTypes.LastName | SortTypes.UserDefault; + + /** + * iOS Only + */ + namespace ContainerTypes { + type Local = 'local'; + type Exchange = 'exchange'; + type CardDAV = 'cardDAV'; + type Unassigned = 'unassigned'; + + const Local: Local; + const Exchange: Exchange; + const CardDAV: CardDAV; + const Unassigned: Unassigned; + } + + type ContainerType = ContainerTypes.Local | ContainerTypes.Exchange | ContainerTypes.CardDAV | ContainerTypes.Unassigned; + + namespace CalendarFormats { + type Gregorian = 'gregorian'; + type Chinese = 'chinese'; + type Hebrew = 'hebrew'; + type Islamic = 'islamic'; + + const Gregorian: Gregorian; + const Chinese: Chinese; + const Hebrew: Hebrew; + const Islamic: Islamic; + } + + type CalendarFormat = CalendarFormats.Gregorian | CalendarFormats.Chinese | CalendarFormats.Hebrew | CalendarFormats.Islamic; + + // Types + + /** + * A set of fields that define information about a single entity. + */ + interface Contact { + id: string; + name: string; + firstName?: string; + middleName?: string; + lastName?: string; + maidenName?: string; + namePrefix?: string; + nameSuffix?: string; + nickname?: string; + phoneticFirstName?: string; + phoneticMiddleName?: string; + phoneticLastName?: string; + company?: string; + jobTitle?: string; + department?: string; + note?: string; + imageAvailable?: boolean; + image?: Image; + rawImage?: Image; + contactType: ContactType; + birthday?: ContactDate; + dates?: ContactDate[]; + relationships?: Relationship[]; + emails?: Email[]; + phoneNumbers?: PhoneNumber[]; + addresses?: Address[]; + instantMessageAddresses?: InstantMessageAddress[]; + urlAddresses?: UrlAddress[]; + /** + * iOS only + */ + nonGregorianBirthday?: ContactDate; + /** + * iOS only + */ + socialProfiles?: SocialProfile[]; + } + + interface ContactDate { + day: number; + month: number; + year: number; + format: CalendarFormat; + id: string; + label: string; + } + + interface Relationship { + name: string; + id: string; + label: string; + } + + interface Email { + email: string; + isPrimary: boolean; + id: string; + label: string; + } + + interface PhoneNumber { + number: string; + isPrimary: boolean; + digits: string; + countryCode: string; + id: string; + label: string; + } + + interface Address { + street: string; + city: string; + country: string; + region: string; + neighborhood: string; + postalCode: string; + poBox: string; + isoCountryCode: string; + id: string; + label: string; + } + + /** + * iOS only + */ + interface SocialProfile { + service: string; + username: string; + localizedProfile: string; + url: string; + userId: string; + id: string; + label: string; + } + + interface InstantMessageAddress { + service: string; + username: string; + localizedProfile: string; + id: string; + label: string; + } + + interface UrlAddress { + url: string; + id: string; + label: string; + } + + /** + * Information regarding thumbnail images + */ + interface Image { + uri: string; + /** + * iOS only + * In Android you can get dimensions using `ReactNative.Image.getSize` + */ + width?: number; + /** + * iOS only + * In Android you can get dimensions using `ReactNative.Image.getSize` + */ + height?: number; + /** + * Avoid using Base 64 in React Native + * iOS only + */ + base64?: string; + } + + /** + * A parent to contacts. A contact can belong to multiple groups. + * iOS Only + */ + interface Group { + id: string; + name: string; + } + + /** + * A parent to contacts and groups. + * iOS Only + */ + interface Container { + id: string; + name: string; + } + + /** + * Denotes the functionality of a native contact form + */ + interface FormOptions { + displayedPropertyKeys?: Field[]; + message?: string; + alternateName?: string; + cancelButtonTitle?: string; + groupId?: string; + allowsEditing?: boolean; + allowsActions?: boolean; + shouldShowLinkedContacts?: boolean; + isNew?: boolean; + preventAnimation?: boolean; + } + + /** + * Used to query contacts from the user's device + */ + interface ContactQuery { + fields?: Field[]; + pageSize?: number; + pageOffset?: number; + id?: string; + /** Android Only */ + sort?: SortType; + /** iOS Only */ + name?: string; + /** iOS Only */ + groupId?: string; + /** iOS Only */ + containerID?: string; + /** iOS Only */ + rawContacts?: boolean; + } + + interface ContactResponse { + data: Contact[]; + /** + * This will be true if there are more contacts to retrieve beyond what is returned + */ + hasNextPage: boolean; + /** + * `true` if there are previous contacts that weren't retrieved due to `pageOffset` + */ + hasPreviousPage: boolean; + } + + /** + * Used to query native contact groups. + * iOS Only + */ + interface GroupQuery { + groupName?: string; + groupId?: string; + containerId?: string; + } + + /** + * Used to query native contact containers. + * iOS Only + */ + interface ContainerQuery { + contactId?: string; + groupId?: string; + containerId?: string; + } + + // Methods + + /** + * Return a list of contacts that fit a given criteria. You can get all of the contacts by passing no criteria. + */ + function getContactsAsync(contactQuery?: ContactQuery): Promise; + /** + * Returns a contact matching the input id. Used for gathering precise data about a contact. + */ + function getContactByIdAsync(contactId: string, fields?: Field[]): Promise; + + // iOS Only - temporary + /** + * Creates a new contact and adds it to the system. + * iOS Only - temporary + */ + function addContactAsync(contact: Contact, containerId?: string): Promise; + /** + * Mutate the information of an existing contact. + * iOS Only - temporary + */ + function updateContactAsync(contact: Contact): Promise; + /** + * Delete a contact from the system. + * iOS Only - temporary + */ + function removeContactAsync(contactId: string): Promise; + /** + * Query a set of contacts and write them to a local uri that can be used for sharing with `ReactNative.Share`. + * iOS Only - temporary + */ + function writeContactToFileAsync(contactQuery: ContactQuery): Promise; + + // iOS Only + /** + * Present a native form for manipulating contacts. + * iOS Only + */ + function presentFormAsync(contactId: string, contact?: Contact, formOptions?: FormOptions): Promise; + /** + * Add a group to a container. + * iOS Only + */ + function addExistingGroupToContainerAsync(groupId: string, containerId: string): Promise; + /** + * Create a group with a name, and add it to a container. If the container is undefined, the default container will be targeted. + * iOS Only + */ + function createGroupAsync(groupName: string, containerId?: string): Promise; + /** + * Change the name of an existing group. + * iOS Only + */ + function updateGroupNameAsync(groupName: string, groupId: string): Promise; + /** + * Delete a group from the device. + * iOS Only + */ + function removeGroupAsync(groupId: string): Promise; + /** + * Add a contact as a member to a group. A contact can be a member of multiple groups. + * iOS Only + */ + function addExistingContactToGroupAsync(contactId: string, groupId: string): Promise; + /** + * Remove a contact's membership from a given group. This will not delete the contact. + * iOS Only + */ + function removeContactFromGroupAsync(contactId: string, groupId: string): Promise; + /** + * Query and return a list of system groups. + * iOS Only + */ + function getGroupsAsync(query: GroupQuery): Promise; + /** + * Get the default container's ID. + * iOS Only + */ + function getDefaultContainerIdAsync(): Promise; + /** + * Query a list of system containers. + * iOS Only + */ + function getContainersAsync(containerQuery: ContainerQuery): Promise; +} + +/** + * DocumentPicker + */ +export namespace DocumentPicker { + interface Options { + type?: string; + } + + type Response = { + type: 'success'; + uri: string; + name: string; + size: number; + } | { + type: 'cancel'; + }; + + function getDocumentAsync(options?: Options): Promise; +} + +/** + * ErrorRecovery + */ +export namespace ErrorRecovery { + function setRecoveryProps(props: HashMap): void; +} + +/** + * Facebook + */ +export namespace Facebook { + interface Options { + permissions?: string[]; + behavior?: 'web' | 'native' | 'browser' | 'system'; + } + interface Response { + type: 'cancel' | 'success'; + token?: string; + expires?: number; + } + function logInWithReadPermissionsAsync(appId: string, options?: Options): Promise; +} + +/** + * Facebook Ads + */ +export namespace FacebookAds { + /** + * Interstitial Ads + */ + namespace InterstitialAdManager { + function showAd(placementId: string): Promise; + } + + /** + * Native Ads + */ + type MediaCachePolicy = 'none' | 'icon' | 'image' | 'all'; + class NativeAdsManager { + constructor(placementId: string, numberOfAdsToRequest?: number); + disableAutoRefresh(): void; + setMediaCachePolicy(cachePolicy: MediaCachePolicy): void; + } + + interface NativeAd { + /** + * The headline the advertiser entered when they created their ad. This is usually the ad's main + * title. + */ + headline?: string; + + /** + * The link description which is additional information that the advertiser may have entered + */ + linkDescription?: string; + + /** + * The name of the Facebook Page or mobile app that represents the business running the ad + */ + advertiserName?: string; + + /** + * The ad's social context, such as, "Over half a million users" + */ + socialContext?: string; + + /** + * The call-to-action phrase of the ad, such as, "Install Now" + */ + callToActionText?: string; + + /** + * The body text, truncated to 90 characters, that contains the text the advertiser entered when + * they created their ad to tell people what the ad promotes + */ + bodyText?: string; + + /** + * The word "ad", translated into the viewer's language + */ + adTranslation?: string; + + /** + * The word "promoted", translated into the viewer's language + */ + promotedTranslation?: string; + + /** + * The word "sponsored", translated into the viewer's language + */ + sponsoredTranslation?: string; + } + + function withNativeAd

(component: Component

): Component< + { + adsManager: NativeAdsManager, + onAdLoaded?: ((ad: NativeAd) => void) | null; + } & P, + { ad: NativeAd | null, canRequestAds: boolean } + >; + + /** + * Banner View + */ + type AdType = 'large' | 'rectangle' | 'standard'; + + interface BannerViewProps { + type: AdType; + placementId: string; + onPress: () => void; + onError: () => void; + } + + class BannerView extends Component { } + + type AdTriggerViewProps

= { + renderInteractiveComponent?: (props: P) => React.ReactElement

; + } & P; + + class AdTriggerView

extends Component> { } + + class AdIconView extends Component { } + + class AdMediaView extends Component { } + + /** + * Ad Settings + */ + namespace AdSettings { + const currentDeviceHash: string; + function addTestDevice(device: string): void; + function clearTestDevices(): void; + type SDKLogLevel = 'none' | 'debug' | 'verbose' | 'warning' | 'error' | 'notification'; + function setLogLevel(logLevel: SDKLogLevel): void; + function setIsChildDirected(isDirected: boolean): void; + function setMediationService(mediationService: string): void; + function setUrlPrefix(urlPrefix: string): void; + } +} + +/** + * FaceDetector + */ +export interface Point { + x: Axis; + y: Axis; +} + +export interface FaceFeature { + bounds: { + size: { + width: number; + height: number; + }, + origin: Point; + }; + smilingProbability?: number; + leftEarPosition?: Point; + rightEarPosition?: Point; + leftEyePosition?: Point; + leftEyeOpenProbability?: number; + rightEyePosition?: Point; + rightEyeOpenProbability?: number; + leftCheekPosition?: Point; + rightCheekPosition?: Point; + leftMouthPosition?: Point; + mouthPosition?: Point; + rightMouthPosition?: Point; + bottomMouthPosition?: Point; + noseBasePosition?: Point; + yawAngle?: number; + rollAngle?: number; +} + +export interface TrackedFaceFeature extends FaceFeature { + faceID?: number; +} + +export namespace FaceDetector { + interface DetectFaceResult { + faces: FaceFeature[]; + image: { + uri: string; + width: number; + height: number; + orientation: number; + }; + } + interface Mode { + fast: 'fast'; + accurate: 'accurate'; + } + interface _Shared { + all: 'all'; + none: 'none'; + } + type Landmarks = _Shared; + type Classifications = _Shared; + interface _Constants { + Mode: Mode; + Landmarks: Landmarks; + Classifications: Classifications; + } + + const Constants: _Constants; + + interface DetectionOptions { + mode?: keyof Mode; + detectLandmarks?: keyof Landmarks; + runClassifications?: keyof Classifications; + } + + function detectFaces(uri: string, options?: DetectionOptions): Promise; +} +/** + * FileSystem + */ +export namespace FileSystem { + type EncodingType = "utf8" | "base64"; + + type FileInfo = { + exists: true; + isDirectory: boolean; + uri: string; + size: number; + modificationTime: number; + md5?: Md5; + } | { + exists: false; + isDirectory: false; + }; + + interface ReadingOptions { + encoding?: EncodingType; + position?: number; + length?: number; + } + + interface WritingOptions { + encoding?: EncodingType; + } + + interface DownloadResult { + uri: string; + status: number; + headers: { [name: string]: string }; + md5?: Md5; + } + + const documentDirectory: string; + const cacheDirectory: string; + + function getInfoAsync(fileUri: string, options?: { md5?: string, size?: boolean; }): Promise; + function readAsStringAsync(fileUri: string, options?: ReadingOptions): Promise; + function writeAsStringAsync(fileUri: string, contents: string, options?: WritingOptions): Promise; + function deleteAsync(fileUri: string, options?: { idempotent: boolean; }): Promise; + function moveAsync(options: { from: string, to: string; }): Promise; + function copyAsync(options: { from: string, to: string; }): Promise; + function makeDirectoryAsync(dirUri: string, options?: { intermediates: boolean }): Promise; + function readDirectoryAsync(dirUri: string): Promise; + function downloadAsync(uri: string, fileUri: string, options?: { md5?: boolean; }): Promise; + function createDownloadResumable( + uri: string, + fileUri: string, + options?: DownloadOptions, + callback?: (totalBytesWritten: number, totalBytesExpectedToWrite: number) => void, + resumeData?: string | null + ): DownloadResumable; + + interface PauseResult { + url: string; + fileUri: string; + options: { md5: boolean; }; + resumeData: string; + } + + interface DownloadOptions { + md5?: boolean; + headers?: { [name: string]: string }; + } + + interface DownloadProgressData { + totalBytesWritten: number; + totalBytesExpectedToWrite: number; + } + + type DownloadProgressCallback = (data: DownloadProgressData) => void; + + class DownloadResumable { + constructor( + url: string, + fileUri: string, + options: DownloadOptions, + callback?: DownloadProgressCallback, + resumeData?: string + ); + + downloadAsync(): Promise; + pauseAsync(): Promise; + resumeAsync(): Promise; + savable(): PauseResult; + } +} + +/** Use TouchID/FaceID (iOS) or the Fingerprint API (Android) to authenticate the user with a fingerprint scan. */ +export namespace LocalAuthentication { + type LocalAuthenticationResult = { + success: true + } | { + success: false, + + /** Error code in the case where authentication fails. */ + error: string + }; + + interface AuthenticationTypeType { + FINGERPRINT: number; + FACIAL_RECOGNITION: number; + } + + /** Determine the auhentication types supported on the device. */ + function supportedAuthenticationTypesAsync(): Promise; + + /** Determine whether a face or fingerprint scanner is available on the device. */ + function hasHardwareAsync(): Promise; + + /** Determine whether the device has saved fingerprints or facial data to use for authentication. */ + function isEnrolledAsync(): Promise; + + /** + * Attempts to authenticate via Fingerprint. Android: When using the fingerprint module on Android, you need to provide a UI component to prompt the user to scan their fingerprint, as the OS has no default alert for it. + * + * @param promptMessage A message that is shown alongside the TouchID/FaceID prompt. (iOS only) + */ + function authenticateAsync(promptMessageIOS?: string): Promise; + + /** Cancels the fingerprint authentication flow. (Android only) */ + function cancelAuthenticate(): void; +} + +/** + * Font + */ +export namespace Font { + interface FontMap { + [name: string]: RequireSource; + } + + function loadAsync(name: string, url: string): Promise; + function loadAsync(map: FontMap): Promise; +} + +// #region GLView +export interface ExpoWebGLRenderingContext extends WebGLRenderingContext { + endFrameEXP(): void; +} + +/** + * A View that acts as an OpenGL ES render target. On mounting, an OpenGL ES + * context is created. Its drawing buffer is presented as the contents of + * the View every frame. + */ +export interface GLViewProps extends ViewProps { + /** + * A function that will be called when the OpenGL ES context is created. + * Passes an object with a WebGLRenderingContext interface as an argument. + */ + onContextCreate(gl: ExpoWebGLRenderingContext): void; + + /** Number of MSAA samples to use on iOS. Defaults to 4. Ignored on Android. */ + msaaSamples?: number; +} + +export class GLView extends Component { } +// #endregion + +/** + * Google + */ +export namespace Google { + interface LogInConfig { + androidClientId?: string; + androidStandaloneAppClientId?: string; + iosClientId?: string; + iosStandaloneAppClientId?: string; + webClientId?: string; + behavior?: 'system' | 'web'; + scopes?: string[]; + } + + type LogInResult = { + type: 'cancel'; + } | { + type: 'success'; + accessToken: string; + idToken?: string; + refreshToken?: string; + serverAuthCode?: string; + user: { + id: string; + name: string; + givenName: string; + familyName: string; + photoUrl?: string; + email?: string; + } + }; + + function logInAsync(config: LogInConfig): Promise; +} + +/** Access the device gyroscope sensor to respond to changes in rotation in 3d space. */ +export namespace Gyroscope { + interface GyroscopeObject { + x: Axis; + y: Axis; + z: Axis; + } + + /** A callback that is invoked when an gyroscope update is available. */ + function addListener(listener: (obj: GyroscopeObject) => any): EventSubscription; + + /** Remove all listeners. */ + function removeAllListeners(): void; + + /** Subscribe for updates to the gyroscope. */ + function setUpdateInterval(intervalMs: number): void; +} + +/** + * ImageManipulator + */ +export namespace ImageManipulator { + type Action = Resize | Rotate | Flip | Crop; + + interface Resize { + resize: { width?: number, height?: number }; + } + + interface Rotate { + rotate: number; + } + + interface Flip { + flip?: { vertical?: boolean; horizontal?: boolean }; + } + + interface Crop { + originX: number; + originY: number; + width: number; + height: number; + } + + interface ImageResult { + uri: string; + width: number; + height: number; + base64?: string; + } + + interface SaveOptions { + base64?: boolean; + /** A value in range `0` - `1` specifying compression level of the result image. `1` means no compression and `0` the highest compression. */ + compress?: number; + format?: 'jpeg' | 'png'; + } + + function manipulateAsync(uri: string, actions: Action[], saveOptions?: SaveOptions): Promise; +} + +/** + * Image Picker + */ +export namespace ImagePicker { + interface ImageInfo { + uri: string; + width: number; + height: number; + type: 'video' | 'image'; + base64?: string; + exif?: object; + duration?: number; + } + + type ImageResult = { cancelled: true } | ({ cancelled: false } & ImageInfo); + + interface _MediaTypeOptions { + All: 'All'; + Videos: 'Videos'; + Images: 'Images'; + } + + const MediaTypeOptions: _MediaTypeOptions; + + interface ImageLibraryOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + base64?: boolean; + exif?: boolean; + mediaTypes?: keyof _MediaTypeOptions; + } + + /** + * require Permissions.CAMERA_ROLL + */ + function launchImageLibraryAsync(options?: ImageLibraryOptions): Promise; + + interface CameraOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + base64?: boolean; + exif?: boolean; + } + + /** + * require Permissions.CAMERA_ROLL + */ + function launchCameraAsync(options?: CameraOptions): Promise; +} + +/** + * IntentLauncherAndroid + */ +export namespace IntentLauncherAndroid { + const ACTION_ACCESSIBILITY_SETTINGS: 'android.settings.ACCESSIBILITY_SETTINGS'; + const ACTION_APP_NOTIFICATION_REDACTION: 'android.settings.ACTION_APP_NOTIFICATION_REDACTION'; + const ACTION_CONDITION_PROVIDER_SETTINGS: 'android.settings.ACTION_CONDITION_PROVIDER_SETTINGS'; + const ACTION_NOTIFICATION_LISTENER_SETTINGS: 'android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS'; + const ACTION_PRINT_SETTINGS: 'android.settings.ACTION_PRINT_SETTINGS'; + const ACTION_ADD_ACCOUNT_SETTINGS: 'android.settings.ADD_ACCOUNT_SETTINGS'; + const ACTION_AIRPLANE_MODE_SETTINGS: 'android.settings.AIRPLANE_MODE_SETTINGS'; + const ACTION_APN_SETTINGS: 'android.settings.APN_SETTINGS'; + const ACTION_APPLICATION_DETAILS_SETTINGS: 'android.settings.APPLICATION_DETAILS_SETTINGS'; + const ACTION_APPLICATION_DEVELOPMENT_SETTINGS: 'android.settings.APPLICATION_DEVELOPMENT_SETTINGS'; + const ACTION_APPLICATION_SETTINGS: 'android.settings.APPLICATION_SETTINGS'; + const ACTION_APP_NOTIFICATION_SETTINGS: 'android.settings.APP_NOTIFICATION_SETTINGS'; + const ACTION_APP_OPS_SETTINGS: 'android.settings.APP_OPS_SETTINGS'; + const ACTION_BATTERY_SAVER_SETTINGS: 'android.settings.BATTERY_SAVER_SETTINGS'; + const ACTION_BLUETOOTH_SETTINGS: 'android.settings.BLUETOOTH_SETTINGS'; + const ACTION_CAPTIONING_SETTINGS: 'android.settings.CAPTIONING_SETTINGS'; + const ACTION_CAST_SETTINGS: 'android.settings.CAST_SETTINGS'; + const ACTION_DATA_ROAMING_SETTINGS: 'android.settings.DATA_ROAMING_SETTINGS'; + const ACTION_DATE_SETTINGS: 'android.settings.DATE_SETTINGS'; + const ACTION_DEVICE_INFO_SETTINGS: 'android.settings.DEVICE_INFO_SETTINGS'; + const ACTION_DEVICE_NAME: 'android.settings.DEVICE_NAME'; + const ACTION_DISPLAY_SETTINGS: 'android.settings.DISPLAY_SETTINGS'; + const ACTION_DREAM_SETTINGS: 'android.settings.DREAM_SETTINGS'; + const ACTION_HARD_KEYBOARD_SETTINGS: 'android.settings.HARD_KEYBOARD_SETTINGS'; + const ACTION_HOME_SETTINGS: 'android.settings.HOME_SETTINGS'; + const ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS: 'android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS'; + const ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS: 'android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS'; + const ACTION_INPUT_METHOD_SETTINGS: 'android.settings.INPUT_METHOD_SETTINGS'; + const ACTION_INPUT_METHOD_SUBTYPE_SETTINGS: 'android.settings.INPUT_METHOD_SUBTYPE_SETTINGS'; + const ACTION_INTERNAL_STORAGE_SETTINGS: 'android.settings.INTERNAL_STORAGE_SETTINGS'; + const ACTION_LOCALE_SETTINGS: 'android.settings.LOCALE_SETTINGS'; + const ACTION_LOCATION_SOURCE_SETTINGS: 'android.settings.LOCATION_SOURCE_SETTINGS'; + const ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS: 'android.settings.MANAGE_ALL_APPLICATIONS_SETTINGS'; + const ACTION_MANAGE_APPLICATIONS_SETTINGS: 'android.settings.MANAGE_APPLICATIONS_SETTINGS'; + const ACTION_MANAGE_DEFAULT_APPS_SETTINGS: 'android.settings.MANAGE_DEFAULT_APPS_SETTINGS'; + const ACTION_MEMORY_CARD_SETTINGS: 'android.settings.MEMORY_CARD_SETTINGS'; + const ACTION_MONITORING_CERT_INFO: 'android.settings.MONITORING_CERT_INFO'; + const ACTION_NETWORK_OPERATOR_SETTINGS: 'android.settings.NETWORK_OPERATOR_SETTINGS'; + const ACTION_NFCSHARING_SETTINGS: 'android.settings.NFCSHARING_SETTINGS'; + const ACTION_NFC_PAYMENT_SETTINGS: 'android.settings.NFC_PAYMENT_SETTINGS'; + const ACTION_NFC_SETTINGS: 'android.settings.NFC_SETTINGS'; + const ACTION_NIGHT_DISPLAY_SETTINGS: 'android.settings.NIGHT_DISPLAY_SETTINGS'; + const ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS: 'android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS'; + const ACTION_NOTIFICATION_SETTINGS: 'android.settings.NOTIFICATION_SETTINGS'; + const ACTION_PAIRING_SETTINGS: 'android.settings.PAIRING_SETTINGS'; + const ACTION_PRIVACY_SETTINGS: 'android.settings.PRIVACY_SETTINGS'; + const ACTION_QUICK_LAUNCH_SETTINGS: 'android.settings.QUICK_LAUNCH_SETTINGS'; + const ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS: 'android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS'; + const ACTION_SECURITY_SETTINGS: 'android.settings.SECURITY_SETTINGS'; + const ACTION_SETTINGS: 'android.settings.SETTINGS'; + const ACTION_SHOW_ADMIN_SUPPORT_DETAILS: 'android.settings.SHOW_ADMIN_SUPPORT_DETAILS'; + const ACTION_SHOW_INPUT_METHOD_PICKER: 'android.settings.SHOW_INPUT_METHOD_PICKER'; + const ACTION_SHOW_REGULATORY_INFO: 'android.settings.SHOW_REGULATORY_INFO'; + const ACTION_SHOW_REMOTE_BUGREPORT_DIALOG: 'android.settings.SHOW_REMOTE_BUGREPORT_DIALOG'; + const ACTION_SOUND_SETTINGS: 'android.settings.SOUND_SETTINGS'; + const ACTION_STORAGE_MANAGER_SETTINGS: 'android.settings.STORAGE_MANAGER_SETTINGS'; + const ACTION_SYNC_SETTINGS: 'android.settings.SYNC_SETTINGS'; + const ACTION_SYSTEM_UPDATE_SETTINGS: 'android.settings.SYSTEM_UPDATE_SETTINGS'; + const ACTION_TETHER_PROVISIONING_UI: 'android.settings.TETHER_PROVISIONING_UI'; + const ACTION_TRUSTED_CREDENTIALS_USER: 'android.settings.TRUSTED_CREDENTIALS_USER'; + const ACTION_USAGE_ACCESS_SETTINGS: 'android.settings.USAGE_ACCESS_SETTINGS'; + const ACTION_USER_DICTIONARY_INSERT: 'android.settings.USER_DICTIONARY_INSERT'; + const ACTION_USER_DICTIONARY_SETTINGS: 'android.settings.USER_DICTIONARY_SETTINGS'; + const ACTION_USER_SETTINGS: 'android.settings.USER_SETTINGS'; + const ACTION_VOICE_CONTROL_AIRPLANE_MODE: 'android.settings.VOICE_CONTROL_AIRPLANE_MODE'; + const ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE: 'android.settings.VOICE_CONTROL_BATTERY_SAVER_MODE'; + const ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE: 'android.settings.VOICE_CONTROL_DO_NOT_DISTURB_MODE'; + const ACTION_VOICE_INPUT_SETTINGS: 'android.settings.VOICE_INPUT_SETTINGS'; + const ACTION_VPN_SETTINGS: 'android.settings.VPN_SETTINGS'; + const ACTION_VR_LISTENER_SETTINGS: 'android.settings.VR_LISTENER_SETTINGS'; + const ACTION_WEBVIEW_SETTINGS: 'android.settings.WEBVIEW_SETTINGS'; + const ACTION_WIFI_IP_SETTINGS: 'android.settings.WIFI_IP_SETTINGS'; + const ACTION_WIFI_SETTINGS: 'android.settings.WIFI_SETTINGS'; + const ACTION_WIRELESS_SETTINGS: 'android.settings.WIRELESS_SETTINGS'; + const ACTION_ZEN_MODE_AUTOMATION_SETTINGS: 'android.settings.ZEN_MODE_AUTOMATION_SETTINGS'; + const ACTION_ZEN_MODE_EVENT_RULE_SETTINGS: 'android.settings.ZEN_MODE_EVENT_RULE_SETTINGS'; + const ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS: 'android.settings.ZEN_MODE_EXTERNAL_RULE_SETTINGS'; + const ACTION_ZEN_MODE_PRIORITY_SETTINGS: 'android.settings.ZEN_MODE_PRIORITY_SETTINGS'; + const ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS: 'android.settings.ZEN_MODE_SCHEDULE_RULE_SETTINGS'; + const ACTION_ZEN_MODE_SETTINGS: 'android.settings.ZEN_MODE_SETTINGS'; + + function startActivityAsync(activity: string, data?: HashMap): Promise; +} + +/** + * KeepAwake + */ +export class KeepAwake extends Component { + static activate(): void; + static deactivate(): void; +} + +// #region LinearGradient +/** + * LinearGradient + */ +export interface LinearGradientProps { + colors: string[]; + start?: [number, number]; + end?: [number, number]; + locations?: number[]; + style?: StyleProp; +} + +export class LinearGradient extends Component { } +// #endregion + +/** + * Linking + */ +export interface LinkInfo { + path: string; + queryParams: Partial; +} + +export interface LinkingStatic extends ReactNativeLinkingStatic { + makeUrl(path: string, queryParams?: HashMap): string; + parse(url: string): LinkInfo; + parseInitialURLAsync(): Promise; +} +export const Linking: LinkingStatic; + +/** + * Location + */ +export namespace Location { + interface LocationOptions { + enableHighAccuracy?: boolean; + timeInterval?: number; + distanceInterval?: number; + timeout?: number; + } + + interface LocationProps { + latitude: number; + longitude: number; + } + + interface Coords extends LocationProps { + altitude: number; + accuracy: number; + } + + interface LocationData { + coords: { + heading: number; + speed: number + } & Coords; + timestamp: number; + } + + interface ProviderStatus { + locationServicesEnabled: boolean; + gpsAvailable?: boolean; + networkAvailable?: boolean; + passiveAvailable?: boolean; + } + + interface HeadingStatus { + magHeading: number; + trueHeading: number; + accuracy: number; + } + + interface GeocodeData { + city: string; + street: string; + region: string; + postalCode: string; + country: string; + name: string; + } + + type LocationCallback = (data: LocationData) => void; + + function getCurrentPositionAsync(options: LocationOptions): Promise; + function watchPositionAsync(options: LocationOptions, callback: LocationCallback): EventSubscription; + function getProviderStatusAsync(): Promise; + function getHeadingAsync(): Promise; + function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription; + function geocodeAsync(address: string): Promise; + function reverseGeocodeAsync(location: LocationProps): Promise; + function setApiKey(key: string): void; +} + +/** + * Magnetometer + */ +export namespace Magnetometer { + interface MagnetometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: MagnetometerObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Notifications + */ +export namespace Notifications { + interface Notification { + origin: 'selected' | 'received'; + data: any; + remote: boolean; + isMultiple: boolean; + } + + interface LocalNotification { + title: string; + body?: string; + data?: any; + ios?: { + sound?: boolean + }; + android?: { + sound?: boolean; + icon?: string; + color?: string; + priority?: 'min' | 'low' | 'high' | 'max'; + sticky?: boolean; + vibrate?: boolean | number[]; + link?: string; + }; + } + + interface SchedulingOptions { + time: Date | number; + repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; + intervalMs?: number; + } + + interface ChannelAndroid { + name: string; + description?: string; + sound?: boolean; + priority?: 'min' | 'low' | 'default' | 'high' | 'max'; + vibrate?: boolean | number[]; + badge?: boolean; + } + + type LocalNotificationId = string | number; + + function addListener(listener: (notification: Notification) => any): EventSubscription; + function getExpoPushTokenAsync(): Promise; + function presentLocalNotificationAsync(localNotification: LocalNotification): Promise; + function scheduleLocalNotificationAsync( + localNotification: LocalNotification, + schedulingOptions: { time: Date | number, repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' } + ): Promise; + function dismissNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function dismissAllNotificationsAsync(): Promise; + function cancelScheduledNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function cancelAllScheduledNotificationsAsync(): Promise; + function createChannelAndroidAsync(id: string, channel: ChannelAndroid): Promise; + function deleteChannelAndroidAsync(id: string): Promise; + function getBadgeNumberAsync(): Promise; + function setBadgeNumberAsync(number: number): Promise; +} + +/** + * Pedometer + */ +export namespace Pedometer { + function isAvailableAsync(): Promise; + function getStepCountAsync(start: Date, end: Date): Promise<{ steps: number; }>; + function watchStepCount(callback: (params: { steps: number; }) => void): EventSubscription; +} + +/** + * Permissions + */ +export namespace Permissions { + type PermissionType = 'audioRecording' | 'calendar' | + 'cameraRoll' | 'camera' | 'contacts' | 'location' | 'reminders' | + 'notifications' | 'systemBrightness' | 'userFacingNotifications' | 'SMS'; + type PermissionStatus = 'undetermined' | 'granted' | 'denied'; + type PermissionExpires = 'never'; + + interface PermissionDetailsLocationIOS { + scope: 'whenInUse' | 'always'; + } + + interface PermissionDetailsLocationAndroid { + scope: 'fine' | 'coarse' | 'none'; + } + + interface SinglePermissionResponse { + status: PermissionStatus; + expires: PermissionExpires; + ios?: PermissionDetailsLocationIOS; + android?: PermissionDetailsLocationAndroid; + } + + interface PermissionResponse { + status: PermissionStatus; + expires: PermissionExpires; + permissions: { + [key in PermissionType]: SinglePermissionResponse + }; + } + + function getAsync(...permissionTypes: PermissionType[]): Promise; + function askAsync(...permissionTypes: PermissionType[]): Promise; + + const AUDIO_RECORDING: 'audioRecording'; + const CALENDAR: 'calendar'; + const CAMERA_ROLL: 'cameraRoll'; + const CAMERA: 'camera'; + const CONTACTS: 'contacts'; + const LOCATION: 'location'; + const NOTIFICATIONS: 'notifications'; + const REMINDERS: 'reminders'; + const SYSTEM_BRIGHTNESS: 'systemBrightness'; + const USER_FACING_NOTIFICATIONS: 'userFacingNotifications'; + /** + * Will be removed in SDK 32 + */ + const SMS: 'SMS'; +} + +/** + * Register Root Component + */ +export function registerRootComponent(component: ComponentType): void; + +/** + * ScreenOrientation + */ +export namespace ScreenOrientation { + interface Orientations { + ALL: 'ALL'; + ALL_BUT_UPSIDE_DOWN: 'ALL_BUT_UPSIDE_DOWN'; + PORTRAIT: 'PORTRAIT'; + PORTRAIT_UP: 'PORTRAIT_UP'; + PORTRAIT_DOWN: 'PORTRAIT_DOWN'; + LANDSCAPE: 'LANDSCAPE'; + LANDSCAPE_LEFT: 'LANDSCAPE_LEFT'; + LANDSCAPE_RIGHT: 'LANDSCAPE_RIGHT'; + } + + const Orientation: Orientations; + + function allow(orientation: keyof Orientations): void; +} + +/** + * SecureStore + */ +export namespace SecureStore { + interface SecureStoreOptions { + keychainService?: string; + } + + interface SecureStoreSetOptions extends SecureStoreOptions { + keychainAccessible?: number; + } + + function setItemAsync(key: string, value: string, options?: SecureStoreSetOptions): Promise; + function getItemAsync(key: string, options?: SecureStoreOptions): Promise; + function deleteItemAsync(key: string, options?: SecureStoreOptions): Promise; + + const WHEN_UNLOCKED: number; + const AFTER_FIRST_UNLOCK: number; + const ALWAYS: number; + const WHEN_UNLOCKED_THIS_DEVICE_ONLY: number; + const WHEN_PASSCODE_SET_THIS_DEVICE_ONLY: number; + const AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: number; + const ALWAYS_THIS_DEVICE_ONLY: number; +} + +/** + * Segment + */ +export namespace Segment { + function initialize(keys: { + androidWriteKey: string; + iosWriteKey: string; + }): void; + function identify(userId: string): void; + function identifyWithTraits(userId: string, traits: object): void; + function track(event: string): void; + function alias(newId: string, options?: { [key: string]: any }): Promise; + function reset(): void; + function trackWithProperties(event: string, properties: object): void; + function screen(screenName: string): void; + function screenWithProperties(screenName: string, properties: object): void; + function flush(): void; + function getEnabledAsync(): void; + function setEnabledAsync(enabled: boolean): void; +} + +/** + * Speech + */ +export namespace Speech { + interface SpeechOptions { + language?: string; + pitch?: number; + rate?: number; + onStart?: () => void; + onStopped?: () => void; + onDone?: () => void; + onError?: (error: Error) => void; + } + + function speak(text: string, options?: SpeechOptions): void; + function stop(): void; + function isSpeakingAsync(): Promise; + + /** Available on iOS only */ + function pause(): void; + + /** Available on iOS only */ + function resume(): void; +} + +/** + * SQLite + */ +export namespace SQLite { + type Error = any; + + interface Database { + transaction( + callback: (transaction: Transaction) => any, + error?: (error: Error) => any, // TODO def of error + success?: () => any + ): void; + } + + interface Transaction { + executeSql( + sqlStatement: string, + arguments?: string[] | number[], + success?: (transaction: Transaction, resultSet: ResultSet) => any, + error?: (transaction: Transaction, error: Error) => any + ): void; + } + + interface ResultSet { + insertId: number; + rowAffected: number; + rows: { + length: number; + item: (index: number) => any; + _array: HashMap[]; + }; + } + + function openDatabase( + name: string | { + name: string, + version?: string, + description?: string, + size?: number, + callback?: () => any + }, + version?: string, + description?: string, + size?: number, + callback?: () => any + ): any; +} + +// #region Svg +/** + * Svg + */ +export interface SvgCommonProps { + fill?: string; + fillOpacity?: number | string; + fillRule?: 'nonzero' | 'evenodd'; + opacity?: number | string; + stroke?: string; + strokeWidth?: number | string; + strokeOpacity?: number | string; + strokeLinecap?: string; + strokeLineJoin?: string; + strokeDasharray?: any[]; + strokeDashoffset?: any; + transform?: string | object; + x?: number | string; + y?: number | string; + rotate?: number | string; + rotation?: number | string; + scale?: number | string; + origin?: number | string; + originX?: number | string; + originY?: number | string; + id?: string; + disabled?: boolean; + onPress?: () => any; + onPressIn?: () => any; + onPressOut?: () => any; + onLongPress?: () => any; + delayPressIn?: number; + delayPressOut?: number; + delayLongPress?: number; +} + +export interface SvgRectProps extends SvgCommonProps { + width: number | string; + height: number | string; +} + +export interface SvgCircleProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + r: number | string; +} + +export interface SvgEllipseProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + rx: number | string; + ry: number | string; +} + +export interface SvgLineProps extends SvgCommonProps { + x1: number | string; + y1: number | string; + x2: number | string; + y2: number | string; +} + +export interface SvgPolyProps extends SvgCommonProps { + points: string; +} + +export interface SvgPathProps extends SvgCommonProps { + d: string; +} + +export interface SvgTextProps extends SvgCommonProps { + textAnchor?: string; + fontSize?: number | string; + fontWeight?: string; +} + +export interface SvgTSpanProps extends SvgTextProps { + dx?: string; + dy?: string; +} + +export interface SvgTextPathProps extends SvgCommonProps { + href?: string; + startOffset?: string; +} + +export interface SvgUseProps extends SvgCommonProps { + href: string; + x: number | string; + y: number | string; + width?: number | string; + height?: number | string; +} + +export interface SvgSymbolProps extends SvgCommonProps { + viewBox: string; + preserveAspectRatio?: string; + width: number | string; + height: number | string; +} + +export interface SvgLinearGradientProps extends SvgCommonProps { + x1: number | string; + x2: number | string; + y1: number | string; + y2: number | string; +} + +export interface SvgRadialGradientProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + rx: number | string; + ry: number | string; + fx: number | string; + fy: number | string; + gradientUnits?: string; +} + +export interface SvgStopProps extends SvgCommonProps { + offset?: string; + stopColor?: string; + stopOpacity?: string; +} + +export class Svg extends Component<{ width: number, height: number, viewBox?: string, preserveAspectRatio?: string }> { + static Circle: ComponentClass; + static ClipPath: ComponentClass; + static Defs: ComponentClass; + static Ellipse: ComponentClass; + static G: ComponentClass; + static Line: ComponentClass; + static LinearGradient: ComponentClass; + static Path: ComponentClass; + static Polygon: ComponentClass; + static Polyline: ComponentClass; + static RadialGradient: ComponentClass; + static Rect: ComponentClass; + static Stop: ComponentClass; + static Symbol: ComponentClass; + static Text: ComponentClass; + static TextPath: ComponentClass; + static TSpan: ComponentClass; + static Use: ComponentClass; +} +// #endregion + +/** + * Take Snapshot + */ +export function takeSnapshotAsync( + view?: (number | React.ReactElement), + options?: { + width?: number, + height?: number, + format?: 'png' | 'jpg' | 'jpeg' | 'webm', + quality?: number, + result?: 'file' | 'base64' | 'data-uri', + } +): Promise; + +/** Helpful utility functions that don’t fit anywhere else, including some localization and internationalization methods. */ +export namespace Util { + /** Returns the current device country code. */ + function getCurrentDeviceCountryAsync(): Promise; + + /** Returns the current device locale as a string. */ + function getCurrentLocaleAsync(): Promise; + + /** Returns the current device time zone name. */ + function getCurrentTimeZoneAsync(): Promise; + + /** Reloads the current experience. This will fetch and load the newest available JavaScript supported by the device’s Expo environment. This is useful for triggering an update of your experience if you have published a new version. */ + function reload(): void; + + /** _Android only_. Invokes a callback when a new version of your app is successfully downloaded in the background. */ + function addNewVersionListenerExperimental(listener: (event: { + manifest: object; + }) => void): { remove(): void; }; +} + +// #region Video +/** + * Expo Video + */ +export interface NaturalSize { + width: number; + height: number; + orientation: Orientation; +} + +export interface ReadyForDisplayEvent { + naturalSize: NaturalSize; + status: PlaybackStatus; +} + +export enum FullscreenUpdateVariants { + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT = 0, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT = 1, + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS = 2, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS = 3 +} + +export interface FullscreenUpdateEvent { + fullscreenUpdate: FullscreenUpdateVariants; + status: PlaybackStatus; +} + +export interface VideoProps { + source?: PlaybackSource | null; + posterSource?: URISource | RequireSource; + + resizeMode?: ResizeModeContain | ResizeModeCover | ResizeModeStretch; + useNativeControls?: boolean; + usePoster?: boolean; + + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void; + onReadyForDisplay?: (event: ReadyForDisplayEvent) => void; + onIOSFullscreenUpdate?: (event: FullscreenUpdateEvent) => void; + + onLoadStart?: () => void; + onLoad?: (status: PlaybackStatus) => void; + onError?: (error: string) => void; + + status?: PlaybackStatusToSet; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: number; + shouldCorrectPitch?: boolean; + volume?: number; + isMuted?: boolean; + isLooping?: boolean; + + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; + rotation?: number; + ref?: Ref; + style?: StyleProp; +} + +export interface VideoState { + showPoster: boolean; +} + +export class Video extends Component { + static RESIZE_MODE_CONTAIN: ResizeModeContain; + static RESIZE_MODE_COVER: ResizeModeCover; + static RESIZE_MODE_STRETCH: ResizeModeStretch; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS; +} +// #endregion + +/** + * Web Browser + */ +export namespace WebBrowser { + function openBrowserAsync(url: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function openAuthSessionAsync(url: string, redirectUrl?: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function dismissBrowser(): Promise<{ type: 'dismissed' }>; +} + +// #region Calendar +/** + * Calendar + * + * Provides an API for interacting with the device’s system calendars, events, reminders, and associated records. + */ +export namespace Calendar { + interface Calendar { + /** Internal ID that represents this calendar on the device */ + id?: string; + + /** Visible name of the calendar */ + title?: string; + + sourceId?: string; // iOS + + /** Object representing the source to be used for the calendar */ + source?: Source; + + /** Type of calendar this object represents */ + type?: CalendarType; // iOS + + /** Color used to display this calendar’s events */ + color?: string; + + /** Whether the calendar is used in the Calendar or Reminders OS app */ + entityType?: EntityTypes; // iOS + + /** Boolean value that determines whether this calendar can be modified */ + allowsModifications?: boolean; + + /** Availability types that this calendar supports */ + allowedAvailabilities?: Availability[]; + + /** Boolean value indicating whether this is the device’s primary calendar */ + isPrimary?: boolean; // Android + + /** Internal system name of the calendar */ + name?: string; // Android + + /** Name for the account that owns this calendar */ + ownerAccount?: string; // Android + + /** Time zone for the calendar */ + timeZone?: string; // Android + + /** Alarm methods that this calendar supports */ + allowedReminders?: AlarmMethod[]; // Android + + /** Attendee types that this calendar supports */ + allowedAttendeeTypes?: AttendeeType[]; // Android + + /** Indicates whether the OS displays events on this calendar */ + isVisible?: boolean; // Android + + /** Indicates whether this calendar is synced and its events stored on the device */ + isSynced?: boolean; // Android + + /** Level of access that the user has for the calendar */ + accessLevel?: CalendarAccessLevel; // Android + } + + interface Source { + /** Internal ID that represents this source on the device */ + id?: string; // iOS only ?? + + /** Type of account that owns this calendar */ + type?: string; + + /** Name for the account that owns this calendar */ + name?: string; + + /** Whether this source is the local phone account */ + isLocalAccount?: boolean; // Android + } + + interface Event { + /** Internal ID that represents this event on the device */ + id?: string; + + /** ID of the calendar that contains this event */ + calendarId?: string; + + /** Visible name of the event */ + title?: string; + + /** Location field of the event */ + location?: string; + + /** Date when the event record was created */ + creationDate?: string; // iOS + + /** Date when the event record was last modified */ + lastModifiedDate?: string; // iOS + + /** Time zone the event is scheduled in */ + timeZone?: string; + + /** Time zone for the event end time */ + endTimeZone?: string; // Android + + /** URL for the event */ + url?: string; // iOS + + /** Description or notes saved with the event */ + notes?: string; + + /** Array of Alarm objects which control automated reminders to the user */ + alarms?: Alarm[]; + + /** Object representing rules for recurring or repeating events. Null for one-time events. */ + recurrenceRule?: RecurrenceRule; + + /** Date object or string representing the time when the event starts */ + startDate?: string | Date; + + /** Date object or string representing the time when the event ends */ + endDate?: string | Date; + + /** For recurring events, the start date for the first (original) instance of the event */ + originalStartDate?: string; // iOS + + /** Boolean value indicating whether or not the event is a detached (modified) instance of a recurring event */ + isDetached?: boolean; // iOS + + /** Whether the event is displayed as an all-day event on the calendar */ + allDay?: boolean; + + /** The availability setting for the event */ + availability?: Availability; // Availability + + /** Status of the event */ + status?: EventStatus; // Status + + /** Organizer of the event, as an Attendee object */ + organizer?: string; // Organizer - iOS + + /** Email address of the organizer of the event */ + organizerEmail?: string; // Android + + /** User’s access level for the event */ + accessLevel?: EventAccessLevel; // Android, + + /** Whether invited guests can modify the details of the event */ + guestsCanModify?: boolean; // Android, + + /** Whether invited guests can invite other guests */ + guestsCanInviteOthers?: boolean; // Android + + /** Whether invited guests can see other guests */ + guestsCanSeeGuests?: boolean; // Android + + /** For detached (modified) instances of recurring events, the ID of the original recurring event */ + originalId?: string; // Android + + /** For instances of recurring events, volatile ID representing this instance; not guaranteed to always refer to the same instance */ + instanceId?: string; // Android + } + + interface Attendee { + /** Internal ID that represents this attendee on the device */ + id?: string; // Android + + /** Indicates whether or not this attendee is the current OS user */ + isCurrentUser?: boolean; // iOS + + /** Displayed name of the attendee */ + name?: string; + + /** Role of the attendee at the event */ + role?: AttendeeRole; + + /** Status of the attendee in relation to the event */ + status?: AttendeeStatus; + + /** Type of the attendee */ + type?: AttendeeType; + + /** URL for the attendee */ + url?: string; // iOS + + /** Email address of the attendee */ + email?: string; // Android + } + + interface Reminder { + /** Internal ID that represents this reminder on the device */ + id?: string; + + /** ID of the calendar that contains this reminder */ + calendarId?: string; + + /** Visible name of the reminder */ + title?: string; + + /** Location field of the reminder */ + location?: string; + + /** Date when the reminder record was created */ + creationDate?: string; + + /** Date when the reminder record was last modified */ + lastModifiedDate?: string; + + /** Time zone the reminder is scheduled in */ + timeZone?: string; + + /** URL for the reminder */ + url?: string; + + /** Description or notes saved with the reminder */ + notes?: string; + + /** Array of Alarm objects which control automated alarms to the user about the task */ + alarms?: Alarm[]; + + /** Object representing rules for recurring or repeated reminders. Null for one-time tasks. */ + recurrenceRule?: RecurrenceRule; + + /** Date object or string representing the start date of the reminder task */ + startDate?: string; + + /** Date object or string representing the time when the reminder task is due */ + dueDate?: string; + + /** Indicates whether or not the task has been completed */ + completed?: boolean; + + /** Date object or string representing the date of completion, if completed is true */ + completionDate?: string; + } + + interface Alarm { + /** Date object or string representing an absolute time the alarm should occur; overrides relativeOffset and structuredLocation if specified alongside either */ + absoluteDate?: string; // iOS + + /** Number of minutes from the startDate of the calendar item that the alarm should occur; use negative values to have the alarm occur before the startDate */ + relativeOffset?: string; + structuredLocation?: { + // iOS + title?: string; + proximity?: string; // Proximity + radius?: number; + coords?: { + latitude?: number; + longitude?: number; + }; + }; + + /** Method of alerting the user that this alarm should use; on iOS this is always a notification */ + method?: AlarmMethod; // Method, Android + } + + interface RecurrenceRule { + /** How often the calendar item should recur */ + frequency: Frequency; // Frequency + + /** Interval at which the calendar item should recur. For example, an interval: 2 with frequency: DAILY would yield an event that recurs every other day. Defaults to 1 . */ + interval?: number; + + /** Date on which the calendar item should stop recurring; overrides occurrence if both are specified */ + endDate?: string; + + /** Number of times the calendar item should recur before stopping */ + occurrence?: number; + } + + enum EntityTypes { + EVENT = 'event', + REMINDER = 'reminder', + } + + enum CalendarType { + LOCAL = 'local', + CALDAV = 'caldav', + EXCHANGE = 'exchange', + SUBSCRIBED = 'subscribed', + BIRTHDAYS = 'birthdays' + } + + enum Availability { + NOT_SUPPORTED = 'notSupported', // iOS + BUSY = 'busy', + FREE = 'free', + TENTATIVE = 'tentative', + UNAVAILABLE = 'unavailable' // iOS + } + + enum AlarmMethod { + ALARM = 'alarm', + ALERT = 'alert', + EMAIL = 'email', + SMS = 'sms', + DEFAULT = 'default', + } + + enum AttendeeType { + UNKNOWN = 'unknown', // iOS + PERSON = 'person', // iOS + ROOM = 'room', // iOS + GROUP = 'group', // iOS + RESOURCE = 'resource', + OPTIONAL = 'optional', // Android + REQUIRED = 'required', // Android + NONE = 'none' // Android + } + + enum CalendarAccessLevel { + CONTRIBUTOR = 'contributor', + EDITOR = 'editor', + FREEBUSY = 'freebusy', + OVERRIDE = 'override', + OWNER = 'owner', + READ = 'read', + RESPOND = 'respond', + ROOT = 'root', + NONE = 'none' + } + + enum EventAccessLevel { + CONFIDENTIAL = 'confidential', + PRIVATE = 'private', + PUBLIC = 'public', + DEFAULT = 'default' + } + + enum EventStatus { + NONE = 'none', + CONFIRMED = 'confirmed', + TENTATIVE = 'tentative', + CANCELED = 'canceled' + } + + enum AttendeeRole { + UNKNOWN = 'unknown', // iOS + REQUIRED = 'required', // iOS + OPTIONAL = 'optional', // iOS + CHAIR = 'chair', // iOS + NON_PARTICIPANT = 'nonParticipant', // iOS + ATTENDEE = 'attendee', // Android + ORGANIZER = 'organizer', // Android + PERFORMER = 'performer', // Android + SPEAKER = 'speaker', // Android + NONE = 'none' // Android + } + + enum AttendeeStatus { + UNKNOWN = 'unknown', // iOS + PENDING = 'pending', // iOS + ACCEPTED = 'accepted', + DECLINED = 'declined', + TENTATIVE = 'tentative', + DELEGATED = 'delegated', // iOS + COMPLETED = 'completed', // iOS + IN_PROCESS = 'inProcess', // iOS + INVITED = 'invited', // Android + NONE = 'none' // Android + } + + enum Frequency { + DAILY = 'daily', + WEEKLY = 'weekly', + MONTHLY = 'monthly', + YEARLY = 'yearly' + } + + enum ReminderStatus { + COMPLETED = 'completed', + INCOMPLETE = 'incomplete' + } + + interface RecurringEventOptions { + futureEvents?: boolean; + instanceStartDate?: string; + } + + /** Gets an array of calendar objects with details about the different calendars stored on the device. */ + function getCalendarsAsync( + /** (iOS only) Not required, but if defined, filters the returned calendars to a specific entity type. */ + entityType?: EntityTypes + ): Promise; + + /** Creates a new calendar on the device, allowing events to be added later and displayed. */ + function createCalendarAsync(details: Calendar): Promise; + + /** Updates the provided details of an existing calendar stored on the device. To remove a property, explicitly set it to null in details */ + function updateCalendarAsync(id: string, details?: Calendar | null): Promise; + + /** Deletes an existing calendar and all associated events/reminders/attendees from the device. Use with caution. */ + function deleteCalendarAsync(id: string): Promise; + + /** Returns all events in a given set of calendars over a specified time period. */ + function getEventsAsync( + /** Array of IDs of calendars to search for events in. Required. */ + calendarIds: string[], + + /** Beginning of time period to search for events in. Required. */ + startDate: Date, + + /** End of time period to search for events in. Required. */ + endDate: Date + ): Promise; + + /** Returns a specific event selected by ID. If a specific instance of a recurring event is desired, the start date of this instance must also be provided, as instances of recurring events do not have their own unique and stable IDs on either iOS or Android. */ + function getEventAsync( + /** ID of the event to return. Required. */ + id: string, + + /** A map of options for recurring events */ + recurringEventOptions?: RecurringEventOptions + ): Promise; + + /** Creates a new event on the specified calendar. */ + function createEventAsync( + /** ID of the calendar to create this event in. Required. */ + calendarId: string, + details?: Event + ): Promise; + + /** Updates the provided details of an existing calendar stored on the device. To remove a property, explicitly set it to null in details */ + function updateEventAsync( + /** ID of the event to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Event | null, + + /** A map of options for recurring events */ + recurrentEventOptions?: RecurringEventOptions + ): Promise; + + /** Deletes an existing event from the device. Use with caution. */ + function deleteEventAsync( + /** ID of the event to be deleted. Required. */ + id: string, + + /** A map of options for recurring events */ + recurringEventOptions?: RecurringEventOptions + ): Promise; + + /** Gets all attendees for a given event (or instance of a recurring event). */ + function getAttendeesForEventAsync( + /** ID of the event to return attendees for. Required. */ + eventId: string, + + /** A map of options for recurring events */ + recurrentEventOptions?: RecurringEventOptions + ): Promise; + + /** Available on Android only. Creates a new attendee record and adds it to the specified event. Note that if eventId specifies a recurring event, this will add the attendee to every instance of the event. */ + function createAttendeeAsync( + /** ID of the event to add this attendee to. Required. */ + eventId: string, + + /** A map of details for the attendee to be created */ + details?: Attendee + ): Promise; + + /** Available on Android only. Updates an existing attendee record. To remove a property, explicitly set it to null in details. */ + function updateAttendeeAsync( + /** ID of the attendee record to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Attendee | null + ): Promise; + + /** Available on Android only. Deletes an existing attendee record from the device. Use with caution. */ + function deleteAttendeeAsync(id: string): Promise; + + /** Available on iOS only. Returns a list of reminders matching the provided criteria. */ + function getRemindersAsync( + /** Array of IDs of calendars to search for reminders in. Required. */ + calendarIds: string[], + + status?: ReminderStatus, + + /** Beginning of time period to search for reminders in. Required if status is defined. */ + startDate?: Date, + + /** End of time period to search for reminders in. Required if status is defined. */ + endDate?: Date + ): Promise; + + /** Available on iOS only. Returns a specific reminder selected by ID. */ + function getReminderAsync(id: string): Promise; + + /** Available on iOS only. Creates a new reminder on the specified calendar. */ + function createReminderAsync( + /** ID of the calendar to create this reminder in. Required. */ + calendarId: string, + + /** A map of details for the reminder to be created */ + details?: Reminder + ): Promise; + + /** Available on iOS only. Updates the provided details of an existing reminder stored on the device. To remove a property, explicitly set it to null in details. */ + function updateReminderAsync( + /** ID of the reminder to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Reminder | null + ): Promise; + + /** Available on iOS only. Deletes an existing reminder from the device. Use with caution. */ + function deleteReminderAsync(id: string): Promise; + + /** Available on iOS only. */ + function getSourcesAsync(): Promise; + + /** Available on iOS only. Returns a specific source selected by ID. */ + function getSourceAsync(id: string): Promise; + + /** Available on Android only. Sends an intent to open the specified event in the OS Calendar app. */ + function openEventInCalendar( + /** ID of the event to open. Required. */ + id: string + ): void; +} +// #endregion + +// #region MailComposer +/** + * An API to compose mails using OS specific UI. + */ +export namespace MailComposer { + interface ComposeOptions { + /** An array of e-mail addressess of the recipients. */ + recipients?: string[]; + + /** An array of e-mail addressess of the CC recipients. */ + ccRecipients?: string[]; + + /** An array of e-mail addressess of the BCC recipients. */ + bccRecipients?: string[]; + + /** Subject of the mail. */ + subject?: string; + + /** Body of the mail. */ + body?: string; + + /** Whether the body contains HTML tags so it could be formatted properly. Not working perfectly on Android. */ + isHtml?: boolean; + + /** An array of app’s internal file uris to attach. */ + attachments?: string[]; + } + + /** Resolves to a promise with object containing status field that could be either sent, saved or cancelled. Android does not provide such info so it always resolves to sent. */ + function composeAsync( + /** A map defining the data to fill the mail */ + options: ComposeOptions + ): Promise<{ status: 'sent' | 'saved' | 'cancelled' }>; +} +// #endregion + +export namespace Updates { + namespace EventType { + /** A new update is available and has started downloading. */ + type DownloadStart = 'downloadStart'; + /** A new update is currently being downloaded and will be stored in the device's cache. */ + type DownloadProgress = 'downloadProgress'; + /** A new update has finished downloading and is now stored in the device's cache. */ + type DownloadFinished = 'downloadFinished'; + /** No updates are available, and the most up-to-date bundle of this experience is already running. */ + type NoUpdateAvailable = 'noUpdateAvailable'; + /** An error occurred trying to fetch the latest update. */ + type Error = 'error'; + + /** A new update is available and has started downloading. */ + const DOWNLOAD_STARTED: DownloadStart; + /** A new update is currently being downloaded and will be stored in the device's cache. */ + const DOWNLOAD_PROGRESS: DownloadProgress; + /** A new update has finished downloading and is now stored in the device's cache. */ + const DOWNLOAD_FINISHED: DownloadFinished; + /** No updates are available, and the most up-to-date bundle of this experience is already running. */ + const NO_UPDATE_AVAILABLE: NoUpdateAvailable; + /** An error occurred trying to fetch the latest update. */ + const ERROR: Error; + } + + interface UpdateCheck { + /** True if an update is available, false if you're already running the most up-to-date JS bundle. */ + isAvailable: boolean; + /** If `isAvailable` is true, the manifest of the available update. Undefined otherwise. */ + manifest?: Constants.Manifest; + } + + interface UpdateBundle { + /** True if the fetched bundle is new (i.e. a different version that the what's currently running). */ + isNew: boolean; + /** Manifest of the fetched update. */ + manifest: Constants.Manifest; + } + + /** An object that is passed into each event listener when a new version is available. */ + interface UpdateEvent { + /** Type of the event */ + type: EventType.DownloadStart + | EventType.DownloadProgress + | EventType.DownloadFinished + | EventType.NoUpdateAvailable + | EventType.Error; + /** If `type === Expo.Updates.EventType.DOWNLOAD_FINISHED`, the manifest of the newly downloaded update. Undefined otherwise. */ + manifest?: Constants.Manifest; + /** If `type === Expo.Updates.EventType.ERROR`, the error message. Undefined otherwise. */ + message?: string; + } + + /** An optional params object passed to fetchUpdateAsync. */ + interface FetchUpdateAsyncParams { + eventListener: UpdateEventListener; + } + + type UpdateEventListener = (event: UpdateEvent) => any; + + /** + * Invokes a callback when updates-related events occur, + * either on the initial app load or as a result of a call to `Expo.Updates.fetchUpdateAsync`. + */ + function addListener(listener: UpdateEventListener): EventSubscription; + + /** + * Check if a new published version of your project is available. + * Does not actually download the update. + * Rejects if `updates.enabled` is `false` in app.json. + */ + function checkForUpdateAsync(): Promise; + + /** + * Downloads the most recent published version of your experience to the device's local cache. + * Rejects if `updates.enabled` is `false` in app.json. + */ + function fetchUpdateAsync(params?: FetchUpdateAsyncParams): Promise; + + /** + * Immediately reloads the current experience. + * This will use your app.json updates configuration to fetch and load the newest available JS supported by the device's Expo environment. + * This is useful for triggering an update of your experience if you have published a new version. + */ + function reload(): void; + + /** + * Immediately reloads the current experience using the most recent cached version. + * This is useful for triggering an update of your experience if you have published and already downloaded a new version. + */ + function reloadFromCache(): void; +} + +// #region MediaLibrary +/** + * https://docs.expo.io/versions/latest/sdk/media-library + * Provides access to user's media library + * Requires Permissions.CAMERA_ROLL permissions. + */ + +export namespace MediaLibrary { + /** + * Creates an asset from existing file. The most common use case is to save a picture taken by Camera. + */ + function createAssetAsync(localUri: string): Promise; + + /** + * Fetches a page of assets matching the provided criteria. + */ + function getAssetsAsync(options: GetAssetsOptions): Promise; + + /** + * Provides more informations about an asset, including GPS location, local URI and EXIF metadata. + */ + function getAssetInfoAsync(asset: string | Asset): Promise; + + /** + * Deletes assets from the library. On iOS it deletes assets from all albums they belong to, while on Android it keeps all copies of them + * (album is strictly connected to the asset). Also, there is additional dialog on iOS that requires user to confirm this action. + */ + function deleteAssetsAsync(asset: string[] | Asset[]): Promise; + + /** + * Queries for user-created albums in media gallery. + */ + function getAlbumsAsync(): Promise; + + /** + * Queries for an album with a specific name. + */ + function getAlbumAsync(albumName: string): Promise; + + /** + * Creates an album with given name and initial asset. + * The asset parameter is required on Android, since it's not possible to create empty album on this platform. + */ + function createAlbumAsync(albumName: string, asset: string | Asset): Promise; + + /** + * Adds array of assets to the album. + * On Android, by default it copies assets from the current album to provided one, however it's also possible to move them by passing false as copyAssets argument. + * In case they're copied you should keep in mind that getAssetsAsync will return duplicated assets. + */ + function addAssetsToAlbumAsync(assets: Asset[], album: string | Album, copyAssets?: boolean /* default true */): Promise; + + /** + * Removes given assets from album. + * On Android, album will be automatically deleted if there are no more assets inside. + */ + function removeAssetsFromAlbumAsync(assets: Asset[], album: string | Album): Promise; + + /** + * Available on iOS only. Fetches a list of moments, which is a group of assets taken around the same place and time. + */ + function getMomentsAsync(): Promise; + + enum MediaType { + audio = 'audio', + photo = 'photo', + video = 'video', + unknow = 'unknow' + } + + enum SortBy { + default = 'default', + id = 'id', + creationTime = 'creationTime', + modificationTime = 'modificationTime', + mediaType = 'mediaType', + width = 'width', + height = 'height', + duration = 'duration' + } + + // region Asset + interface AssetAndroid { + albumId?: string; + } + + interface AssetIos { + mediaSubtypes?: MediaType[]; + // * + orientation: number; + // * + isFavorite: boolean; + } + + interface Asset extends AssetAndroid, AssetIos { + id: string; + filename: string; + uri: string; + mediaType: string; + width: number; + height: number; + creationTime: number; + modificationTime: number; + duration: number; + // * + localUri?: string; + // * + location?: Location.LocationProps; + // * + exif?: object; + } + + /** + * These fields can be obtained only by calling getAssetInfoAsync method + */ + //#endregion + + // #region Album + interface AlbumIos { + type?: string; + // * + startTime: number; + // * + endTime: number; + // * + approximateLocation?: Location.LocationProps; + // * + locationNames?: string[]; + } + + /** + * These fields apply only to albums whose type is moment + */ + + interface Album extends AlbumIos { + id: string; + title: string; + assetCount: number; + } + // #endregion + + interface GetAssetsOptions { + first?: number; + after?: string; + album?: string | Album; + sortBy?: SortBy; + mediaType?: MediaType; + } + + interface GetAssetsResult { + assets: Asset[]; + endCursor: string; + hasNextPage: boolean; + totalCount: number; + } +} +// #endregion + +// #region Haptic +/** + * https://docs.expo.io/versions/latest/sdk/haptic + * Provides haptic feedback for iOS 10+ devices using the Taptic Engine. + * If this is used in Android the device will use ReactNative.Vibrate instead, it's best to just avoid this. + */ +export namespace Haptic { + /** + * Used to let a user know when a selection change has been registered + */ + function selection(): void; + function notification(notificationType?: NotificationType): void; + function impact(impactStyles?: ImpactStyles): void; + + enum ImpactStyles { + Light = 'light', + Medium = 'medium', + Heavy = 'heavy' + } + + enum NotificationType { + Success = 'success', + Warning = 'warning', + Error = 'error' + } +} +// #endregion diff --git a/types/expo/v31/tsconfig.json b/types/expo/v31/tsconfig.json new file mode 100644 index 0000000000..ae698d5f5e --- /dev/null +++ b/types/expo/v31/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "expo": [ + "expo/v31" + ], + "expo/*": [ + "expo/v31/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expo-tests.tsx" + ] +} diff --git a/types/expo/v31/tslint.json b/types/expo/v31/tslint.json new file mode 100644 index 0000000000..8270136207 --- /dev/null +++ b/types/expo/v31/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "void-return": false, + "max-line-length": false + } +} diff --git a/types/express-unless/express-unless-tests.ts b/types/express-unless/express-unless-tests.ts index 4a90728f1c..b4d579e742 100644 --- a/types/express-unless/express-unless-tests.ts +++ b/types/express-unless/express-unless-tests.ts @@ -1,11 +1,11 @@ - -import express = require('express'); -import unless = require('express-unless'); +import express = require("express"); +import unless = require("express-unless"); var app = express(); -var middleware:unless.RequestHandler = function (req, res, next) { +var middleware: unless.RequestHandler = function(req, res, next) { next(); -} +}; middleware.unless = unless; -app.use(middleware.unless({ method: 'OPTIONS' })); \ No newline at end of file +app.use(middleware.unless({ method: "OPTIONS" })); +app.use(middleware.unless(req => req.path === "test")); diff --git a/types/express-unless/index.d.ts b/types/express-unless/index.d.ts index 7d7056f766..79eb870cb3 100644 --- a/types/express-unless/index.d.ts +++ b/types/express-unless/index.d.ts @@ -1,19 +1,21 @@ -// Type definitions for express-unless +// Type definitions for express-unless 0.5 // Project: https://www.npmjs.org/package/express-unless // Definitions by: Wonshik Kim +// Joao Vieira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import express = require('express'); +import express = require("express"); declare function unless(options: unless.Options): express.RequestHandler; +declare function unless(options: unless.Options["custom"]): express.RequestHandler; declare namespace unless { export interface Options { custom?: (req: express.Request) => boolean; - path?: any; // TODO: union type 'string|string[]' is not supported yet - ext?: any; // TODO: union type 'string|string[]' is not supported yet - method?: any; // TODO: union type 'string|string[]' is not supported yet + path?: string | string[]; + ext?: string | string[]; + method?: string | string[]; } export interface RequestHandler extends express.RequestHandler { unless?: typeof unless; diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 6a90a19481..5cc59d0941 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -614,6 +614,10 @@ interface IPatternOptions { * The source for the pattern */ source: string | HTMLImageElement; + /** + * Transform matrix to change the pattern, imported from svgs + */ + patternTransform?: number[]; } export interface Pattern extends IPatternOptions { } export class Pattern { @@ -3770,7 +3774,18 @@ interface IAllFilters { */ fromObject(object: any): IBrightnessFilter }; - Convolute: { + ColorMatrix: { + new(options?: { + /** Filter matrix */ + matrix?: number[] + }): IColorMatrix; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IColorMatrix + }; + Convolute: { new(options?: { opaque?: boolean, /** Filter matrix */ @@ -3958,6 +3973,13 @@ interface IBrightnessFilter extends IBaseFilter { */ applyTo(canvasEl: HTMLCanvasElement): void; } +interface IColorMatrix extends IBaseFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} interface IConvoluteFilter extends IBaseFilter { /** * Applies filter to canvas element @@ -4638,6 +4660,11 @@ interface IUtilMisc { */ qrDecompose(a: number[]): { angle: number, scaleX: number, scaleY: number, skewX: number, skewY: number, translateX: number, translateY: number }; + /** + * Creates a transform matrix with the specified scale and skew + */ + customTransformMatrix(scaleX: number, scaleY: number, skewX: number): number[]; + /** * Returns string representation of function body * @param fn Function to get body of diff --git a/types/fastify-cors/fastify-cors-tests.ts b/types/fastify-cors/fastify-cors-tests.ts deleted file mode 100644 index 5fcd7e20d4..0000000000 --- a/types/fastify-cors/fastify-cors-tests.ts +++ /dev/null @@ -1,89 +0,0 @@ -import fastifyCors = require("fastify-cors"); - -fastifyCors(); - -const fastifyCorsOptions: fastifyCors.FastifyCorsOptions = { - origin: true, - allowedHeaders: "authorization,content-type", - methods: "GET,POST,PUT,PATCH,DELETE,OPTIONS", - credentials: true, - exposedHeaders: "authorization", - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const fastifyCorsOptionsArray: fastifyCors.FastifyCorsOptions = { - origin: true, - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originString: fastifyCors.FastifyCorsOptions = { - origin: "*", - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originRegexp: fastifyCors.FastifyCorsOptions = { - origin: /\*/, - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originStringArray: fastifyCors.FastifyCorsOptions = { - origin: ["*", "something"], - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originRegexpArray: fastifyCors.FastifyCorsOptions = { - origin: [/\*/, /something/], - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originCallback: fastifyCors.FastifyCorsOptions = { - origin: (err: Error, allow: boolean) => { - throw err; - }, - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; diff --git a/types/fastify-cors/index.d.ts b/types/fastify-cors/index.d.ts deleted file mode 100644 index 907689a72c..0000000000 --- a/types/fastify-cors/index.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -// Type definitions for fastify-cors 0.1 -// Project: https://github.com/fastify/fastify-cors#readme -// Definitions by: Jannik Keye -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -type originCallback = (err: Error, allow: boolean) => void; - -/** - * fastify-cors enables the use of CORS in a Fastify application. - */ -declare function fastifyCors(): void; - -declare namespace fastifyCors { - /** - * Options for configuring the fastify-cors plugin. - */ - interface FastifyCorsOptions { - /** - * Configures the Access-Control-Allow-Origin CORS header. - */ - origin?: string | boolean | RegExp | string[] | RegExp[] | originCallback; - /** - * Configures the Access-Control-Allow-Credentials CORS header. - * Set to true to pass the header, otherwise it is omitted. - */ - credentials?: boolean; - /** - * Configures the Access-Control-Expose-Headers CORS header. - * Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') - * or an array (ex: ['Content-Range', 'X-Content-Range']). - * If not specified, no custom headers are exposed. - */ - exposedHeaders?: string | string[]; - /** - * Configures the Access-Control-Allow-Headers CORS header. - * Expects a comma-delimited string (ex: 'Content-Type,Authorization') - * or an array (ex: ['Content-Type', 'Authorization']). If not - * specified, defaults to reflecting the headers specified in the - * request's Access-Control-Request-Headers header. - */ - allowedHeaders?: string | string[]; - /** - * Configures the Access-Control-Allow-Methods CORS header. - * Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: ['GET', 'PUT', 'POST']). - */ - methods?: string | string[]; - /** - * Configures the Access-Control-Max-Age CORS header. - * Set to an integer to pass the header, otherwise it is omitted. - */ - maxAge?: number; - /** - * Pass the CORS preflight response to the route handler (default: false). - */ - preflightContinue?: boolean; - /** - * Provides a status code to use for successful OPTIONS requests, - * since some legacy browsers (IE11, various SmartTVs) choke on 204. - */ - optionsSuccessStatus?: number; - /** - * Pass the CORS preflight response to the route handler (default: false). - */ - preflight?: boolean; - } -} - -export = fastifyCors; diff --git a/types/fastify-static/fastify-static-tests.ts b/types/fastify-static/fastify-static-tests.ts deleted file mode 100644 index 630fc0ef52..0000000000 --- a/types/fastify-static/fastify-static-tests.ts +++ /dev/null @@ -1,16 +0,0 @@ -import path = require("path"); -import fastify = require("fastify"); -import fastifyStatic = require("fastify-static"); - -const app = fastify(); - -app.register(fastifyStatic, { - root: path.join(__dirname, "public"), - prefix: "/public/", // optional: default '/' - immutable: true, - maxAge: 42 -}); - -app.get("/another/path", (req, reply) => { - reply.sendFile("myHtml.html"); // serving path.join(__dirname, 'public', 'myHtml.html') directly -}); diff --git a/types/fastify-static/index.d.ts b/types/fastify-static/index.d.ts deleted file mode 100644 index ef4eda1952..0000000000 --- a/types/fastify-static/index.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Type definitions for fastify-static 0.14 -// Project: https://github.com/fastify/fastify-static -// Definitions by: Leonhard Melzer -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 - -import fastify = require("fastify"); - -import { Server, IncomingMessage, ServerResponse } from "http"; - -declare module "fastify" { - interface FastifyReply { - sendFile(filename: string): FastifyReply; - } -} - -declare function fastifyStatic(): void; - -declare namespace fastifyStatic { - interface FastifyStaticOptions { - root: string; - prefix?: string; - serve?: boolean; - decorateReply?: boolean; - schemaHide?: boolean; - setHeaders?: () => void; - - // Passed on to `send` - acceptRanges?: boolean; - cacheControl?: boolean; - dotfiles?: boolean; - etag?: boolean; - extensions?: string[]; - immutable?: boolean; - index?: string[]; - lastModified?: boolean; - maxAge?: string | number; - } -} - -export = fastifyStatic; diff --git a/types/feathersjs__errors/index.d.ts b/types/feathersjs__errors/index.d.ts index 056acff676..3994e2056c 100644 --- a/types/feathersjs__errors/index.d.ts +++ b/types/feathersjs__errors/index.d.ts @@ -1,11 +1,26 @@ -// Type definitions for @feathersjs/errors 3.2 +// Type definitions for @feathersjs/errors 3.3 // Project: http://feathersjs.com/ // Definitions by: Jan Lohage +// RazzM13 // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript // TypeScript Version: 2.2 +export interface FeathersErrorJSON { + readonly name: string; + readonly message: string; + readonly code: number; + readonly className: string; + readonly data: any; + readonly errors: any; +} + export class FeathersError extends Error { - constructor(msg: string | Error, name: string, code: number, className: string, data: any) + readonly code: number; + readonly className: string; + readonly data: any; + readonly errors: any; + constructor(msg: string | Error, name: string, code: number, className: string, data: any); + toJSON(): FeathersErrorJSON; } export class BadRequest extends FeathersError { diff --git a/types/generic-pool/generic-pool-tests.ts b/types/generic-pool/generic-pool-tests.ts index 28590def30..09a46ccf84 100644 --- a/types/generic-pool/generic-pool-tests.ts +++ b/types/generic-pool/generic-pool-tests.ts @@ -29,6 +29,7 @@ const opts = { min: 2, maxWaitingClients: 2, testOnBorrow: true, + testOnReturn: true, acquireTimeoutMillis: 100, fifo: true, priorityRange: 5, diff --git a/types/generic-pool/index.d.ts b/types/generic-pool/index.d.ts index 6bb537e9ba..14fea9497f 100644 --- a/types/generic-pool/index.d.ts +++ b/types/generic-pool/index.d.ts @@ -38,6 +38,7 @@ export interface Options { min?: number; maxWaitingClients?: number; testOnBorrow?: boolean; + testOnReturn?: boolean; acquireTimeoutMillis?: number; fifo?: boolean; priorityRange?: number; diff --git a/types/hexo/hexo-tests.ts b/types/hexo/hexo-tests.ts new file mode 100644 index 0000000000..3c00489c3a --- /dev/null +++ b/types/hexo/hexo-tests.ts @@ -0,0 +1,462 @@ +import Hexo = require('hexo'); +import fs = require('fs'); +import Bunyan = require('bunyan'); +import { ParsedArgs } from 'minimist'; +import util = require('hexo-util'); +import http = require('http'); + +const config: Hexo.InstanceOptions = {}; +config.debug = false; +config.safe = false; +config.silent = false; +config.config = '_config.yml'; + +let h: Hexo; +h = hexo; +h = new Hexo(); +h = new Hexo('./'); +h = new Hexo('./', config); + +const logger: Bunyan = h.log; +console.log(h.base_dir); +console.log(h.public_dir); +console.log(h.source_dir); +console.log(h.plugin_dir); +console.log(h.script_dir); +console.log(h.scaffold_dir); +console.log(h.theme_dir); +console.log(h.theme_script_dir); +console.log(h.config_path); +console.log(h.env.args); +console.log(h.env.debug); +console.log(h.env.safe); +console.log(h.env.silent); +console.log(h.env.env); +console.log(h.env.version); +console.log(h.env.init); +console.log(h.config.title); +console.log(h.config.subtitle); +console.log(h.config.description); +console.log(h.config.author); +console.log(h.config.language); +console.log(h.config.timezone); +console.log(h.config.url); +console.log(h.config.root); +console.log(h.config.permalink); +console.log(h.config.permalink_defaults); +console.log(h.config.source_dir); +console.log(h.config.public_dir); +console.log(h.config.tag_dir); +console.log(h.config.archive_dir); +console.log(h.config.category_dir); +console.log(h.config.code_dir); +console.log(h.config.i18n_dir); +console.log(h.config.skip_render); +console.log(h.config.new_post_name); +console.log(h.config.default_layout); +console.log(h.config.titlecase); +console.log(h.config.external_link); +console.log(h.config.filename_case); +console.log(h.config.render_drafts); +console.log(h.config.post_asset_folder); +console.log(h.config.relative_link); +console.log(h.config.future); +console.log(h.config.highlight.enable); +console.log(h.config.highlight.line_number); +console.log(h.config.highlight.auto_detect); +console.log(h.config.highlight.tab_replace); +console.log(h.config.default_category); +console.log(h.config.category_map); +console.log(h.config.tag_map); +console.log(h.config.time_format); +console.log(h.config.per_page); +console.log(h.config.pagination_dir); +console.log(h.config.theme); +console.log(h.config.theme_config); +console.log(h.config.deploy); +console.log(h.config.include); +console.log(h.config.exclude); +console.log(h.config.ignore); + +h.init().then(async () => { + await h.watch(); + h.unwatch(); + + await h.theme.watch(); + h.theme.unwatch(); + + await h.source.watch(); + h.source.unwatch(); + + await h.load(); + h.call('config', {_: ['arg1']}, (err, value) => {}); + + await h.exit(); +}); + +h.on('ready', () => { + h.on('deployBefore', () => {}); + h.on('deployAfter', () => {}); + h.on('exit', err => { + console.log(err); + }); + h.on('generateBefore', () => {}); + h.on('generateAfter', () => {}); + h.on('new', param => { + const path: string = param.path; + const content: string = param.content; + }); + h.on('processBefore', (type, path) => { + const t: Hexo.Box.File['type'] = type; + const p: string = path; + }); + h.on('processAfter', (type, path) => { + const t: Hexo.Box.File['type'] = type; + const p: string = path; + }); + h.on('ready', () => {}); + + { + let local: Hexo.Locals.Post[] = []; + const model = hexo.locals.get('posts'); + + local = model.toArray(); + const count: number = model.count(); + model.filter(v => true); + model.forEach(v => {}); + model.map(v => v.name); + } + + { + let local: Hexo.Locals.Page[] = []; + const model = hexo.locals.get('pages'); + + local = model.toArray(); + const count: number = model.count(); + model.filter(v => true); + model.forEach(v => {}); + model.map(v => v.name); + } + + { + let local: Hexo.Locals.Category[] = []; + const model = hexo.locals.get('categories'); + + local = model.toArray(); + const count: number = model.count(); + model.filter(v => true); + model.forEach(v => {}); + model.map(v => v.name); + } + + { + let local: Hexo.Locals.Tag[] = []; + const model = hexo.locals.get('tags'); + + local = model.toArray(); + const count: number = model.count(); + model.filter(v => true); + model.forEach(v => {}); + model.map(v => v.name); + } + + { + h.locals.set('some-data', () => 'some vlue'); + h.locals.remove('some-data'); + h.locals.toObject(); + h.locals.invalidate(); + } + + { + const route = h.route.get('index.html'); + if (route) { + console.log(route.modified); + console.log(route.read()); + } + + const data: Hexo.Router.Data = { + data: 'some data', + modified: true, + }; + data.data = new Buffer([]); + data.data = () => 'return'; + + let router: Hexo.Router; + router = h.route; + router = h.route.set('index.html', 'content'); + router = h.route.set('index.html', new Buffer([])); + router = h.route.set('index.html', new util.Pattern(() => false)); + router = h.route.set('index.html', { data: 'index', modified: false }); + + router = h.route.remove('index.html'); + + const list: string[] = h.route.list(); + const format: string = h.route.format('/'); + } + + { + h.source.process(() => {}); + h.source.addProcessor('path', file => { + console.log(file.source); + console.log(file.path); + console.log(file.type); + console.log(file.params); + + file.read((err, content) => { + console.log(err, content.toString()); + console.log(content); + }); + + file.read({encoding: 'utf8', flag: 'r'}, (err, content) => { + console.log(err, content.toString()); + console.log(content); + }); + + file.readSync({encoding: 'utf8', flag: 'r'}); + + file.stat((err, stat) => { + console.log(err); + console.log(stat.mtime); + console.log(stat.ctime); + console.log(stat.atime); + }); + + file.stat().then(stat => { + console.log(stat.mtime); + console.log(stat.ctime); + console.log(stat.atime); + }); + + const stat: fs.Stats = file.statSync(); + + let render = ''; + file.render({}, (err, result) => { + render = result; + }); + file.render((err, result) => { + render = result; + }); + file.render().then(result => { + render = result; + }); + render = file.renderSync(); + }); + } + + { + let _bool = true; + _bool = h.render.isRenderable('path'); + _bool = h.render.isRenderableSync('path'); + + const option: Hexo.Render.Data = { + engine: 'ejs', + text: 'test', + path: __filename, + }; + + let _string = ''; + h.render.render({text: 'example', engine: 'swig'}).then(result => { + _string = result; + }); + h.render.render({path: __filename}).then(result => { + _string = result; + }); + h.render.render({text: ''}, {foo: 'foo'}).then(result => { + _string = result; + }); + _string = h.render.renderSync({text: 'example'}); + + _string = h.render.getOutput('ejs'); + } + + { + const data: Hexo.Post.Data = {}; + data.title = 'Title'; + data.slug = 'URL'; + data.layout = 'layout_name'; + data.path = 'path'; + data.date = new Date(); + + h.post.create(data, false, () => {}); + h.post.create(data, () => {}); + + h.post.publish(data, false, () => {}); + h.post.publish(data, () => {}); + + const renderData: Hexo.Post.RenderData = {}; + renderData.content = 'content'; + renderData.engine = 'ejs'; + h.post.render(null, renderData, () => {}); + } + + { + h.scaffold.get('post').then(result => ''); + h.scaffold.set('post', '').then(() => {}); + h.scaffold.remove('post').then(() => {}); + } + + { + const themeConfig: Hexo['config'] = h.theme.config; + let v: Hexo.View | undefined; + h.theme.setView('path-name', {}); + v = h.theme.getView('post'); + if (v) { + console.log(v.path); + console.log(v.source); + + v.render().then(result => {}); + v.renderSync(); + } + + h.theme.removeView('path-name'); + h.theme.process(() => {}); + } + + { + const options: Hexo.extend.Console.Options = {}; + options.usage = '[layout] '; + options.arguments = [ + {name: 'layout', desc: 'Post layout'}, + {name: 'title', desc: 'Post title'}, + ]; + options.options = [ + {name: '-r, --replace', desc: 'Replace existing files'}, + ]; + options.desc = 'desc'; + + h.extend.console.register('name', 'description', options, args => { + const a: ParsedArgs = args; + }); + h.extend.console.register('name', options, args => {}); + h.extend.console.register('name', 'description', args => {}); + h.extend.console.register('name', args => {}); + } + + { + h.extend.deployer.register('name', args => { + console.log(args.type); + console.log(args.someExtraArg); + }); + } + + { + h.extend.filter.register('before_post_render', data => data); + h.extend.filter.register('before_post_render', data => undefined); + h.extend.filter.register('before_post_render', data => undefined, 1); + + h.extend.filter.register('after_post_render', data => data); + h.extend.filter.register('after_post_render', data => undefined); + h.extend.filter.register('after_post_render', data => undefined, 1); + + h.extend.filter.register('before_exit', () => {}); + h.extend.filter.register('before_exit', () => {}, 1); + + h.extend.filter.register('before_generate', data => data); + h.extend.filter.register('before_generate', data => undefined); + h.extend.filter.register('before_generate', data => undefined, 1); + + h.extend.filter.register('after_generate', () => {}); + h.extend.filter.register('after_generate', () => {}, 1); + + h.extend.filter.register('template_locals', locals => locals); + h.extend.filter.register('template_locals', locals => undefined); + h.extend.filter.register('template_locals', locals => undefined, 1); + + h.extend.filter.register('after_init', () => {}); + h.extend.filter.register('after_init', () => {}, 1); + + h.extend.filter.register('new_post_path', (data, replace) => undefined); + h.extend.filter.register('new_post_path', (data, replace) => undefined, 1); + + h.extend.filter.register('post_permalink', permalink => permalink); + h.extend.filter.register('post_permalink', permalink => permalink, 1); + + h.extend.filter.register('after_render:html', (result, data) => result); + h.extend.filter.register('after_render:html', (result, data) => result, 1); + + h.extend.filter.register('after_clean', () => {}); + h.extend.filter.register('after_clean', () => {}, 1); + + h.extend.filter.register('server_middleware', app => { + app.use((req: http.IncomingMessage, res: http.ServerResponse) => { + res.setHeader('X-Powered-By', 'Hexo'); + }); + }); + + const filter = (data: any) => data; + h.extend.filter.register('custom_filter', filter); + h.extend.filter.unregister('custom_filter', filter); + + const options: Hexo.extend.Filter.Options = {}; + options.args = ['foo', 'bar']; + options.context = h; + h.extend.filter.exec('custom_filter', options); + h.extend.filter.exec('custom_filter'); + h.extend.filter.execSync('custom_filter', options); + h.extend.filter.execSync('custom_filter'); + } + + { + const ret: Hexo.extend.Generator.Return = { + data: {}, + layout: 'layout-name', + path: '/', + }; + h.extend.generator.register('name', local => ret); + h.extend.generator.register('name', local => [ret]); + h.extend.generator.register('name', local => { + console.log(local.data); + const categories: Hexo.Locals.Category[] = local.categories.toArray(); + const pages: Hexo.Locals.Page[] = local.pages.toArray(); + const posts: Hexo.Locals.Post[] = local.posts.toArray(); + const tags: Hexo.Locals.Tag[] = local.tags.toArray(); + + return ret; + }); + } + + { + h.extend.helper.register('name', (...args) => { + return 'ret'; + }); + } + + { + h.extend.migrator.register('name', args => { + const a: ParsedArgs = args; + }); + } + + { + let f: Hexo.Box.File; + h.extend.processor.register('pattern', file => f = file); + h.extend.processor.register(/pattern/, file => f = file); + h.extend.processor.register((str) => true , file => f = file); + h.extend.processor.register(file => f = file); + } + + { + h.extend.renderer.register('ts', 'js', (data, options) => { + console.log(data.path); + console.log(data.text); + return 'result'; + }, true); + + h.extend.renderer.register('ts', 'js', (data, options) => Promise.resolve('result'), false); + h.extend.renderer.register('ts', 'js', (data, options) => Promise.resolve('result')); + } + + { + const option: Hexo.extend.Tag.Options = {}; + option.async = true; + option.ends = true; + + h.extend.tag.register('name', (args, content) => { + if (content) { + const c: string = content; + } + const a: string[] = args; + return 'content'; + }); + } +}); diff --git a/types/hexo/index.d.ts b/types/hexo/index.d.ts new file mode 100644 index 0000000000..0f3a9dcc78 --- /dev/null +++ b/types/hexo/index.d.ts @@ -0,0 +1,976 @@ +// Type definitions for hexo 3.8 +// Project: https://hexo.io/ +// Definitions by: KentarouTakeda <https://github.com/kentarouTakeda> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import EventEmitter = require('events'); +import moment = require('moment'); +import { ParsedArgs } from 'minimist'; +import Logger = require('bunyan'); +import underscore = require('underscore'); +import connect = require('connect'); +import Stream = require('stream'); +import util = require('hexo-util'); +import fs = require('fs'); + +declare global { + const hexo: Hexo; +} + +interface HexoConfig { + [key: string]: any; + /** + * The title of your website + */ + readonly title: string; + + /** + * The subtitle of your website + */ + readonly subtitle: string; + + /** + * The description of your website + */ + readonly description: string; + + /* + * Your name + */ + readonly author: string; + + /** + * The language of your website. Use a 2-lettter ISO-639-1 code. Default is en. + */ + readonly language: string; + + /** + * The timezone of your website. Hexo uses the setting on your computer by default. + * You can find the list of available timezones [here]{@link https://en.wikipedia.org/wiki/List_of_tz_database_time_zones} . + * Some examples are `America/New_York` , `Japan` , and `UTC` . + */ + readonly timezone: string; + + /* + * The URL of your website + */ + readonly url: string; + + /** + * The root directory of your website + */ + readonly root: string; + + /** + * The permalink format of articles + */ + readonly permalink: string; + + /** + * Default values of each segment in permalink + */ + readonly permalink_defaults: string|null; + + /** + * Source folder. Where your content is stored + */ + readonly source_dir: string; + + /** + * Public folder. Where the static site will be generated + */ + readonly public_dir: string; + + /** + * Tag directory + */ + readonly tag_dir: string; + + /** + * Archive directory + */ + readonly archive_dir: string; + + /** + * Category directory + */ + readonly category_dir: string; + + /** + * Include code directory (subdirectory of source_dir) + */ + readonly code_dir: string; + + /** + * i18n directory + */ + readonly i18n_dir: string; + + /** + * Paths that will be copied to public raw, without being rendered. You can use glob expressions for path matching. + */ + readonly skip_render: string|string[]|null; + + /** + * The filename format for new posts + */ + readonly new_post_name: string; + + /** + * Default layout + */ + readonly default_layout: string; + + /** + * Transform titles into title case? + */ + readonly titlecase: boolean; + + /** + * Open external links in a new tab? + */ + readonly external_link: boolean; + + /** + * Transform filenames to 1 lower case; 2 upper case + */ + readonly filename_case: number; + + /** + * Display drafts? + */ + readonly render_drafts: boolean; + + /** + * Enable the Asset Folder? + */ + readonly post_asset_folder: boolean; + + /** + * Make links relative to the root folder? + */ + readonly relative_link: boolean; + + /** + * Display future posts? + */ + readonly future: boolean; + + /** + * Code block settings + */ + readonly highlight: { + readonly enable: boolean; + readonly line_number: boolean; + readonly auto_detect: boolean; + readonly tab_replace: string|null; + }; + + /** + * Default category + */ + readonly default_category: string; + + /** + * Category slugs + */ + readonly category_map: {[key: string]: string|number}; + + /** + * Tag slugs + */ + readonly tag_map: {[key: string]: string|number}; + + /** + * Date format + * https://momentjs.com/ + */ + readonly date_format: string; + + /** + * Time format + * https://momentjs.com/ + */ + readonly time_format: string; + + /** + * The amount of posts displayed on a single page. 0 disables pagination + */ + readonly per_page: number; + + /** + * Pagination directory + */ + readonly pagination_dir: string; + + /** + * Theme name. false disables theming + */ + readonly theme: string|false; + + /** + * Theme configuration. Include any custom theme settings under this key to override theme defaults. + */ + readonly theme_config: {[key: string]: string|number}; + + /** + * Deployment settings + */ + readonly deploy: Hexo.extend.Deployer.Config | Hexo.extend.Deployer.Config | null; + + /** + * Hexo by default ignores hidden files and folders, but setting this field will make Hexo process them + */ + readonly include ?: string[]; + + /** + * Hexo process will ignore files list under this field + */ + readonly exclude ?: string[]; + readonly ignore: string[]; +} + +interface Model<T> { + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + toArray(): T[]; + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + count(): number; + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + forEach(fn: (v: T, i: number) => void): void; + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + filter(fn: (v: T, i: number) => boolean): Model<T>; + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + map<U>(fn: (v: T, i: number) => U): U[]; +} + +interface Site { + posts: Model<Hexo.Locals.Post>; + pages: Model<Hexo.Locals.Page>; + categories: Model<Hexo.Locals.Category>; + tags: Model<Hexo.Locals.Tag>; + data: {[key: string]: any}; +} + +declare class Hexo extends EventEmitter { + /** + * Create a Hexo instance. + * @param base the root directory of the website, `base_dir` . + * @param args an object containing the initialization options. + */ + constructor(base?: string, args?: Hexo.InstanceOptions); + + /** + * Load configuration and plugins. + */ + init(): Promise<void>; + + /** + * Loading all files in the `source` folder as well as the theme data. + */ + load(fn?: (err: any, value: any) => void): Promise<any>; + + /** + * The same things `load` does, but will also start watching for file changes continuously. + */ + watch(fn?: (err: any, value: any) => void): Promise<any>; + + unwatch(): void; + + /** + * Any console command can be called explicitly using the call method on the Hexo instance. + */ + call(name: string, args?: any, fn?: (err: any, value: any) => void): Promise<any>; + call(name: string, fn?: (err: any, value: any) => void): Promise<any>; + + /** + * You should call the `exit` method upon successful or unsuccessful completion of a console command. + * This allows Hexo to exit gracefully and finish up important things such as saving the database. + */ + exit(err?: any): Promise<void>; + + /** + * Site settings in `_config.yml` + */ + readonly config: HexoConfig; + + readonly theme: Hexo.Theme; + readonly source: Hexo.Box; + readonly post: Hexo.Post; + readonly render: Hexo.Render; + + /** + * Local variables are used for template rendering, which is the `site` variable in templates. + * https://hexo.io/api/locals + */ + readonly locals: Hexo.Locals; + + readonly base_dir: string; + + /** + * Public folder. Where the static site will be generated + */ + readonly public_dir: string; + + /** + * Source folder. Where your content is stored + */ + readonly source_dir: string; + + readonly plugin_dir: string; + readonly script_dir: string; + readonly scaffold_dir: string; + readonly theme_dir: string; + readonly theme_script_dir: string; + readonly config_path: string; + readonly env: { + readonly args: ParsedArgs; + readonly debug: boolean; + readonly safe: boolean; + readonly silent: boolean; + readonly env: string; + readonly version: string; + readonly init: boolean; + }; + + /** + * Logger object + * https://www.npmjs.com/package/bunyan + */ + readonly log: Logger; + + readonly extend: { + /** + * The console forms the bridge between Hexo and its users. It registers and describes the available console commands. + */ + readonly console: Hexo.extend.Console; + /** + * A deployer helps users quickly deploy their site to a remote server without complicated commands. + */ + readonly deployer: Hexo.extend.Deployer; + /** + * A filter is used to modify some specified data. Hexo passes data to filters in sequence and the filters then modify the data one after the other. + */ + readonly filter: Hexo.extend.Filter; + /** + * A generator builds routes based on processed files. + */ + readonly generator: Hexo.extend.Generator; + /** + * A helper makes it easy to quickly add snippets to your templates. We recommend using helpers instead of templates when you’re dealing with more complicated code. + */ + readonly helper: Hexo.extend.Helper; + /** + * A migrator helps users migrate from other systems to Hexo. + */ + readonly migrator: Hexo.extend.Migrator; + /** + * A processor is used to process source files in the source folder. + */ + readonly processor: Hexo.extend.Processor; + /** + * A renderer is used to render content. + */ + readonly renderer: Hexo.extend.Renderer; + /** + * A tag allows users to quickly and easily insert snippets into their posts. + */ + readonly tag: Hexo.extend.Tag; + }; + + readonly route: Hexo.Router; + readonly scaffold: Hexo.Scaffold; + + /** + * Emitted before deployment begins. + */ + on(ev: 'deployBefore', fn: () => void): this; + + /** + * Emitted after deployment finishes. + */ + on(ev: 'deployAfter', fn: () => void): this; + + /** + * Emitted before Hexo exits. + */ + on(ev: 'exit', fn: (err: any) => void): this; + + /** + * Emitted before generation begins. + */ + on(ev: 'generateBefore', fn: () => void): this; + + /** + * Emitted after generation finishes. + */ + on(ev: 'generateAfter', fn: () => void): this; + + /** + * Emitted after a new post has been created. This event returns the post data: + */ + on(ev: 'new', fn: (post: {path: string, content: string}) => void): this; + + /** + * Emitted before processing begins. This event returns a path representing the root directory of the box. + */ + on(ev: 'processBefore', fn: (type: Hexo.Box.File['type'], path: string) => void): this; + + /** + * Emitted after processing finishes. This event returns a path representing the root directory of the box. + */ + on(ev: 'processAfter', fn: (type: Hexo.Box.File['type'], path: string) => void): this; + + /** + * Emitted after initialization finishes. + */ + on(ev: 'ready', fn: () => void): this; +} + +declare namespace Hexo { + interface InstanceOptions { + debug?: boolean; + safe?: boolean; + silent?: boolean; + config?: string; + } + + interface Locals { + get(type: 'posts'): Model<Locals.Post>; + get(type: 'pages'): Model<Locals.Page>; + get(type: 'categories'): Model<Locals.Category>; + get(type: 'tags'): Model<Locals.Tag>; + /** + * Get a Variable + */ + get(type: string): any; + + /** + * Set a Variable + */ + set(type: string, fn: () => any): this; + + /** + * Remove a Variable + */ + remove(type: string): this; + + /** + * Get All Variable + */ + toObject(): any; + + /** + * Invalidate the cache + */ + invalidate(): this; + } + namespace Locals { + interface Page { + title: string; + date: moment.Moment; + updated?: moment.Moment; + comments: boolean; + layout: string; + content: string; + excerpt?: string; + more?: string; + source: string; + full_source: string; + path: string; + permalink: string; + prev?: null|Page; + next?: null|Page; + raw?: string; + photos?: string[]; + link?: string; + [key: string]: any; + } + + interface Post extends Page { + published?: boolean; + categories?: string[]; + tags: string[]; + } + + interface Tag { + name: string; + slug: string; + path: string; + permalink: string; + posts: Model<Post>; + length: number; + } + interface Category extends Tag { + parent: string; + } + } + + namespace extend { + interface Console { + register(name: string, desc: string, options: Console.Options, fn: (args: ParsedArgs) => void): void; + register(name: string, options: Console.Options, fn: (args: ParsedArgs) => void): void; + register(name: string, desc: string, fn: (args: ParsedArgs) => void): void; + register(name: string, fn: (args: ParsedArgs) => void): void; + } + namespace Console { + interface Options { + /** + * The usage of a console command. + */ + usage?: string; + + /** + * The description of each argument of a console command. + */ + arguments?: Array<{name: string, desc: string}>; + + /** + * The description of each option of a console command. + */ + options?: Array<{name: string, desc: string}>; + + /** + * More detailed information about a console command. + */ + desc?: string; + } + } + + interface Deployer { + register(name: string, fn: (args: Deployer.Config) => void): void; + } + namespace Deployer { + interface Config { + readonly type: string|undefined; + readonly [key: string]: any; + } + } + + interface Filter { + register(type: string, fn: (data: any, ...args: any[]) => any, priority?: number): void; + + /** + * Executed before a post is rendered. Refer to post rendering to learn the execution steps. + */ + register(type: 'before_post_render', fn: (data: { content: string, [key: string]: any }) => { content: string, [key: string]: any }|void, priority?: number): void; + + /** + * Executed after a post is rendered. Refer to post rendering to learn the execution steps. + */ + register(type: 'after_post_render', fn: (data: { content: string, [key: string]: any }) => { content: string, [key: string]: any }|void, priority?: number): void; + + /** + * Executed before Hexo is about to exit – this will run right after `hexo.exit` is called. + */ + register(type: 'before_exit', fn: () => void, priority?: number): void; + + /** + * Executed before generation begins. + */ + register(type: 'before_generate', fn: (data: any) => any, priority?: number): void; + + /** + * Executed after generation finishes. + */ + register(type: 'after_generate', fn: () => void, priority?: number): void; + + /** + * Modify [local variables](https://hexo.io/docs/variables) in templates. + */ + register(type: 'template_locals', fn: (locals: TemplateLocals) => TemplateLocals|void, priority?: number): void; + + /** + * Executed after Hexo is initialized – this will run right after `hexo.init` completes. + */ + register(type: 'after_init', fn: () => void, priority?: number): void; + + /** + * Executed when creating a post to determine the path of new posts. + */ + register(type: 'new_post_path', fn: (data: Post.Data, replace: boolean|undefined) => void, priority?: number): void; + + /** + * Used to determine the permalink of posts. + */ + register(type: 'post_permalink', fn: (permalink: string) => string, priority?: number): void; + + /** + * Executed after rendering finishes. You can see rendering for more info. + */ + register(type: 'after_render:html', fn: (result: string, data: {path: string, text: string, [key: string]: any}) => string|void, priority?: number): void; + + /** + * Executed after generated files and cache are removed with hexo clean command. + */ + register(type: 'after_clean', fn: () => void, priority?: number): void; + + /** + * Add middleware to the server. app is a Connect instance. + */ + register(type: 'server_middleware', fn: (app: connect.Server) => connect.Server|void, priority?: number): void; + + unregister(type: string, fn: (...args: any[]) => any): void; + exec(type: string, data?: any, options?: Filter.Options): any; + execSync(type: string, data?: any, options?: Filter.Options): any; + } + namespace Filter { + interface Options { + /** + * `hexo` object. + */ + context?: Hexo; + /** + * Arguments. This must be an array. + */ + args?: any[]; + } + } + + interface Generator { + register(name: string, fn: (locals: Site) => Generator.Return| Generator.Return[]): void; + } + namespace Generator { + interface Return { + /** + * Path not including the prefixing `/` . + */ + path: string; + + /** + * Layout. Specify the layouts for rendering. The value can be a string or an array. If it’s ignored then the route will return data directly. + */ + layout: string|string[]; + + data: any; + } + } + + interface Helper { + register(name: string, fn: (...args: any[]) => any): void; + } + + interface Migrator { + register(name: string, fn: (args: ParsedArgs, fn: (err: any) => void) => void): void; + } + + interface Processor { + register(pattern: RegExp | string | ((str: string) => any), fn: (file: Box.File) => void): void; + register(fn: (file: Box.File) => void): void; + } + + interface Renderer { + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options: any) => string, sync: true): void; + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options: any) => Promise<string>, sync: false): void; + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options: any) => Promise<string>): void; + } + + interface Tag { + register(name: string, fn: (args: string[], content: string|undefined) => string, options?: Tag.Options): void; + } + namespace Tag { + interface Options { + ends?: boolean; + async?: boolean; + } + } + } + + interface Router { + /** + * The `get` method returns a `Stream`. + */ + get(path: string): Router.RouteStream|undefined; + + /** + * The `set` method takes a string, a `Buffer` or a function. + */ + set(path: string, data: string|Buffer|util.Pattern<boolean>|Router.Data): this; + + /** + * Remove a Path + */ + remove(path: string): this; + + /** + * Get the List of Routes + */ + list(): string[]; + + /** + * The `format` method transforms a string to a valid path. + */ + format(path: string): string; + } + namespace Router { + interface Data { + data: string | Buffer | Callback; + modified: boolean; + } + + interface RouteStream extends Stream.Readable { + readonly modified: boolean; + } + + type Callback = ((err: any, result: string) => void) | (() => Promise<string>); + } + + interface Scaffold { + /** + * Get a Scaffold + */ + get(name: string, fn?: (err: any, result: string) => void): Promise<string>; + /** + * Set a Scaffold + */ + set(name: string, content: string, fn?: (err: any) => void): Promise<void>; + /** + * Remove a Scaffold + */ + remove(name: string, fn?: (err: any) => void): Promise<void>; + } + + interface Box extends EventEmitter { + /** + * Loads all files in the folder. + */ + process(fn: (err: any) => void): Promise<void>; + /** + * Loads all files in the folder and start watching for file changes. + */ + watch(fn?: (err: any) => void): Promise<void>; + /** + * Stop watching. + */ + unwatch(): void; + + /** + * A processor is an essential element of `Box` and is used to process files. + * You can use path matching as described above to restrict what exactly the processor should process. + * Register a new processor with the `addProcessor` method. + */ + addProcessor(pattern: string|RegExp|util.Pattern<boolean>, fn: (file: Box.File) => void): void; + } + namespace Box { + interface File { + /** + * Full path of the file + */ + readonly source: string; + + /** + * Relative path to the box of the file + */ + readonly path: string; + + /** + * File type. The value can be `create` , `update` , `skip`, `delete` . + */ + readonly type: 'create' | 'update' | 'skip' | 'delete'; + + /** + * The information from path matching. + */ + readonly params: any; + + /** + * Read a file + */ + read(option?: {encoding?: string|null, flag?: string}, fn?: (err: any, result: string|Buffer) => void): Promise<string|Buffer>; + read(fn?: (err: any, result: string|Buffer) => void): Promise<string|Buffer>; + + /** + * Read a file synchronously + */ + readSync(option?: {encoding?: string|null, flag?: string}): string|Buffer; + + /** + * Read the status of a file + */ + stat(fn?: (err: any, result: fs.Stats) => void): Promise<fs.Stats>; + + /** + * Read the status of a file synchronously + */ + statSync(): fs.Stats; + + /** + * Render a file + */ + render(fn?: (err: any, result: string) => void): Promise<string>; + render(option?: any, fn?: (err: any, result: string) => void): Promise<string>; + + /** + * Render a file synchronously + */ + renderSync(option?: any): string; + } + } + + interface Render { + render(data: Render.Data, option?: any, fn?: (err: any, result: string) => void): Promise<string>; + render(data: Render.Data, fn?: (err: any, result: string) => void): Promise<string>; + renderSync(data: Render.Data, option?: any): string; + + /** + * Check whether a file is renderable synchronously. + */ + isRenderable(path: string): boolean; + + /** + * Check whether a file is renderable. + */ + isRenderableSync(path: string): boolean; + + /** + * Get the Output Extension + */ + getOutput(path: string): string; + } + namespace Render { + interface Data { + text?: string; + engine?: string; + path?: string; + } + } + + interface Post { + /** + * Create a Post + */ + create(data: Post.Data, replace?: boolean, fn?: (err: any) => void): Promise<void>; + create(data: Post.Data, fn?: (err: any) => void): Promise<void>; + + /** + * Publish a Draft + */ + publish(data: Post.Data, replace?: boolean, fn?: (err: any) => void): Promise<void>; + publish(data: Post.Data, fn?: (err: any) => void): Promise<void>; + + render(source: string|null|undefined, data: Post.RenderData, fn: (err: any) => void): Promise<void>; + } + namespace Post { + interface Data { + title?: string; + slug?: string; + layout?: string; + path?: string; + date?: moment.MomentInput; + } + interface RenderData { + engine?: string; + content?: string; + } + } + + interface Theme extends Box { + config: HexoConfig; + + /** + * Get a View + */ + getView(path: string): View|undefined; + + /** + * Set a View + */ + setView(path: string, data: any): void; + + /** + * Remove a View + */ + removeView(path: string): void; + } + + interface View { + readonly path: string; + readonly source: string; + + /** + * Remove a View + */ + render(options?: any, fn?: (err: any, result: string) => void): Promise<string>; + render(fn: (err: any, result: string) => void): Promise<any>; + + /** + * Remove a View synchronously. + */ + renderSync(options?: any): string; + } +} + +interface TemplateLocals { + /** + * Underscore object + */ + _: underscore.UnderscoreStatic; + page: Hexo.Locals.Post | Hexo.Locals.Page | Hexo.Locals.Category | Hexo.Locals.Tag | IndexPage | ArchivePage | CategoryPage | TagPage; + path: string; + url: string; + + /** + * Site settings in `_config.yml` + */ + config: HexoConfig; + theme: HexoConfig; + env: Hexo['env']; + layout: string; + view_dir: string; + site: any; +} + +interface IndexPage { + per_page?: number; + total?: number; + current?: number; + current_url?: string; + posts?: object; + prev?: number; + prev_link?: string; + next?: number; + next_link?: string; + path?: string; +} + +interface ArchivePage extends IndexPage { + archive?: boolean; + year?: number; + month?: number; +} + +interface CategoryPage extends IndexPage { + category: string; +} + +interface TagPage extends IndexPage { + tag: string; +} + +interface HexoRendererData { + /** + * File content. + */ + readonly text: string; + /** + * File path. + */ + readonly path?: string; +} + +export = Hexo; diff --git a/types/hexo/tsconfig.json b/types/hexo/tsconfig.json new file mode 100644 index 0000000000..6e37a832a0 --- /dev/null +++ b/types/hexo/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hexo-tests.ts" + ] +} diff --git a/types/hexo/tslint.json b/types/hexo/tslint.json new file mode 100644 index 0000000000..d2e0e4cec1 --- /dev/null +++ b/types/hexo/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false + } + +} diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index 6beeccb08f..0075f8a273 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ioBroker/ioBroker // Definitions by: AlCalzone <https://github.com/AlCalzone> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 3.2 // Note: This is not the definition for the package `iobroker`, // which is just an installer, not a library. @@ -296,14 +296,28 @@ declare global { /** attached history information */ history?: any; + + /** Custom settings for this state */ + custom?: Record<string, any>; } interface ChannelCommon extends ObjectCommon { /** description of this channel */ desc?: string; + + // Only states can have common.custom + custom?: undefined; } - type OtherCommon = ObjectCommon & { + interface DeviceCommon extends ObjectCommon { + // Only states can have common.custom + custom?: undefined; + // TODO: any other definition for device? + } + interface OtherCommon extends ObjectCommon { [propName: string]: any; - }; + + // Only states can have common.custom + custom?: undefined; + } interface BaseObject { /** The ID of this object */ @@ -311,7 +325,7 @@ declare global { native: Record<string, any>; enums?: Record<string, string>; type: string; // specified in the derived interfaces - common: ObjectCommon; + common: StateCommon | ChannelCommon | DeviceCommon | OtherCommon; acl?: ObjectACL; } @@ -335,10 +349,10 @@ declare global { interface DeviceObject extends BaseObject { type: "device"; - common: ObjectCommon; // TODO: any definition for device? + common: DeviceCommon; } interface PartialDeviceObject extends Partial<Pick<DeviceObject, "_id" | "native" | "enums" | "type" | "acl">> { - common?: Partial<ObjectCommon>; + common?: Partial<DeviceCommon>; } interface OtherObject extends BaseObject { @@ -350,11 +364,15 @@ declare global { } type Object = StateObject | ChannelObject | DeviceObject | OtherObject; + + type SettableObjectWorker<T extends ioBroker.Object> = + Pick<T, Exclude<keyof T, "_id" | "acl">> & { + _id?: T["_id"]; + acl?: T["acl"]; + }; + // In set[Foreign]Object[NotExists] methods, the ID and acl of the object is optional - interface SettableObject extends Pick<ioBroker.Object, Exclude<keyof ioBroker.Object, "_id" | "acl">> { - _id?: ioBroker.Object["_id"]; - acl?: ioBroker.Object["acl"]; - } + type SettableObject = SettableObjectWorker<ioBroker.Object>; type PartialObject = PartialStateObject | PartialChannelObject | PartialDeviceObject | PartialOtherObject; /** Defines access rights for a single file */ diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index 01ab0c6fc4..a2c89cb893 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -209,8 +209,8 @@ switch (adapter.log.level) { adapter.sendTo("foo.0", "command", "message"); adapter.sendTo("foo.0", "message"); -adapter.sendTo("foo.0", "command", {msg: "message"}); -adapter.sendTo("foo.0", {msg: "message"}); +adapter.sendTo("foo.0", "command", { msg: "message" }); +adapter.sendTo("foo.0", { msg: "message" }); function handleMessageResponse(response?: ioBroker.Message) { if (!response) return; @@ -226,28 +226,28 @@ function handleMessageResponse(response?: ioBroker.Message) { } adapter.sendTo("foo.0", "command", "message", handleMessageResponse); adapter.sendTo("foo.0", "message", handleMessageResponse); -adapter.sendTo("foo.0", "command", {msg: "message"}, handleMessageResponse); -adapter.sendTo("foo.0", {msg: "message"}, handleMessageResponse); +adapter.sendTo("foo.0", "command", { msg: "message" }, handleMessageResponse); +adapter.sendTo("foo.0", { msg: "message" }, handleMessageResponse); adapter.sendToAsync("foo.0", "command", "message").then(handleMessageResponse); adapter.sendToAsync("foo.0", "message").then(handleMessageResponse); -adapter.sendToAsync("foo.0", "command", {msg: "message"}).then(handleMessageResponse); -adapter.sendToAsync("foo.0", {msg: "message"}).then(handleMessageResponse); +adapter.sendToAsync("foo.0", "command", { msg: "message" }).then(handleMessageResponse); +adapter.sendToAsync("foo.0", { msg: "message" }).then(handleMessageResponse); adapter.sendToHost("host-foo", "command", "message"); adapter.sendToHost("host-foo", "message"); -adapter.sendToHost("host-foo", "command", {msg: "message"}); -adapter.sendToHost("host-foo", {msg: "message"}); +adapter.sendToHost("host-foo", "command", { msg: "message" }); +adapter.sendToHost("host-foo", { msg: "message" }); adapter.sendToHost("host-foo", "command", "message", handleMessageResponse); adapter.sendToHost("host-foo", "message", handleMessageResponse); -adapter.sendToHost("host-foo", "command", {msg: "message"}, handleMessageResponse); -adapter.sendToHost("host-foo", {msg: "message"}, handleMessageResponse); +adapter.sendToHost("host-foo", "command", { msg: "message" }, handleMessageResponse); +adapter.sendToHost("host-foo", { msg: "message" }, handleMessageResponse); adapter.sendToHostAsync("host-foo", "command", "message").then(handleMessageResponse); adapter.sendToHostAsync("host-foo", "message").then(handleMessageResponse); -adapter.sendToHostAsync("host-foo", "command", {msg: "message"}).then(handleMessageResponse); -adapter.sendToHostAsync("host-foo", {msg: "message"}).then(handleMessageResponse); +adapter.sendToHostAsync("host-foo", "command", { msg: "message" }).then(handleMessageResponse); +adapter.sendToHostAsync("host-foo", { msg: "message" }).then(handleMessageResponse); function handleError(err?: string) { } adapter.subscribeStates("*", handleError); @@ -259,3 +259,30 @@ adapter.subscribeStatesAsync("*").catch(handleError); adapter.subscribeForeignStatesAsync("*").catch(handleError); adapter.unsubscribeStatesAsync("*").catch(handleError); adapter.unsubscribeForeignStatesAsync("*").catch(handleError); + +// Repro from https://github.com/ioBroker/adapter-core/issues/3 +const repro1: ioBroker.ObjectChangeHandler = (id, obj) => { + if (!obj || !obj.common) return; + if (obj.common.custom) { + const test1: ioBroker.StateCommon = obj.common; + } + obj + && obj.common + && obj.common.custom + && obj.common.custom["adapter.0"] + && obj.common.custom["adapter.0"].enabled + ; +}; + +// Repro from https://github.com/ioBroker/adapter-core/issues/4 +function repro2() { + // Prepare custom object + const obj = { + common: { + custom: { + "adapter.namespace": { start_day: null as any } + } + } + }; + adapter.extendForeignObject("obj.id", obj, (err) => { }); +} diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts new file mode 100644 index 0000000000..e19423d928 --- /dev/null +++ b/types/jscodeshift/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for jscodeshift 0.6 +// Project: https://github.com/facebook/jscodeshift#readme +// Definitions by: Brie Bunge <https://github.com/brieb> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import core = require("./src/core"); + +export = core; diff --git a/types/jscodeshift/package.json b/types/jscodeshift/package.json new file mode 100644 index 0000000000..a501c0f28d --- /dev/null +++ b/types/jscodeshift/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "ast-types": "0.12.1", + "recast": "0.17.2" + } +} diff --git a/types/jscodeshift/src/Collection.d.ts b/types/jscodeshift/src/Collection.d.ts new file mode 100644 index 0000000000..2cab87b153 --- /dev/null +++ b/types/jscodeshift/src/Collection.d.ts @@ -0,0 +1,131 @@ +import recast = require("recast"); +import JSXElement = require("./collections/JSXElement"); +import NodeCollection = require("./collections/Node"); +import VariableDeclarator = require("./collections/VariableDeclarator"); + +type ASTPath<N> = recast.NodePath<N, N>; + +export interface Collection<N> + extends NodeCollection.TraversalMethods, + NodeCollection.MutationMethods<N>, + VariableDeclarator.GlobalMethods, + VariableDeclarator.TransformMethods<N>, + JSXElement.GlobalMethods, + JSXElement.TraversalMethods { + /** + * @param paths An array of AST paths + * @param parent A parent collection + * @param types An array of types all the paths in the collection + * have in common. If not passed, it will be inferred from the paths. + */ + new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Array<recast.Type<any>>): this; + + /** + * Returns a new collection containing the nodes for which the callback returns true. + */ + filter<S extends N>( + callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => path is ASTPath<S> + ): Collection<S>; + filter( + callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean + ): Collection<N>; + + /** + * Executes callback for each node/path in the collection. + */ + forEach(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => void): this; + + /** + * Tests whether at-least one path passes the test implemented by the provided callback. + */ + some(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; + + /** + * Tests whether all paths pass the test implemented by the provided callback. + */ + every(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; + + /** + * Executes the callback for every path in the collection and returns a new + * collection from the return values (which must be paths). + * + * The callback can return null to indicate to exclude the element from the + * new collection. + * + * If an array is returned, the array will be flattened into the result + * collection. + * + * @param callback + * @param type Force the new collection to be of a specific type + */ + map<T = recast.ASTNode>( + callback: ( + path: ASTPath<N>, + i: number, + paths: Array<ASTPath<N>> + ) => ASTPath<T> | Array<ASTPath<T>> | null | undefined, + type: recast.Type<any> + ): Collection<T>; + + /** Returns the number of elements in this collection. */ + size(): number; + + /** Returns the number of elements in this collection. */ + length: number; + + /** Returns an array of AST nodes in this collection. */ + nodes(): N[]; + + /** Returns an array of ASTPaths in this this collection. */ + paths(): Array<ASTPath<N>>; + + getAST(): Array<ASTPath<any>>; + + /** + * Converts the AST back to a string, using recast. + * @param options directly passed to recast's printer + */ + toSource(options?: recast.Options): string; + + /** + * Returns a new collection containing only the element at position index. + * In case of a negative index, the element is taken from the end: + * .at(0) - first element + * .at(-1) - last element + */ + at(index: number): Collection<N>; + + /** Calls "get" on the first path (same as "collection.paths(0).get(...)"). */ + get(...fields: Array<string | number>): any; + + /** + * Returns the type(s) of the collection. This is only used for unit tests, + * don't think other consumers would need it. + */ + getTypes(): string[]; + + /** + * Returns true if this collection has the type 'type'. + */ + isOfType(type: recast.Type<any>): boolean; +} + +export function fromPaths(...args: any[]): any; + +export function fromNodes(...args: any[]): any; + +/** + * This function adds the provided methods to the prototype of the corresponding + * typed collection. If no type is passed, the methods are added to + * Collection.prototype and are available for all collections. + * + * @param methods Methods to add to the prototype + * @param type Optional type to add the methods to + */ +export function registerMethods(methods: object, type?: recast.Type<any>): void; + +export function hasConflictingRegistration(...args: any[]): any; + +export function setDefaultCollectionType(...args: any[]): any; + +export {}; // shut off automatic exporting diff --git a/types/jscodeshift/src/collections/JSXElement.d.ts b/types/jscodeshift/src/collections/JSXElement.d.ts new file mode 100644 index 0000000000..0490e40f76 --- /dev/null +++ b/types/jscodeshift/src/collections/JSXElement.d.ts @@ -0,0 +1,71 @@ +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("../Collection"); + +type ASTPath<N> = recast.NodePath<N, N>; +type JSXElement = nodes.JSXElement; + +export interface GlobalMethods { + /** + * Finds all JSXElements optionally filtered by name + */ + findJSXElements(name?: string): Collection.Collection<JSXElement>; + + /** + * Finds all JSXElements by module name. Given + * + * var Bar = require('Foo'); + * <Bar /> + * + * findJSXElementsByModuleName('Foo') will find <Bar />, without having to + * know the variable name. + */ + findJSXElementsByModuleName(moduleName: string): Collection.Collection<JSXElement>; +} + +type Defined<T> = T extends undefined ? never : T; +type JSXElementChild = Defined<JSXElement["children"]>[0]; + +export interface TraversalMethods { + /** + * Returns all child nodes, including literals and expressions. + * This method only applies to JSXElement typed collections. + */ + childNodes(): Collection.Collection<JSXElementChild>; + + /** + * Returns all children that are JSXElements. + * This method only applies to JSXElement typed collections. + */ + childElements(): Collection.Collection<JSXElement>; +} + +interface Filter { + (path: ASTPath<any>): boolean; +} + +export interface FilterMethods { + /** + * Filter method for attributes. + */ + hasAttributes(attributeFilter: { [attributeName: string]: any }): Filter; + + /** + * Filter elements which contain a specific child type + */ + hasChildren(name: string): Filter; +} + +export interface MappingMethods { + /** + * Given a JSXElement, returns its "root" name. E.g. it would return "Foo" for + * both <Foo /> and <Foo.Bar />. + */ + getRootName(path: ASTPath<any>): string; +} + +export function register(): void; +export const filters: FilterMethods; +export const mappings: MappingMethods; + +export {}; // shut off automatic exporting diff --git a/types/jscodeshift/src/collections/Node.d.ts b/types/jscodeshift/src/collections/Node.d.ts new file mode 100644 index 0000000000..d1e74f314d --- /dev/null +++ b/types/jscodeshift/src/collections/Node.d.ts @@ -0,0 +1,57 @@ +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("../Collection"); + +type ASTPath<N> = recast.NodePath<N, N>; + +export interface TraversalMethods { + /** + * Find nodes of a specific type within the nodes of this collection. + */ + find<T>(type: recast.Type<T>, filter?: ((value: any) => boolean) | object): Collection.Collection<T>; + + /** + * Returns a collection containing the paths that create the scope of the + * currently selected paths. Dedupes the paths. + */ + closestScope(): Collection.Collection<nodes.ASTNode>; + + /** + * Traverse the AST up and finds the closest node of the provided type. + */ + closest<T>(type: recast.Type<T>, filter?: any): Collection.Collection<T>; + + /** + * Finds the declaration for each selected path. Useful for member expressions + * or JSXElements. Expects a callback function that maps each path to the name + * to look for. + * + * If the callback returns a falsy value, the element is skipped. + */ + getVariableDeclarators(nameGetter: (...args: any[]) => any): Collection.Collection<nodes.VariableDeclarator>; +} + +export interface MutationMethods<N> { + /** + * Simply replaces the selected nodes with the provided node. If a function + * is provided it is executed for every node and the node is replaced with the + * functions return value. + */ + replaceWith<T>(nodes: T | T[] | ((path: ASTPath<N>, i: number) => T)): Collection.Collection<T>; + + /** + * Inserts a new node before the current one. + */ + insertBefore(insert: any): Collection.Collection<N>; + + /** + * Inserts a new node after the current one. + */ + insertAfter(insert: any): Collection.Collection<N>; + + remove(): Collection.Collection<N>; +} + +export function register(): void; + +export {}; // shut off automatic exporting diff --git a/types/jscodeshift/src/collections/VariableDeclarator.d.ts b/types/jscodeshift/src/collections/VariableDeclarator.d.ts new file mode 100644 index 0000000000..eb7c8bcdfd --- /dev/null +++ b/types/jscodeshift/src/collections/VariableDeclarator.d.ts @@ -0,0 +1,39 @@ +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("../Collection"); + +type ASTPath<N> = recast.NodePath<N, N>; + +export interface GlobalMethods { + /** + * Finds all variable declarators, optionally filtered by name. + */ + findVariableDeclarators(name?: string): Collection.Collection<nodes.VariableDeclarator>; +} + +export interface TransformMethods<N> { + /** + * Renames a variable and all its occurrences. + * This method only applies to VariableDeclarator typed collections. + */ + renameTo(newName: string): Collection.Collection<N>; +} + +interface Filter { + (path: ASTPath<any>): boolean; +} + +export interface FilterMethods { + /** + * Returns a function that returns true if the provided path is a variable + * declarator and requires one of the specified module names. + * + * @param names A module name or an array of module names + */ + requiresModule(names: string | string[]): Filter; +} + +export function register(): void; +export const filters: FilterMethods; + +export {}; // shut off automatic exporting diff --git a/types/jscodeshift/src/core.d.ts b/types/jscodeshift/src/core.d.ts new file mode 100644 index 0000000000..9b9f48305d --- /dev/null +++ b/types/jscodeshift/src/core.d.ts @@ -0,0 +1,363 @@ +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("./Collection"); +import template = require("./template"); +import VariableDeclarator = require("./collections/VariableDeclarator"); +import JSXElement = require("./collections/JSXElement"); + +declare namespace core { + type Parser = recast.Parser; + + interface Filters { + JSXElement: JSXElement.FilterMethods; + VariableDeclarator: VariableDeclarator.FilterMethods; + } + + interface Mappings { + JSXElement: JSXElement.MappingMethods; + } + + interface Plugin { + (core: Core): void; + } + + interface FileInfo { + /** The absolute path to the current file. */ + path: string; + /** The source code of the current file. */ + source: string; + } + + interface Stats { + /** + * Helper function to collect data during --dry runs. + * This function keeps a counter for how often it was called with a specific argument. + * The result is shown in the console. Useful for finding out how many files match a criterion. + */ + (name: string, quantity?: number): void; + } + + type ASTPath<N = ASTNode> = recast.NodePath<N, N>; + + interface Core { + (source: string, options?: Options): Collection.Collection<any>; + (source: ASTNode | ASTNode[] | ASTPath | ASTPath[]): Collection.Collection<any>; + + registerMethods: typeof Collection.registerMethods; + + types: typeof recast.default.types; + + match( + path: ASTNode | ASTPath, + filter: ((path: ASTNode) => boolean) | ASTNode + ): boolean; + + /** template, bound to default parser */ + template: template.Template; + + filters: Filters; + + mappings: Mappings; + + /** + * Utility function for registering plugins. + * + * Plugins are simple functions that are passed the core jscodeshift instance. + * They should extend jscodeshift by calling `registerMethods`, etc. + * This method guards against repeated registrations (the plugin callback will only be called once). + */ + use(plugin: Plugin): void; + + /** + * Returns a version of the core jscodeshift function "bound" to a specific + * parser. + */ + withParser(parser: string | Parser): JSCodeshift; + } + + type JSCodeshift = Core & recast.NamedTypes & recast.Builders; + + interface API { + j: JSCodeshift; + jscodeshift: JSCodeshift; + stats: Stats; + report: (msg: string) => void; + } + + interface Options { + [option: string]: any; + } + + interface Transform { + /** + * If a string is returned and it is different from passed source, the transform is considered to be successful. + * If a string is returned but it's the same as the source, the transform is considered to be unsuccessful. + * If nothing is returned, the file is not supposed to be transformed (which is ok). + */ + (file: FileInfo, api: API, options: Options): string | null | undefined | void; + } + + type ASTNode = nodes.ASTNode; + + type AnyTypeAnnotation = nodes.AnyTypeAnnotation; + type ArrayExpression = nodes.ArrayExpression; + type ArrayPattern = nodes.ArrayPattern; + type ArrayTypeAnnotation = nodes.ArrayTypeAnnotation; + type ArrowFunctionExpression = nodes.ArrowFunctionExpression; + type AssignmentExpression = nodes.AssignmentExpression; + type AssignmentPattern = nodes.AssignmentPattern; + type AwaitExpression = nodes.AwaitExpression; + type BigIntLiteral = nodes.BigIntLiteral; + type BinaryExpression = nodes.BinaryExpression; + type BindExpression = nodes.BindExpression; + type Block = nodes.Block; + type BlockStatement = nodes.BlockStatement; + type BooleanLiteral = nodes.BooleanLiteral; + type BooleanLiteralTypeAnnotation = nodes.BooleanLiteralTypeAnnotation; + type BooleanTypeAnnotation = nodes.BooleanTypeAnnotation; + type BreakStatement = nodes.BreakStatement; + type CallExpression = nodes.CallExpression; + type CatchClause = nodes.CatchClause; + type ClassBody = nodes.ClassBody; + type ClassDeclaration = nodes.ClassDeclaration; + type ClassExpression = nodes.ClassExpression; + type ClassImplements = nodes.ClassImplements; + type ClassMethod = nodes.ClassMethod; + type ClassPrivateMethod = nodes.ClassPrivateMethod; + type ClassPrivateProperty = nodes.ClassPrivateProperty; + type ClassProperty = nodes.ClassProperty; + type ClassPropertyDefinition = nodes.ClassPropertyDefinition; + type Comment = nodes.Comment; + type CommentBlock = nodes.CommentBlock; + type CommentLine = nodes.CommentLine; + type ComprehensionBlock = nodes.ComprehensionBlock; + type ComprehensionExpression = nodes.ComprehensionExpression; + type ConditionalExpression = nodes.ConditionalExpression; + type ContinueStatement = nodes.ContinueStatement; + type DebuggerStatement = nodes.DebuggerStatement; + type Declaration = nodes.Declaration; + type DeclareClass = nodes.DeclareClass; + type DeclaredPredicate = nodes.DeclaredPredicate; + type DeclareExportAllDeclaration = nodes.DeclareExportAllDeclaration; + type DeclareExportDeclaration = nodes.DeclareExportDeclaration; + type DeclareFunction = nodes.DeclareFunction; + type DeclareInterface = nodes.DeclareInterface; + type DeclareModule = nodes.DeclareModule; + type DeclareModuleExports = nodes.DeclareModuleExports; + type DeclareOpaqueType = nodes.DeclareOpaqueType; + type DeclareTypeAlias = nodes.DeclareTypeAlias; + type DeclareVariable = nodes.DeclareVariable; + type Decorator = nodes.Decorator; + type Directive = nodes.Directive; + type DirectiveLiteral = nodes.DirectiveLiteral; + type DoExpression = nodes.DoExpression; + type DoWhileStatement = nodes.DoWhileStatement; + type EmptyStatement = nodes.EmptyStatement; + type EmptyTypeAnnotation = nodes.EmptyTypeAnnotation; + type ExistentialTypeParam = nodes.ExistentialTypeParam; + type ExistsTypeAnnotation = nodes.ExistsTypeAnnotation; + type ExportAllDeclaration = nodes.ExportAllDeclaration; + type ExportBatchSpecifier = nodes.ExportBatchSpecifier; + type ExportDeclaration = nodes.ExportDeclaration; + type ExportDefaultDeclaration = nodes.ExportDefaultDeclaration; + type ExportDefaultSpecifier = nodes.ExportDefaultSpecifier; + type ExportNamedDeclaration = nodes.ExportNamedDeclaration; + type ExportNamespaceSpecifier = nodes.ExportNamespaceSpecifier; + type ExportSpecifier = nodes.ExportSpecifier; + type Expression = nodes.Expression; + type ExpressionStatement = nodes.ExpressionStatement; + type File = nodes.File; + type Flow = nodes.Flow; + type FlowPredicate = nodes.FlowPredicate; + type FlowType = nodes.FlowType; + type ForAwaitStatement = nodes.ForAwaitStatement; + type ForInStatement = nodes.ForInStatement; + type ForOfStatement = nodes.ForOfStatement; + type ForStatement = nodes.ForStatement; + type Function = nodes.Function; + type FunctionDeclaration = nodes.FunctionDeclaration; + type FunctionExpression = nodes.FunctionExpression; + type FunctionTypeAnnotation = nodes.FunctionTypeAnnotation; + type FunctionTypeParam = nodes.FunctionTypeParam; + type GeneratorExpression = nodes.GeneratorExpression; + type GenericTypeAnnotation = nodes.GenericTypeAnnotation; + type Identifier = nodes.Identifier; + type IfStatement = nodes.IfStatement; + type Import = nodes.Import; + type ImportDeclaration = nodes.ImportDeclaration; + type ImportDefaultSpecifier = nodes.ImportDefaultSpecifier; + type ImportNamespaceSpecifier = nodes.ImportNamespaceSpecifier; + type ImportSpecifier = nodes.ImportSpecifier; + type InferredPredicate = nodes.InferredPredicate; + type InterfaceDeclaration = nodes.InterfaceDeclaration; + type InterfaceExtends = nodes.InterfaceExtends; + type InterfaceTypeAnnotation = nodes.InterfaceTypeAnnotation; + type InterpreterDirective = nodes.InterpreterDirective; + type IntersectionTypeAnnotation = nodes.IntersectionTypeAnnotation; + type JSXAttribute = nodes.JSXAttribute; + type JSXClosingElement = nodes.JSXClosingElement; + type JSXClosingFragment = nodes.JSXClosingFragment; + type JSXElement = nodes.JSXElement; + type JSXEmptyExpression = nodes.JSXEmptyExpression; + type JSXExpressionContainer = nodes.JSXExpressionContainer; + type JSXFragment = nodes.JSXFragment; + type JSXIdentifier = nodes.JSXIdentifier; + type JSXMemberExpression = nodes.JSXMemberExpression; + type JSXNamespacedName = nodes.JSXNamespacedName; + type JSXOpeningElement = nodes.JSXOpeningElement; + type JSXOpeningFragment = nodes.JSXOpeningFragment; + type JSXSpreadAttribute = nodes.JSXSpreadAttribute; + type JSXSpreadChild = nodes.JSXSpreadChild; + type JSXText = nodes.JSXText; + type LabeledStatement = nodes.LabeledStatement; + type Line = nodes.Line; + type Literal = nodes.Literal; + type LogicalExpression = nodes.LogicalExpression; + type MemberExpression = nodes.MemberExpression; + type MemberTypeAnnotation = nodes.MemberTypeAnnotation; + type MetaProperty = nodes.MetaProperty; + type MethodDefinition = nodes.MethodDefinition; + type MixedTypeAnnotation = nodes.MixedTypeAnnotation; + type ModuleSpecifier = nodes.ModuleSpecifier; + type NewExpression = nodes.NewExpression; + type Node = nodes.Node; + type Noop = nodes.Noop; + type NullableTypeAnnotation = nodes.NullableTypeAnnotation; + type NullLiteral = nodes.NullLiteral; + type NullLiteralTypeAnnotation = nodes.NullLiteralTypeAnnotation; + type NullTypeAnnotation = nodes.NullTypeAnnotation; + type NumberLiteralTypeAnnotation = nodes.NumberLiteralTypeAnnotation; + type NumberTypeAnnotation = nodes.NumberTypeAnnotation; + type NumericLiteral = nodes.NumericLiteral; + type NumericLiteralTypeAnnotation = nodes.NumericLiteralTypeAnnotation; + type ObjectExpression = nodes.ObjectExpression; + type ObjectMethod = nodes.ObjectMethod; + type ObjectPattern = nodes.ObjectPattern; + type ObjectProperty = nodes.ObjectProperty; + type ObjectTypeAnnotation = nodes.ObjectTypeAnnotation; + type ObjectTypeCallProperty = nodes.ObjectTypeCallProperty; + type ObjectTypeIndexer = nodes.ObjectTypeIndexer; + type ObjectTypeInternalSlot = nodes.ObjectTypeInternalSlot; + type ObjectTypeProperty = nodes.ObjectTypeProperty; + type ObjectTypeSpreadProperty = nodes.ObjectTypeSpreadProperty; + type OpaqueType = nodes.OpaqueType; + type OptionalCallExpression = nodes.OptionalCallExpression; + type OptionalMemberExpression = nodes.OptionalMemberExpression; + type ParenthesizedExpression = nodes.ParenthesizedExpression; + type Pattern = nodes.Pattern; + type Position = nodes.Position; + type Printable = nodes.Printable; + type PrivateName = nodes.PrivateName; + type Program = nodes.Program; + type Property = nodes.Property; + type PropertyPattern = nodes.PropertyPattern; + type QualifiedTypeIdentifier = nodes.QualifiedTypeIdentifier; + type RegExpLiteral = nodes.RegExpLiteral; + type RestElement = nodes.RestElement; + type RestProperty = nodes.RestProperty; + type ReturnStatement = nodes.ReturnStatement; + type SequenceExpression = nodes.SequenceExpression; + type SourceLocation = nodes.SourceLocation; + type Specifier = nodes.Specifier; + type SpreadElement = nodes.SpreadElement; + type SpreadElementPattern = nodes.SpreadElementPattern; + type SpreadProperty = nodes.SpreadProperty; + type SpreadPropertyPattern = nodes.SpreadPropertyPattern; + type Statement = nodes.Statement; + type StringLiteral = nodes.StringLiteral; + type StringLiteralTypeAnnotation = nodes.StringLiteralTypeAnnotation; + type StringTypeAnnotation = nodes.StringTypeAnnotation; + type Super = nodes.Super; + type SwitchCase = nodes.SwitchCase; + type SwitchStatement = nodes.SwitchStatement; + type TaggedTemplateExpression = nodes.TaggedTemplateExpression; + type TemplateElement = nodes.TemplateElement; + type TemplateLiteral = nodes.TemplateLiteral; + type ThisExpression = nodes.ThisExpression; + type ThisTypeAnnotation = nodes.ThisTypeAnnotation; + type ThrowStatement = nodes.ThrowStatement; + type TryStatement = nodes.TryStatement; + type TSAnyKeyword = nodes.TSAnyKeyword; + type TSArrayType = nodes.TSArrayType; + type TSAsExpression = nodes.TSAsExpression; + type TSBooleanKeyword = nodes.TSBooleanKeyword; + type TSCallSignatureDeclaration = nodes.TSCallSignatureDeclaration; + type TSConditionalType = nodes.TSConditionalType; + type TSConstructorType = nodes.TSConstructorType; + type TSConstructSignatureDeclaration = nodes.TSConstructSignatureDeclaration; + type TSDeclareFunction = nodes.TSDeclareFunction; + type TSDeclareMethod = nodes.TSDeclareMethod; + type TSEnumDeclaration = nodes.TSEnumDeclaration; + type TSEnumMember = nodes.TSEnumMember; + type TSExportAssignment = nodes.TSExportAssignment; + type TSExpressionWithTypeArguments = nodes.TSExpressionWithTypeArguments; + type TSExternalModuleReference = nodes.TSExternalModuleReference; + type TSFunctionType = nodes.TSFunctionType; + type TSHasOptionalTypeAnnotation = nodes.TSHasOptionalTypeAnnotation; + type TSHasOptionalTypeParameters = nodes.TSHasOptionalTypeParameters; + type TSImportEqualsDeclaration = nodes.TSImportEqualsDeclaration; + type TSIndexedAccessType = nodes.TSIndexedAccessType; + type TSIndexSignature = nodes.TSIndexSignature; + type TSInferType = nodes.TSInferType; + type TSInterfaceBody = nodes.TSInterfaceBody; + type TSInterfaceDeclaration = nodes.TSInterfaceDeclaration; + type TSIntersectionType = nodes.TSIntersectionType; + type TSLiteralType = nodes.TSLiteralType; + type TSMappedType = nodes.TSMappedType; + type TSMethodSignature = nodes.TSMethodSignature; + type TSModuleBlock = nodes.TSModuleBlock; + type TSModuleDeclaration = nodes.TSModuleDeclaration; + type TSNamespaceExportDeclaration = nodes.TSNamespaceExportDeclaration; + type TSNeverKeyword = nodes.TSNeverKeyword; + type TSNonNullExpression = nodes.TSNonNullExpression; + type TSNullKeyword = nodes.TSNullKeyword; + type TSNumberKeyword = nodes.TSNumberKeyword; + type TSObjectKeyword = nodes.TSObjectKeyword; + type TSOptionalType = nodes.TSOptionalType; + type TSParameterProperty = nodes.TSParameterProperty; + type TSParenthesizedType = nodes.TSParenthesizedType; + type TSPropertySignature = nodes.TSPropertySignature; + type TSQualifiedName = nodes.TSQualifiedName; + type TSRestType = nodes.TSRestType; + type TSStringKeyword = nodes.TSStringKeyword; + type TSSymbolKeyword = nodes.TSSymbolKeyword; + type TSThisType = nodes.TSThisType; + type TSTupleType = nodes.TSTupleType; + type TSType = nodes.TSType; + type TSTypeAliasDeclaration = nodes.TSTypeAliasDeclaration; + type TSTypeAnnotation = nodes.TSTypeAnnotation; + type TSTypeAssertion = nodes.TSTypeAssertion; + type TSTypeLiteral = nodes.TSTypeLiteral; + type TSTypeOperator = nodes.TSTypeOperator; + type TSTypeParameter = nodes.TSTypeParameter; + type TSTypeParameterDeclaration = nodes.TSTypeParameterDeclaration; + type TSTypeParameterInstantiation = nodes.TSTypeParameterInstantiation; + type TSTypePredicate = nodes.TSTypePredicate; + type TSTypeQuery = nodes.TSTypeQuery; + type TSTypeReference = nodes.TSTypeReference; + type TSUndefinedKeyword = nodes.TSUndefinedKeyword; + type TSUnionType = nodes.TSUnionType; + type TSUnknownKeyword = nodes.TSUnknownKeyword; + type TSVoidKeyword = nodes.TSVoidKeyword; + type TupleTypeAnnotation = nodes.TupleTypeAnnotation; + type TypeAlias = nodes.TypeAlias; + type TypeAnnotation = nodes.TypeAnnotation; + type TypeCastExpression = nodes.TypeCastExpression; + type TypeofTypeAnnotation = nodes.TypeofTypeAnnotation; + type TypeParameter = nodes.TypeParameter; + type TypeParameterDeclaration = nodes.TypeParameterDeclaration; + type TypeParameterInstantiation = nodes.TypeParameterInstantiation; + type UnaryExpression = nodes.UnaryExpression; + type UnionTypeAnnotation = nodes.UnionTypeAnnotation; + type UpdateExpression = nodes.UpdateExpression; + type VariableDeclaration = nodes.VariableDeclaration; + type VariableDeclarator = nodes.VariableDeclarator; + type Variance = nodes.Variance; + type VoidTypeAnnotation = nodes.VoidTypeAnnotation; + type WhileStatement = nodes.WhileStatement; + type WithStatement = nodes.WithStatement; + type YieldExpression = nodes.YieldExpression; +} + +declare const core: core.JSCodeshift; +export = core; diff --git a/types/jscodeshift/src/template.d.ts b/types/jscodeshift/src/template.d.ts new file mode 100644 index 0000000000..cfc0a3c543 --- /dev/null +++ b/types/jscodeshift/src/template.d.ts @@ -0,0 +1,18 @@ +import recast = require("recast"); + +export = template; + +declare const template: typeof withParser; + +declare function withParser(parser: recast.Parser): template.Template; + +declare namespace template { + interface Template { + /** Tagged template function. Parses the string as source and returns an array of Statement AST nodes. */ + statements(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Statement AST node. */ + statement(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Expression AST node. */ + expression(...args: any[]): any; + } +} diff --git a/types/jscodeshift/test/js-transforms/README.md b/types/jscodeshift/test/js-transforms/README.md new file mode 100644 index 0000000000..f314daaa44 --- /dev/null +++ b/types/jscodeshift/test/js-transforms/README.md @@ -0,0 +1,2 @@ +Sample jscodeshift transforms taken from https://github.com/jhgg/js-transforms +and converted to TypeScript, for use as real-world test cases. diff --git a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts new file mode 100644 index 0000000000..1c6d8cda56 --- /dev/null +++ b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts @@ -0,0 +1,25 @@ +/** + * This transform converts stuff like: + * + * let x = this.foo.bind(this); + * + * to + * + * let x = ::this.foo; + * + */ +import j = require("jscodeshift"); + +const transform: j.Transform = (file, api) => { + const j = api.jscodeshift; + return j(file.source) + // Find stuff that looks like this.xyz.bind(this) + .find(j.CallExpression, {callee: {object: {object: j.ThisExpression}, property: {name: 'bind'}}}) + // Ensure that .bind() is being called with only one argument, and that argument is "this". + .filter(p => p.value.arguments.length === 1 && p.value.arguments[0].type === "ThisExpression") + // We can now replace it with ::this.xyz + .replaceWith(p => j.bindExpression(null, (p.value.callee as j.MemberExpression).object)) + .toSource(); +}; + +export = transform; diff --git a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts new file mode 100644 index 0000000000..09cdf3f29e --- /dev/null +++ b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts @@ -0,0 +1,60 @@ +/** + * Converts + * onClick(function(a, b) { + * return a + b; + * }.bind(this), + * function(b, c) { + * return 1; + * }.bind(this)); + * + * onClick(function(a) { + * var a = 1; + * return a; + * }.bind(this)); + * + * var a = function(c) { return c; }.bind(this); + * + * to + * onClick((a, b) => a + b, + * (b, c) => 1); + * + * onClick(a => { + * var a = 1; + * return a; + * }); + * + * var a = c => c; + * + */ +import { Transform, MemberExpression, FunctionExpression, ArrowFunctionExpression } from "jscodeshift"; + +const transform: Transform = (file, api) => { + const j = api.jscodeshift; + + return j(file.source) + // We're looking for a CallExpression that's calling .bind() onto a FunctionExpression. + .find(j.CallExpression, {callee: {property: {name: 'bind'}, object: {type: 'FunctionExpression'}}}) + // Verify that .bind() is only being called with `this` as it's sole arguments. + .filter(p => p.value.arguments.length === 1 && p.value.arguments[0].type === "ThisExpression") + .replaceWith(p => { + const callee = p.value.callee as MemberExpression; + const object = callee.object as FunctionExpression; + // Grab the function body. Since we looked for the CallExpression originally, the "callee.object" would refer + // to the FunctionExpression that's being called .bind(this) on. We need the body of that function + // to transform into an ArrowFunctionExpression. + let body: ArrowFunctionExpression['body'] = object.body; + // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, + // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } + let useExpression = false; + if (body.type === 'BlockStatement' && body.body.length === 1) { + const first = body.body[0]; + if (first.type === "ReturnStatement") { + useExpression = true; + body = first.argument!; + } + } + + return j.arrowFunctionExpression(object.params, body, useExpression); + }) + .toSource(); +}; diff --git a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts new file mode 100644 index 0000000000..b960c920cd --- /dev/null +++ b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts @@ -0,0 +1,53 @@ +/** + * Converts a FunctionExpression to an ArrowFunctionExpression when safe to do so. + * + * var a = function(a, b) { + * return a + b; + * } + * + * var b = function(a, b) { + * var c = 0; + * return a + b + c; + * } + * + * var a = function(a, b) { + * return a + b + this.c; + * } + * + * var a = (a, b) => a + b + * + * var b = (a, b) => { + * var c = 0; + * return a + b + c; + * } + * + * var a = function(a, b) { + * return a + b + this.c; + * } + */ +import { Transform, ArrowFunctionExpression } from "jscodeshift"; + +const transform: Transform = (file, api) => { + const j = api.jscodeshift; + + return j(file.source) + .find(j.FunctionExpression) + // We check for this expression, as if it's in a function expression, we don't want to re-bind "this" by + // using the arrowFunctionExpression. As that could potentially have some unintended consequences. + .filter(p => j(p).find(j.ThisExpression).size() === 0) + .replaceWith(p => { + let body: ArrowFunctionExpression['body'] = p.value.body; + // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, + // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } + let useExpression = false; + if (body.type === 'BlockStatement' && body.body.length === 1) { + const first = body.body[0]; + if (first.type === "ReturnStatement") { + useExpression = true; + body = first.argument!; + } + } + return j.arrowFunctionExpression(p.value.params, body, useExpression); + }) + .toSource(); +}; diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts new file mode 100644 index 0000000000..db4caff58c --- /dev/null +++ b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts @@ -0,0 +1,142 @@ +/** + * Transforms: + * class C extends React.Component() { + * render() { + * return <div foo={this.props.foo} bar={this.props.bar} /> + * } + * } + * + * To: + * + * class C extends React.Component() { + * render() { + * const { + * foo, + * bar + * } = this.props; + * + * return <div foo={foo} bar={bar} /> + * } + * } + * + */ +import { Transform, VariableDeclarator, ObjectPattern, Identifier } from "jscodeshift"; + +// tslint:disable-next-line max-line-length +const keywordsStr = 'this function if return var else for new in typeof while case break try catch delete throw switch continue default instanceof do void finally with debugger implements interface package private protected public static class enum export extends import super true false null abstract boolean byte char const double final float goto int long native short synchronized throws transient volatile'; +const keywords = keywordsStr.split(' ').reduce<{ [key: string]: boolean }>((f, k) => { + f[k] = true; + return f; +}, {}); +const isKeyword = (k: string) => keywords.hasOwnProperty(k); + +const transform: Transform = (file, api) => { + const j = api.jscodeshift; + const {statement} = j.template; + + return j(file.source) + .find(j.FunctionExpression) + .replaceWith(p => { + // console.log(p); + const root = j(p.value); + const variablesToReplace: { [name: string]: boolean } = {}; + + // Figure out if the variable was defined from props, so that we can re-use that definition. + const isFromProps = (name: string, resolvedScope: any) => { + return resolvedScope.getBindings()[name].every( + (p: any) => { + const decl = j(p).closest(j.VariableDeclarator); + // What happens when our VariableDeclarator is too high up the parent AST? + + if (!decl.size()) return false; + const node: VariableDeclarator = decl.nodes()[0]; + + if (!(node.init != null && + node.init.type === 'MemberExpression' && + node.init.object.type === 'ThisExpression' && + node.init.property.type === 'Identifier' && + node.init.property.name === 'props')) + return false; + + // Check for the case where it could be aliased (i.e.) { baz: foo } = this.props; + // In this case, we won't do a substitution. + if (p.parentPath.value.type === 'Property' && p.parentPath.value.key.name !== name) + return false; + + return true; + } + ); + }; + + // Transform "this.props.xyz" to "xyz", and record what we've transformed. + // Transform as long as we don't have "xyz" already defined in the scope. + root + .find(j.MemberExpression, { + object: { + type: 'MemberExpression', + object: {type: 'ThisExpression'}, + property: {name: 'props'} + } + }) + .filter(e => { + const resolvedScope = e.scope.lookup((e.value.property as Identifier).name); + // If the scope is null, that means that this property isn't defined in the scope yet, + // and we can use it. Otherwise, if it is defined, we should see if it was defined from `this.props` + // if none of these cases are true, we can't do substitution. + return resolvedScope === null || isFromProps((e.value.property as Identifier).name, resolvedScope); + }) + // Ensure that our substitution won't cause us to define a keyword, i.e. `this.props.while` won't + // get converted into `while`. + .filter(p => !isKeyword((p.value.property as Identifier).name)) + // Now, do the replacement, `this.props.xyz` => `xyz`. + .replaceWith(p => p.value.property as Identifier) + // Finally, mark the variable as something we will need to define earlier in the function, + // if it's not already defined. + .forEach(p => { + // Is this prop already defined somewhere else. + if (!p.scope.lookup(p.value.name)) + variablesToReplace[p.value.name] = true; + }); + + // Create property definitions for variables that we've replaced. + const properties = Object.keys(variablesToReplace) + .sort() + .map(k => { + const prop = j.property('init', j.identifier(k), j.identifier(k)); + prop.shorthand = true; + return prop; + }); + + // We have no properties to inject, so we can bail here. + if (!properties.length) + return p.value; + + // See if we already have a VariableDeclarator like { a, b, c } = this.props; + const propDefinitions = root + .find(j.VariableDeclarator, { + id: {type: 'ObjectPattern'}, + init: {type: 'MemberExpression', object: {type: 'ThisExpression'}, property: {name: 'props'}} + }); + + if (propDefinitions.size()) { + const nodePath = propDefinitions.paths()[0]; + const node = nodePath.value; + // TODO(brieb): support narrowing based on second argument to `find` + const newPattern = j.objectPattern((node.id as ObjectPattern).properties.concat(properties)); + nodePath.replace(j.variableDeclarator(newPattern, node.init)); + return p.value; + } + + // Otherwise, we'll have to create our own, as none were suitable for use. + // Create the variable definition `const { xyz } = this.props;` + const decl = statement`const { ${properties} } = this.props;`; + + // Add the variable definition to the top of the function expression body. + return j.functionExpression( + p.value.id, + p.value.params, + j.blockStatement([decl].concat(p.value.body.body)) + ); + } + ).toSource(); +}; diff --git a/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts new file mode 100644 index 0000000000..6d1a30c378 --- /dev/null +++ b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts @@ -0,0 +1,64 @@ +/** For when you've gone too pure and want to go back. */ +/** + * Converts + * let HistoryItem = (props) => { + * const { + * item + * } = props; + * return <li>{item}</li>; + * }; + * + * let X = (props) => <div>foo</div>; + * + * to + * + * class HistoryItem extends Component { + * render() { + * const { + * item + * } = this.props; + * return <li>{item}</li>; + * } + * } + * + * class X extends Component { + * render() { + * return <div>foo</div>; + * } + * } + */ + +import { Transform, ASTNode } from "jscodeshift"; + +const transform: Transform = (file, api) => { + const j = api.jscodeshift; + const {statement} = j.template; + + function hasJSXElement(ast: ASTNode) { + return j(ast).find(j.JSXElement).size() > 0; + } + + return j(file.source) + .find(j.VariableDeclaration) + .filter(p => p.value.declarations.length === 1) + .replaceWith(p => { + const decl = p.value.declarations[0]; + if (decl.type === "VariableDeclarator" && decl.init != null) { + if (decl.init.type !== 'ArrowFunctionExpression' || + (!hasJSXElement(decl.init.body) && decl.init.body.type !== "JSXElement")) + return p.value; + + let body: any = decl.init.body; + body = body.type === "JSXElement" ? j.returnStatement(body) : body = body.body; + + j(body) + .find(j.Identifier, {name: 'props'}) + .replaceWith(p => j.memberExpression(j.thisExpression(), j.identifier('props'))); + + return statement`class ${decl.id} extends Component { + render() { ${body} } + }`; + } + }) + .toSource(); +}; diff --git a/types/jscodeshift/test/jscodeshift-tests.ts b/types/jscodeshift/test/jscodeshift-tests.ts new file mode 100644 index 0000000000..f426eb37b7 --- /dev/null +++ b/types/jscodeshift/test/jscodeshift-tests.ts @@ -0,0 +1,75 @@ +import { ASTNode, FileInfo, API, Transform, Parser } from "jscodeshift"; + +// Can define transform with `function`. +function replaceWithFooTransform(fileInfo: FileInfo, api: API) { + return api + .jscodeshift(fileInfo.source) + .findVariableDeclarators("foo") + .renameTo("bar") + .toSource(); +} + +// Can define transform with arrow function, using `Transform` type. +const reverseIdentifiersTransform: Transform = (file, api) => { + const j = api.jscodeshift; + + return j(file.source) + .find(j.Identifier) + .forEach(path => { + j(path).replaceWith( + j.identifier( + path.node.name + .split("") + .reverse() + .join("") + ) + ); + }) + .toSource(); +}; + +// Can define a custom parser. +const parser: Parser = { + parse(source, options) { + // return estree compatible AST + return { type: "root" }; + } +}; + +// Can pass options to recast +const transformWithRecastFormattingOptions: Transform = (file, { j }) => { + return j(file.source).toSource({ quote: "single" }); +}; + +const transformWithRecastParseOptions: Transform = (file, { j }) => { + return j(file.source, { + /* ...passes options to recast's parse method... */ + }).toSource(); +}; + +// `ASTNode` supports type narrowing. +{ + const node = ({} as any) as ASTNode; + if (node.type === "CatchClause") { + // $ExpectType CatchClause + node; + + if (node.param && node.param.type === "Identifier") { + // $ExpectType Identifier + node.param; + + if ( + node.param.typeAnnotation && + node.param.typeAnnotation.type === "TSTypeAnnotation" + ) { + // $ExpectType TSTypeAnnotation + node.param.typeAnnotation; + + if (node.param.typeAnnotation.typeAnnotation.type === "TSArrayType") { + // $ExpectType TSArrayType + node.param.typeAnnotation.typeAnnotation; + } + } + } + } +} diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json new file mode 100644 index 0000000000..5937bd483a --- /dev/null +++ b/types/jscodeshift/tsconfig.json @@ -0,0 +1,34 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "src/core.d.ts", + "src/Collection.d.ts", + "src/collections/JSXElement.d.ts", + "src/collections/Node.d.ts", + "src/collections/VariableDeclarator.d.ts", + "src/template.d.ts", + "test/jscodeshift-tests.ts", + "test/js-transforms/bind-this-to-bind-expression.ts", + "test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts", + "test/js-transforms/function-expression-to-arrow-function-expression.ts", + "test/js-transforms/props-to-destructuring.ts", + "test/js-transforms/pure-to-composite-component.ts" + ] +} diff --git a/types/jscodeshift/tslint.json b/types/jscodeshift/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/jscodeshift/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/kissfft-js/index.d.ts b/types/kissfft-js/index.d.ts new file mode 100644 index 0000000000..dc745354ec --- /dev/null +++ b/types/kissfft-js/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for kissfft-js 0.1 +// Project: https://github.com/j-funk/kissfft-js#readme +// Definitions by: racerhere <https://github.com/racerhere> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/types/kissfft-js + +export class FFT { + constructor(size: number); + forward(input: number[]): number[]; + inverse(input: number[]): number[]; + dispose(): void; +} + +export class FFTR { + constructor(size: number); + forward(input: number[]): number[]; + inverse(input: number[]): number[]; + dispose(): void; +} diff --git a/types/kissfft-js/kissfft-js-tests.ts b/types/kissfft-js/kissfft-js-tests.ts new file mode 100644 index 0000000000..7de3255660 --- /dev/null +++ b/types/kissfft-js/kissfft-js-tests.ts @@ -0,0 +1,11 @@ +import * as kissFFT from "kissfft-js"; + +const fft = new kissFFT.FFT(0); // $ExpectType FFT +fft.forward([1, 2, 3]); // $ExpectType number[] +fft.inverse([1, 2, 3]); // $ExpectType number[] +fft.dispose(); // $ExpectType void + +const fftr = new kissFFT.FFTR(0); // $ExpectType FFTR +fftr.forward([1, 2, 3]); // $ExpectType number[] +fftr.inverse([1, 2, 3]); // $ExpectType number[] +fftr.dispose(); // $ExpectType void diff --git a/types/kissfft-js/tsconfig.json b/types/kissfft-js/tsconfig.json new file mode 100644 index 0000000000..5164a8f4bd --- /dev/null +++ b/types/kissfft-js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "kissfft-js-tests.ts" + ] +} diff --git a/types/kissfft-js/tslint.json b/types/kissfft-js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/kissfft-js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-compose/index.d.ts b/types/koa-compose/index.d.ts index 88047abcc9..f35b9ca208 100644 --- a/types/koa-compose/index.d.ts +++ b/types/koa-compose/index.d.ts @@ -2,6 +2,13 @@ // Project: https://github.com/koajs/compose // Definitions by: jKey Lu <https://github.com/jkeylu> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as Koa from "koa"; + +declare function compose<T, U, V, W>( + middleware: [Koa.Middleware<T, U>, Koa.Middleware<V, W>] +): Koa.Middleware<T & V, U & W>; declare function compose<T>(middleware: Array<compose.Middleware<T>>): compose.ComposedMiddleware<T>; diff --git a/types/koa-compose/koa-compose-tests.ts b/types/koa-compose/koa-compose-tests.ts index ed1c705e5d..56b105e900 100644 --- a/types/koa-compose/koa-compose-tests.ts +++ b/types/koa-compose/koa-compose-tests.ts @@ -1,4 +1,5 @@ import compose = require('koa-compose'); +import * as Koa from "koa"; const fn1: compose.Middleware<any> = (context: any, next: () => Promise<void>): Promise<any> => Promise @@ -11,3 +12,40 @@ const fn2: compose.Middleware<any> = (context: any, next: () => Promise<void>): .then(next); const fn = compose([fn1, fn2]); + +interface FooCtx { + foo: string; +} + +const fooMiddleware: Koa.Middleware<FooCtx> = async (ctx, next) => { + ctx.state.foo = "foo"; + await next(); +}; + +interface BarCtx { + bar: string; +} + +const barMiddleware: Koa.Middleware<BarCtx> = async (ctx, next) => { + ctx.state.bar = "bar"; + await next(); +}; + +interface WooCtx { + woo: string; +} + +const wooMiddleware: Koa.Middleware<WooCtx> = async (ctx, next) => { + ctx.state.woo = "woo"; + await next(); +}; + +new Koa<{}, {}>() + .use(compose([compose([fooMiddleware, barMiddleware]), wooMiddleware])) + .use(async (ctx, next) => { + ctx.state.foo; + ctx.state.bar; + ctx.state.woo; + ctx.body = "Something"; + await next(); + }); diff --git a/types/koa-joi-router/index.d.ts b/types/koa-joi-router/index.d.ts index b767984d73..54cf148240 100644 --- a/types/koa-joi-router/index.d.ts +++ b/types/koa-joi-router/index.d.ts @@ -1,14 +1,16 @@ -// Type definitions for koa-joi-router 5.1 +// Type definitions for koa-joi-router 5.2 // Project: https://github.com/koajs/joi-router // Definitions by: Matthew Bull <https://github.com/wingsbob> // Dave Welsh <https://github.com/move-zig> // Hiroshi Ioka <https://github.com/hirochachacha> +// Tiger Oakes <https://github.com/NotWoods> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 import * as Koa from 'koa'; import * as Joi from 'joi'; import * as KoaRouter from 'koa-router'; +import * as CoBody from 'co-body'; declare module "koa" { interface Request { @@ -23,10 +25,9 @@ interface createRouter { } declare namespace createRouter { - type PartialHandler = (ctx: Koa.Context) => any; type FullHandler = (ctx: Koa.Context, next: () => Promise<any>) => any; - interface NestedHandler extends ReadonlyArray<PartialHandler|FullHandler|NestedHandler> {} - type Handler = PartialHandler | FullHandler| NestedHandler; + interface NestedHandler extends ReadonlyArray<Handler> {} + type Handler = FullHandler | NestedHandler; type Method = (path: string|RegExp, handlerOrConfig: Handler | object, ...handlers: Handler[]) => Router; @@ -34,17 +35,22 @@ declare namespace createRouter { method: string|string[]; path: string|RegExp; handler: Handler; + pre?: Handler; validate?: { - header?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; - query?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; - params?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; - body?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + header?: Joi.SchemaLike; + query?: Joi.SchemaLike; + params?: Joi.SchemaLike; + body?: Joi.SchemaLike; maxBody?: number; failure?: number; type?: 'form'|'json'|'multipart'; - output?: {[status: number]: Joi.AnySchema}; + formOptions?: CoBody.Options; + jsonOptions?: CoBody.Options; + multipartOptions?: CoBody.Options; + output?: {[status: string]: Joi.SchemaLike}; continueOnError?: boolean; }; + meta?: any; } interface Router { diff --git a/types/koa-joi-router/koa-joi-router-tests.ts b/types/koa-joi-router/koa-joi-router-tests.ts index 6ff956c2ef..160c3834c1 100644 --- a/types/koa-joi-router/koa-joi-router-tests.ts +++ b/types/koa-joi-router/koa-joi-router-tests.ts @@ -30,6 +30,7 @@ const spec3: router.Spec = { body: Joi.any(), }, handler: (ctx: koa.Context) => ctx.status = 201, + pre: (_ctx, next) => next(), }; router().route(spec3); @@ -41,9 +42,13 @@ const spec4: router.Spec = { type: 'json', output: { 201: Joi.object(), + '400,404': Joi.object(), + }, + jsonOptions: { + limit: '10kb' } }, - handler: (ctx: koa.Context) => { + handler(ctx) { ctx.status = 201; ctx.body = {}; }, @@ -54,10 +59,11 @@ router().route(spec4); const spec5: router.Spec = { method: 'PUT', path: '/user', - handler: (ctx: koa.Context) => { + handler: (ctx) => { ctx.status = 201; ctx.body = ctx.request.body; }, + meta: 'meta data', }; router().route(spec5); diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index 96bcb3277a..22f71a9187 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Alejandro Sánchez <https://github.com/alejo90> // Arne Schubert <https://github.com/atd-schubert> // Michael Auer <https://github.com/mcauer> +// Roni Karilkar <https://github.com/ronikar> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -579,6 +580,32 @@ export class ImageOverlay extends Layer { export function imageOverlay(imageUrl: string, bounds: LatLngBoundsExpression, options?: ImageOverlayOptions): ImageOverlay; +export interface VideoOverlayOptions extends ImageOverlayOptions { + autoplay?: boolean; + loop?: boolean; +} + +export class VideoOverlay extends Layer { /** VideoOverlay doesn't extend ImageOverlay because ImageOverlay.getElement returns HTMLImageElement */ + constructor(video: string | string[] | HTMLVideoElement, bounds: LatLngBoundsExpression, options?: VideoOverlayOptions); + setOpacity(opacity: number): this; + bringToFront(): this; + bringToBack(): this; + setUrl(url: string): this; + + /** Update the bounds that this VideoOverlay covers */ + setBounds(bounds: LatLngBounds): this; + + /** Get the bounds that this VideoOverlay covers */ + getBounds(): LatLngBounds; + + /** Get the video element that represents the VideoOverlay on the map */ + getElement(): HTMLVideoElement | undefined; + + options: VideoOverlayOptions; +} + +export function videoOverlay(video: string | string[] | HTMLVideoElement, bounds: LatLngBoundsExpression, options?: VideoOverlayOptions): VideoOverlay; + export type LineCapShape = 'butt' | 'round' | 'square' | 'inherit'; export type LineJoinShape = 'miter' | 'round' | 'bevel' | 'inherit'; diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index a6c9b6ccc3..8b024d790e 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -1,13 +1,13 @@ import * as L from 'leaflet'; -const latLngLiteral: L.LatLngLiteral = {lat: 12, lng: 13}; +const latLngLiteral: L.LatLngLiteral = { lat: 12, lng: 13 }; const latLngTuple: L.LatLngTuple = [12, 13]; let latLng: L.LatLng; latLng = L.latLng(12, 13); latLng = L.latLng(12, 13, 0); latLng = L.latLng(latLngLiteral); -latLng = L.latLng({lat: 12, lng: 13, alt: 0}); +latLng = L.latLng({ lat: 12, lng: 13, alt: 0 }); latLng = L.latLng(latLngTuple); latLng = L.latLng([12, 13, 0]); @@ -34,7 +34,7 @@ let point: L.Point; point = L.point(12, 13); point = L.point(12, 13, true); point = L.point(pointTuple); -point = L.point({x: 12, y: 13}); +point = L.point({ x: 12, y: 13 }); point = new L.Point(12, 13); point = new L.Point(12, 13, true); @@ -171,7 +171,7 @@ map.removeEventListener('moveend'); map.removeEventListener('moveend', () => {}); map.removeEventListener('moveend', () => {}, {}); -map.panInside(latLng, {padding: [50, 50], paddingBottomRight: point, paddingTopLeft: [100, 100]}); +map.panInside(latLng, { padding: [50, 50], paddingBottomRight: point, paddingTopLeft: [100, 100] }); // map.getRenderer @@ -218,25 +218,25 @@ mapPixelBounds = map.getPixelWorldBounds(12); let tileLayerOptions: L.TileLayerOptions = {}; tileLayerOptions = { - minZoom: 0, - maxZoom: 18, - maxNativeZoom: 2, - errorTileUrl: '', - zoomOffset: 0, - tms: true, - zoomReverse: true, - detectRetina: true, - crossOrigin: false, - opacity: 1, - updateWhenIdle: true, - updateWhenZooming: true, - updateInterval: 500, - attribution: '', - zIndex: 1, - noWrap: true, - pane: '', - className: '', - keepBuffer: 1, + minZoom: 0, + maxZoom: 18, + maxNativeZoom: 2, + errorTileUrl: '', + zoomOffset: 0, + tms: true, + zoomReverse: true, + detectRetina: true, + crossOrigin: false, + opacity: 1, + updateWhenIdle: true, + updateWhenZooming: true, + updateInterval: 500, + attribution: '', + zIndex: 1, + noWrap: true, + pane: '', + className: '', + keepBuffer: 1, }; tileLayerOptions.subdomains = 'a'; @@ -259,14 +259,14 @@ tileLayer = new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', tileLayer // imageOverlay let imageOverlayOptions: L.ImageOverlayOptions; imageOverlayOptions = { - opacity: 100, - alt: 'alt', - interactive: true, - attribution: 'attribution', - crossOrigin: true, - className: 'className', - bubblingMouseEvents: false, - pane: 'pane' + opacity: 100, + alt: 'alt', + interactive: true, + attribution: 'attribution', + crossOrigin: true, + className: 'className', + bubblingMouseEvents: false, + pane: 'pane' }; const imageOverlayBounds = latLngBounds; @@ -274,22 +274,42 @@ let imageOverlay: L.ImageOverlay; imageOverlay = L.imageOverlay('https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png', imageOverlayBounds); imageOverlay = L.imageOverlay('https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png', imageOverlayBounds, imageOverlayOptions); imageOverlay = L.imageOverlay('https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png', imageOverlayBounds, { - opacity: 100, - alt: 'alt', - className: 'className', + opacity: 100, + alt: 'alt', + className: 'className', }); -const eventHandler = () => {}; +// videoOverlay +let videoOverlayOptions: L.VideoOverlayOptions; +videoOverlayOptions = { + interactive: true, + opacity: 100, + autoplay: true, + loop: false +}; + +const videoOverlayBounds = latLngBounds; +const videoOverlayUrls = ['https://www.mapbox.com/bites/00188/patricia_nasa.webm']; +const videoElement = document.createElement('video'); + +let videoOverlay: L.VideoOverlay; +videoOverlay = L.videoOverlay('https://www.mapbox.com/bites/00188/patricia_nasa.webm', videoOverlayBounds); +videoOverlay = L.videoOverlay(videoOverlayUrls, videoOverlayBounds, videoOverlayOptions); +videoOverlay = L.videoOverlay(videoElement, videoOverlayBounds, { + autoplay: true +}); + +const eventHandler = () => { }; const domEvent: Event = {} as Event; L.DomEvent .on(htmlElement, 'click', eventHandler) .addListener(htmlElement, 'click', eventHandler) .off(htmlElement, 'click', eventHandler) .removeListener(htmlElement, 'click', eventHandler) - .on(htmlElement, {click: eventHandler}) - .addListener(htmlElement, {click: eventHandler}) - .off(htmlElement, {click: eventHandler}, eventHandler) - .removeListener(htmlElement, {click: eventHandler}, eventHandler) + .on(htmlElement, { click: eventHandler }) + .addListener(htmlElement, { click: eventHandler }) + .off(htmlElement, { click: eventHandler }, eventHandler) + .removeListener(htmlElement, { click: eventHandler }, eventHandler) .stopPropagation(domEvent) .disableScrollPropagation(htmlElement) .disableClickPropagation(htmlElement) @@ -415,13 +435,13 @@ let threeCoords: [number, number, number] = [1, 2, 3]; latLng = L.GeoJSON.coordsToLatLng(threeCoords); threeCoords = L.GeoJSON.latLngToCoords(latLng) as [number, number, number]; -let nestedTwoCoords = [ [12, 13], [13, 14], [14, 15] ]; +let nestedTwoCoords = [[12, 13], [13, 14], [14, 15]]; const nestedLatLngs: L.LatLng[] = L.GeoJSON.coordsToLatLngs(nestedTwoCoords, 1); nestedTwoCoords = L.GeoJSON.latLngsToCoords(nestedLatLngs, 1); const geojson = new L.GeoJSON(); const style: L.PathOptions = { - className: "string", + className: "string", }; const styler: L.StyleFunction<MyProperties> = () => style; geojson.setStyle(style); @@ -441,7 +461,7 @@ class MyLayer extends L.Layer { class MyIcon extends L.Icon { constructor() { - super({iconUrl: 'icon.png'}); + super({ iconUrl: 'icon.png' }); } } @@ -451,9 +471,9 @@ class MyDivIcon extends L.DivIcon { } } -const divIcon = L.divIcon({html: ''}); +const divIcon = L.divIcon({ html: '' }); let defaultIcon = new L.Icon.Default(); -defaultIcon = new L.Icon.Default({imagePath: 'apath'}); +defaultIcon = new L.Icon.Default({ imagePath: 'apath' }); const myControlClass = L.Control.extend({}); const myControl = new myControlClass(); @@ -511,11 +531,11 @@ const complexPolygonLatLngs2: L.LatLng[][] = polygon.getLatLngs() as L.LatLng[][ // multi polygon const multiPolygonLatLngs: L.LatLngExpression[][][] = [ [ // first polygon - [[37, -109.05], [41, -109.03], [41, -102.05], [37, -102.04]], // outer ring - [[37.29, -108.58], [40.71, -108.58], [40.71, -102.50], [37.29, -102.50]] // hole + [[37, -109.05], [41, -109.03], [41, -102.05], [37, -102.04]], // outer ring + [[37.29, -108.58], [40.71, -108.58], [40.71, -102.50], [37.29, -102.50]] // hole ], [ // second polygon - [[41, -111.03], [45, -111.04], [45, -104.05], [41, -104.05]] + [[41, -111.03], [45, -111.04], [45, -104.05], [41, -104.05]] ] ]; polygon = L.polygon(multiPolygonLatLngs); @@ -534,8 +554,8 @@ const simplePolylineLatLngs2: L.LatLng[] = polyline.getLatLngs() as L.LatLng[]; // multi polyline const multiPolylineLatLngs: L.LatLngExpression[][] = [ - [[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]], - [[40.78, -73.91], [41.83, -87.62], [32.76, -96.72]] + [[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]], + [[40.78, -73.91], [41.83, -87.62], [32.76, -96.72]] ]; polyline = L.polyline(multiPolylineLatLngs); polyline = new L.Polyline(multiPolylineLatLngs); @@ -569,7 +589,7 @@ const extended3: typeof obj1 & typeof obj2 & typeof obj3 & typeof obj4 = L.Util. const extended4: typeof obj1 & typeof obj2 & typeof obj3 & typeof obj4 & typeof obj5 = L.Util.extend(obj1, obj2, obj3, obj4, obj5); L.Util.create({}); -L.Util.create(null, {foo: {writable: true, value: 'bar'}}); +L.Util.create(null, { foo: { writable: true, value: 'bar' } }); L.Util.bind(() => {}, {}); L.Util.stamp({}); diff --git a/types/libxmljs/index.d.ts b/types/libxmljs/index.d.ts index a29a6adeda..6540561a07 100644 --- a/types/libxmljs/index.d.ts +++ b/types/libxmljs/index.d.ts @@ -14,12 +14,48 @@ export const libxml_parser_version: string; // tslint:disable-next-line:strict-export-declare-modifiers interface StringMap { [key: string]: string; } -export function parseXml(source: string, options?: StringMap): Document; -export function parseXmlString(source: string, options?: StringMap): Document; +// tslint:disable-next-line:strict-export-declare-modifiers +interface ParserOptions { + recover?: boolean; + noent?: boolean; + dtdload?: boolean; + doctype?: boolean; + dtdattr?: any; + dtdvalid?: boolean; + noerror?: boolean; + errors?: boolean; + nowarning?: boolean; + warnings?: boolean; + pedantic?: boolean; + noblanks?: boolean; + blanks?: boolean; + sax1?: boolean; + xinclude?: boolean; + nonet?: boolean; + net?: boolean; + nodict?: boolean; + dict?: boolean; + nsclean?: boolean; + implied?: boolean; + nocdata?: boolean; + cdata?: boolean; + noxincnode?: boolean; + compact?: boolean; + old?: boolean; + nobasefix?: boolean; + basefix?: boolean; + huge?: boolean; + oldsax?: boolean; + ignore_enc?: boolean; + big_lines?: boolean; +} -export function parseHtml(source: string, options?: StringMap): Document; -export function parseHtmlString(source: string, options?: StringMap): Document; -export function parseHtmlFragment(source: string, options?: StringMap): Document; +export function parseXml(source: string, options?: ParserOptions): Document; +export function parseXmlString(source: string, options?: ParserOptions): Document; + +export function parseHtml(source: string, options?: ParserOptions): Document; +export function parseHtmlString(source: string, options?: ParserOptions): Document; +export function parseHtmlFragment(source: string, options?: ParserOptions): Document; export function memoryUsage(): number; export function nodeCount(): number; @@ -113,6 +149,7 @@ export class Element extends Node { prevElement(): Element|null; nextElement(): Element|null; addNextSibling(siblingNode: Node): Node; + addPrevSibling(siblingNode: Node): Node; find(xpath: string, ns_uri?: string): Node[]; find(xpath: string, namespaces: StringMap): Node[]; diff --git a/types/list.js/index.d.ts b/types/list.js/index.d.ts index 0c31e24e20..8209d87e67 100644 --- a/types/list.js/index.d.ts +++ b/types/list.js/index.d.ts @@ -4,25 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.7 -interface ListOptions { - valueNames?: string[]; - item?: string; - listClass?: string; - searchClass?: string; - sortClass?: string; - indexAsync?: boolean; - page?: number; - i?: number; - pagination?: boolean; -} - -interface SortOptions { - order?: string; - alphabet?: string; - insensitive?: boolean; - sortFunction?: ((a: object, b: object) => number|undefined); -} - declare class List { listContainer: HTMLElement; list: HTMLElement; @@ -32,15 +13,15 @@ declare class List { searched: boolean; filtered: boolean; - constructor(element: string|HTMLElement, options?: ListOptions, values?: object[]); + constructor(element: string|HTMLElement, options?: List.ListOptions, values?: object[]); - add(values: object[], callback?: (item: ListItem) => void): void; + add(values: object[], callback?: (item: List.ListItem) => void): void; remove(valueName: string, value: any): number; - get(valueName: string, value: any): ListItem[]; - sort(valueName: string, options: SortOptions): void; + get(valueName: string, value: any): List.ListItem[]; + sort(valueName: string, options: List.SortOptions): void; search(searchString: string, columns?: string[]): void; clear(): void; - filter(filterFunction: (item: ListItem) => boolean): void; + filter(filterFunction: (item: List.ListItem) => boolean): void; size(): number; show(i: number, page: number): void; update(): void; @@ -49,15 +30,36 @@ declare class List { on(event: string, callback: () => void): void; } -declare class ListItem { - elm: HTMLElement; +declare namespace List { + interface ListItem { + elm: HTMLElement; - values(newValues: object): void; - values(): object; - show(): void; - hide(): void; - matching(): boolean; - visible(): boolean; + values(newValues: object): void; + values(): object; + show(): void; + hide(): void; + matching(): boolean; + visible(): boolean; + } + + interface ListOptions { + valueNames?: string[]; + item?: string; + listClass?: string; + searchClass?: string; + sortClass?: string; + indexAsync?: boolean; + page?: number; + i?: number; + pagination?: boolean; + } + + interface SortOptions { + order?: string; + alphabet?: string; + insensitive?: boolean; + sortFunction?: ((a: object, b: object) => number|undefined); + } } export = List; diff --git a/types/loglevel/index.d.ts b/types/loglevel/index.d.ts index 3ad9faf707..64eee88aa6 100644 --- a/types/loglevel/index.d.ts +++ b/types/loglevel/index.d.ts @@ -6,7 +6,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -declare var log: log.Logger; +declare var log: log.DefaultLogger; export as namespace log; export = log; @@ -44,6 +44,30 @@ declare namespace log { type MethodFactory = (methodName: string, level: LogLevelNumbers, loggerName: string) => LoggingMethod; + interface DefaultLogger extends Logger { + /** + * If you're using another JavaScript library that exposes a 'log' global, you can run into conflicts with loglevel. + * Similarly to jQuery, you can solve this by putting loglevel into no-conflict mode immediately after it is loaded + * onto the page. This resets to 'log' global to its value before loglevel was loaded (typically undefined), and + * returns the loglevel object, which you can then bind to another name yourself. + */ + noConflict(): any; + + /** + * This gets you a new logger object that works exactly like the root log object, but can have its level and + * logging methods set independently. All loggers must have a name (which is a non-empty string). Calling + * getLogger() multiple times with the same name will return an identical logger object. + * In large applications, it can be incredibly useful to turn logging on and off for particular modules as you are + * working with them. Using the getLogger() method lets you create a separate logger for each part of your + * application with its own logging level. Likewise, for small, independent modules, using a named logger instead + * of the default root logger allows developers using your module to selectively turn on deep, trace-level logging + * when trying to debug problems, while logging only errors or silencing logging altogether under normal + * circumstances. + * @param name The name of the produced logger + */ + getLogger(name: string): Logger; + } + interface Logger { /** * Available log levels. @@ -105,14 +129,6 @@ declare namespace log { */ setLevel(level: LogLevelDesc, persist?: boolean): void; - /** - * If you're using another JavaScript library that exposes a 'log' global, you can run into conflicts with loglevel. - * Similarly to jQuery, you can solve this by putting loglevel into no-conflict mode immediately after it is loaded - * onto the page. This resets to 'log' global to its value before loglevel was loaded (typically undefined), and - * returns the loglevel object, which you can then bind to another name yourself. - */ - noConflict(): any; - /** * Returns the current logging level, as a value from LogLevel. * It's very unlikely you'll need to use this for normal application logging; it's provided partly to help plugin @@ -137,20 +153,6 @@ declare namespace log { */ setDefaultLevel(level: LogLevelDesc): void; - /** - * This gets you a new logger object that works exactly like the root log object, but can have its level and - * logging methods set independently. All loggers must have a name (which is a non-empty string). Calling - * getLogger() multiple times with the same name will return an identical logger object. - * In large applications, it can be incredibly useful to turn logging on and off for particular modules as you are - * working with them. Using the getLogger() method lets you create a separate logger for each part of your - * application with its own logging level. Likewise, for small, independent modules, using a named logger instead - * of the default root logger allows developers using your module to selectively turn on deep, trace-level logging - * when trying to debug problems, while logging only errors or silencing logging altogether under normal - * circumstances. - * @param name The name of the produced logger - */ - getLogger(name: string): Logger; - /** * This enables all log messages, and is equivalent to log.setLevel("trace"). * diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index b5f1134fb5..eebf89497d 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for luxon 1.10 +// Type definitions for luxon 1.11 // Project: https://github.com/moment/luxon#readme // Definitions by: Colby DeHart <https://github.com/colbydehart> // Hyeonseok Yang <https://github.com/FourwingsY> @@ -436,7 +436,7 @@ export class Interval { splitAt(...dateTimes: DateTime[]): Interval[]; splitBy(duration: Duration | DurationObject | number): Interval[]; toDuration( - unit: DurationUnit | DurationUnit[], + unit?: DurationUnit | DurationUnit[], options?: DiffOptions ): Duration; toFormat( diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index df5481094b..59566c35c3 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -144,6 +144,7 @@ i.mapEndpoints((d) => d); // $ExpectType Interval i.toISO(); // $ExpectType string i.toString(); // $ExpectType string i.toDuration('months'); // $ExpectType Duration +i.toDuration(); // $ExpectType Duration if (Interval.isInterval(anything)) { anything; // $ExpectType Interval diff --git a/types/material__textfield/foundation.d.ts b/types/material__textfield/foundation.d.ts index ffc0436f45..255495f003 100644 --- a/types/material__textfield/foundation.d.ts +++ b/types/material__textfield/foundation.d.ts @@ -71,6 +71,8 @@ export default class MDCTextFieldFoundation extends MDCFoundation<MDCTextFieldAd setValid(isValid: boolean): void; + setUseNativeValidation(useNativeValidation: boolean): void; + isDisabled(): boolean; setDisabled(disabled: boolean): void; diff --git a/types/material__textfield/index.d.ts b/types/material__textfield/index.d.ts index b3e61550c9..883be449a1 100644 --- a/types/material__textfield/index.d.ts +++ b/types/material__textfield/index.d.ts @@ -78,4 +78,12 @@ export class MDCTextField extends MDCComponent<MDCTextFieldAdapter, MDCTextField * Recomputes the outline SVG path for the outline element. */ layout(): void; + + /** + * Ideally we would use a 'writeonly' modifier here since this is a setter, + * but such a thing does not exist. + * https://github.com/Microsoft/TypeScript/issues/4839 + * https://github.com/Microsoft/TypeScript/issues/21759 + */ + useNativeValidation: boolean; } diff --git a/types/meteor/globals/meteor.d.ts b/types/meteor/globals/meteor.d.ts index 7a90b0611e..63f60df310 100644 --- a/types/meteor/globals/meteor.d.ts +++ b/types/meteor/globals/meteor.d.ts @@ -25,7 +25,7 @@ declare module Meteor { _id?: string; username?: string; emails?: UserEmail[]; - createdAt?: number; + createdAt?: Date; profile?: any; services?: any; } @@ -49,7 +49,15 @@ declare module Meteor { /** Error **/ /** Method **/ - function methods(methods: Object): void; + interface MethodThisType { + isSimulation: boolean; + userId: string | null; + connection: Connection | null; + setUserId(userId: string): void; + unblock(): void; + } + + function methods(methods: {[key: string]: (this: MethodThisType, ...args: any[]) => any}): void; function call(name: string, ...args: any[]): any; diff --git a/types/meteor/meteor.d.ts b/types/meteor/meteor.d.ts index ca08c31c98..559308cc69 100644 --- a/types/meteor/meteor.d.ts +++ b/types/meteor/meteor.d.ts @@ -26,7 +26,7 @@ declare module "meteor/meteor" { _id?: string; username?: string; emails?: UserEmail[]; - createdAt?: number; + createdAt?: Date; profile?: any; services?: any; } @@ -50,7 +50,15 @@ declare module "meteor/meteor" { /** Error **/ /** Method **/ - function methods(methods: Object): void; + interface MethodThisType { + isSimulation: boolean; + userId: string | null; + connection: Connection | null; + setUserId(userId: string): void; + unblock(): void; + } + + function methods(methods: {[key: string]: (this: MethodThisType, ...args: any[]) => any}): void; function call(name: string, ...args: any[]): any; @@ -63,11 +71,16 @@ declare module "meteor/meteor" { /** Method **/ /** Url **/ - function absoluteUrl(path?: string, options?: { - secure?: boolean; - replaceLocalhost?: boolean; - rootUrl?: string; - }): string; + var absoluteUrl: { + (path?: string, options?: absoluteUrlOptions): string; + defaultOptions: absoluteUrlOptions; + } + + interface absoluteUrlOptions { + secure?: boolean; + replaceLocalhost?: boolean; + rootUrl?: string; + } /** Url **/ /** Timeout **/ diff --git a/types/meteor/mongo.d.ts b/types/meteor/mongo.d.ts index 84b2d53528..079bf6272d 100644 --- a/types/meteor/mongo.d.ts +++ b/types/meteor/mongo.d.ts @@ -96,7 +96,7 @@ declare module "meteor/mongo" { { $each?: T[P], $position?: number, $slice?: number, $sort?: 1 | -1 | Dictionary<number> } } type ArraysOrEach<T> = { - [P in keyof T]?: OnlyArrays<T[P]> | { $each: T[P] } + [P in keyof T]?: OnlyElementsOfArrays<T[P]> | { $each: T[P] } } type CurrentDateModifier = { $type: "timestamp" | "date" } | true type Modifier<T> = T | { diff --git a/types/meteor/test/meteor-tests.ts b/types/meteor/test/meteor-tests.ts index 8e14f39fb1..db6815caf2 100644 --- a/types/meteor/test/meteor-tests.ts +++ b/types/meteor/test/meteor-tests.ts @@ -246,7 +246,13 @@ Items.insert({ list: groceriesId, name: "Persimmons" }); /** * From Collections, collection.update section */ -var Players = new Mongo.Collection('Players'); + +interface Players { + score: number + badges: string[] +} + +var Players: Mongo.Collection<Players> = new Mongo.Collection('Players'); Template['adminDashboard'].events({ 'click .givePoints': function () { @@ -265,6 +271,17 @@ Meteor.methods({ } }); +/** + * Also from Collections, collection.update section + */ +Meteor.methods({ + declareWinners: function () { + Players.update({ score: { $gt: 10 } }, + { $addToSet: { badges: {$each: ["Winner", "Super"]} } }, + { multi: true }); + } +}); + /** * From Collections, collection.remove section */ @@ -795,3 +812,10 @@ const collectionWithoutConnection = new Mongo.Collection<MonkeyDAO>("monkey", { }); } // End of namespace + +// absoluteUrl +Meteor.absoluteUrl('/sub', {rootUrl: 'http://wonderful.com'}); +Meteor.absoluteUrl.defaultOptions = { + rootUrl: 'http://123.com', + secure: false +}; diff --git a/types/mime/index.d.ts b/types/mime/index.d.ts index 2ff497ac12..771898cf91 100644 --- a/types/mime/index.d.ts +++ b/types/mime/index.d.ts @@ -13,5 +13,3 @@ export interface TypeMap { [key: string]: string[]; } export function getType(path: string): string | null; export function getExtension(mime: string): string | null; export function define(mimes: TypeMap, force?: boolean): void; - -export const default_type: string; diff --git a/types/moment-precise-range-plugin/index.d.ts b/types/moment-precise-range-plugin/index.d.ts new file mode 100644 index 0000000000..ad28b3d009 --- /dev/null +++ b/types/moment-precise-range-plugin/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for moment-precise-range 0.2 +// Project: https://github.com/codebox/moment-precise-range +// Definitions by: Mitchell Grice <https://github.com/gricey432> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import moment = require('moment'); + +export = moment; + +declare module "moment" { + interface PreciseRangeValueObject { + years: number; + months: number; + days: number; + hours: number; + minutes: number; + seconds: number; + firstDateWasLater: boolean; + } + + interface Moment { + preciseDiff(d2: Moment, returnValueObject?: false): string; + preciseDiff(d2: Moment, returnValueObject: true): PreciseRangeValueObject; + } + + function preciseDiff(d1: Moment, d2: Moment, returnValueObject?: false): string; + function preciseDiff(d1: Moment, d2: Moment, returnValueObject: true): PreciseRangeValueObject; +} diff --git a/types/moment-precise-range-plugin/moment-precise-range-plugin-tests.ts b/types/moment-precise-range-plugin/moment-precise-range-plugin-tests.ts new file mode 100644 index 0000000000..427d513fb9 --- /dev/null +++ b/types/moment-precise-range-plugin/moment-precise-range-plugin-tests.ts @@ -0,0 +1,14 @@ +import moment = require("moment"); +import * as momentPreciseRange from "moment-precise-range-plugin"; + +// Static methods +const m1 = moment.utc(); +const m2 = moment.utc(); +moment.preciseDiff(m1, m2); +moment.preciseDiff(m1, m2, true); +moment.preciseDiff(m1, m2, false); + +// Instance methods +m1.preciseDiff(m2); +m1.preciseDiff(m2, true); +m1.preciseDiff(m2, false); diff --git a/types/fastify-static/package.json b/types/moment-precise-range-plugin/package.json similarity index 64% rename from types/fastify-static/package.json rename to types/moment-precise-range-plugin/package.json index e8c68ab969..19e5fb0d14 100644 --- a/types/fastify-static/package.json +++ b/types/moment-precise-range-plugin/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "fastify": "^1.11.2" + "moment": ">=2.14.0" } } diff --git a/types/moment-precise-range-plugin/tsconfig.json b/types/moment-precise-range-plugin/tsconfig.json new file mode 100644 index 0000000000..cfb6dcbd4d --- /dev/null +++ b/types/moment-precise-range-plugin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "moment-precise-range-plugin-tests.ts" + ] +} diff --git a/types/moment-precise-range-plugin/tslint.json b/types/moment-precise-range-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/moment-precise-range-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/next/document.d.ts b/types/next/document.d.ts index e0879e1c68..d0e6d2c91b 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -27,8 +27,15 @@ export type Enhancer<E extends PageProps = AnyPageProps, P extends any = E> = ( */ export interface NextDocumentContext<Q extends DefaultQuery = DefaultQuery> extends NextContext<Q> { /** A callback that executes the actual React rendering logic (synchronously) */ - renderPage<E extends PageProps = AnyPageProps, P extends any = E>( - enhancer?: Enhancer<E, P> // tslint:disable-line no-unnecessary-generics + renderPage< + E extends PageProps = AnyPageProps, + P = E, + EA extends PageProps = AnyPageProps, + PA = EA, + >( + enhancer?: + | Enhancer<E, P> // tslint:disable-line no-unnecessary-generics + | { enhanceApp?: Enhancer<EA, PA>; enhanceComponent?: Enhancer<E, P> } // tslint:disable-line no-unnecessary-generics ): RenderPageResponse; } diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index 83d0a0e8a3..1cd217a749 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -38,12 +38,20 @@ class MyDoc extends Document<WithUrlProps> { static async getInitialProps(ctx: NextDocumentContext) { const { req, renderPage } = ctx; - // without callback + // without enhancer const _page = renderPage(); - // with callback - const enhancer: Enhancer<PageProps, {}> = App => props => <App />; - const { html, head, buildManifest } = renderPage(enhancer); + // with component enhancer + const enhancer: Enhancer<PageProps, {}> = Component => props => <Component />; + const _enhancedPage = renderPage(enhancer); + + // with app and component enhancers + const enhanceApp: Enhancer<PageProps, {}> = App => props => <App />; + const enhanceComponent: Enhancer<PageProps, {}> = Component => props => <Component />; + const { html, head, buildManifest } = renderPage({ + enhanceApp, + enhanceComponent + }); const initialProps = await Document.getInitialProps(ctx); diff --git a/types/node-fetch/index.d.ts b/types/node-fetch/index.d.ts index 1177e8da25..03ae639d26 100644 --- a/types/node-fetch/index.d.ts +++ b/types/node-fetch/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Torsten Werner <https://github.com/torstenwerner> // Niklas Lindgren <https://github.com/nikcorg> // Vinay Bedre <https://github.com/vinaybedre> +// Antonio Román <https://github.com/kyranet> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> @@ -134,6 +135,9 @@ export class Body { export class FetchError extends Error { name: "FetchError"; constructor(message: string, type: string, systemError: string); + type: string; + code?: string; + errno?: string; } export class Response extends Body { diff --git a/types/node/base.d.ts b/types/node/base.d.ts new file mode 100644 index 0000000000..70983d9515 --- /dev/null +++ b/types/node/base.d.ts @@ -0,0 +1,41 @@ +// base definnitions for all NodeJS modules that are not specific to any version of TypeScript +/// <reference path="globals.d.ts" /> +/// <reference path="assert.d.ts" /> +/// <reference path="async_hooks.d.ts" /> +/// <reference path="buffer.d.ts" /> +/// <reference path="child_process.d.ts" /> +/// <reference path="cluster.d.ts" /> +/// <reference path="console.d.ts" /> +/// <reference path="constants.d.ts" /> +/// <reference path="crypto.d.ts" /> +/// <reference path="dgram.d.ts" /> +/// <reference path="dns.d.ts" /> +/// <reference path="domain.d.ts" /> +/// <reference path="events.d.ts" /> +/// <reference path="fs.d.ts" /> +/// <reference path="http.d.ts" /> +/// <reference path="http2.d.ts" /> +/// <reference path="https.d.ts" /> +/// <reference path="inspector.d.ts" /> +/// <reference path="module.d.ts" /> +/// <reference path="net.d.ts" /> +/// <reference path="os.d.ts" /> +/// <reference path="path.d.ts" /> +/// <reference path="perf_hooks.d.ts" /> +/// <reference path="process.d.ts" /> +/// <reference path="punycode.d.ts" /> +/// <reference path="querystring.d.ts" /> +/// <reference path="readline.d.ts" /> +/// <reference path="repl.d.ts" /> +/// <reference path="stream.d.ts" /> +/// <reference path="string_decoder.d.ts" /> +/// <reference path="timers.d.ts" /> +/// <reference path="tls.d.ts" /> +/// <reference path="trace_events.d.ts" /> +/// <reference path="tty.d.ts" /> +/// <reference path="url.d.ts" /> +/// <reference path="util.d.ts" /> +/// <reference path="v8.d.ts" /> +/// <reference path="vm.d.ts" /> +/// <reference path="worker_threads.d.ts" /> +/// <reference path="zlib.d.ts" /> diff --git a/types/node/buffer.d.ts b/types/node/buffer.d.ts index 86fdfdb36c..1d618f2c4b 100644 --- a/types/node/buffer.d.ts +++ b/types/node/buffer.d.ts @@ -1,6 +1,12 @@ declare module "buffer" { export const INSPECT_MAX_BYTES: number; const BuffType: typeof Buffer; - const SlowBuffType: typeof SlowBuffer; - export { BuffType as Buffer, SlowBuffType as SlowBuffer }; + + export const SlowBuffer: { + /** @deprecated since v6.0.0, use Buffer.allocUnsafeSlow() */ + new(size: number): Buffer; + prototype: Buffer; + }; + + export { BuffType as Buffer }; } diff --git a/types/node/globals.d.ts b/types/node/globals.d.ts index 1b268a9501..9ae9077a63 100644 --- a/types/node/globals.d.ts +++ b/types/node/globals.d.ts @@ -142,34 +142,8 @@ interface ErrorConstructor { stackTraceLimit: number; } -// compat for TypeScript 1.8 and default es5 target -// if you use with --target es3 or --target es5 and use below definitions, -// use the lib.es6.d.ts that is bundled with TypeScript 1.8. -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } - -interface Set<T> {} -interface ReadonlySet<T> {} - -// Forward-declare needed types from lib.es2015.d.ts (in case users are using `--lib es5`) -interface Iterable<T> { } -interface Iterator<T> { - next(value?: any): IteratorResult<T>; -} -interface IteratorResult<T> { } -interface IterableIterator<T> { } -interface AsyncIterableIterator<T> {} interface SymbolConstructor { readonly observable: symbol; - readonly iterator: symbol; - readonly asyncIterator: symbol; -} -declare var Symbol: SymbolConstructor; -interface SharedArrayBuffer { - readonly byteLength: number; - slice(begin?: number, end?: number): SharedArrayBuffer; } // Node.js ESNEXT support @@ -249,16 +223,6 @@ declare var module: NodeModule; // Same as module.exports declare var exports: any; -declare const SlowBuffer: { - new(str: string, encoding?: string): Buffer; - new(size: number): Buffer; - new(size: Uint8Array): Buffer; - new(array: any[]): Buffer; - prototype: Buffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: Buffer[], totalLength?: number): Buffer; -}; // Buffer class type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; diff --git a/types/node/http.d.ts b/types/node/http.d.ts index e5f3741003..98b730c0c6 100644 --- a/types/node/http.d.ts +++ b/types/node/http.d.ts @@ -7,14 +7,14 @@ declare module "http" { // incoming headers will never contain number interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; @@ -50,9 +50,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 9126f5504b..a237502039 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -35,43 +35,51 @@ // Kyle Uehlein <https://github.com/kuehlein> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// <reference path="globals.d.ts" /> -/// <reference path="assert.d.ts" /> -/// <reference path="async_hooks.d.ts" /> -/// <reference path="buffer.d.ts" /> -/// <reference path="child_process.d.ts" /> -/// <reference path="cluster.d.ts" /> -/// <reference path="console.d.ts" /> -/// <reference path="constants.d.ts" /> -/// <reference path="crypto.d.ts" /> -/// <reference path="dgram.d.ts" /> -/// <reference path="dns.d.ts" /> -/// <reference path="domain.d.ts" /> -/// <reference path="events.d.ts" /> -/// <reference path="fs.d.ts" /> -/// <reference path="http.d.ts" /> -/// <reference path="http2.d.ts" /> -/// <reference path="https.d.ts" /> -/// <reference path="inspector.d.ts" /> -/// <reference path="module.d.ts" /> -/// <reference path="net.d.ts" /> -/// <reference path="os.d.ts" /> -/// <reference path="path.d.ts" /> -/// <reference path="perf_hooks.d.ts" /> -/// <reference path="process.d.ts" /> -/// <reference path="punycode.d.ts" /> -/// <reference path="querystring.d.ts" /> -/// <reference path="readline.d.ts" /> -/// <reference path="repl.d.ts" /> -/// <reference path="stream.d.ts" /> -/// <reference path="string_decoder.d.ts" /> -/// <reference path="timers.d.ts" /> -/// <reference path="tls.d.ts" /> -/// <reference path="trace_events.d.ts" /> -/// <reference path="tty.d.ts" /> -/// <reference path="url.d.ts" /> -/// <reference path="util.d.ts" /> -/// <reference path="v8.d.ts" /> -/// <reference path="vm.d.ts" /> -/// <reference path="worker_threads.d.ts" /> -/// <reference path="zlib.d.ts" /> +// NOTE: These definitions support NodeJS and TypeScript 3.1. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 2.1 +// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 + +// NOTE: Augmentations for TypeScript 3.1 and later should use individual files for overrides +// within the respective ~/ts3.1 (or later) folder. However, this is disallowed for versions +// prior to TypeScript 3.1, so the older definitions will be found here. + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// <reference path="base.d.ts" /> + +// TypeScript 2.1-specific augmentations: + +// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } +interface Set<T> {} +interface ReadonlySet<T> {} +interface IteratorResult<T> { } +interface Iterable<T> { } +interface Iterator<T> { + next(value?: any): IteratorResult<T>; +} +interface IterableIterator<T> { } +interface AsyncIterableIterator<T> {} +interface SymbolConstructor { + readonly iterator: symbol; + readonly asyncIterator: symbol; +} +declare var Symbol: SymbolConstructor; +interface SharedArrayBuffer { + readonly byteLength: number; + slice(begin?: number, end?: number): SharedArrayBuffer; +} + +declare module "util" { + namespace inspect { + const custom: symbol; + } + namespace promisify { + const custom: symbol; + } +} diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 617e0efc77..cdf495d113 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -473,11 +473,7 @@ function bufferTests() { const arrUint8: Uint8Array = new Uint8Array(2); const buf5: Buffer = Buffer.from(arrUint8); const buf6: Buffer = Buffer.from(buf1); - const sharedArrayBuffer: SharedArrayBuffer = { - byteLength: 10, - slice: (begin?: number, end?: number) => sharedArrayBuffer - }; - const buf7: Buffer = Buffer.from(sharedArrayBuffer); + const buf7: Buffer = Buffer.from(undefined as SharedArrayBuffer); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) diff --git a/types/node/package.json b/types/node/package.json new file mode 100644 index 0000000000..c1f0c68752 --- /dev/null +++ b/types/node/package.json @@ -0,0 +1,11 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { + "*": [ + "ts3.1/*" + ] + } + } +} \ No newline at end of file diff --git a/types/node/ts3.1/index.d.ts b/types/node/ts3.1/index.d.ts new file mode 100644 index 0000000000..be36602300 --- /dev/null +++ b/types/node/ts3.1/index.d.ts @@ -0,0 +1,18 @@ +// NOTE: These definitions support NodeJS and TypeScript 3.1. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 2.1 +// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 + +// Reference required types from the default lib: +/// <reference lib="es2018" /> +/// <reference lib="esnext.asyncIterable" /> +/// <reference lib="esnext.intl" /> + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +// tslint:disable-next-line:no-bad-reference +/// <reference path="../base.d.ts" /> + +// TypeScript 3.1-specific augmentations: +/// <reference path="util.d.ts" /> diff --git a/types/node/ts3.1/node-tests.ts b/types/node/ts3.1/node-tests.ts new file mode 100644 index 0000000000..18db498871 --- /dev/null +++ b/types/node/ts3.1/node-tests.ts @@ -0,0 +1,2 @@ +// tslint:disable-next-line:no-bad-reference +import "../node-tests"; diff --git a/types/node/ts3.1/tsconfig.json b/types/node/ts3.1/tsconfig.json new file mode 100644 index 0000000000..e1a9ddb149 --- /dev/null +++ b/types/node/ts3.1/tsconfig.json @@ -0,0 +1,25 @@ +{ + "files": [ + "index.d.ts", + "node-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/node/ts3.1/tslint.json b/types/node/ts3.1/tslint.json new file mode 100644 index 0000000000..1a8ddd9863 --- /dev/null +++ b/types/node/ts3.1/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "unified-signatures": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "strict-export-declare-modifiers": false // http2 needs this + } +} diff --git a/types/node/ts3.1/util.d.ts b/types/node/ts3.1/util.d.ts new file mode 100644 index 0000000000..e35ef8d0f1 --- /dev/null +++ b/types/node/ts3.1/util.d.ts @@ -0,0 +1,10 @@ +// tslint:disable-next-line:no-bad-reference +/// <reference path="../util.d.ts" /> +declare module "util" { + namespace inspect { + const custom: unique symbol; + } + namespace promisify { + const custom: unique symbol; + } +} diff --git a/types/node/tsconfig.json b/types/node/tsconfig.json index 9675935b6a..37cfa4baed 100644 --- a/types/node/tsconfig.json +++ b/types/node/tsconfig.json @@ -1,6 +1,7 @@ { "files": [ "index.d.ts", + "base.d.ts", "globals.d.ts", "assert.d.ts", "async_hooks.d.ts", diff --git a/types/node/util.d.ts b/types/node/util.d.ts index f918286559..9da88fe9cb 100644 --- a/types/node/util.d.ts +++ b/types/node/util.d.ts @@ -12,18 +12,17 @@ declare module "util" { function print(...param: any[]): void; /** @deprecated since v0.11.3 - use a third party module instead. */ function log(string: string): void; - const inspect: { - (object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - (object: any, options: InspectOptions): string; - colors: { + function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + function inspect(object: any, options: InspectOptions): string; + namespace inspect { + let colors: { [color: string]: [number, number] | undefined - } - styles: { + }; + let styles: { [style: string]: string | undefined - } - defaultOptions: InspectOptions; - custom: symbol; - }; + }; + let defaultOptions: InspectOptions; + } /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ function isArray(object: any): object is any[]; /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ @@ -108,9 +107,6 @@ declare module "util" { fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error | null) => void) => void, ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>; function promisify(fn: Function): Function; - namespace promisify { - const custom: symbol; - } namespace types { function isAnyArrayBuffer(object: any): boolean; diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index 26210a1857..f52a8d01f8 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -672,14 +672,14 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; @@ -703,9 +703,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 5ed74da702..6dd1ad1dc0 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -741,14 +741,14 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; @@ -772,9 +772,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index 932d988912..a4fde30a97 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -738,14 +738,14 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; @@ -769,9 +769,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index e0e901fea6..1fac090367 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -967,18 +967,18 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; - 'authorization'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; + 'authorization'?: string; 'cache-control'?: string; 'connection'?: string; 'content-disposition'?: string; @@ -999,9 +999,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 5bafe1ec47..220afd9e60 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -1052,18 +1052,18 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; - 'authorization'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; + 'authorization'?: string; 'cache-control'?: string; 'connection'?: string; 'content-disposition'?: string; @@ -1084,9 +1084,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index ffb686b3d2..be6822cf36 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -20,7 +20,7 @@ declare namespace Office { */ var Promise: IPromiseConstructor; - // Note: this is a copy of the PromiseConstructor object from + // **Note**: this is a copy of the PromiseConstructor object from // https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es2015.promise.d.ts // It is necessary so that even with targeting "ES5" and not specifying any libs, // developers will still get IntelliSense for "Office.Promise" just as they would with a regular Promise. @@ -628,7 +628,7 @@ declare namespace Office { * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the * `getSelectedDataAsync` and `setSelectedDataAsync` methods of the {@link Office.Document | Document} object. * - * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. + * **Note**: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. * To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. * * **Support details** @@ -1446,7 +1446,7 @@ declare namespace Office { /** * Specifies a table of sample data displayed in the prompt UI as an example of the kinds of fields (columns) that can be bound by your add-in. * The headers provided in the TableData object specify the labels used in the field selection UI. - * Note: This parameter is used only in add-ins for Access. It is ignored if provided when calling the method in an add-in for Excel. + * **Note**: This parameter is used only in add-ins for Access. It is ignored if provided when calling the method in an add-in for Excel. */ sampleData?: Office.TableData /** @@ -1781,43 +1781,43 @@ declare namespace Office { * Return or set data as tabular data with no headers. Data is returned or set as an array of arrays containing one-dimensional runs of * characters. For example, three rows of string values in two columns would be: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. * - * Note: Only applies to data in Excel and Word. + * **Note**: Only applies to data in Excel and Word. */ Matrix, /** * Return or set data as tabular data with optional headers. Data is returned or set as an array of arrays with optional headers. * - * Note: Only applies to data in Access, Excel, and Word. + * **Note**: Only applies to data in Access, Excel, and Word. */ Table, /** * Return or set data as HTML. * - * Note: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). + * **Note**: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). */ Html, /** * Return or set data as Office Open XML. * - * Note: Only applies to data in Word. + * **Note**: Only applies to data in Word. */ Ooxml, /** * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides. For example, * `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. * - * Note: Only applies to data in PowerPoint when calling the {@link Office.Document | Document}.getSelectedData method to get the current + * **Note**: Only applies to data in PowerPoint when calling the {@link Office.Document | Document}.getSelectedData method to get the current * slide or selected range of slides. */ SlideRange, /** * Data is returned or set as an image stream. - * Note: Only applies to data in Excel, Word, and PowerPoint. + * **Note**: Only applies to data in Excel, Word, and PowerPoint. */ Image, /** * Data is returned or set as XML data containing an SVG image. - * Note: Only applies to data in Excel, Word, and PowerPoint. + * **Note**: Only applies to data in Excel, Word, and PowerPoint. */ XmlSvg } @@ -2523,7 +2523,7 @@ declare namespace Office { * </tr> * <tr> * <td>An {@link Office.TableData} object, and the shape of the table matches the bound table.</td> - * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> + * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> * </tr> * </table> * @@ -2654,7 +2654,7 @@ declare namespace Office { * </tr> * <tr> * <td>An {@link Office.TableData} object, and the shape of the table matches the bound table.</td> - * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> + * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> * </tr> * </table> * @@ -2825,7 +2825,7 @@ declare namespace Office { * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. * - * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * **Note**: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of * the table in this format: "Sheet1!Table1" * * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other @@ -2835,7 +2835,7 @@ declare namespace Office { * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. * - * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * **Note**: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. * * **Support details** @@ -2871,7 +2871,7 @@ declare namespace Office { * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. * - * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * **Note**: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of * the table in this format: "Sheet1!Table1" * * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other @@ -2881,7 +2881,7 @@ declare namespace Office { * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. * - * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * **Note**: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. * * **Support details** @@ -4542,7 +4542,7 @@ declare namespace Office { * <table> * <tr><td>Word</td><td>If there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion point</td><td>If `data` is a string, the specified text is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.</td></tr> - * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> + * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> * <tr><td></td><td></td><td>If `data` is Office Open XML, the specified XML is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is a base64 encoded image stream, the specified image is inserted.</td></tr></td></tr> * <tr><td></td><td>If there is a selection</td><td>It will be replaced with the specified `data` following the same rules as above.</td></tr> @@ -4659,7 +4659,7 @@ declare namespace Office { * <table> * <tr><td>Word</td><td>If there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion point</td><td>If `data` is a string, the specified text is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.</td></tr> - * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> + * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> * <tr><td></td><td></td><td>If `data` is Office Open XML, the specified XML is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is a base64 encoded image stream, the specified image is inserted.</td></tr></td></tr> * <tr><td></td><td>If there is a selection</td><td>It will be replaced with the specified `data` following the same rules as above.</td></tr> @@ -5151,7 +5151,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of resources in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5177,7 +5177,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of resources in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the highest index number in the current project's resource collection. @@ -5202,7 +5202,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5228,7 +5228,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the highest index number in the current project's task collection. @@ -5253,7 +5253,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceIndex The index of the resource in the collection of resources for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -5280,7 +5280,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceIndex The index of the resource in the collection of resources for the project. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5306,7 +5306,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskIndex The index of the task in the collection of tasks for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -5333,7 +5333,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskIndex The index of the task in the collection of tasks for the project. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5359,7 +5359,7 @@ declare namespace Office { /** * Project documents only. Set resource field for specified resource Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceId Either a string or value of the Resource Id. * @param fieldId Resource Fields. @@ -5387,7 +5387,7 @@ declare namespace Office { /** * Project documents only. Set resource field for specified resource Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceId Either a string or value of the Resource Id. * @param fieldId Resource Fields. @@ -5414,7 +5414,7 @@ declare namespace Office { /** * Project documents only. Set task field for specified task Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskId Either a string or value of the Task Id. * @param fieldId Task Fields. @@ -5442,7 +5442,7 @@ declare namespace Office { /** * Project documents only. Set task field for specified task Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskId Either a string or value of the Task Id. * @param fieldId Task Fields. @@ -5662,7 +5662,7 @@ declare namespace Office { /** * Adds an event handler for the settingsChanged event. * - * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. * @@ -5719,7 +5719,7 @@ declare namespace Office { /** * Adds an event handler for the settingsChanged event. * - * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. * @@ -5862,7 +5862,7 @@ declare namespace Office { /** * Removes the specified setting. * - * Important: Be aware that the Settings.remove method affects only the in-memory copy of the settings property bag. To persist the removal of + * **Important**: Be aware that the Settings.remove method affects only the in-memory copy of the settings property bag. To persist the removal of * the specified setting in the document, at some point after calling the Settings.remove method and before the add-in is closed, you must * call the Settings.saveAsync method. * @@ -5970,7 +5970,7 @@ declare namespace Office { * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are * available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * **Note**: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to * all instances. @@ -6027,7 +6027,7 @@ declare namespace Office { * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are * available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * **Note**: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to * all instances. @@ -6078,7 +6078,7 @@ declare namespace Office { /** * Sets or creates the specified setting. * - * Important: Be aware that the Settings.set method affects only the in-memory copy of the settings property bag. + * **Important**: Be aware that the Settings.set method affects only the in-memory copy of the settings property bag. * To make sure that additions or changes to settings will be available to your add-in the next time the document is opened, at some point * after calling the Settings.set method and before the add-in is closed, you must call the Settings.saveAsync method to persist settings in * the document. @@ -6128,7 +6128,7 @@ declare namespace Office { * The settingsChanged event was designed to let you to handle potential conflicts when two or more users are * attempting to save settings at the same time when your add-in is used in a shared (co-authored) document. * - * **Important:** Your add-in's code can register a handler for the settingsChanged event when the add-in + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in * is running with any Excel client, but the event will fire only when the add-in is loaded with a spreadsheet * that is opened in Excel Online, and more than one user is editing the spreadsheet (co-authoring). * Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. @@ -10541,7 +10541,7 @@ declare namespace Office { /** * Represents an attachment on an item from the server. Read mode only. * - * An array of AttachmentDetail objects is returned as the attachments property of an Appointment or Message object. + * An array of **AttachmentDetails** objects is returned as the attachments property of an appointment or message item. * * [Api set: Mailbox 1.0] * @@ -11741,16 +11741,18 @@ declare namespace Office { /** * The subclass of {@link Office.Item} dealing with appointments. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of Office.context.mailbox.item. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface Appointment extends Item { } /** * The appointment organizer mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface AppointmentCompose extends Appointment, ItemCompose { /** @@ -11765,32 +11767,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets or sets the date and time that the appointment is to end. * @@ -11904,9 +11880,9 @@ declare namespace Office { * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance * in a series. `null` is returned for single appointments and meeting requests of single appointments. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single * appointment and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -11938,7 +11914,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -12295,7 +12271,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -12330,7 +12306,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -12590,11 +12566,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12634,11 +12610,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12667,11 +12643,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12701,11 +12677,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12842,8 +12818,9 @@ declare namespace Office { /** * The appointment attendee mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of 'Office.context.mailbox.item'. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface AppointmentRead extends Appointment, ItemRead { /** @@ -12857,7 +12834,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Attendee</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. For more information, see + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * */ @@ -12875,7 +12852,7 @@ declare namespace Office { */ body: Body; /** - * Gets the date and time that an item was created. Read mode only. + * Gets the date and time that an item was created. * * [Api set: Mailbox 1.0] * @@ -12887,7 +12864,7 @@ declare namespace Office { */ dateTimeCreated: Date; /** - * Gets the date and time that an item was last modified. Read mode only. + * Gets the date and time that an item was last modified. * * [Api set: Mailbox 1.0] * @@ -12897,7 +12874,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Attendee</td></tr></table> * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ dateTimeModified: Date; /** @@ -12985,7 +12962,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -13087,9 +13064,9 @@ declare namespace Office { * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance * in a series. `null` is returned for single appointments and meeting requests of single appointments. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single * appointment and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -13137,7 +13114,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. Before making REST API calls using this value, it * should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -13232,7 +13209,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13257,7 +13234,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13275,7 +13252,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -13304,7 +13281,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -13326,7 +13303,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13340,7 +13317,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13408,7 +13385,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13438,7 +13415,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13464,7 +13441,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13483,7 +13460,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -13510,7 +13487,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -13622,32 +13599,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Compose or read</td></tr></table> */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets the type of item that an instance represents. * @@ -13676,36 +13627,13 @@ declare namespace Office { */ notificationMessages: NotificationMessages; - /** - * Gets or sets the recurrence pattern of an appointment. Gets the recurrence pattern of a meeting request. - * Read and compose modes for appointment items. Read mode for meeting request items. - * - * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance - * in a series. `null` is returned for single appointments and meeting requests of single appointments. - * `undefined` is returned for messages that are not meeting requests. - * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. - * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment - * and NOT a part of a series. - * - * [Api set: Mailbox 1.7] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Compose or read</td></tr></table> - */ - recurrence: Recurrence; - /** * Gets the id of the series that an instance belongs to. * * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -13774,7 +13702,7 @@ declare namespace Office { addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult<void>) => void): void; /** - * Gets an attachment from a message or appointment and returns it as an `AttachmentContent` object. + * Gets an attachment from a message or appointment and returns it as an **AttachmentContent** object. * * The `getAttachmentContentAsync` method gets the attachment with the specified identifier from the item. As a best practice, you should use * the identifier to retrieve an attachment in the same session that the attachmentIds were retrieved with the `getAttachmentsAsync` or @@ -13806,7 +13734,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -13950,8 +13878,9 @@ declare namespace Office { /** * The compose mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface ItemCompose extends Item { /** @@ -14237,7 +14166,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -14272,7 +14201,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -14467,11 +14396,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14513,11 +14442,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14546,11 +14475,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14581,11 +14510,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14724,8 +14653,9 @@ declare namespace Office { /** * The read mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface ItemRead extends Item { /** @@ -14738,7 +14668,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. * For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * @@ -14788,7 +14718,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -14845,7 +14775,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14870,7 +14800,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14888,7 +14818,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -14917,7 +14847,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -14940,7 +14870,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14954,7 +14884,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15023,7 +14953,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15053,7 +14983,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15079,7 +15009,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15098,7 +15028,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -15123,7 +15053,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -15143,8 +15073,9 @@ declare namespace Office { /** * A subclass of {@link Office.Item} for messages. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface Message extends Item { /** @@ -15171,8 +15102,9 @@ declare namespace Office { /** * The message compose mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface MessageCompose extends Message, ItemCompose { /** @@ -15234,32 +15166,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> */ conversationId: string; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets the email address of the sender of a message. * @@ -15320,35 +15226,13 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> */ notificationMessages: NotificationMessages; - /** - * Gets or sets the recurrence pattern of an appointment. Gets the recurrence pattern of a meeting request. - * Read and compose modes for appointment items. Read mode for meeting request items. - * - * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance - * in a series. `null` is returned for single appointments and meeting requests of single appointments. - * `undefined` is returned for messages that are not meeting requests. - * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. - * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment - * and NOT a part of a series. - * - * [Api set: Mailbox 1.7] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - */ - recurrence: Recurrence; /** * Gets the id of the series that an instance belongs to. * * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -15708,7 +15592,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -15743,7 +15627,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -16007,11 +15891,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16052,11 +15936,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16084,11 +15968,11 @@ declare namespace Office { * Since appointments have no draft state, if saveAsync is called on an appointment in compose mode, the item will be saved as a normal * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16119,11 +16003,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16259,8 +16143,9 @@ declare namespace Office { /** * The message read mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of Office.context.mailbox.item. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface MessageRead extends Message, ItemRead { /** @@ -16274,7 +16159,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Read</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. * For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * @@ -16328,7 +16213,7 @@ declare namespace Office { */ conversationId: string; /** - * Gets the date and time that an item was created. Read mode only. + * Gets the date and time that an item was created. * * [Api set: Mailbox 1.0] * @@ -16340,7 +16225,7 @@ declare namespace Office { */ dateTimeCreated: Date; /** - * Gets the date and time that an item was last modified. Read mode only. + * Gets the date and time that an item was last modified. * * [Api set: Mailbox 1.0] * @@ -16350,7 +16235,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Read</td></tr></table> * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ dateTimeModified: Date; /** @@ -16359,7 +16244,7 @@ declare namespace Office { * The from and sender properties represent the same person unless the message is sent by a delegate. * In that case, the from property represents the delegator, and the sender property represents the delegate. * - * Note: The recipientType property of the EmailAddressDetails object in the from property is undefined. + * **Note**: The recipientType property of the EmailAddressDetails object in the from property is undefined. * * The from property returns an EmailAddressDetails object. * @@ -16444,7 +16329,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -16509,9 +16394,9 @@ declare namespace Office { * in a series. `null` is returned for single appointments and meeting requests of single appointments. * `undefined` is returned for messages that are not meeting requests. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment * and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -16529,7 +16414,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -16552,7 +16437,7 @@ declare namespace Office { * The from and sender properties represent the same person unless the message is sent by a delegate. * In that case, the from property represents the delegator, and the sender property represents the delegate. * - * Note: The recipientType property of the EmailAddressDetails object in the sender property is undefined. + * **Note**: The recipientType property of the EmailAddressDetails object in the sender property is undefined. * * [Api set: Mailbox 1.0] * @@ -16657,7 +16542,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16682,7 +16567,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16701,7 +16586,7 @@ declare namespace Office { * Gets initialization data passed when the add-in is * {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -16731,7 +16616,7 @@ declare namespace Office { * Gets initialization data passed when the add-in is * {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the * web for Office 365. * * [Api set: Mailbox Preview] @@ -16754,7 +16639,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16768,7 +16653,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16838,7 +16723,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16868,7 +16753,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16894,7 +16779,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16913,7 +16798,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -16940,7 +16825,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -17278,7 +17163,7 @@ declare namespace Office { * * The ewsUrl value can be used by a remote service to make EWS calls to the user's mailbox. For example, you can create a remote service to {@link https://docs.microsoft.com/outlook/add-ins/get-attachments-of-an-outlook-item | get attachments from the selected item}. * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ ewsUrl: string; /** @@ -17339,7 +17224,7 @@ declare namespace Office { * Item IDs retrieved via a REST API (such as the Outlook Mail API or the Microsoft Graph) use a different format than the format used by * Exchange Web Services (EWS). The convertToEwsId method converts a REST-formatted ID into the proper format for EWS. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.3] * @@ -17380,7 +17265,7 @@ declare namespace Office { /** * Converts an item ID formatted for EWS into REST format. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.3] * @@ -17431,7 +17316,7 @@ declare namespace Office { * If the specified item identifier does not identify an existing appointment, a blank pane opens on the client computer or device, and * no error message will be returned. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17457,7 +17342,7 @@ declare namespace Office { * Do not use the displayMessageForm with an itemId that represents an appointment. Use the displayAppointmentForm method to display * an existing appointment, and displayNewAppointmentForm to display a form to create a new appointment. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17486,7 +17371,7 @@ declare namespace Office { * * If any of the parameters exceed the specified size limits, or if an unknown parameter name is specified, an exception is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17568,7 +17453,7 @@ declare namespace Office { * * The add-in should use the ewsUrl property to determine the correct URL to use when making EWS calls. * - * Note: It is recommended that add-ins use the REST APIs instead of Exchange Web Services whenever possible. + * **Note**: It is recommended that add-ins use the REST APIs instead of Exchange Web Services whenever possible. * * [Api set: Mailbox 1.5] * @@ -17690,13 +17575,13 @@ declare namespace Office { * The XML result of the EWS call is provided as a string in the asyncResult.value property. * If the result exceeds 1 MB in size, an error message is returned instead. * - * Note: This method is not supported in the following scenarios: + * **Note**: This method is not supported in the following scenarios: * * - In Outlook for iOS or Outlook for Android. * * - When the add-in is loaded in a Gmail mailbox. * - * Note: The server administrator must set OAuthAuthentication to true on the Client Access Server EWS directory to enable the + * **Note**: The server administrator must set OAuthAuthentication to true on the Client Access Server EWS directory to enable the * makeEwsRequestAsync method to make EWS requests. * * *Version differences* @@ -17779,7 +17664,7 @@ declare namespace Office { /** * Gets a string that was identified as a meeting suggestion. */ - meetingstring: string; + meetingString: string; /** * Gets the date and time that a suggested meeting is to begin. */ @@ -18577,7 +18462,7 @@ declare namespace Office { /** * Sets the recurrence pattern of an appointment series. * - * Note: setAsync should only be available for series items and not instance items. + * **Note**: setAsync should only be available for series items and not instance items. * * [Api set: Mailbox 1.7] * @@ -18604,7 +18489,7 @@ declare namespace Office { /** * Sets the recurrence pattern of an appointment series. * - * Note: setAsync should only be available for series items and not instance items. + * **Note**: setAsync should only be available for series items and not instance items. * * [Api set: Mailbox 1.7] * @@ -18746,7 +18631,7 @@ declare namespace Office { * * The RoamingSettings object is accessible via the roamingSettings property in the Office.context namespace. * - * Important: The RoamingSettings object is initialized from the persisted storage only when the add-in is first loaded. + * **Important**: The RoamingSettings object is initialized from the persisted storage only when the add-in is first loaded. * For task panes, this means that it is only initialized when the task pane first opens. * If the task pane navigates to another page or reloads the current page, the in-memory object is reset to its initial values, even if * your add-in has persisted changes. The persisted changes will not be available until the task pane is closed and reopened. @@ -19386,7 +19271,7 @@ declare namespace Office { /** * Gets the account type of the user associated with the mailbox. * - * Note: This member is currently only supported in Outlook 2016 for Mac, build 16.9.1212 and greater. + * **Note**: This member is currently only supported in Outlook 2016 for Mac, build 16.9.1212 and greater. * * [Api set: Mailbox 1.6] * diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 0b4346ef8b..caafa47822 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -20,7 +20,7 @@ declare namespace Office { */ var Promise: IPromiseConstructor; - // Note: this is a copy of the PromiseConstructor object from + // **Note**: this is a copy of the PromiseConstructor object from // https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es2015.promise.d.ts // It is necessary so that even with targeting "ES5" and not specifying any libs, // developers will still get IntelliSense for "Office.Promise" just as they would with a regular Promise. @@ -628,7 +628,7 @@ declare namespace Office { * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the * `getSelectedDataAsync` and `setSelectedDataAsync` methods of the {@link Office.Document | Document} object. * - * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. + * **Note**: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. * To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. * * **Support details** @@ -1446,7 +1446,7 @@ declare namespace Office { /** * Specifies a table of sample data displayed in the prompt UI as an example of the kinds of fields (columns) that can be bound by your add-in. * The headers provided in the TableData object specify the labels used in the field selection UI. - * Note: This parameter is used only in add-ins for Access. It is ignored if provided when calling the method in an add-in for Excel. + * **Note**: This parameter is used only in add-ins for Access. It is ignored if provided when calling the method in an add-in for Excel. */ sampleData?: Office.TableData /** @@ -1781,43 +1781,43 @@ declare namespace Office { * Return or set data as tabular data with no headers. Data is returned or set as an array of arrays containing one-dimensional runs of * characters. For example, three rows of string values in two columns would be: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. * - * Note: Only applies to data in Excel and Word. + * **Note**: Only applies to data in Excel and Word. */ Matrix, /** * Return or set data as tabular data with optional headers. Data is returned or set as an array of arrays with optional headers. * - * Note: Only applies to data in Access, Excel, and Word. + * **Note**: Only applies to data in Access, Excel, and Word. */ Table, /** * Return or set data as HTML. * - * Note: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). + * **Note**: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). */ Html, /** * Return or set data as Office Open XML. * - * Note: Only applies to data in Word. + * **Note**: Only applies to data in Word. */ Ooxml, /** * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides. For example, * `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. * - * Note: Only applies to data in PowerPoint when calling the {@link Office.Document | Document}.getSelectedData method to get the current + * **Note**: Only applies to data in PowerPoint when calling the {@link Office.Document | Document}.getSelectedData method to get the current * slide or selected range of slides. */ SlideRange, /** * Data is returned or set as an image stream. - * Note: Only applies to data in Excel, Word, and PowerPoint. + * **Note**: Only applies to data in Excel, Word, and PowerPoint. */ Image, /** * Data is returned or set as XML data containing an SVG image. - * Note: Only applies to data in Excel, Word, and PowerPoint. + * **Note**: Only applies to data in Excel, Word, and PowerPoint. */ XmlSvg } @@ -2523,7 +2523,7 @@ declare namespace Office { * </tr> * <tr> * <td>An {@link Office.TableData} object, and the shape of the table matches the bound table.</td> - * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> + * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> * </tr> * </table> * @@ -2654,7 +2654,7 @@ declare namespace Office { * </tr> * <tr> * <td>An {@link Office.TableData} object, and the shape of the table matches the bound table.</td> - * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> + * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> * </tr> * </table> * @@ -2825,7 +2825,7 @@ declare namespace Office { * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. * - * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * **Note**: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of * the table in this format: "Sheet1!Table1" * * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other @@ -2835,7 +2835,7 @@ declare namespace Office { * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. * - * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * **Note**: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. * * **Support details** @@ -2871,7 +2871,7 @@ declare namespace Office { * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. * - * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * **Note**: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of * the table in this format: "Sheet1!Table1" * * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other @@ -2881,7 +2881,7 @@ declare namespace Office { * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. * - * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * **Note**: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. * * **Support details** @@ -4542,7 +4542,7 @@ declare namespace Office { * <table> * <tr><td>Word</td><td>If there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion point</td><td>If `data` is a string, the specified text is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.</td></tr> - * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> + * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> * <tr><td></td><td></td><td>If `data` is Office Open XML, the specified XML is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is a base64 encoded image stream, the specified image is inserted.</td></tr></td></tr> * <tr><td></td><td>If there is a selection</td><td>It will be replaced with the specified `data` following the same rules as above.</td></tr> @@ -4659,7 +4659,7 @@ declare namespace Office { * <table> * <tr><td>Word</td><td>If there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion point</td><td>If `data` is a string, the specified text is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.</td></tr> - * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> + * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> * <tr><td></td><td></td><td>If `data` is Office Open XML, the specified XML is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is a base64 encoded image stream, the specified image is inserted.</td></tr></td></tr> * <tr><td></td><td>If there is a selection</td><td>It will be replaced with the specified `data` following the same rules as above.</td></tr> @@ -5151,7 +5151,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of resources in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5177,7 +5177,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of resources in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the highest index number in the current project's resource collection. @@ -5202,7 +5202,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5228,7 +5228,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the highest index number in the current project's task collection. @@ -5253,7 +5253,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceIndex The index of the resource in the collection of resources for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -5280,7 +5280,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceIndex The index of the resource in the collection of resources for the project. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5306,7 +5306,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskIndex The index of the task in the collection of tasks for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -5333,7 +5333,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskIndex The index of the task in the collection of tasks for the project. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5359,7 +5359,7 @@ declare namespace Office { /** * Project documents only. Set resource field for specified resource Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceId Either a string or value of the Resource Id. * @param fieldId Resource Fields. @@ -5387,7 +5387,7 @@ declare namespace Office { /** * Project documents only. Set resource field for specified resource Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceId Either a string or value of the Resource Id. * @param fieldId Resource Fields. @@ -5414,7 +5414,7 @@ declare namespace Office { /** * Project documents only. Set task field for specified task Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskId Either a string or value of the Task Id. * @param fieldId Task Fields. @@ -5442,7 +5442,7 @@ declare namespace Office { /** * Project documents only. Set task field for specified task Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskId Either a string or value of the Task Id. * @param fieldId Task Fields. @@ -5662,7 +5662,7 @@ declare namespace Office { /** * Adds an event handler for the settingsChanged event. * - * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. * @@ -5719,7 +5719,7 @@ declare namespace Office { /** * Adds an event handler for the settingsChanged event. * - * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. * @@ -5862,7 +5862,7 @@ declare namespace Office { /** * Removes the specified setting. * - * Important: Be aware that the Settings.remove method affects only the in-memory copy of the settings property bag. To persist the removal of + * **Important**: Be aware that the Settings.remove method affects only the in-memory copy of the settings property bag. To persist the removal of * the specified setting in the document, at some point after calling the Settings.remove method and before the add-in is closed, you must * call the Settings.saveAsync method. * @@ -5970,7 +5970,7 @@ declare namespace Office { * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are * available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * **Note**: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to * all instances. @@ -6027,7 +6027,7 @@ declare namespace Office { * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are * available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * **Note**: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to * all instances. @@ -6078,7 +6078,7 @@ declare namespace Office { /** * Sets or creates the specified setting. * - * Important: Be aware that the Settings.set method affects only the in-memory copy of the settings property bag. + * **Important**: Be aware that the Settings.set method affects only the in-memory copy of the settings property bag. * To make sure that additions or changes to settings will be available to your add-in the next time the document is opened, at some point * after calling the Settings.set method and before the add-in is closed, you must call the Settings.saveAsync method to persist settings in * the document. @@ -6128,7 +6128,7 @@ declare namespace Office { * The settingsChanged event was designed to let you to handle potential conflicts when two or more users are * attempting to save settings at the same time when your add-in is used in a shared (co-authored) document. * - * **Important:** Your add-in's code can register a handler for the settingsChanged event when the add-in + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in * is running with any Excel client, but the event will fire only when the add-in is loaded with a spreadsheet * that is opened in Excel Online, and more than one user is editing the spreadsheet (co-authoring). * Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. @@ -10541,7 +10541,7 @@ declare namespace Office { /** * Represents an attachment on an item from the server. Read mode only. * - * An array of AttachmentDetail objects is returned as the attachments property of an Appointment or Message object. + * An array of **AttachmentDetails** objects is returned as the attachments property of an appointment or message item. * * [Api set: Mailbox 1.0] * @@ -11741,16 +11741,18 @@ declare namespace Office { /** * The subclass of {@link Office.Item} dealing with appointments. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of Office.context.mailbox.item. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface Appointment extends Item { } /** * The appointment organizer mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface AppointmentCompose extends Appointment, ItemCompose { /** @@ -11765,32 +11767,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets or sets the date and time that the appointment is to end. * @@ -11904,9 +11880,9 @@ declare namespace Office { * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance * in a series. `null` is returned for single appointments and meeting requests of single appointments. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single * appointment and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -11938,7 +11914,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -12295,7 +12271,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -12330,7 +12306,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -12590,11 +12566,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12634,11 +12610,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12667,11 +12643,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12701,11 +12677,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12842,8 +12818,9 @@ declare namespace Office { /** * The appointment attendee mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of 'Office.context.mailbox.item'. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface AppointmentRead extends Appointment, ItemRead { /** @@ -12857,7 +12834,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Attendee</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. For more information, see + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * */ @@ -12875,7 +12852,7 @@ declare namespace Office { */ body: Body; /** - * Gets the date and time that an item was created. Read mode only. + * Gets the date and time that an item was created. * * [Api set: Mailbox 1.0] * @@ -12887,7 +12864,7 @@ declare namespace Office { */ dateTimeCreated: Date; /** - * Gets the date and time that an item was last modified. Read mode only. + * Gets the date and time that an item was last modified. * * [Api set: Mailbox 1.0] * @@ -12897,7 +12874,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Attendee</td></tr></table> * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ dateTimeModified: Date; /** @@ -12985,7 +12962,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -13087,9 +13064,9 @@ declare namespace Office { * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance * in a series. `null` is returned for single appointments and meeting requests of single appointments. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single * appointment and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -13137,7 +13114,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. Before making REST API calls using this value, it * should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -13232,7 +13209,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13257,7 +13234,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13275,7 +13252,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -13304,7 +13281,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -13326,7 +13303,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13340,7 +13317,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13408,7 +13385,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13438,7 +13415,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13464,7 +13441,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13483,7 +13460,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -13510,7 +13487,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -13622,32 +13599,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Compose or read</td></tr></table> */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets the type of item that an instance represents. * @@ -13676,36 +13627,13 @@ declare namespace Office { */ notificationMessages: NotificationMessages; - /** - * Gets or sets the recurrence pattern of an appointment. Gets the recurrence pattern of a meeting request. - * Read and compose modes for appointment items. Read mode for meeting request items. - * - * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance - * in a series. `null` is returned for single appointments and meeting requests of single appointments. - * `undefined` is returned for messages that are not meeting requests. - * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. - * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment - * and NOT a part of a series. - * - * [Api set: Mailbox 1.7] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Compose or read</td></tr></table> - */ - recurrence: Recurrence; - /** * Gets the id of the series that an instance belongs to. * * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -13774,7 +13702,7 @@ declare namespace Office { addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult<void>) => void): void; /** - * Gets an attachment from a message or appointment and returns it as an `AttachmentContent` object. + * Gets an attachment from a message or appointment and returns it as an **AttachmentContent** object. * * The `getAttachmentContentAsync` method gets the attachment with the specified identifier from the item. As a best practice, you should use * the identifier to retrieve an attachment in the same session that the attachmentIds were retrieved with the `getAttachmentsAsync` or @@ -13806,7 +13734,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -13950,8 +13878,9 @@ declare namespace Office { /** * The compose mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface ItemCompose extends Item { /** @@ -14237,7 +14166,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -14272,7 +14201,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -14467,11 +14396,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14513,11 +14442,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14546,11 +14475,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14581,11 +14510,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14724,8 +14653,9 @@ declare namespace Office { /** * The read mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface ItemRead extends Item { /** @@ -14738,7 +14668,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. * For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * @@ -14788,7 +14718,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -14845,7 +14775,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14870,7 +14800,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14888,7 +14818,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -14917,7 +14847,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -14940,7 +14870,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14954,7 +14884,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15023,7 +14953,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15053,7 +14983,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15079,7 +15009,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15098,7 +15028,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -15123,7 +15053,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -15143,8 +15073,9 @@ declare namespace Office { /** * A subclass of {@link Office.Item} for messages. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface Message extends Item { /** @@ -15171,8 +15102,9 @@ declare namespace Office { /** * The message compose mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface MessageCompose extends Message, ItemCompose { /** @@ -15234,32 +15166,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> */ conversationId: string; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets the email address of the sender of a message. * @@ -15320,35 +15226,13 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> */ notificationMessages: NotificationMessages; - /** - * Gets or sets the recurrence pattern of an appointment. Gets the recurrence pattern of a meeting request. - * Read and compose modes for appointment items. Read mode for meeting request items. - * - * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance - * in a series. `null` is returned for single appointments and meeting requests of single appointments. - * `undefined` is returned for messages that are not meeting requests. - * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. - * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment - * and NOT a part of a series. - * - * [Api set: Mailbox 1.7] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - */ - recurrence: Recurrence; /** * Gets the id of the series that an instance belongs to. * * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -15708,7 +15592,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -15743,7 +15627,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -16007,11 +15891,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16052,11 +15936,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16084,11 +15968,11 @@ declare namespace Office { * Since appointments have no draft state, if saveAsync is called on an appointment in compose mode, the item will be saved as a normal * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16119,11 +16003,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16259,8 +16143,9 @@ declare namespace Office { /** * The message read mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of Office.context.mailbox.item. Refer to the Object Model pages for more information. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface MessageRead extends Message, ItemRead { /** @@ -16274,7 +16159,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Read</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. * For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * @@ -16328,7 +16213,7 @@ declare namespace Office { */ conversationId: string; /** - * Gets the date and time that an item was created. Read mode only. + * Gets the date and time that an item was created. * * [Api set: Mailbox 1.0] * @@ -16340,7 +16225,7 @@ declare namespace Office { */ dateTimeCreated: Date; /** - * Gets the date and time that an item was last modified. Read mode only. + * Gets the date and time that an item was last modified. * * [Api set: Mailbox 1.0] * @@ -16350,7 +16235,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Read</td></tr></table> * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ dateTimeModified: Date; /** @@ -16359,7 +16244,7 @@ declare namespace Office { * The from and sender properties represent the same person unless the message is sent by a delegate. * In that case, the from property represents the delegator, and the sender property represents the delegate. * - * Note: The recipientType property of the EmailAddressDetails object in the from property is undefined. + * **Note**: The recipientType property of the EmailAddressDetails object in the from property is undefined. * * The from property returns an EmailAddressDetails object. * @@ -16444,7 +16329,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -16509,9 +16394,9 @@ declare namespace Office { * in a series. `null` is returned for single appointments and meeting requests of single appointments. * `undefined` is returned for messages that are not meeting requests. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment * and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -16529,7 +16414,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -16552,7 +16437,7 @@ declare namespace Office { * The from and sender properties represent the same person unless the message is sent by a delegate. * In that case, the from property represents the delegator, and the sender property represents the delegate. * - * Note: The recipientType property of the EmailAddressDetails object in the sender property is undefined. + * **Note**: The recipientType property of the EmailAddressDetails object in the sender property is undefined. * * [Api set: Mailbox 1.0] * @@ -16657,7 +16542,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16682,7 +16567,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16701,7 +16586,7 @@ declare namespace Office { * Gets initialization data passed when the add-in is * {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -16731,7 +16616,7 @@ declare namespace Office { * Gets initialization data passed when the add-in is * {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the * web for Office 365. * * [Api set: Mailbox Preview] @@ -16754,7 +16639,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16768,7 +16653,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16838,7 +16723,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16868,7 +16753,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16894,7 +16779,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16913,7 +16798,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -16940,7 +16825,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -17278,7 +17163,7 @@ declare namespace Office { * * The ewsUrl value can be used by a remote service to make EWS calls to the user's mailbox. For example, you can create a remote service to {@link https://docs.microsoft.com/outlook/add-ins/get-attachments-of-an-outlook-item | get attachments from the selected item}. * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ ewsUrl: string; /** @@ -17339,7 +17224,7 @@ declare namespace Office { * Item IDs retrieved via a REST API (such as the Outlook Mail API or the Microsoft Graph) use a different format than the format used by * Exchange Web Services (EWS). The convertToEwsId method converts a REST-formatted ID into the proper format for EWS. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.3] * @@ -17380,7 +17265,7 @@ declare namespace Office { /** * Converts an item ID formatted for EWS into REST format. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.3] * @@ -17431,7 +17316,7 @@ declare namespace Office { * If the specified item identifier does not identify an existing appointment, a blank pane opens on the client computer or device, and * no error message will be returned. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17457,7 +17342,7 @@ declare namespace Office { * Do not use the displayMessageForm with an itemId that represents an appointment. Use the displayAppointmentForm method to display * an existing appointment, and displayNewAppointmentForm to display a form to create a new appointment. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17486,7 +17371,7 @@ declare namespace Office { * * If any of the parameters exceed the specified size limits, or if an unknown parameter name is specified, an exception is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17568,7 +17453,7 @@ declare namespace Office { * * The add-in should use the ewsUrl property to determine the correct URL to use when making EWS calls. * - * Note: It is recommended that add-ins use the REST APIs instead of Exchange Web Services whenever possible. + * **Note**: It is recommended that add-ins use the REST APIs instead of Exchange Web Services whenever possible. * * [Api set: Mailbox 1.5] * @@ -17690,13 +17575,13 @@ declare namespace Office { * The XML result of the EWS call is provided as a string in the asyncResult.value property. * If the result exceeds 1 MB in size, an error message is returned instead. * - * Note: This method is not supported in the following scenarios: + * **Note**: This method is not supported in the following scenarios: * * - In Outlook for iOS or Outlook for Android. * * - When the add-in is loaded in a Gmail mailbox. * - * Note: The server administrator must set OAuthAuthentication to true on the Client Access Server EWS directory to enable the + * **Note**: The server administrator must set OAuthAuthentication to true on the Client Access Server EWS directory to enable the * makeEwsRequestAsync method to make EWS requests. * * *Version differences* @@ -17779,7 +17664,7 @@ declare namespace Office { /** * Gets a string that was identified as a meeting suggestion. */ - meetingstring: string; + meetingString: string; /** * Gets the date and time that a suggested meeting is to begin. */ @@ -18577,7 +18462,7 @@ declare namespace Office { /** * Sets the recurrence pattern of an appointment series. * - * Note: setAsync should only be available for series items and not instance items. + * **Note**: setAsync should only be available for series items and not instance items. * * [Api set: Mailbox 1.7] * @@ -18604,7 +18489,7 @@ declare namespace Office { /** * Sets the recurrence pattern of an appointment series. * - * Note: setAsync should only be available for series items and not instance items. + * **Note**: setAsync should only be available for series items and not instance items. * * [Api set: Mailbox 1.7] * @@ -18746,7 +18631,7 @@ declare namespace Office { * * The RoamingSettings object is accessible via the roamingSettings property in the Office.context namespace. * - * Important: The RoamingSettings object is initialized from the persisted storage only when the add-in is first loaded. + * **Important**: The RoamingSettings object is initialized from the persisted storage only when the add-in is first loaded. * For task panes, this means that it is only initialized when the task pane first opens. * If the task pane navigates to another page or reloads the current page, the in-memory object is reset to its initial values, even if * your add-in has persisted changes. The persisted changes will not be available until the task pane is closed and reopened. @@ -19386,7 +19271,7 @@ declare namespace Office { /** * Gets the account type of the user associated with the mailbox. * - * Note: This member is currently only supported in Outlook 2016 for Mac, build 16.9.1212 and greater. + * **Note**: This member is currently only supported in Outlook 2016 for Mac, build 16.9.1212 and greater. * * [Api set: Mailbox 1.6] * @@ -20747,22 +20632,20 @@ declare namespace Excel { /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * + * @remarks + * + * In addition to this signature, this method has the following signatures: + * + * `load(option?: string | string[]): Excel.Application` - Where option is a comma-delimited string or an array of strings that specify the properties to load. + * + * `load(option?: { select?: string; expand?: string; }): Excel.Application` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. + * + * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.Application` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. + * * @param options Provides options for which properties of the object to load. */ load(option?: Excel.Interfaces.ApplicationLoadOptions): Excel.Application; - /** - * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. - * - * @param options The names of the properties to load. - */ load(option?: string | string[]): Excel.Application; - /** - * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. - * - * @param options Provides options for which properties of the object to load. - * `option.select` is a comma-delimited string that specifies the properties to load, - * and `options.expand` is a comma-delimited string that specifies the navigation properties to load. - */ load(option?: { select?: string; expand?: string; diff --git a/types/pathjs/index.d.ts b/types/pathjs/index.d.ts index fa652d0245..2ab8198c59 100644 --- a/types/pathjs/index.d.ts +++ b/types/pathjs/index.d.ts @@ -3,6 +3,10 @@ // Definitions by: Lokesh Peta <https://github.com/lokeshpeta> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export interface IDictionary<T> { + [id: string]: T; +} + interface IPathHistory{ initial: any; pushState(state: any, title: string, path: string):void; @@ -19,11 +23,11 @@ interface IPathRoute{ } interface IPathRoutes{ - current: IPathRoute, - root: IPathRoute, - rescue: Function, - previous: IPathRoute, - defined: {} + current?: string, + root?: string, + rescue?: Function, + previous?: string, + defined: IDictionary<IPathRoute> } interface IPathCore{ @@ -43,7 +47,7 @@ interface IPath { history: IPathHistory; - match(path: string, parameterize: boolean): IPathRoute; + match(path: string, parameterize: boolean): IPathRoute | null; dispatch(passed_route: string): void; diff --git a/types/pathjs/pathjs-tests.ts b/types/pathjs/pathjs-tests.ts index f64fa2a15b..e71dcc7dbb 100644 --- a/types/pathjs/pathjs-tests.ts +++ b/types/pathjs/pathjs-tests.ts @@ -1,4 +1,4 @@ - +import {Path} from "./index"; Path.map("/test/:id") .to(()=>{ }); @@ -30,4 +30,4 @@ var funs = new Array<Function>(); funs.push(test1); funs.push(test2); -route.enter(funs); \ No newline at end of file +route.enter(funs); diff --git a/types/platform/index.d.ts b/types/platform/index.d.ts index b0f640d522..c1db7431f3 100644 --- a/types/platform/index.d.ts +++ b/types/platform/index.d.ts @@ -18,8 +18,8 @@ declare interface Platform { version?: string; toString(): string; }; - parse?(ua: string): Platform; - toString?(): string; + parse(ua: string): Platform; + toString(): string; } declare var platform: Platform; diff --git a/types/platform/platform-tests.ts b/types/platform/platform-tests.ts index 65433ffb13..ce8648e876 100644 --- a/types/platform/platform-tests.ts +++ b/types/platform/platform-tests.ts @@ -16,7 +16,8 @@ var tests: TestContainer = { prerelease: null, product: null, ua: "Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; HTC Sensation XE with Beats Audio Build/IML74K) AppleWebKit/535.7 (KHTML, like Gecko) CrMo/16.0.912.77 Mobile Safari/535.7", - version: "16.0.912.77" + version: "16.0.912.77", + parse: function () {throw new Error()} }, 'WebKit Nightly 528.4 (like Safari 4.x) on Mac OS X 10.4.11': { description: "WebKit Nightly 528.4 (like Safari 4.x) on Mac OS X 10.4.11", @@ -31,7 +32,8 @@ var tests: TestContainer = { prerelease: "alpha", product: null, ua: "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_4_11; tr) AppleWebKit/528.4+ (KHTML, like Gecko) Version/4.0dp1 Safari/526.11.2", - version: "528.4" + version: "528.4", + parse: function () {throw new Error()} } }; diff --git a/types/prettier/index.d.ts b/types/prettier/index.d.ts index 6cef2ef27a..22f82096a8 100644 --- a/types/prettier/index.d.ts +++ b/types/prettier/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for prettier 1.15 +// Type definitions for prettier 1.16 // Project: https://github.com/prettier/prettier // Definitions by: Ika <https://github.com/ikatyang> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -21,7 +21,9 @@ export interface FastPath<T = any> { export type BuiltInParser = (text: string, options?: any) => AST; export type BuiltInParserName = - | 'babylon' + | 'babylon' // deprecated + | 'babel' + | 'babel-flow' | 'flow' | 'typescript' | 'postcss' // deprecated diff --git a/types/prosemirror-test-builder/index.d.ts b/types/prosemirror-test-builder/index.d.ts new file mode 100644 index 0000000000..f6c01420c4 --- /dev/null +++ b/types/prosemirror-test-builder/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for prosemirror-test-builder 1.0 +// Project: https://github.com/prosemirror/prosemirror-test-builder#readme +// Definitions by: Ifiok Jr. <https://github.com/ifiokjr> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Node as ProsemirrorNode, Schema } from 'prosemirror-model'; + +export interface NodeTypeAttributes extends Record<string, any> { + nodeType: string; +} + +export interface MarkTypeAttributes extends Record<string, any> { + markType: string; +} + +export interface TaggedFlatObject<S extends Schema = any> { + tag: Record<string, number>; + flat: Array<TaggedProsemirrorNode<S> | TaggedFlatObject<S>>; +} + +export interface TaggedProsemirrorNode<S extends Schema = any> + extends TaggedFlatObject<S>, + ProsemirrorNode {} + +type TestNodesUnion = + | 'p' + | 'pre' + | 'h1' + | 'h2' + | 'h3' + | 'li' + | 'ul' + | 'ol' + | 'br' + | 'img' + | 'hr' + | 'ordered_list' + | 'bullet_list' + | 'list_item' + | 'doc' + | 'paragraph' + | 'blockquote' + | 'horizontal_rule' + | 'heading' + | 'code_block' + | 'text' + | 'image' + | 'hard_break'; +type TestMarksUnion = 'a' | 'link' | 'em' | 'strong' | 'code'; + +export type TestSchema = Schema<TestNodesUnion, TestMarksUnion>; + +type Args = Array<string | TaggedProsemirrorNode | TaggedFlatObject>; + +type NodeBuilderMethod<S extends Schema = any> = ( + ...args: Args +) => TaggedProsemirrorNode<S>; + +type MarkBuilderMethod<S extends Schema = any> = ( + ...args: Args +) => TaggedFlatObject<S>; + +export interface EqMethod { + eq(param: EqMethod): boolean; +} + +export type Builder = < + Obj extends Record< + string, + NodeTypeAttributes | MarkTypeAttributes + > = Record<string, NodeTypeAttributes | MarkTypeAttributes>, + N extends string = string, + M extends string = string +>( + testSchema: Schema<N, M>, + names: Obj, +) => Record<N, NodeBuilderMethod<Schema<N, M>>> & + Record<M, MarkBuilderMethod<Schema<N, M>>> & + { + [P in keyof Obj]: Obj[P] extends NodeTypeAttributes + ? NodeBuilderMethod<Schema<N, M>> + : MarkBuilderMethod<Schema<N, M>> + }; + +export interface ProsemirrorTestBuilder { + schema: TestSchema; + builders: Builder; + eq(a: EqMethod, b: EqMethod): boolean; + p: NodeBuilderMethod<TestSchema>; + pre: NodeBuilderMethod<TestSchema>; + h1: NodeBuilderMethod<TestSchema>; + h2: NodeBuilderMethod<TestSchema>; + h3: NodeBuilderMethod<TestSchema>; + li: NodeBuilderMethod<TestSchema>; + ul: NodeBuilderMethod<TestSchema>; + ol: NodeBuilderMethod<TestSchema>; + br: NodeBuilderMethod<TestSchema>; + img: NodeBuilderMethod<TestSchema>; + hr: NodeBuilderMethod<TestSchema>; + a: MarkBuilderMethod<TestSchema>; + + // From schema list + ordered_list: NodeBuilderMethod<TestSchema>; + bullet_list: NodeBuilderMethod<TestSchema>; + list_item: NodeBuilderMethod<TestSchema>; + doc: NodeBuilderMethod<TestSchema>; + + // From schema basic + paragraph: NodeBuilderMethod<TestSchema>; + blockquote: NodeBuilderMethod<TestSchema>; + horizontal_rule: NodeBuilderMethod<TestSchema>; + heading: NodeBuilderMethod<TestSchema>; + code_block: NodeBuilderMethod<TestSchema>; + text: NodeBuilderMethod<TestSchema>; + image: NodeBuilderMethod<TestSchema>; + hard_break: NodeBuilderMethod<TestSchema>; + link: MarkBuilderMethod<TestSchema>; + em: MarkBuilderMethod<TestSchema>; + strong: MarkBuilderMethod<TestSchema>; + code: MarkBuilderMethod<TestSchema>; +} + +declare const prosemirrorTestBuilder: ProsemirrorTestBuilder; + +export default prosemirrorTestBuilder; diff --git a/types/prosemirror-test-builder/prosemirror-test-builder-tests.ts b/types/prosemirror-test-builder/prosemirror-test-builder-tests.ts new file mode 100644 index 0000000000..dd5aa0c345 --- /dev/null +++ b/types/prosemirror-test-builder/prosemirror-test-builder-tests.ts @@ -0,0 +1,123 @@ +import { Schema } from 'prosemirror-model'; +import { + EditorState, + NodeSelection, + Selection, + TextSelection, + Transaction, +} from 'prosemirror-state'; +import pm, { TaggedProsemirrorNode } from 'prosemirror-test-builder'; + +export type DispatchFunction = (tr: Transaction) => void; +export type CommandFunction = ( + state: EditorState, + dispatch?: DispatchFunction, +) => boolean; + +function selectionFor(docNode: TaggedProsemirrorNode) { + const aTag = docNode.tag.a; + if (aTag != null) { + const $aTag = docNode.resolve(aTag); + if ($aTag.parent.inlineContent) { + return new TextSelection( + $aTag, + docNode.tag.b != null + ? docNode.resolve(docNode.tag.b) + : undefined, + ); + } else { + return new NodeSelection($aTag); + } + } + return Selection.atStart(docNode); +} + +function createState(d: TaggedProsemirrorNode) { + return EditorState.create({ doc: d, selection: selectionFor(d) }); +} + +export function apply( + docNode: TaggedProsemirrorNode, + command: CommandFunction, + result?: TaggedProsemirrorNode, +): [boolean, TaggedProsemirrorNode] { + let state = createState(docNode); + command(state, tr => (state = state.apply(tr))); + + if (!pm.eq(state.doc, result || docNode)) { + return [false, state.doc as TaggedProsemirrorNode]; + } + + if (result && result.tag.a != null) { + return [ + pm.eq(state.selection, selectionFor(result)), + result || docNode, + ]; + } + return [true, state.doc as TaggedProsemirrorNode]; +} + +const { p, doc, builders } = pm; + +apply(doc(p('hi'), p('<a>there')), () => true, doc(p('hi there'))); + +export const schema = new Schema<'doc' | 'paragraph' | 'blockquote', 'em'>({ + nodes: { + doc: { + content: 'block+', + }, + + paragraph: { + group: 'block', + parseDOM: [{ tag: 'p' }], + toDOM() { + return ['p', 0]; + }, + }, + + blockquote: { + content: 'block+', + group: 'block', + parseDOM: [{ tag: 'blockquote' }], + toDOM() { + return ['blockquote', 0]; + }, + }, + }, + + marks: { + em: { + parseDOM: [ + { tag: 'i' }, + { tag: 'em' }, + { + style: 'font-style', + getAttrs: value => value === 'italic' && null, + }, + ], + toDOM() { + return ['em']; + }, + }, + }, +}); + +const { h1, a } = builders(schema, { + p: { nodeType: 'paragraph' }, + h1: { nodeType: 'heading', level: 1 }, + h2: { nodeType: 'heading', level: 2 }, + hr: { nodeType: 'horizontal_rule' }, + li: { nodeType: 'list_item' }, + ol: { nodeType: 'ordered_list' }, + ul: { nodeType: 'bullet_list' }, + pre: { nodeType: 'code_block' }, + a: { markType: 'link', href: 'foo' }, + br: { nodeType: 'hard_break' }, + img: { nodeType: 'image', src: 'img.png', alt: 'x' }, +}); + +const TEST1 = h1; // $ExpectType NodeBuilderMethod<Schema<"doc" | "paragraph" | "blockquote", "em">> +const TEST2 = a; // $ExpectType MarkBuilderMethod<Schema<"doc" | "paragraph" | "blockquote", "em">> + +h1(''); // $ExpectType TaggedProsemirrorNode<Schema<"doc" | "paragraph" | "blockquote", "em">> +a(''); // $ExpectType TaggedFlatObject<Schema<"doc" | "paragraph" | "blockquote", "em">> diff --git a/types/prosemirror-test-builder/tsconfig.json b/types/prosemirror-test-builder/tsconfig.json new file mode 100644 index 0000000000..3869b95fde --- /dev/null +++ b/types/prosemirror-test-builder/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "module": "commonjs", + "noEmit": true, + "lib": ["es6", "dom"], + "noUnusedLocals": false, + "noUnusedParameters": false, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "prosemirror-test-builder-tests.ts"] +} diff --git a/types/prosemirror-test-builder/tslint.json b/types/prosemirror-test-builder/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/prosemirror-test-builder/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index c10cd506b9..4a8b497506 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -4,7 +4,8 @@ // rollymaduk <https://github.com/rollymaduk>, // vitosamson <https://github.com/vitosamson>, // FlorianDr <https://github.com/FlorianDr>, -// danduh <https://github.com/danduh> +// danduh <https://github.com/danduh>, +// ChristianBoehlke <https://github.com/ChristianBoehlke> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @see https://www.pubnub.com/docs/web-javascript/api-reference-configuration // TypeScript Version: 2.2 @@ -99,6 +100,15 @@ declare class Pubnub { params: Pubnub.SetStateParameters ): Promise<Pubnub.SetStateResponse>; + grant( + params: Pubnub.GrantParameters, + callback: (status: Pubnub.GrantStatus, response: {}) => void + ): void; + + grant( + params: Pubnub.GrantParameters + ): Promise<{}>; + encrypt( data: string, customCipherKey?: string, @@ -348,6 +358,23 @@ declare namespace Pubnub { }; } + // grant + interface GrantParameters { + channels?: string[]; + channelGroups?: string[]; + authKeys?: string[]; + ttl?: number; + read?: boolean; + write?: boolean; + manage?: boolean; + } + + interface GrantStatus { + error: boolean; + operation: string; + statusCode: number; + } + // encrypt & decrypt interface CryptoParameters { encryptKey?: boolean; diff --git a/types/pubnub/pubnub-tests.ts b/types/pubnub/pubnub-tests.ts index 96dd4202ba..8750919e59 100644 --- a/types/pubnub/pubnub-tests.ts +++ b/types/pubnub/pubnub-tests.ts @@ -87,6 +87,17 @@ pubnub.setState({ channels: [] }).then(res => { console.log(res.state); }); +const grantOptions = { + channels: ['channel-1'], + authKeys: ['auth-key'], + read: true, + write: false, + manage: false +}; +pubnub.grant(grantOptions).then(status => { + console.log(status); +}); + pubnub.history({channel: 'channel-1', count: 2}, (status, res) => { console.log(status); console.log(res); diff --git a/types/ramda/es/move.d.ts b/types/ramda/es/move.d.ts new file mode 100644 index 0000000000..3df4ee626e --- /dev/null +++ b/types/ramda/es/move.d.ts @@ -0,0 +1,2 @@ +import { move } from '../index'; +export default move; diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index d84c148d96..459a351c33 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -26,6 +26,7 @@ // Drew Wyatt <https://github.com/drewwyatt> // John Ottenlips <https://github.com/jottenlips> // Nitesh Phadatare <https://github.com/minitesh> +// Krantisinh Deshmukh <https://github.com/krantisinh> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -163,6 +164,7 @@ /// <reference path="./es/minBy.d.ts" /> /// <reference path="./es/min.d.ts" /> /// <reference path="./es/modulo.d.ts" /> +/// <reference path="./es/move.d.ts" /> /// <reference path="./es/multiply.d.ts" /> /// <reference path="./es/nAry.d.ts" /> /// <reference path="./es/negate.d.ts" /> @@ -1575,6 +1577,17 @@ declare namespace R { multiply(a: number, b: number): number; multiply(a: number): (b: number) => number; + /** + * Moves an item, at index `from`, to index `to`, in a `list` of elements. + * A new list will be created containing the new elements order. + */ + move<T>(from: number, to: number, list: ReadonlyArray<T>): T[]; + move(from: number, to: number): <T>(list: ReadonlyArray<T>) => T[]; + move(from: number): { + <T>(to: number, list: ReadonlyArray<T>): T[]; + (to: number): <T>(list: ReadonlyArray<T>) => T[]; + }; + /** * Wraps a function of any arity (including nullary) in a function that accepts exactly n parameters. * Any extraneous parameters will not be passed to the supplied function. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index c67ef3944d..e4039483da 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1115,6 +1115,23 @@ interface Obj { R.addIndex(R.map)(squareEnds)([8, 5, 3, 0, 9]); // => [64, 5, 3, 0, 81] }; +() => { + const sampleList = ['a', 'b', 'c', 'd', 'e', 'f']; + + R.move<string>(0, 2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + R.move<string>(-1, 0, sampleList); // => ['f', 'a', 'b', 'c', 'd', 'e'] list rotation + + const moveCurried1 = R.move(0, 2); + moveCurried1<string>(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + + const moveCurried2 = R.move(0); + moveCurried2<string>(2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + + const moveCurried3 = R.move(0); + const moveCurried4 = moveCurried3(2); + moveCurried4<string>(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] +}; + () => { R.none(R.isNaN, [1, 2, 3]); // => true R.none(R.isNaN, [1, 2, 3, NaN]); // => false diff --git a/types/react-bootstrap-typeahead/index.d.ts b/types/react-bootstrap-typeahead/index.d.ts index 2f1ad8b7be..93fa2c9c6a 100644 --- a/types/react-bootstrap-typeahead/index.d.ts +++ b/types/react-bootstrap-typeahead/index.d.ts @@ -107,6 +107,8 @@ export interface TypeaheadContainerProps<T extends TypeaheadModel> { text: string; } +export type TypeaheadResult<T extends TypeaheadModel> = T & { customOption: boolean }; + export interface TypeaheadProps<T extends TypeaheadModel> { /* For localized accessibility: Should return a string indicating the number of results for screen readers. Receives the current results. */ @@ -252,10 +254,10 @@ export interface TypeaheadProps<T extends TypeaheadModel> { placeholder?: string; /* Callback for custom menu rendering. */ - renderMenu?: (results: T[], menuProps: any) => React.ReactNode; + renderMenu?: (results: Array<TypeaheadResult<T>>, menuProps: any) => React.ReactNode; /* Provides a hook for customized rendering of menu item contents. */ - renderMenuItemChildren?: (option: T, props: TypeaheadMenuProps<T>, index: number) => React.ReactNode; + renderMenuItemChildren?: (option: TypeaheadResult<T>, props: TypeaheadMenuProps<T>, index: number) => React.ReactNode; /* Provides a hook for customized rendering of tokens when multiple selections are enabled. */ renderToken?: (selectedItem: T, props: TypeaheadMenuProps<T>, index: number) => React.ReactNode; diff --git a/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx b/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx index 7e2c3a29a6..f331752cbb 100644 --- a/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx +++ b/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx @@ -107,6 +107,21 @@ class BasicExample extends React.Component { </Highlighter> } /> + <Typeahead + labelKey="name" + options={options} + placeholder="Choose a state..." + renderMenu={(results, menuProps) => ( + <Menu {...menuProps}> + { results.map((result, index) => ( + <MenuItem option={result} position={index} key={index}> + { result.customOption && 'New: ' } + <Highlighter search={menuProps.text}>{result.name}</Highlighter> + </MenuItem> + )) } + </Menu> + )} + /> <Typeahead labelKey="name" options={options} diff --git a/types/react-dom/index.d.ts b/types/react-dom/index.d.ts index 518c0c617c..a6ac5c9d11 100644 --- a/types/react-dom/index.d.ts +++ b/types/react-dom/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for React (react-dom) 16.0 +// Type definitions for React (react-dom) 16.8 // Project: http://facebook.github.io/react/ // Definitions by: Asana <https://asana.com> // AssureSign <http://www.assuresign.com> // Microsoft <https://microsoft.com> // MartynasZilinskas <https://github.com/MartynasZilinskas> // Josh Rutherford <https://github.com/theruther4d> +// Jessica Franco <https://github.com/Jessidhia> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/react-dom/react-dom-tests.tsx b/types/react-dom/react-dom-tests.tsx index c7ccb0052d..46274e3ffd 100644 --- a/types/react-dom/react-dom-tests.tsx +++ b/types/react-dom/react-dom-tests.tsx @@ -178,4 +178,23 @@ describe('React dom test utils', () => { shallowRenderer.getRenderOutput(); }); }); + + describe('act', () => { + it('accepts a sync callback that is void', () => { + ReactTestUtils.act(() => {}); + }); + it('rejects an async callback even if void', () => { + // $ExpectError + ReactTestUtils.act(async () => {}); + }); + it('rejects a callback that returns null', () => { + // $ExpectError + ReactTestUtils.act(() => null); + }); + it('returns a Promise-like that errors out on use', () => { + const result = ReactTestUtils.act(() => {}); + // $ExpectError + Promise.resolve(result); + }); + }); }); diff --git a/types/react-dom/test-utils/index.d.ts b/types/react-dom/test-utils/index.d.ts index f60d088515..8730dc9447 100644 --- a/types/react-dom/test-utils/index.d.ts +++ b/types/react-dom/test-utils/index.d.ts @@ -278,3 +278,26 @@ export function findRenderedComponentWithType<T extends Component<any>, C extend * Call this in your tests to create a shallow renderer. */ export function createRenderer(): ShallowRenderer; + +/** + * Wrap any code rendering and triggering updates to your components into `act()` calls. + * + * Ensures that the behavior in your tests matches what happens in the browser + * more closely by executing pending `useEffect`s before returning. This also + * reduces the amount of re-renders done. + * + * @param callback A synchronous, void callback that will execute as a single, complete React commit. + * + * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks + */ +// the "void | undefined" is here to forbid any sneaky "Promise" returns. +// the actual return value is always a "DebugPromiseLike", +// but having an "| {}" makes it harder to accidentally use. +export function act(callback: () => void | undefined): DebugPromiseLike | {}; + +// Intentionally doesn't extend PromiseLike<never>. +// Ideally this should be as hard to accidentally use as possible. +export interface DebugPromiseLike { + // the actual then() in here is 0-ary, but that doesn't count as a PromiseLike. + then(onfulfilled: (value: never) => never, onrejected: (reason: never) => never): never; +} diff --git a/types/react-dom/tsconfig.json b/types/react-dom/tsconfig.json index f63325026f..6d7d943c8b 100644 --- a/types/react-dom/tsconfig.json +++ b/types/react-dom/tsconfig.json @@ -14,7 +14,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/react-event-listener/index.d.ts b/types/react-event-listener/index.d.ts index c3ff194394..c264735c08 100644 --- a/types/react-event-listener/index.d.ts +++ b/types/react-event-listener/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as React from "react"; +import React = require("react"); export interface EventOptions { /** diff --git a/types/react-event-listener/package.json b/types/react-event-listener/package.json new file mode 100644 index 0000000000..24c89a85ed --- /dev/null +++ b/types/react-event-listener/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*": ["ts3.1/*"] } + } +} \ No newline at end of file diff --git a/types/react-event-listener/react-event-listener-tests.tsx b/types/react-event-listener/react-event-listener-tests.tsx index 8b9aae2c4d..e9a00dcc5f 100644 --- a/types/react-event-listener/react-event-listener-tests.tsx +++ b/types/react-event-listener/react-event-listener-tests.tsx @@ -1,4 +1,4 @@ -import * as React from "react"; +import React = require("react"); import EventListener, { withOptions } from "react-event-listener"; <EventListener target={document} onBeforeUnload={ev => { }} />; diff --git a/types/react-event-listener/ts3.1/index.d.ts b/types/react-event-listener/ts3.1/index.d.ts new file mode 100644 index 0000000000..b6e11bed31 --- /dev/null +++ b/types/react-event-listener/ts3.1/index.d.ts @@ -0,0 +1,220 @@ +import React = require("react"); + +export interface EventOptions extends Pick<AddEventListenerOptions, 'capture' | 'passive'> { } + +export function withOptions<T, TThis = any>(handler: (this: TThis, ev: T) => any, options: EventOptions): (this: TThis, ev: T) => any; + +export type EventListenerThisType<T extends EventTarget | WindowEventTargets> = T extends keyof Window ? Window[T] : T; + +export type OnErrorEventHandlerArgs = OnErrorEventHandlerNonNull extends (...args: infer A) => any ? A : []; + +export interface EventListenerProps<T extends EventTarget | WindowEventTargets> { + // Global events + onPointerCancel?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerCancelCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerDown?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerDownCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerEnter?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerEnterCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerLeave?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerLeaveCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerMove?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerMoveCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerOut?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerOutCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerOver?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerOverCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerUp?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerUpCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onWheel?(this: EventListenerThisType<T>, ev: WheelEvent): any; + onWheelCapture?(this: EventListenerThisType<T>, ev: WheelEvent): any; + onAbort?(this: EventListenerThisType<T>, ev: Event): any; + onAbortCapture?(this: EventListenerThisType<T>, ev: Event): any; + onAfterPrint?(this: EventListenerThisType<T>, ev: Event): any; + onAfterPrintCapture?(this: EventListenerThisType<T>, ev: Event): any; + onBeforePrint?(this: EventListenerThisType<T>, ev: Event): any; + onBeforePrintCapture?(this: EventListenerThisType<T>, ev: Event): any; + onBeforeUnload?(this: EventListenerThisType<T>, ev: BeforeUnloadEvent): any; + onBeforeUnloadCapture?(this: EventListenerThisType<T>, ev: BeforeUnloadEvent): any; + onBlur?(this: EventListenerThisType<T>, ev: FocusEvent): any; + onBlurCapture?(this: EventListenerThisType<T>, ev: FocusEvent): any; + onCanPlay?(this: EventListenerThisType<T>, ev: Event): any; + onCanPlayCapture?(this: EventListenerThisType<T>, ev: Event): any; + onCanPlayThrough?(this: EventListenerThisType<T>, ev: Event): any; + onCanPlayThroughCapture?(this: EventListenerThisType<T>, ev: Event): any; + onChange?(this: EventListenerThisType<T>, ev: Event): any; + onChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onClick?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onClickCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onCompassNeedsCalibration?(this: EventListenerThisType<T>, ev: Event): any; + onCompassNeedsCalibrationCapture?(this: EventListenerThisType<T>, ev: Event): any; + onContextMenu?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onContextMenuCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onDblClick?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onDblClickCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onDeviceMotion?(this: EventListenerThisType<T>, ev: DeviceMotionEvent): any; + onDeviceMotionCapture?(this: EventListenerThisType<T>, ev: DeviceMotionEvent): any; + onDeviceOrientation?(this: EventListenerThisType<T>, ev: DeviceOrientationEvent): any; + onDeviceOrientationCapture?(this: EventListenerThisType<T>, ev: DeviceOrientationEvent): any; + onDrag?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragEnd?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragEndCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragEnter?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragEnterCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragLeave?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragLeaveCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragOver?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragOverCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragStart?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragStartCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDrop?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDropCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDurationChange?(this: EventListenerThisType<T>, ev: Event): any; + onDurationChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onEmptied?(this: EventListenerThisType<T>, ev: Event): any; + onEmptiedCapture?(this: EventListenerThisType<T>, ev: Event): any; + onEnded?(this: EventListenerThisType<T>, ev: Event): any; + onEndedCapture?(this: EventListenerThisType<T>, ev: Event): any; + onError?(this: EventListenerThisType<T>, ...args: OnErrorEventHandlerArgs): any; + onErrorCapture?(this: EventListenerThisType<T>, ...args: OnErrorEventHandlerArgs): any; + onFocus?(this: EventListenerThisType<T>, ev: FocusEvent): any; + onFocusCapture?(this: EventListenerThisType<T>, ev: FocusEvent): any; + onHashChange?(this: EventListenerThisType<T>, ev: HashChangeEvent): any; + onHashChangeCapture?(this: EventListenerThisType<T>, ev: HashChangeEvent): any; + onInput?(this: EventListenerThisType<T>, ev: Event): any; + onInputCapture?(this: EventListenerThisType<T>, ev: Event): any; + onKeyDown?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyDownCapture?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyPress?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyPressCapture?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyUp?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyUpCapture?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onLoad?(this: EventListenerThisType<T>, ev: Event): any; + onLoadCapture?(this: EventListenerThisType<T>, ev: Event): any; + onLoadedData?(this: EventListenerThisType<T>, ev: Event): any; + onLoadedDataCapture?(this: EventListenerThisType<T>, ev: Event): any; + onLoadedMetadata?(this: EventListenerThisType<T>, ev: Event): any; + onLoadedMetadataCapture?(this: EventListenerThisType<T>, ev: Event): any; + onLoadStart?(this: EventListenerThisType<T>, ev: Event): any; + onLoadStartCapture?(this: EventListenerThisType<T>, ev: Event): any; + onMessage?(this: EventListenerThisType<T>, ev: MessageEvent): any; + onMessageCapture?(this: EventListenerThisType<T>, ev: MessageEvent): any; + onMouseDown?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseDownCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseEnter?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseEnterCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseLeave?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseLeaveCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseMove?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseMoveCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseOut?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseOutCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseOver?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseOverCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseUp?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseUpCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseWheel?(this: EventListenerThisType<T>, ev: WheelEvent): any; + onMouseWheelCapture?(this: EventListenerThisType<T>, ev: WheelEvent): any; + onMsGestureChange?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureChangeCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureDoubleTap?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureDoubleTapCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureEnd?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureEndCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureHold?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureHoldCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureStart?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureStartCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureTap?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureTapCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsInertiaStart?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsInertiaStartCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsPointerCancel?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerCancelCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerDown?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerDownCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerEnter?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerEnterCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerLeave?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerLeaveCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerMove?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerMoveCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerOut?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerOutCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerOver?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerOverCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + oNmsPointerUp?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + oNmsPointerUpCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onOffline?(this: EventListenerThisType<T>, ev: Event): any; + onOfflineCapture?(this: EventListenerThisType<T>, ev: Event): any; + onOnline?(this: EventListenerThisType<T>, ev: Event): any; + onOnlineCapture?(this: EventListenerThisType<T>, ev: Event): any; + onOrientationChange?(this: EventListenerThisType<T>, ev: Event): any; + onOrientationChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onPageHide?(this: EventListenerThisType<T>, ev: PageTransitionEvent): any; + onPageHideCapture?(this: EventListenerThisType<T>, ev: PageTransitionEvent): any; + onPageShow?(this: EventListenerThisType<T>, ev: PageTransitionEvent): any; + onPageShowCapture?(this: EventListenerThisType<T>, ev: PageTransitionEvent): any; + onPause?(this: EventListenerThisType<T>, ev: Event): any; + onPauseCapture?(this: EventListenerThisType<T>, ev: Event): any; + onPlay?(this: EventListenerThisType<T>, ev: Event): any; + onPlayCapture?(this: EventListenerThisType<T>, ev: Event): any; + onPlaying?(this: EventListenerThisType<T>, ev: Event): any; + onPlayingCapture?(this: EventListenerThisType<T>, ev: Event): any; + onPopState?(this: EventListenerThisType<T>, ev: PopStateEvent): any; + onPopStateCapture?(this: EventListenerThisType<T>, ev: PopStateEvent): any; + onProgress?(this: EventListenerThisType<T>, ev: ProgressEvent): any; + onProgressCapture?(this: EventListenerThisType<T>, ev: ProgressEvent): any; + onRateChange?(this: EventListenerThisType<T>, ev: Event): any; + onRateChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onReadyStateChange?(this: EventListenerThisType<T>, ev: ProgressEvent): any; + onReadyStateChangeCapture?(this: EventListenerThisType<T>, ev: ProgressEvent): any; + onReset?(this: EventListenerThisType<T>, ev: Event): any; + onResetCapture?(this: EventListenerThisType<T>, ev: Event): any; + onResize?(this: EventListenerThisType<T>, ev: UIEvent): any; + onResizeCapture?(this: EventListenerThisType<T>, ev: UIEvent): any; + onScroll?(this: EventListenerThisType<T>, ev: UIEvent): any; + onScrollCapture?(this: EventListenerThisType<T>, ev: UIEvent): any; + onSeeked?(this: EventListenerThisType<T>, ev: Event): any; + onSeekedCapture?(this: EventListenerThisType<T>, ev: Event): any; + onSeeking?(this: EventListenerThisType<T>, ev: Event): any; + onSeekingCapture?(this: EventListenerThisType<T>, ev: Event): any; + onSelect?(this: EventListenerThisType<T>, ev: UIEvent): any; + onSelectCapture?(this: EventListenerThisType<T>, ev: UIEvent): any; + onSelectionChange?(this: EventListenerThisType<T>, ev: Event): any; + onSelectionChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onStalled?(this: EventListenerThisType<T>, ev: Event): any; + onStalledCapture?(this: EventListenerThisType<T>, ev: Event): any; + onStorage?(this: EventListenerThisType<T>, ev: StorageEvent): any; + onStorageCapture?(this: EventListenerThisType<T>, ev: StorageEvent): any; + onSubmit?(this: EventListenerThisType<T>, ev: Event): any; + onSubmitCapture?(this: EventListenerThisType<T>, ev: Event): any; + onSuspend?(this: EventListenerThisType<T>, ev: Event): any; + onSuspendCapture?(this: EventListenerThisType<T>, ev: Event): any; + onTimeUpdate?(this: EventListenerThisType<T>, ev: Event): any; + onTimeUpdateCapture?(this: EventListenerThisType<T>, ev: Event): any; + onTouchCancel?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchCancelCapture?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchEnd?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchEndCapture?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchMove?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchMoveCapture?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchStart?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchStartCapture?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onUnload?(this: EventListenerThisType<T>, ev: Event): any; + onUnloadCapture?(this: EventListenerThisType<T>, ev: Event): any; + onVolumeChange?(this: EventListenerThisType<T>, ev: Event): any; + onVolumeChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onWaiting?(this: EventListenerThisType<T>, ev: Event): any; + onWaitingCapture?(this: EventListenerThisType<T>, ev: Event): any; + + /** + * Target (window or document) + */ + target: T; +} + +export type WindowEventTargets = {[K in keyof Window]: Window[K] extends EventTarget ? K : never}[keyof Window]; + +export default class EventListener<T extends EventTarget | WindowEventTargets> extends React.PureComponent<EventListenerProps<T>> { } diff --git a/types/react-event-listener/ts3.1/react-event-listener-tests.tsx b/types/react-event-listener/ts3.1/react-event-listener-tests.tsx new file mode 100644 index 0000000000..238b05237b --- /dev/null +++ b/types/react-event-listener/ts3.1/react-event-listener-tests.tsx @@ -0,0 +1,9 @@ +import React = require("react"); +import EventListener, { withOptions } from "react-event-listener"; + +<EventListener target={document} onBeforeUnload={ev => { }} />; +<EventListener target={window} onResize={withOptions((ev: UIEvent) => { }, { passive: true, capture: true })} />; +<EventListener target="window" onResize={() => { }}/>; +<EventListener target={document} onSelectionChange={ev => { }} />; +<EventListener target="document" onError={function() { this.documentElement; }} />; +<EventListener target={window} onBlurCapture={function() { this.pageXOffset; }} />; diff --git a/types/react-event-listener/ts3.1/tsconfig.json b/types/react-event-listener/ts3.1/tsconfig.json new file mode 100644 index 0000000000..8b6f2935ea --- /dev/null +++ b/types/react-event-listener/ts3.1/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-event-listener-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-event-listener/ts3.1/tslint.json b/types/react-event-listener/ts3.1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-event-listener/ts3.1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-grid-layout/index.d.ts b/types/react-grid-layout/index.d.ts index c643e976c3..9f7ee359f0 100644 --- a/types/react-grid-layout/index.d.ts +++ b/types/react-grid-layout/index.d.ts @@ -286,7 +286,7 @@ declare namespace ReactGridLayout { /** * Callback so you can save the layout. */ - onLayoutChange?(currentLayout: Layout, allLayouts: Layouts): void; + onLayoutChange?(currentLayout: Layout[], allLayouts: Layouts): void; /** * Callback when the width changes, so you can modify the layout as needed. diff --git a/types/react-highlight-words/index.d.ts b/types/react-highlight-words/index.d.ts index 9cd72ec411..9dc19130a7 100644 --- a/types/react-highlight-words/index.d.ts +++ b/types/react-highlight-words/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-highlight-words 0.12 +// Type definitions for react-highlight-words 0.16 // Project: https://github.com/bvaughn/react-highlight-words#readme // Definitions by: Mohamed Hegazy <https://github.com/mhegazy> // Diogo Corrêa <https://github.com/diogodca> @@ -25,7 +25,7 @@ interface HighlighterProps { /** The class name to be applied to an active match. Use along with activeIndex */ activeClassName?: string; /** Specify the match index that should be actively highlighted. Use along with activeClassName */ - activeIndex?: string; + activeIndex?: number; /** The inline style to be applied to an active match. Use along with activeIndex */ activeStyle?: React.CSSProperties; /** Escape characters in searchWords which are meaningful in regular expressions */ @@ -48,7 +48,7 @@ interface HighlighterProps { * Type of tag to wrap around highlighted matches; defaults to mark but can also be a React element * (class or functional) */ - highlightTag?: string; + highlightTag?: string | React.ComponentType<any>; /** * Process each search word and text to highlight before comparing (eg remove accents); signature * (text: string): string diff --git a/types/react-highlight-words/react-highlight-words-tests.tsx b/types/react-highlight-words/react-highlight-words-tests.tsx index de63c6d9ec..de1100e0de 100644 --- a/types/react-highlight-words/react-highlight-words-tests.tsx +++ b/types/react-highlight-words/react-highlight-words-tests.tsx @@ -6,17 +6,20 @@ const findChunks = ({ textToHighlight }: FindChunks) => []; +const CustomHighlight: React.FC = ({children}) => (<span>{children}</span>); + class HighlighterTest extends React.Component { render() { return ( <div> <Highlighter + highlightTag="span" searchWords={["el", "or"]} textToHighlight="Hello World" /> <Highlighter activeClassName="activeClassName" - activeIndex="activeIndex" + activeIndex={1} activeStyle={{ color: "red" }} autoEscape={true} className="className" @@ -24,7 +27,7 @@ class HighlighterTest extends React.Component { findChunks={findChunks} highlightClassName="highlightClassName" highlightStyle={{ color: "red" }} - highlightTag="span" + highlightTag={CustomHighlight} sanitize={(text: string) => text} searchWords={["el", "or"]} textToHighlight="Hello World" diff --git a/types/react-intl/index.d.ts b/types/react-intl/index.d.ts index 33effbff95..60a647e744 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -10,6 +10,7 @@ // Martin Raedlinger <https://github.com/formatlos> // Kanitkorn Sujautra <https://github.com/lukyth> // obedm503 <https://github.com/obedm503> +// anion155 <https://github.com/anion155> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -35,11 +36,11 @@ declare namespace ReactIntl { function addLocaleData(data: Locale[] | Locale): void; - interface Messages { - [key: string]: FormattedMessage.MessageDescriptor; - } + type Messages<Names extends keyof any = string> = { + [key in Names]: FormattedMessage.MessageDescriptor; + }; - function defineMessages<T extends Messages>(messages: T): T; + function defineMessages<Names extends keyof any>(messages: Messages<Names>): Messages<Names>; interface IntlConfig { locale: React.Requireable<any>; diff --git a/types/react-native-document-picker/index.d.ts b/types/react-native-document-picker/index.d.ts index 986da6e611..77b91e81bc 100644 --- a/types/react-native-document-picker/index.d.ts +++ b/types/react-native-document-picker/index.d.ts @@ -12,6 +12,8 @@ export const DocumentPickerUtil: { pdf(): string; audio(): string; plainText(): string; + video(): string; + images(): string; }; export interface Options { diff --git a/types/react-native-modal-dropdown/index.d.ts b/types/react-native-modal-dropdown/index.d.ts index 01470ec1cf..01e5dcf30b 100644 --- a/types/react-native-modal-dropdown/index.d.ts +++ b/types/react-native-modal-dropdown/index.d.ts @@ -21,6 +21,7 @@ declare namespace RNModalDropdown { defaultValue?: string; options?: any[]; animated?: boolean; + scrollEnabled?: boolean; showsVerticalScrollIndicator?: boolean; style?: any; textStyle?: any; diff --git a/types/react-native-modal-filter-picker/index.d.ts b/types/react-native-modal-filter-picker/index.d.ts new file mode 100644 index 0000000000..8188a32319 --- /dev/null +++ b/types/react-native-modal-filter-picker/index.d.ts @@ -0,0 +1,61 @@ +// Type definitions for react-native-modal-filter-picker 1.3 +// Project: https://github.com/hiddentao/react-native-modal-filter-picker#readme +// Definitions by: Chang Yanwei <https://github.com/ywchang> +// Cheng Gibson <https://github.com/nossbigg> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; +import { + StyleProp, + ViewStyle, + TextStyle, + ListView, + KeyboardAvoidingView, + ModalProps, + ListViewProps +} from "react-native"; + +export interface ModalFilterPickerOption { + label: string; + key: string; +} + +export interface ModalFilterPickerProps<T extends ModalFilterPickerOption> { + options: T[]; + onSelect: (key: string) => void; + onCancel: () => void; + placeholderText?: string; + placeholderTextColor?: string; + androidUnderlineColor?: string; + cancelButtonText?: string; + title?: string; + noResultsText?: string; + visible?: boolean; + showFilter?: boolean; + modal?: ModalProps; + selectedOption?: string; + listViewProps?: Partial<ListViewProps>; + renderOption?: (option: T, isSelected: boolean) => JSX.Element; + renderList?: () => JSX.Element; + renderCancelButton?: () => JSX.Element; + keyboardShouldPersistTaps?: "never" | "always" | "handle"; + autoFocus?: boolean; + + // styling props + overlayStyle?: StyleProp<KeyboardAvoidingView>; + listContainerStyle?: StyleProp<ViewStyle>; + filterTextInputContainerStyle?: StyleProp<ViewStyle>; + filterTextInputStyle?: StyleProp<TextStyle>; + cancelContainerStyle?: StyleProp<ViewStyle>; + cancelButtonStyle?: StyleProp<ViewStyle>; + cancelButtonTextStyle?: StyleProp<TextStyle>; + titleTextStyle?: StyleProp<TextStyle>; + optionTextStyle?: StyleProp<TextStyle>; +} + +declare class ModalFilterPicker< + T extends ModalFilterPickerOption +> extends React.Component<ModalFilterPickerProps<T>> {} + +export default ModalFilterPicker; diff --git a/types/react-native-modal-filter-picker/react-native-modal-filter-picker-tests.tsx b/types/react-native-modal-filter-picker/react-native-modal-filter-picker-tests.tsx new file mode 100644 index 0000000000..05fc770e5a --- /dev/null +++ b/types/react-native-modal-filter-picker/react-native-modal-filter-picker-tests.tsx @@ -0,0 +1,64 @@ +import * as React from "react"; +import ModalFilterPicker, { + ModalFilterPickerOption +} from "react-native-modal-filter-picker"; +import { View, Button, Text } from "react-native"; + +interface MyModalFilterPickerOption extends ModalFilterPickerOption { + customField: string; +} + +const modalFilterPickerOptions: MyModalFilterPickerOption[] = [ + { + label: "some-label-1", + key: "some-key-1", + customField: "some-customfield-1" + }, + { + label: "some-label-2", + key: "some-key-2", + customField: "some-customfield-2" + } +]; + +const renderPicker = () => ( + <ModalFilterPicker + options={modalFilterPickerOptions} + onSelect={key => { + console.log(key); + }} + onCancel={() => {}} + placeholderText="Filter..." + placeholderTextColor="#ccc" + androidUnderlineColor="rgba(0,0,0,0)" + cancelButtonText="Cancel" + title="some-title" + noResultsText="No matches" + visible + showFilter + modal={{ animated: true }} + selectedOption="some-option-key" + listViewProps={{ accessible: true }} + renderOption={(option, isSelected) => ( + <View key={option.key}> + <Text> + `${option.label} ${option.customField} ${isSelected}` + </Text> + </View> + )} + renderList={() => <View />} + renderCancelButton={() => <Button title="Cancel" onPress={() => {}} />} + keyboardShouldPersistTaps={"never"} + autoFocus={false} + /> +); + +const renderPickerWithRequiredPropsOnly = () => ( + <ModalFilterPicker + options={modalFilterPickerOptions} + onSelect={key => { + console.log(key); + }} + onCancel={() => {}} + /> +); diff --git a/types/react-native-modal-filter-picker/tsconfig.json b/types/react-native-modal-filter-picker/tsconfig.json new file mode 100644 index 0000000000..66da37bb6b --- /dev/null +++ b/types/react-native-modal-filter-picker/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": ["index.d.ts", "react-native-modal-filter-picker-tests.tsx"] +} diff --git a/types/react-native-modal-filter-picker/tslint.json b/types/react-native-modal-filter-picker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-modal-filter-picker/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-popup-dialog/index.d.ts b/types/react-native-popup-dialog/index.d.ts index d0a9d22a4b..b81533a6bc 100644 --- a/types/react-native-popup-dialog/index.d.ts +++ b/types/react-native-popup-dialog/index.d.ts @@ -17,7 +17,7 @@ export interface DialogContentProps { style?: StyleProp<ViewStyle>; } -export interface DialogActionListProps { +export interface DialogFooterProps { bordered?: boolean; style?: StyleProp<ViewStyle>; } @@ -70,9 +70,7 @@ export interface DialogProps { onDismiss?: () => void; onTouchOutside?: () => void; onHardwareBackPress?: () => boolean; - actions?: any[]; - actionContainerStyle?: StyleProp<ViewStyle>; - actionsBordered?: boolean; + footer?: any; useNativeDriver?: boolean; } @@ -97,7 +95,7 @@ export class SlideAnimation { } export class DialogContent extends React.Component<DialogContentProps, any> { } -export class DialogActionList extends React.Component<DialogActionListProps, any> { } +export class DialogFooter extends React.Component<DialogFooterProps, any> { } export class DialogButton extends React.Component<DialogButtonProps, any> { } export class DialogTitle extends React.Component<DialogTitleProps, any> { } export class Overlay extends React.Component<OverlayProps, any> { } diff --git a/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx b/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx index 55f979f506..2dc943d35b 100644 --- a/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx +++ b/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx @@ -7,6 +7,7 @@ import Dialog, { SlideAnimation, ScaleAnimation, FadeAnimation, + DialogFooter, } from 'react-native-popup-dialog'; const slideAnimation = new SlideAnimation({ slideFrom: 'bottom' }); @@ -50,14 +51,22 @@ class Test extends React.Component<any> { <Dialog ref={(popupDialog) => this.scalingPopupDialog = popupDialog} dialogTitle={<DialogTitle title="Popup Dialog - Scale Animation" />} dialogAnimation={scaleAnimation} - actions={[ - <DialogButton - text="CLOSE" - onPress={(event) => this.dismissPopupDialog(this.scalingPopupDialog)} - textStyle={{ color: "red" }} - key="button-1" - />, - ]} + footer={ + <DialogFooter> + <DialogButton + text="CLOSE" + onPress={(event) => this.dismissPopupDialog(this.scalingPopupDialog)} + textStyle={{ color: "red" }} + bordered + key="button-1" + /> + <DialogButton + text="OK" + onPress={() => {}} + key="button-2" + /> + </DialogFooter> + } /> <Dialog ref={(popupDialog) => this.slidingPopupDialog = popupDialog} dialogTitle={<DialogTitle title="Popup Dialog - Slide Animation" />} diff --git a/types/react-native-tab-view/index.d.ts b/types/react-native-tab-view/index.d.ts index 078247e97d..8118239f8a 100644 --- a/types/react-native-tab-view/index.d.ts +++ b/types/react-native-tab-view/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Kalle Ott <https://github.com/kaoDev> // Kyle Roach <https://github.com/iRoachie> // Tim Wang <https://github.com/timwangdev> +// Gerardo Pacheco <https://github.com/geriux> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { PureComponent, ReactNode, ComponentType } from 'react' @@ -214,6 +215,7 @@ export type TabBarProps<T extends RouteBase = RouteBase> = SceneRendererProps< indicatorStyle?: StyleProp<ViewStyle> labelStyle?: StyleProp<ViewStyle> style?: StyleProp<ViewStyle> + useNativeDriver?: boolean; } export class TabBar<T extends Route = Route> extends PureComponent<TabBarProps<T>> {} diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 4b06119df2..2be1a48992 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -16,6 +16,7 @@ // Kacper Wiszczuk <https://github.com/esemesek> // Ryan Nickel <https://github.com/mrnickel> // Souvik Ghosh <https://github.com/souvik-ghosh> +// Cheng Gibson <https://github.com/nossbigg> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -8995,8 +8996,44 @@ export interface ARTStatic { Text: typeof ARTText; } +export type KeyboardEventName = + | "keyboardWillShow" + | "keyboardDidShow" + | "keyboardWillHide" + | "keyboardDidHide" + | "keyboardWillChangeFrame" + | "keyboardDidChangeFrame"; + +export type KeyboardEventEasing = + | "easeIn" + | "easeInEaseOut" + | "easeOut" + | "linear" + | "keyboard"; + +type ScreenRect = { + screenX: number; + screenY: number; + width: number; + height: number; +}; + +export interface KeyboardEvent { + duration: number; + easing: KeyboardEventEasing; + endCoordinates: ScreenRect; + startCoordinates: ScreenRect; + isEventFromThisApp: boolean; +} + +type KeyboardEventListener = (event: KeyboardEvent) => void; + export interface KeyboardStatic extends NativeEventEmitter { dismiss: () => void; + addListener( + eventType: KeyboardEventName, + listener: KeyboardEventListener + ): EmitterSubscription; } ////////////////////////////////////////////////////////////////////////// diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 801565dc8d..dfa327ce7b 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -85,6 +85,7 @@ import { DatePickerAndroid, ViewPropTypes, requireNativeComponent, + Keyboard, } from "react-native"; declare module "react-native" { @@ -843,3 +844,8 @@ const ShareTest = () => { } }); }; + +const KeyboardTest = () => { + const subscriber = Keyboard.addListener("keyboardDidHide", (event) => {event}); + subscriber.remove(); +} diff --git a/types/react-paginate/index.d.ts b/types/react-paginate/index.d.ts index d66309d489..626f459fc5 100644 --- a/types/react-paginate/index.d.ts +++ b/types/react-paginate/index.d.ts @@ -7,12 +7,13 @@ // Yasunori Ohoka <https://github.com/yasupeke> // Shingo Sato <https://github.com/sugarshin> // SPWizard01 <https://github.com/SPWizard01> +// Kevin Rambaud <https://github.com/kevinrambaud> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; -interface ReactPaginateProps { +export interface ReactPaginateProps { /** * The total number of pages. */ diff --git a/types/react-paginate/v5/index.d.ts b/types/react-paginate/v5/index.d.ts index 83a03ac838..7529a6b12f 100644 --- a/types/react-paginate/v5/index.d.ts +++ b/types/react-paginate/v5/index.d.ts @@ -5,12 +5,13 @@ // pegel03 <https://github.com/pegel03> // Simon Archer <https://github.com/archy-bold> // Yasunori Ohoka <https://github.com/yasupeke> +// Kevin Rambaud <https://github.com/kevinrambaud> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; -interface ReactPaginateProps { +export interface ReactPaginateProps { /** * The total number of pages. */ diff --git a/types/react-tabs/index.d.ts b/types/react-tabs/index.d.ts index 013973e8df..0eabf0c613 100644 --- a/types/react-tabs/index.d.ts +++ b/types/react-tabs/index.d.ts @@ -1,13 +1,18 @@ -// Type definitions for react-tabs 2.3.0 +// Type definitions for react-tabs 2.3 // Project: https://github.com/reactjs/react-tabs/ -// Definitions by: Yuu Igarashi <https://github.com/yu-i9/>, Daniel Tschinder <https://github.com/danez>, Ummon Karpe <https://github.com/Equationist> +// Definitions by: Yuu Igarashi <https://github.com/yu-i9> +// Daniel Tschinder <https://github.com/danez> +// Ummon Karpe <https://github.com/Equationist> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as React from 'react'; +import * as React from "react"; -export interface TabsProps { - className?: string | Array<string> | { [name: string]: boolean; }; +type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; + +export interface TabsProps + extends Omit<React.HTMLProps<HTMLDivElement>, "className" | "onSelect"> { + className?: string | string[] | { [name: string]: boolean }; defaultFocus?: boolean; defaultIndex?: number; disabledTabClassName?: string; @@ -19,27 +24,30 @@ export interface TabsProps { selectedTabPanelClassName?: string; } -export interface TabListProps { - className?: string | Array<string> | { [name: string]: boolean; }; +export interface TabListProps + extends Omit<React.HTMLProps<HTMLUListElement>, "className"> { + className?: string | string[] | { [name: string]: boolean }; } -export interface TabProps { - className?: string | Array<string> | { [name: string]: boolean; }; +export interface TabProps + extends Omit<React.HTMLProps<HTMLLIElement>, "className" | "tabIndex"> { + className?: string | string[] | { [name: string]: boolean }; disabled?: boolean; disabledClassName?: string; selectedClassName?: string; tabIndex?: string; } -export interface TabPanelProps { - className?: string | Array<string> | { [name: string]: boolean; }; +export interface TabPanelProps + extends Omit<React.HTMLProps<HTMLDivElement>, "className"> { + className?: string | string[] | { [name: string]: boolean }; forceRender?: boolean; selectedClassName?: string; } -export declare class Tabs extends React.Component<TabsProps> { } -export declare class TabList extends React.Component<TabListProps> { } -export declare class Tab extends React.Component<TabProps> { } -export declare class TabPanel extends React.Component<TabPanelProps> { } +export declare class Tabs extends React.Component<TabsProps> {} +export declare class TabList extends React.Component<TabListProps> {} +export declare class Tab extends React.Component<TabProps> {} +export declare class TabPanel extends React.Component<TabPanelProps> {} export declare function resetIdCounter(): void; diff --git a/types/react-tabs/react-tabs-tests.ts b/types/react-tabs/react-tabs-tests.ts index a7b86de6e0..7488a8a55a 100644 --- a/types/react-tabs/react-tabs-tests.ts +++ b/types/react-tabs/react-tabs-tests.ts @@ -9,7 +9,8 @@ import { TabProps, TabPanel, TabPanelProps, - resetIdCounter } from "react-tabs"; + resetIdCounter +} from "react-tabs"; resetIdCounter(); @@ -26,15 +27,18 @@ class TestApp extends React.Component { } render() { - return React.createElement(Tabs, {onSelect: this.onSelect, selectedIndex: 1}, - React.createElement(TabList, {className: "test-class"}, - React.createElement(Tab, {disabled: true}, "Tab1"), - React.createElement(Tab, {selectedClassName: "active"}, "Tab2"), - React.createElement(Tab, {}, "Tab3")), - React.createElement(TabPanel, {}, React.createElement("h2", {}, "Content1")), - React.createElement(TabPanel, {}, React.createElement("h2", {}, "Content2")), - React.createElement(TabPanel, {}, React.createElement("h2", {}, "Content3"))); + return React.createElement(Tabs, { onSelect: this.onSelect, selectedIndex: 1, defaultFocus: true, name: 'Tabs', autoFocus: true }, + React.createElement(TabList, { className: "test-class" }, + React.createElement(Tab, { disabled: true }, "Tab1"), + React.createElement(Tab, { selectedClassName: "active" }, "Tab2"), + React.createElement(Tab, {}, "Tab3")), + React.createElement(TabPanel, {}, React.createElement("h2", {}, "Content1")), + React.createElement(TabPanel, {}, React.createElement("h2", {}, "Content2")), + React.createElement(TabPanel, {}, React.createElement("h2", {}, "Content3"))); } } -ReactDOM.render(React.createElement(TestApp, {}), document.getElementById("test-app")); +ReactDOM.render( + React.createElement(TestApp, {}), + document.getElementById("test-app") +); diff --git a/types/react-tabs/tslint.json b/types/react-tabs/tslint.json index a41bf5d19a..3d429fc065 100644 --- a/types/react-tabs/tslint.json +++ b/types/react-tabs/tslint.json @@ -1,79 +1,12 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "void-return": false } } diff --git a/types/react-test-renderer/index.d.ts b/types/react-test-renderer/index.d.ts index c147d5c190..abdae1c908 100644 --- a/types/react-test-renderer/index.d.ts +++ b/types/react-test-renderer/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for react-test-renderer 16.0 +// Type definitions for react-test-renderer 16.8 // Project: https://facebook.github.io/react/ // Definitions by: Arvitaly <https://github.com/arvitaly> // Lochbrunner <https://github.com/lochbrunner> // John Reilly <https://github.com/johnnyreilly> // John Gozde <https://github.com/jgoz> +// Jessica Franco <https://github.com/Jessidhia> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -50,3 +51,26 @@ export interface TestRendererOptions { createNodeMock(element: ReactElement<any>): any; } export function create(nextElement: ReactElement<any>, options?: TestRendererOptions): ReactTestRenderer; + +/** + * Wrap any code rendering and triggering updates to your components into `act()` calls. + * + * Ensures that the behavior in your tests matches what happens in the browser + * more closely by executing pending `useEffect`s before returning. This also + * reduces the amount of re-renders done. + * + * @param callback A synchronous, void callback that will execute as a single, complete React commit. + * + * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks + */ +// the "void | undefined" is here to forbid any sneaky "Promise" returns. +// the actual return value is always a "DebugPromiseLike", +// but having an "| {}" makes it harder to accidentally use. +export function act(callback: () => void | undefined): DebugPromiseLike | {}; + +// Intentionally doesn't extend PromiseLike<never>. +// Ideally this should be as hard to accidentally use as possible. +export interface DebugPromiseLike { + // the actual then() in here is 0-ary, but that doesn't count as a PromiseLike. + then(onfulfilled: (value: never) => never, onrejected: (reason: never) => never): never; +} diff --git a/types/react-test-renderer/react-test-renderer-tests.ts b/types/react-test-renderer/react-test-renderer-tests.ts index 83dc510e2b..48d861cf62 100644 --- a/types/react-test-renderer/react-test-renderer-tests.ts +++ b/types/react-test-renderer/react-test-renderer-tests.ts @@ -1,5 +1,5 @@ -import * as React from "react"; -import { create, ReactTestInstance } from "react-test-renderer"; +import React = require("react"); +import { act, create, ReactTestInstance } from "react-test-renderer"; import { createRenderer } from 'react-test-renderer/shallow'; class TestComponent extends React.Component { } @@ -66,3 +66,12 @@ const shallowRenderer = createRenderer(); shallowRenderer.render(component); shallowRenderer.getRenderOutput(); shallowRenderer.getMountedInstance(); + +// Only synchronous, void callbacks are acceptable for act() +act(() => {}); +// $ExpectError +act(async () => {}); +// $ExpectError +act(() => null); +// $ExpectError +Promise.resolve(act(() => {})); diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 929a698775..9e46bc5ca9 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -783,11 +783,9 @@ declare namespace React { // TODO (TypeScript 3.0): ReadonlyArray<unknown> type DependencyList = ReadonlyArray<any>; - // NOTE: Currently, in alpha.0, the effect callbacks are actually allowed to return anything, - // but functions are treated specially. The next version published with hooks will warn if you actually - // return anything besides `void` or a callback. Async effects need to call an async function inside - // them. - type EffectCallback = () => (void | (() => void)); + // NOTE: callbacks are _only_ allowed to return either void, or a destructor. + // The destructor is itself only allowed to return void. + type EffectCallback = () => (void | (() => void | undefined)); interface MutableRefObject<T> { current: T; @@ -853,12 +851,16 @@ declare namespace React { * @version 16.8.0 * @see https://reactjs.org/docs/hooks-reference.html#usereducer */ + // I'm not sure if I keep this 2-ary or if I make it (2,3)-ary; it's currently (2,3)-ary. // The Flow types do have an overload for 3-ary invocation with undefined initializer. - // NOTE: the documentation or any alphas aren't updated, this is current for master. - // NOTE 2: without the ReducerState indirection, TypeScript would reduce S to be the most common + + // NOTE: without the ReducerState indirection, TypeScript would reduce S to be the most common // supertype between the reducer's return type and the initialState (or the initializer's return type), // which would prevent autocompletion from ever working. + + // TODO: double-check if this weird overload logic is necessary. It is possible it's either a bug + // in older versions, or a regression in newer versions of the typescript completion service. function useReducer<R extends Reducer<any, any>>( reducer: R, initialState: ReducerState<R>, diff --git a/types/react/test/hooks.tsx b/types/react/test/hooks.tsx index 12fcc28222..26ff634e89 100644 --- a/types/react/test/hooks.tsx +++ b/types/react/test/hooks.tsx @@ -120,6 +120,23 @@ function useEveryHook(ref: React.Ref<{ id: number }>|undefined): () => boolean { setState(reducerState.age); }, []); + // effects are only allowed to either be actually void or return actually void functions + React.useEffect(() => () => {}); + // indistinguishable + React.useEffect(() => () => undefined); + // $ExpectError + React.useEffect(() => null); + // $ExpectError + React.useEffect(() => Math.random() ? null : undefined); + // $ExpectError + React.useEffect(() => () => null); + // $ExpectError + React.useEffect(() => () => Math.random() ? null : undefined); + // $ExpectError + React.useEffect(() => async () => {}); + // $ExpectError + React.useEffect(async () => () => {}); + React.useDebugValue(id, value => value.toFixed()); React.useDebugValue(id); diff --git a/types/reactstrap/lib/CustomInput.d.ts b/types/reactstrap/lib/CustomInput.d.ts index 8527c29455..5d0af9f5c8 100644 --- a/types/reactstrap/lib/CustomInput.d.ts +++ b/types/reactstrap/lib/CustomInput.d.ts @@ -10,7 +10,7 @@ export type CustomInputType = export type CustomInputProps<T = {}> = React.InputHTMLAttributes<HTMLInputElement> & { type: CustomInputType; - label?: string; + label?: React.ReactNode; inline?: boolean; bsSize?: 'lg' | 'sm'; valid?: boolean; diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index f3678813de..67c24bce28 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -4112,7 +4112,8 @@ class Example119 extends React.Component<any, any> { <div> <CustomInput type="checkbox" id="exampleCustomCheckbox" label="Check this custom checkbox" /> <CustomInput type="checkbox" id="exampleCustomCheckbox2" label="Or this one" /> - <CustomInput type="checkbox" id="exampleCustomCheckbox3" label="But not this disabled one" disabled /> + <CustomInput type="checkbox" id="exampleCustomCheckbox3" label={<span>Or this one</span>} /> + <CustomInput type="checkbox" id="exampleCustomCheckbox4" label="But not this disabled one" disabled /> </div> </FormGroup> <FormGroup> @@ -4120,7 +4121,8 @@ class Example119 extends React.Component<any, any> { <div> <CustomInput type="radio" id="exampleCustomRadio" name="customRadio" label="Select this custom radio" /> <CustomInput type="radio" id="exampleCustomRadio2" name="customRadio" label="Or this one" /> - <CustomInput type="radio" id="exampleCustomRadio3" label="But not this disabled one" disabled /> + <CustomInput type="radio" id="exampleCustomRadio3" name="customRadio" label={<span>Or this one</span>} /> + <CustomInput type="radio" id="exampleCustomRadio4" label="But not this disabled one" disabled /> </div> </FormGroup> <FormGroup> @@ -4128,6 +4130,7 @@ class Example119 extends React.Component<any, any> { <div> <CustomInput type="checkbox" id="exampleCustomInline" label="An inline custom input" inline /> <CustomInput type="checkbox" id="exampleCustomInline2" label="and another one" inline /> + <CustomInput type="checkbox" id="exampleCustomInline3" label={<span>and this one</span>} inline /> </div> </FormGroup> <FormGroup> @@ -4181,6 +4184,7 @@ class Example119 extends React.Component<any, any> { <FormGroup> <Label for="exampleCustomFileBrowser">File Browser with Custom Label</Label> <CustomInput type="file" id="exampleCustomFileBrowser" name="customFile" label="Yo, pick a file!" /> + <CustomInput type="file" id="exampleCustomFileBrowser1" name="customFile" label={<span>Yo, pick a file!</span>} /> </FormGroup> <FormGroup> <Label for="exampleCustomFileBrowser">File Browser Disabled</Label> diff --git a/types/rebass/index.d.ts b/types/rebass/index.d.ts index 0536a600ee..20c73079ad 100644 --- a/types/rebass/index.d.ts +++ b/types/rebass/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: rhysd <https://github.com/rhysd> // ryee-dev <https://github.com/ryee-dev> // jamesmckenzie <https://github.com/jamesmckenzie> +// sara f-p <https://github.com/gretzky> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -10,7 +11,7 @@ import * as React from "react"; export interface BaseProps<C> extends React.ClassAttributes<C> { className?: string; - as?: string; + as?: any; } export interface SpaceProps<C> extends BaseProps<C> { diff --git a/types/redux-form/immutable/index.d.ts b/types/redux-form/immutable/index.d.ts index 742027ccad..2ce6164232 100644 --- a/types/redux-form/immutable/index.d.ts +++ b/types/redux-form/immutable/index.d.ts @@ -24,5 +24,7 @@ export { isSubmitting, isAsyncValidating, isValid, - SubmissionError -} from "../"; + SubmissionError, + startSubmit, + stopSubmit, +} from '../'; diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index 6915032138..8997d682a8 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redux-form 7.4 +// Type definitions for redux-form 7.5 // Project: https://github.com/erikras/redux-form // Definitions by: Carson Full <https://github.com/carsonf> // Daniel Lytkin <https://github.com/aikoven> @@ -12,6 +12,7 @@ // Maddi Joyce <https://github.com/maddijoyce> // Kamil Wojcik <https://github.com/smifun> // Mohamed Shaaban <https://github.com/mshaaban088> +// Ethan Setnik <https://github.com/esetnik> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 import { diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index 25f395884c..56d782eda7 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -26,9 +26,12 @@ import { SubmissionError, FieldArrayFieldsProps } from "redux-form"; + import { Field as ImmutableField, - reduxForm as immutableReduxForm + reduxForm as immutableReduxForm, + startSubmit as immutableStartSubmit, + stopSubmit as immutableStopSubmit } from "redux-form/immutable"; import LibField, { diff --git a/types/rollup-plugin-buble/index.d.ts b/types/rollup-plugin-buble/index.d.ts new file mode 100644 index 0000000000..d6e3414346 --- /dev/null +++ b/types/rollup-plugin-buble/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for rollup-plugin-buble 0.19 +// Project: https://github.com/rollup/rollup-plugin-buble#readme +// Definitions by: Hugo Alliaume <https://github.com/Kocal> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// <reference types="node" /> + +import { Plugin } from 'rollup'; +import { TransformOptions } from 'buble'; + +export interface Options extends TransformOptions { + // Every files will be parsed by default, but you can specify which files to include or exclude + include?: Array<string | RegExp> | string | RegExp | null; + exclude?: Array<string | RegExp> | string | RegExp | null; +} + +export default function buble(options?: Options): Plugin; diff --git a/types/rollup-plugin-buble/package.json b/types/rollup-plugin-buble/package.json new file mode 100644 index 0000000000..ee69ca3cd2 --- /dev/null +++ b/types/rollup-plugin-buble/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "rollup": "^0.63.4" + } +} diff --git a/types/rollup-plugin-buble/rollup-plugin-buble-tests.ts b/types/rollup-plugin-buble/rollup-plugin-buble-tests.ts new file mode 100644 index 0000000000..d020539f8b --- /dev/null +++ b/types/rollup-plugin-buble/rollup-plugin-buble-tests.ts @@ -0,0 +1,57 @@ +import buble from 'rollup-plugin-buble'; + +// No options (default) +(() => { + // $ExpectType Plugin + buble(); +})(); + +// With every options +(() => { + // $ExpectType Plugin + buble({ + target: { + chrome: 71, + firefox: 64, + }, + objectAssign: true, + transforms: { + arrow: true, + classes: false, + collections: true, + computedProperty: false, + conciseMethodProperty: true, + constLoop: false, + dangerousForOf: true, + dangerousTaggedTemplateString: false, + defaultParameter: true, + destructuring: false, + forOf: true, + generator: false, + letConst: true, + modules: false, + numericLiteral: true, + parameterDestructuring: false, + reservedProperties: true, + spreadRest: false, + stickyRegExp: true, + templateString: false, + unicodeRegExp: true, + } + }); +})(); + +// Filter files +(() => { + // $ExpectType Plugin + buble({ + include: '*.js', + exclude: '*.js', + }); + + // $ExpectType Plugin + buble({ + include: /.js$/, + exclude: ['foo.js', 'bar.js'], + }); +})(); diff --git a/types/rollup-plugin-buble/tsconfig.json b/types/rollup-plugin-buble/tsconfig.json new file mode 100644 index 0000000000..80dec6b110 --- /dev/null +++ b/types/rollup-plugin-buble/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "rollup-plugin-buble-tests.ts" + ] +} diff --git a/types/rollup-plugin-buble/tslint.json b/types/rollup-plugin-buble/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rollup-plugin-buble/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sarif/index.d.ts b/types/sarif/index.d.ts index 4bece2d3f8..2a4e57fe25 100644 --- a/types/sarif/index.d.ts +++ b/types/sarif/index.d.ts @@ -5,8 +5,8 @@ // TypeScript Version: 2.4 /** - * Static Analysis Results Format (SARIF) Version 2.0.0-csd.2.beta-2018-10-10 JSON Schema: - * a standard format for the output of static analysis tools. + * Static Analysis Results Format (SARIF) Version 2.0.0-csd.2.beta-2019-01-09 JSON Schema: a standard format for the + * output of static analysis tools. */ export interface Log { /** @@ -23,11 +23,16 @@ export interface Log { * The set of runs contained in this log file. */ runs: Run[]; + + /** + * Key/value pairs that provide additional information about the log file. + */ + properties?: PropertyBag; } export namespace Log { type version = - "2.0.0-csd.2.beta.2018-10-10"; + "2.0.0-csd.2.beta.2019-01-09"; } /** @@ -53,6 +58,11 @@ export interface Attachment { * An array of regions of interest within the attachment. */ regions?: Region[]; + + /** + * Key/value pairs that provide additional information about the attachment. + */ + properties?: PropertyBag; } /** @@ -188,57 +198,81 @@ export interface Exception { stack?: Stack; /** - * Key/value pairs that provide additional information about the exception + * Key/value pairs that provide additional information about the exception. */ properties?: PropertyBag; } /** - * References to external files that should be inlined with the content of a root log file. + * TBD */ -export interface ExternalFiles { +export interface ExternalPropertyFile { /** - * The location of a file containing a run.conversion object to be merged with the root log file. + * The location of the external property file. */ - conversion?: FileLocation; + fileLocation?: FileLocation; /** - * The location of a file containing a run.files object to be merged with the root log file. + * A stable, unique identifer for the external property file in the form of a GUID. */ - files?: FileLocation; + instanceGuid?: string; /** - * The location of a file containing a run.graphs object to be merged with the root log file. + * A non-negative integer specifying the number of items contained in the external property file. */ - graphs?: FileLocation; + itemCount?: number; /** - * An array of locations of files containing arrays of run.invocation objects to be merged with the root log - * file. - */ - invocations?: FileLocation[]; - - /** - * The location of a file containing a run.logicalLocations object to be merged with the root log file. - */ - logicalLocations?: FileLocation; - - /** - * The location of a file containing a run.resources object to be merged with the root log file. - */ - resources?: FileLocation; - - /** - * An array of locations of files containins arrays of run.result objects to be merged with the root log file. - */ - results?: FileLocation[]; - - /** - * Key/value pairs that provide additional information about the external files + * Key/value pairs that provide additional information about the external property file. */ properties?: PropertyBag; } +/** + * References to external property files that should be inlined with the content of a root log file. + */ +export interface ExternalPropertyFiles { + /** + * An external property file containing a run.conversion object to be merged with the root log file. + */ + conversion?: ExternalPropertyFile; + + /** + * An array of external property files containing run.files arrays to be merged with the root log file. + */ + files?: ExternalPropertyFile[]; + + /** + * An external property file containing a run.graphs object to be merged with the root log file. + */ + graphs?: ExternalPropertyFile; + + /** + * An array of external property files containing run.invocations arrays to be merged with the root log file. + */ + invocations?: ExternalPropertyFile[]; + + /** + * An array of external property files containing run.logicalLocations arrays to be merged with the root log file. + */ + logicalLocations?: ExternalPropertyFile[]; + + /** + * An external property file containing a run.resources object to be merged with the root log file. + */ + resources?: ExternalPropertyFile; + + /** + * An array of external property files containing run.results arrays to be merged with the root log file. + */ + results?: ExternalPropertyFile[]; + + /** + * An external property file containing a run.properties object to be merged with the root log file. + */ + properties?: ExternalPropertyFile; +} + /** * A single file. In some cases, this file might be nested within another file. */ @@ -286,15 +320,20 @@ export interface File { offset?: number; /** - * Identifies the key of the immediate parent of the file, if this file is nested. + * Identifies the index of the immediate parent of the file, if this file is nested. */ - parentKey?: string; + parentIndex?: number; /** * The role or roles played by the file in the analysis. */ roles?: File.roles[]; + /** + * Specifies the source language for any file object that refers to a text file that contains source code. + */ + sourceLanguage?: string; + /** * Key/value pairs that provide additional information about the file. */ @@ -362,6 +401,11 @@ export interface FileContent { * Specifies the location of a file. */ export interface FileLocation { + /** + * The index within the run files array of the file object associated with the file location. + */ + fileIndex?: number; + /** * A string containing a valid relative or absolute URI. */ @@ -413,7 +457,7 @@ export interface Graph { /** * An array of edge objects representing the edges of the graph. */ - edges: Edge[]; + edges?: Edge[]; /** * A string that uniquely identifies the graph within a run.graphs or result.graphs array. @@ -423,7 +467,7 @@ export interface Graph { /** * An array of node objects representing the nodes of the graph. */ - nodes: Node[]; + nodes?: Node[]; /** * Key/value pairs that provide additional information about the graph. @@ -443,7 +487,7 @@ export interface GraphTraversal { /** * The sequences of edges traversed by this graph traversal. */ - edgeTraversals: EdgeTraversal[]; + edgeTraversals?: EdgeTraversal[]; /** * A string that uniquely identifies that graph being traversed. @@ -611,6 +655,11 @@ export interface Location { */ fullyQualifiedLogicalName?: string; + /** + * The index within the logical locations array of the logical location associated with the result. + */ + logicalLocationIndex?: number; + /** * A message relevant to the location. */ @@ -643,9 +692,9 @@ export interface LogicalLocation { fullyQualifiedName?: string; /** - * The type of construct this logicalLocationComponent refers to. Should be one of 'function', 'member', - * 'module', 'namespace', 'package', 'parameter', 'resource', 'returnType', 'type', or 'variable', if any of - * those accurately describe the construct. + * The type of construct this logical location component refers to. Should be one of 'function', 'member', + * 'module', 'namespace', 'parameter', 'resource', 'returnType', 'type', or 'variable', if any of those + * accurately describe the construct. */ kind?: string; @@ -656,10 +705,10 @@ export interface LogicalLocation { name?: string; /** - * Identifies the key of the immediate parent of the construct in which the result was detected. For example, + * Identifies the index of the immediate parent of the construct in which the result was detected. For example, * this property might point to a logical location that represents the namespace that holds a type. */ - parentKey?: string; + parentIndex?: number; /** * Key/value pairs that provide additional information about the logical location. @@ -763,11 +812,15 @@ export interface Notification { physicalLocation?: PhysicalLocation; /** - * The stable, unique identifier of the rule (if any) to which this notification is relevant. This member can be - * used to retrieve rule metadata from the rules dictionary, if it exists. + * The stable, unique identifier of the rule, if any, to which this notification is relevant. */ ruleId?: string; + /** + * The index within the run resources array of the rule object, if any, associated with this notification. + */ + ruleIndex?: number; + /** * The thread identifier of the code that generated the notification. */ @@ -917,6 +970,11 @@ export interface Region { */ snippet?: FileContent; + /** + * Specifies the source language, if any, of the portion of the file specified by the region object. + */ + sourceLanguage?: string; + /** * The column number of the first character in the region. */ @@ -963,10 +1021,14 @@ export interface Resources { messageStrings?: { [key: string]: string }; /** - * A dictionary, each of whose keys is a string and each of whose values is a 'rule' object, that describe all - * rules associated with an analysis tool or a specific run of an analysis tool. + * An array of rule objects relevant to the run. */ - rules?: { [key: string]: Rule }; + rules?: Rule[]; + + /** + * Key/value pairs that provide additional information about the resources. + */ + properties?: PropertyBag; } /** @@ -994,12 +1056,6 @@ export interface Result { */ codeFlows?: CodeFlow[]; - /** - * An array of physicalLocation objects which specify the portions of an analysis tool's output that a converter - * transformed into the result object. - */ - conversionProvenance?: PhysicalLocation[]; - /** * A stable, unique identifier for the equivalence class of logically identical results to which this result * belongs, in the form of a GUID. @@ -1027,6 +1083,11 @@ export interface Result { */ graphTraversals?: GraphTraversal[]; + /** + * An absolute URI at which the result can be viewed. + */ + hostedViewerUri?: string; + /** * A stable, unique identifer for the result in the form of a GUID. */ @@ -1038,7 +1099,7 @@ export interface Result { level?: Result.level; /** - * One or more locations where the result occurred. Specify only one location unless the problem indicated by + * The set of locations where the result was detected. Specify only one location unless the problem indicated by * the result can only be corrected by making a change at every specified location. */ locations?: Location[]; @@ -1047,7 +1108,7 @@ export interface Result { * A message that describes the result. The first sentence of the message only will be displayed when visible * space is limited. */ - message?: Message; + message: Message; /** * A positive integer specifying the number of times this logically unique result was observed in this run. @@ -1059,17 +1120,32 @@ export interface Result { */ partialFingerprints?: { [key: string]: string }; + /** + * Information about how and when the result was detected. + */ + provenance?: ResultProvenance; + + /** + * A number representing the priority or importance of the result. + */ + rank?: number; + /** * A set of locations relevant to this result. */ relatedLocations?: Location[]; /** - * The stable, unique identifier of the rule (if any) to which this notification is relevant. This member can be + * The stable, unique identifier of the rule, if any, to which this notification is relevant. This member can be * used to retrieve rule metadata from the rules dictionary, if it exists. */ ruleId?: string; + /** + * The index within the run resources array of the rule object associated with this result. + */ + ruleIndex?: number; + /** * An array of 'stack' objects relevant to the result. */ @@ -1081,7 +1157,7 @@ export interface Result { suppressionStates?: Result.suppressionStates[]; /** - * The URIs of the work items associated with this result + * The URIs of the work items associated with this result. */ workItemUris?: string[]; @@ -1110,6 +1186,52 @@ export namespace Result { "absent"; } +/** + * Contains information about how and when a result was detected. + */ +export interface ResultProvenance { + /** + * An array of physicalLocation objects which specify the portions of an analysis tool's output that a + * converter transformed into the result. + */ + conversionSources?: PhysicalLocation[]; + + /** + * A GUID-valued string equal to the id.instanceGuid property of the run in which the result was first + * detected. + */ + firstDetectionRunInstanceGuid?: string; + + /** + * The Coordinated Universal Time (UTC) date and time at which the result was first detected. See "Date/time + * properties" in the SARIF spec for the required format. + */ + firstDetectionTimeUtc?: string; + + /** + * The index within the run.invocations array of the invocation object which describes the tool invocation that + * detected the result. + */ + invocationIndex?: number; + + /** + * A GUID-valued string equal to the id.instanceGuid property of the run in which the result was most recently + * detected. + */ + lastDetectionRunInstanceGuid?: string; + + /** + * The Coordinated Universal Time (UTC) date and time at which the result was most recently detected. See + * "Date/time properties" in the SARIF spec for the required format. + */ + lastDetectionTimeUtc?: string; + + /** + * Key/value pairs that provide additional information about the result. + */ + properties?: PropertyBag; +} + /** * Describes an analysis rule. */ @@ -1119,6 +1241,12 @@ export interface Rule { */ configuration?: RuleConfiguration; + /** + * An array of stable, opaque identifiers by which this rule was known in some previous version of the analysis + * tool. + */ + deprecatedIds?: string[]; + /** * A description of the rule. Should, as far as possible, provide details sufficient to enable resolution of any * problem indicated by the result. @@ -1176,10 +1304,15 @@ export interface Rule { */ export interface RuleConfiguration { /** - * Specifies the default severity level of the result. + * Specifies the default severity level for results generated by this rule. */ defaultLevel?: RuleConfiguration.defaultLevel; + /** + * Specifies the default priority or importance for results generated by this rule. + */ + defaultRank?: number; + /** * Specifies whether the rule will be evaluated during the scan. */ @@ -1200,8 +1333,7 @@ export namespace RuleConfiguration { type defaultLevel = "note" | "warning" | - "error" | - "open"; + "error"; } /** @@ -1213,11 +1345,6 @@ export interface Run { */ aggregateIds?: RunAutomationDetails[]; - /** - * The hardware architecture for which the run was targeted. - */ - architecture?: string; - /** * The 'instanceGuid' property of a previous SARIF 'run' that comprises the baseline that was used to compute * result 'baselineState' properties for the run. @@ -1241,9 +1368,20 @@ export interface Run { defaultFileEncoding?: string; /** - * A dictionary, each of whose keys is a URI and each of whose values is a file object. + * Specifies the default source language for any file object that refers to a text file that contains source + * code. */ - files?: { [key: string]: File }; + defaultSourceLanguage?: string; + + /** + * References to external property files that should be inlined with the content of a root log file. + */ + externalPropertyFiles?: ExternalPropertyFiles; + + /** + * An array of file objects relevant to the run. + */ + files?: File[]; /** * A dictionary, each of whose keys is the id of a graph and each of whose values is a 'graph' object with that @@ -1262,9 +1400,15 @@ export interface Run { invocations?: Invocation[]; /** - * A dictionary, each of whose keys specifies a logical location such as a namespace, type or function. + * An array of logical locations such as namespaces, types or functions. */ - logicalLocations?: { [key: string]: LogicalLocation }; + logicalLocations?: LogicalLocation[]; + + /** + * An ordered list of character sequences that were treated as line breaks when computing region information + * for the run. + */ + newlineSequences?: string[]; /** * The file location specified by each uriBaseId symbol on the machine where the tool originally ran. @@ -1472,7 +1616,7 @@ export interface ThreadFlowLocation { module?: string; /** - * An integer representing a containment hierarchy within the thread flow + * An integer representing a containment hierarchy within the thread flow. */ nestingLevel?: number; @@ -1505,17 +1649,17 @@ export namespace ThreadFlowLocation { * The analysis tool that was run. */ export interface Tool { + /** + * The binary version of the tool's primary executable file expressed as four non-negative integers separated + * by a period (for operating systems that express file versions in this way). + */ + dottedQuadFileVersion?: string; + /** * The absolute URI from which the tool can be downloaded. */ downloadUri?: string; - /** - * The binary version of the tool's primary executable file (for operating systems such as Windows that provide - * that information). - */ - fileVersion?: string; - /** * The name of the tool along with its version and any other useful identifying information, such as its locale. */ @@ -1555,7 +1699,7 @@ export interface Tool { } /** - * TBD + * Specifies the information necessary to retrieve a desired revision from a version control system. */ export interface VersionControlDetails { /** @@ -1569,6 +1713,12 @@ export interface VersionControlDetails { */ branch?: string; + /** + * The location in the local file system to which the root of the repository was mapped at the time of the + * analysis. + */ + mappedTo?: FileLocation; + /** * The absolute URI of the repository. */ diff --git a/types/slate/index.d.ts b/types/slate/index.d.ts index 22cf22f8ef..567b7ee52e 100644 --- a/types/slate/index.d.ts +++ b/types/slate/index.d.ts @@ -299,7 +299,7 @@ export class Text extends Immutable.Record({}) { ): Immutable.Set<Mark>; getMarks(): Immutable.OrderedSet<Mark>; getMarksAsArray(): Mark[]; - getMarksAtIndex(index: number): Mark; + getMarksAtIndex(index: number): Immutable.OrderedSet<Mark>; getNode(key: string): Node | null; getPath(key: string | Path): Path; hasNode(key: string): boolean; diff --git a/types/spellchecker/index.d.ts b/types/spellchecker/index.d.ts new file mode 100644 index 0000000000..01064d0688 --- /dev/null +++ b/types/spellchecker/index.d.ts @@ -0,0 +1,61 @@ +// Type definitions for spellchecker 3.5 +// Project: http://atom.github.io/node-spellchecker +// Definitions by: Dale Fenton <https://github.com/dalevfenton> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/* --------------------------------------------------------------------------- + Custom Types / Interfaces +--------------------------------------------------------------------------- */ +/** + * MisspelledLocation - shape of an object returned by checkSpelling to + * identify locations of misspelled words in a corpus. + * @description a misspelled word can be found by corpus.slice(start, end) + * start - start index of a misspelled word in a corpus + * end - end index of a misspelled word in a corpus + */ +export interface MisspelledLocation { + start: number; + end: number; +} + +/* --------------------------------------------------------------------------- + Methods +--------------------------------------------------------------------------- */ +/** + * Spellchecker.isMisspelled - Check if a word is misspelled. + * @param word - String word to check. + * @returns boolean - true if the word is misspelled, false otherwise. + */ +export function isMisspelled(word: string): boolean; + +/** + * Spellchecker.getCorrectionsForMisspelling - Get the corrections for a misspelled word. + * @param word - String word to get corrections for. + * @returns array - Returns a non-null but possibly empty array of string corrections. + */ +export function getCorrectionsForMisspelling(word: string): string[]; + +/** + * Spellchecker.checkSpelling - Identify misspelled words in a corpus of text. + * @param corpus - String corpus of text to spellcheck. + * @returns array - Returns an Array containing {start, end} objects that describe an + * index range within the original String that contains a misspelled word. + */ +export function checkSpelling(corpus: string): MisspelledLocation[]; + +/** + * Spellchecker.checkSpellingAsync - Asynchronously identify misspelled words. + * @param corpus - String corpus of text to spellcheck. + * @returns array - Returns a Promise that resolves with the Array described by checkSpelling(). + */ +export function checkSpellingAsync(corpus: string): Promise<MisspelledLocation[]>; + +/** + * Spellchecker.add - Adds a word to the dictionary. + * When using Hunspell, this will not modify the .dic file; + * new words must be added each time the spellchecker is created. Use a custom dictionary file. + * @param word - String word to add. + * @returns void + */ +export function add(word: string): void; diff --git a/types/spellchecker/spellchecker-tests.ts b/types/spellchecker/spellchecker-tests.ts new file mode 100644 index 0000000000..7f53b26ab0 --- /dev/null +++ b/types/spellchecker/spellchecker-tests.ts @@ -0,0 +1,41 @@ +import * as Spellchecker from 'spellchecker'; + +const additionalDictionary = ['Xynoronmalade']; + +// add words to the dictionary +additionalDictionary.forEach(word => Spellchecker.add(word)); + +let testWord = 'kat'; +let testCorpus = 'The queeck brown fox jumped over the lazy dog, from Xynoronmalade'; +let testCorpusAsync = 'The queeck brown fox jumped over the lazy dog, from Xynoronmalade'; + +// check and correct a single word +if (Spellchecker.isMisspelled(testWord)) { + const corrections = Spellchecker.getCorrectionsForMisspelling(testWord); + if (corrections.length > 0) { + testWord = corrections[0]; + } +} + +// check and correct words in a body of text +const misspellings = Spellchecker.checkSpelling(testCorpus); +misspellings.forEach(location => { + const misspelled = testCorpus.slice(location.start, location.end); + const corrections = Spellchecker.getCorrectionsForMisspelling(misspelled); + if (corrections.length > 0) { + testCorpus = testCorpus.replace(misspelled, corrections[0]); + } +}); + +// check for corrections asynchronously +const asyncSpellCheck = async () => { + // check and correct words in a body of text + const misspellings = await Spellchecker.checkSpellingAsync(testCorpusAsync); + misspellings.forEach(location => { + const misspelled = testCorpusAsync.slice(location.start, location.end); + const corrections = Spellchecker.getCorrectionsForMisspelling(misspelled); + if (corrections.length > 0) { + testCorpusAsync = testCorpusAsync.replace(misspelled, corrections[0]); + } + }); +}; diff --git a/types/spellchecker/tsconfig.json b/types/spellchecker/tsconfig.json new file mode 100644 index 0000000000..6817057d8c --- /dev/null +++ b/types/spellchecker/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "spellchecker-tests.ts" + ] +} diff --git a/types/spellchecker/tslint.json b/types/spellchecker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/spellchecker/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/stellar-base/index.d.ts b/types/stellar-base/index.d.ts index a230c36942..b020369f60 100644 --- a/types/stellar-base/index.d.ts +++ b/types/stellar-base/index.d.ts @@ -49,6 +49,8 @@ export class Asset { export const FastSigning: boolean; +export type KeypairType = 'ed25519'; + export class Keypair { static fromRawEd25519Seed(secretSeed: Buffer): Keypair; static fromBase58Seed(secretSeed: string): Keypair; @@ -57,17 +59,18 @@ export class Keypair { static fromPublicKey(publicKey: string): Keypair; static random(): Keypair; - constructor(keys: { type: 'ed25519', secretKey: string } | { type: 'ed25519', Key: string }) + constructor(keys: { type: KeypairType, secretKey: string, publicKey?: string } | { type: KeypairType, publicKey: string }) + readonly type: KeypairType; publicKey(): string; secret(): string; rawPublicKey(): Buffer; rawSecretKey(): Buffer; canSign(): boolean; - sign(data: Buffer): Buffer; + sign(data: Buffer): xdr.Signature; signDecorated(data: Buffer): xdr.DecoratedSignature; signatureHint(): xdr.SignatureHint; - verify(data: Buffer, signature: Buffer): boolean; + verify(data: Buffer, signature: xdr.Signature): boolean; } export const MemoNone = 'none'; @@ -439,10 +442,13 @@ export class Transaction<TMemo extends Memo = Memo, TOps extends Operation[] = O signatures: xdr.DecoratedSignature[]; } +export const TimeoutInfinite = 0; + export class TransactionBuilder { constructor(sourceAccount: Account, options?: TransactionBuilder.TransactionBuilderOptions) addOperation(operation: xdr.Operation): this; addMemo(memo: Memo): this; + setTimeout(timeoutInSeconds: number): this; build(): Transaction; } @@ -498,5 +504,5 @@ export namespace xdr { } export function hash(data: Buffer): Buffer; -export function sign(data: Buffer, rawSecret: Buffer): Buffer; -export function verify(data: Buffer, signature: Buffer, rawPublicKey: Buffer): boolean; +export function sign(data: Buffer, rawSecret: Buffer): xdr.Signature; +export function verify(data: Buffer, signature: xdr.Signature, rawPublicKey: Buffer): boolean; diff --git a/types/stellar-base/stellar-base-tests.ts b/types/stellar-base/stellar-base-tests.ts index 83a52cbe7b..4884a5a6a5 100644 --- a/types/stellar-base/stellar-base-tests.ts +++ b/types/stellar-base/stellar-base-tests.ts @@ -6,6 +6,7 @@ const account = new StellarSdk.Account(sourceKey.publicKey(), '1'); const transaction = new StellarSdk.TransactionBuilder(account) .addOperation(StellarSdk.Operation.accountMerge({destination: destKey.publicKey()})) .addMemo(new StellarSdk.Memo(StellarSdk.MemoText, "memo")) + .setTimeout(5) .build(); // $ExpectType () => Transaction<Memo<MemoType>, Operation[]> const sig = StellarSdk.xdr.DecoratedSignature.fromXDR(Buffer.of(1, 2)); // $ExpectType DecoratedSignature @@ -38,3 +39,5 @@ StellarSdk.Operation.fromXDRObject(newSignerXDR2).signer; // $ExpectType Sha256H const newSignerXDR3 = StellarSdk.Operation.setOptions({signer: {preAuthTx: '', weight: 1}}); StellarSdk.Operation.fromXDRObject(newSignerXDR3).signer; // $ExpectType PreAuthTx + +StellarSdk.TimeoutInfinite; // $ExpectType 0 diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index 5eebdd2ff0..2b46cbb3af 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -4870,6 +4870,18 @@ declare namespace Stripe { interface ISubscriptionCancellationOptions extends IDataOptions { /** + * Will generate a final invoice that invoices for any un-invoiced metered usage and new/pending proration invoice items. + */ + invoice_now?: boolean; + + /** + * Will generate a proration invoice item that credits remaining unused time until the subscription period end. + */ + prorate?: boolean; + + /** + * @deprecated Use subscription update with cancel_at_period_end option as of 2018-08-23. + * * A flag that if set to true will delay the cancellation of the subscription until the end of the current period. */ at_period_end?: boolean; diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index 19b9afcd5f..788e8c305f 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -421,6 +421,8 @@ export interface JustifyItemsProps { justifyItems?: ResponsiveValue<CSS.JustifyItemsProperty>; } +export function justifyItems(...args: any[]): any; + export interface JustifyContentProps { /** * The CSS justify-content property defines how the browser distributes space between and around content items diff --git a/types/styled-system/styled-system-tests.tsx b/types/styled-system/styled-system-tests.tsx index 397e1b0402..1a008fa045 100644 --- a/types/styled-system/styled-system-tests.tsx +++ b/types/styled-system/styled-system-tests.tsx @@ -43,6 +43,8 @@ import { alignContent, justifyContent, JustifyContentProps, + justifyItems, + JustifyItemsProps, FlexWrapProps, flexWrap, flexBasis, @@ -253,7 +255,8 @@ interface FlexComponentProps JustifyContentProps, FlexWrapProps, FlexBasisProps, - FlexDirectionProps {} + FlexDirectionProps, + JustifyItemsProps {} const Flex: React.ComponentType<FlexComponentProps> = styled` ${alignItems}; ${alignContent}; @@ -261,6 +264,7 @@ const Flex: React.ComponentType<FlexComponentProps> = styled` ${flexWrap}; ${flexBasis}; ${flexDirection}; + ${justifyItems}; `; interface GridComponentProps @@ -427,6 +431,10 @@ const test = () => ( <Flex flexDirection="column" /> <Flex flexDirection={["column"]} /> <Flex flexDirection={{ sm: "column" }} /> + // justifyItems + <Flex justifyItems="baseline" /> + <Flex justifyItems={["baseline", "center"]} /> + <Flex justifyItems={{ sm: "baseline", md: "center" }} /> // gridGap <Grid gridGap="1px" /> <Grid gridGap={["1", "2"]} /> diff --git a/types/supercluster/index.d.ts b/types/supercluster/index.d.ts index 7fd487ae09..74ef517d7e 100644 --- a/types/supercluster/index.d.ts +++ b/types/supercluster/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for supercluster 3.0 +// Type definitions for supercluster 5.0 // Project: https://github.com/mapbox/supercluster // Definitions by: Denis Carriere <https://github.com/DenisCarriere> +// Nick Zahn <https://github.com/Manc> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -8,113 +9,164 @@ import * as GeoJSON from 'geojson'; export as namespace supercluster; -export interface Options { +export interface Options<P, C> { /** * Minimum zoom level at which clusters are generated. + * + * @default 0 */ minZoom?: number; + /** * Maximum zoom level at which clusters are generated. + * + * @default 16 */ maxZoom?: number; + /** * Cluster radius, in pixels. + * + * @default 40 */ radius?: number; + /** * (Tiles) Tile extent. Radius is calculated relative to this value. + * + * @default 512 */ extent?: number; + /** * Size of the KD-tree leaf node. Affects performance. + * + * @default 64 */ nodeSize?: number; + /** * Whether timing info should be logged. + * + * @default false */ log?: boolean; + /** - * a reduce function for calculating custom cluster properties + * A function that returns cluster properties corresponding to a single point. * * @example - * function (accumulated, props) { accumulated.sum += props.sum; } + * (props) => ({sum: props.myValue}) */ - reduce?: (accumulated: any, props: any) => void; + map?: (props: P) => C; + /** - * initial properties of a cluster (before running the reducer) + * A reduce function that merges properties of two clusters into one. * * @example - * function () { return {sum: 0}; } + * (accumulated, props) => { accumulated.sum += props.sum; } */ - initial?: () => any; - /** - * properties to use for individual points when running the reducer - * - * @example - * function (props) { return {sum: props.my_value}; } - */ - map?: (props: any) => any; -} - -export class Supercluster { - /** - * Loads an array of GeoJSON.Feature objects. Each feature's geometry must be a GeoJSON.Point. Once loaded, index is immutable. - */ - load(points: Points): Supercluster; - /** - * For the given bbox array ([westLng, southLat, eastLng, northLat]) and integer zoom, returns an array of clusters and points as GeoJSON.Feature objects. - */ - getClusters(bbox: BBox, zoom: number): Clusters; - - /** - * For a given zoom and x/y coordinates, returns a geojson-vt-compatible JSON tile object with cluster/point features. - */ - getTile(z: number, x: number, y: number): Tile; - - /** - * Returns the children of a cluster (on the next zoom level) given its id (cluster_id value from feature properties) and zoom the cluster was from. - */ - getChildren(clusterId: number, clusterZoom: number): Clusters; - - /** - * Returns all the points of a cluster (given its cluster_id and zoom), - * with pagination support: limit is the number of points to return (set to Infinity for all points), - * and offset is the amount of points to skip (for pagination). - */ - getLeaves(clusterId: number, clusterZoom: number, limit?: number, offset?: number): Clusters; - - /** - * Returns the zoom on which the cluster expands into several children (useful for "click to zoom" feature), given the cluster's cluster_id and zoom. - */ - getClusterExpansionZoom(clusterId: number, clusterZoom: number): number; + reduce?: (accumulated: C, props: Readonly<C>) => void; } /** - * A very fast JavaScript library for geospatial point clustering for browsers and Node. + * Default properties type, allowing any properties. + * Try to avoid this for better typesafety by using proper types. */ -export default function supercluster(options: Options): Supercluster; +export interface AnyProps { + [name: string]: any; +} + +/** + * A very fast geospatial point clustering library for browsers and Node. + */ +export default class Supercluster<P extends GeoJSON.GeoJsonProperties = AnyProps, C extends GeoJSON.GeoJsonProperties = AnyProps> { + constructor(options?: Options<P, C>); + + /** + * Loads an array of GeoJSON Feature objects. Each feature's geometry + * must be a GeoJSON Point. Once loaded, index is immutable. + * + * @param points Array of GeoJSON Features, the geometries being GeoJSON Points. + */ + load(points: Array<PointFeature<P>>): Supercluster<P, C>; + + /** + * Returns an array of clusters and points as `GeoJSON.Feature` objects + * for the given bounding box (`bbox`) and zoom level (`zoom`). + * + * @param bbox Bounding box (`[westLng, southLat, eastLng, northLat]`). + * @param zoom Zoom level. + */ + getClusters(bbox: GeoJSON.BBox, zoom: number): Array<ClusterFeature<C> | PointFeature<P>>; + + /** + * For a given zoom and x/y coordinates, returns a + * [geojson-vt](https://github.com/mapbox/geojson-vt)-compatible JSON + * tile object with cluster any point features. + */ + getTile(zoom: number, x: number, y: number): Tile<C, P> | null; + + /** + * Returns the children of a cluster (on the next zoom level). + * + * @param clusterId Cluster ID (`cluster_id` value from feature properties). + * @throws {Error} If `clusterId` does not exist. + */ + getChildren(clusterId: number): Array<ClusterFeature<C> | PointFeature<P>>; + + /** + * Returns all the points of a cluster (with pagination support). + * + * @param clusterId Cluster ID (`cluster_id` value from feature properties). + * @param limit The number of points to return (set to `Infinity` for all points). + * @param offset The amount of points to skip (for pagination). + */ + getLeaves(clusterId: number, limit?: number, offset?: number): Array<ClusterFeature<C> | PointFeature<P>>; // Cluster[]; + + /** + * Returns the zoom level on which the cluster expands into several + * children (useful for "click to zoom" feature). + * + * @param clusterId Cluster ID (`cluster_id` value from feature properties). + */ + getClusterExpansionZoom(clusterId: number): number; +} + +/** + * [GeoJSON Feature](https://tools.ietf.org/html/rfc7946#section-3.2), + * with the geometry being a + * [GeoJSON Point](https://tools.ietf.org/html/rfc7946#section-3.1.2). + */ +export type PointFeature<P> = GeoJSON.Feature<GeoJSON.Point, P>; -export type Point = GeoJSON.Feature<GeoJSON.Point>; -export type Points = Point[]; -export type Clusters = Cluster[]; -export type TileFeatures = TileFeature[]; -export type BBox = [number, number, number, number]; export interface ClusterProperties { - cluster?: boolean; - cluster_id?: number; - point_count?: number; - point_count_abbreviated?: number; - sum?: number; - [key: string]: any; + /** + * Always `true` to indicate that the Feature is a Cluster and not + * an individual point. + */ + cluster: true; + /** Cluster ID */ + cluster_id: number; + /** Number of points in the cluster. */ + point_count: number; + /** + * Abbreviated number of points in the cluster as string if the number + * is 1000 or greater (e.g. `1.3k` if the number is 1298). + * + * For less than 1000 points it is the same value as `point_count`. + */ + point_count_abbreviated: string | number; } -export interface Cluster extends Point { - properties: ClusterProperties; -} -export interface TileFeature { + +export type ClusterFeature<C> = PointFeature<ClusterProperties & C>; + +export interface TileFeature<C, P> { type: 1; geometry: Array<[number, number]>; - tags: ClusterProperties; + tags: (ClusterProperties & C) | P; } -export interface Tile { - features: TileFeatures; + +export interface Tile<C, P> { + features: Array<TileFeature<C, P>>; } diff --git a/types/supercluster/supercluster-tests.ts b/types/supercluster/supercluster-tests.ts index e3120206e9..6da89ef104 100644 --- a/types/supercluster/supercluster-tests.ts +++ b/types/supercluster/supercluster-tests.ts @@ -1,43 +1,101 @@ -import supercluster, { Point } from 'supercluster'; +import Supercluster, { PointFeature, ClusterProperties } from 'supercluster'; -const point1: Point = { - type: 'Feature', - properties: {my_value: 2}, - geometry: { type: 'Point', coordinates: [10, 20] } -}; -const point2: Point = { - type: 'Feature', - properties: {my_value: 3}, - geometry: { type: 'Point', coordinates: [20, 30] } -}; -const points = [point1, point2]; +// +// Test 1: strictly typed +// -const initialFunction = () => { - return {sum: 0}; -}; +interface TestPointProps { + myTestFeatureName: string; +} -const mapFunction = (props: any) => { - return {sum: props.my_value}; -}; +interface TestClusterProps { + myTestClusterName: string; +} -const reduceFunction = (accumulated: any, props: any) => { - accumulated.sum += props.sum; -}; +const points: Array<PointFeature<TestPointProps>> = [ + { + type: 'Feature', + properties: { myTestFeatureName: 'a' }, + geometry: { type: 'Point', coordinates: [10, 20] } + }, + { + type: 'Feature', + properties: { myTestFeatureName: 'b' }, + geometry: { type: 'Point', coordinates: [20, 30] } + } +]; -const index = supercluster({ - radius: 40, - maxZoom: 16, - extent: 256, - log: true, - initial: initialFunction, - map: mapFunction, - reduce: reduceFunction, +// construct() +new Supercluster(); +new Supercluster({}); +const index = new Supercluster({ + minZoom: 5, + maxZoom: 16, + radius: 40, + extent: 256, + nodeSize: 64, + log: true, + map: (props: TestPointProps): TestClusterProps => ({ + myTestClusterName: props.myTestFeatureName.toUpperCase() + }), + reduce: (accumulated, props) => { + accumulated.myTestClusterName += ` & ${props.myTestClusterName}`; + }, }); + +// load() index.load(points); + +// getClusters() const clusters = index.getClusters([-180, -85, 180, 85], 2); -clusters[0].properties.cluster_id; -index.getTile(0, 0, 0); -index.getChildren(0, 0); -index.getLeaves(0, 0, 10, 5); -index.getClusterExpansionZoom(0, 0); -index.getTile(0, 0, 0).features[0].tags.sum; +const firstProps = clusters[0].properties; // Either cluster or point properties +// Generic cluster properties +(<ClusterProperties> firstProps).cluster; +(<ClusterProperties> firstProps).point_count; +// Custom cluster properties +(<TestClusterProps> firstProps).myTestClusterName; +// Custom point properties +(<TestPointProps> firstProps).myTestFeatureName; + +// getTile() +const tile = index.getTile(0, 0, 0); +if (tile) { + const tileProps = tile.features[0].tags; // Either cluster or point properties + // Generic cluster properties + (<ClusterProperties> tileProps).cluster; + (<ClusterProperties> tileProps).point_count; + // Custom cluster properties + (<TestClusterProps> tileProps).myTestClusterName; + // Custom point properties + (<TestPointProps> tileProps).myTestFeatureName; +} + +// Other methods +index.getChildren(0); +index.getLeaves(0); +index.getLeaves(0, Infinity); +index.getLeaves(0, 0, 10); +index.getClusterExpansionZoom(0); + +// +// Test 2: loosely typed +// + +const index2 = new Supercluster(); +index2.load([ + { + type: 'Feature', + properties: { testPropertyA: 100 }, + geometry: { type: 'Point', coordinates: [10, 20] } + }, + { + type: 'Feature', + properties: { testPropertyB: 'test' }, + geometry: { type: 'Point', coordinates: [20, 30] } + } +]); +const clusters2 = index2.getClusters([-180, -85, 180, 85], 2); +const firstProps2 = clusters2[0].properties; +(<ClusterProperties> firstProps2).cluster_id; +firstProps2.testPropertyA; +firstProps2.testPropertyB; diff --git a/types/supercluster/tslint.json b/types/supercluster/tslint.json index 440efbd687..3db14f85ea 100644 --- a/types/supercluster/tslint.json +++ b/types/supercluster/tslint.json @@ -1,7 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - // TODO - "no-duplicate-imports": false - } -} +{ "extends": "dtslint/dt.json" } diff --git a/types/url-parse/index.d.ts b/types/url-parse/index.d.ts index 8fc22dbfc0..cb3bc75dd5 100644 --- a/types/url-parse/index.d.ts +++ b/types/url-parse/index.d.ts @@ -23,6 +23,8 @@ declare namespace URLParse { | 'username'; type QueryParser = (query: string) => object; + + type StringifyQuery = (query: object) => string; } interface URLParse { @@ -40,7 +42,7 @@ interface URLParse { readonly slashes: boolean; readonly username: string; set(part: URLParse.URLPart, value: string | object | number | undefined, fn?: boolean | URLParse.QueryParser): URLParse; - toString(): string; + toString(stringify?: URLParse.StringifyQuery): string; } declare const URLParse: { @@ -57,7 +59,7 @@ declare const URLParse: { location(url: string): object; qs: { parse: URLParse.QueryParser; - stringify(query: object): string; + stringify: URLParse.StringifyQuery; }; }; diff --git a/types/utif/index.d.ts b/types/utif/index.d.ts new file mode 100644 index 0000000000..569dfd949c --- /dev/null +++ b/types/utif/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for utif 2.0 +// Project: https://github.com/photopea/UTIF.js +// Definitions by: Jan Pesa <https://github.com/smajl> +// Naveen Kumar Sangi <https://github.com/nkprince007> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import 'node'; + +export as namespace UTIF; + +export type TiffTag = string[] | number[]; + +/** + * Each IFD is an object, keys are "tXYZ" (XYZ is a TIFF tag number), values are values of these tags. + * You can get the the dimension (and other properties, "metadata") of the image without decompressing pixel data. + * For more information on what each tag means, refer https://github.com/photopea/UTIF.js/blob/master/UTIF.js#L742 or TIFF 6 specification. + */ +// tslint:disable-next-line:interface-name +export interface IFD { + [property: string]: TiffTag | number | Uint8Array; + data: Uint8Array; + width: number; + height: number; +} + +/** + * Returns an array of "IFDs" (image file directories). + * + * @param buffer A Buffer or ArrayBuffer containing TIFF or EXIF data. + */ +export function decode(buffer: Buffer | ArrayBuffer): IFD[]; + +/** + * Loops through each IFD. If there is an image inside it, it is decoded and three new properties are added to the IFD: width, height and data. + * Note: TIFF files may have various number of channels and various color depth. The interpretation of data depends on many tags (see the TIFF 6 specification). + * + * @param buffer A Buffer or ArrayBuffer containing TIFF or EXIF data + * @param ifds An array of image file directories parsed via UTIF.decode() + */ +export function decodeImages(buffer: Buffer | ArrayBuffer, ifds: IFD[]): void; + +/** + * Returns Uint8Array of the image in RGBA format, 8 bits per channel (ready to use in context2d.putImageData() etc.) + * + * @param ifd An image file directory + */ +export function toRGBA8(ifd: IFD): Uint8Array; + +/** + * Returns an ArrayBuffer of the binary TIFF file. + * Note: No compression available right now. + * + * @param rgba A Uint8Array containing RGBA pixel data. + * @param w Width of the image. + * @param h Height of the image. + * @param metadata [optional] The image file directory which should be encoded. + */ +export function encodeImage(rgba: Uint8Array, w: number, h: number, metadata?: IFD): ArrayBuffer; + +/** + * Returns ArrayBuffer of binary data which can be used to encode EXIF data. + * + * @param ifds The array of IFDs (image file directories) to be encoded. + */ +export function encode(ifds: IFD[]): ArrayBuffer; + +/** + * Replaces all Image elements in the document with Canvas elements. + * The attributes "id", "class" and "style" will be copied from the original Image to the new Canvas. + */ +export function replaceIMG(): void; diff --git a/types/utif/tsconfig.json b/types/utif/tsconfig.json new file mode 100644 index 0000000000..cd4c8aa8fe --- /dev/null +++ b/types/utif/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "utif-tests.ts" + ] +} diff --git a/types/utif/tslint.json b/types/utif/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/utif/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/utif/utif-tests.ts b/types/utif/utif-tests.ts new file mode 100644 index 0000000000..66455e2f4a --- /dev/null +++ b/types/utif/utif-tests.ts @@ -0,0 +1,15 @@ +import * as UTIF from "utif"; + +// $ExpectType IFD[] +const IFDs = UTIF.decode(new ArrayBuffer(64)); +// $ExpectType Uint8Array +const rgba = UTIF.toRGBA8(IFDs[0]); + +// $ExpectType ArrayBuffer +UTIF.encodeImage(rgba, 8, 8); +// $ExpectType ArrayBuffer +UTIF.encode(IFDs); +// $ExpectType void +UTIF.decodeImages(new ArrayBuffer(64), IFDs); +// $ExpectType void +UTIF.replaceIMG(); diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index 49cfcf7a83..e2f1cb8111 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -33,17 +33,20 @@ declare module "victory" { "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; // Many victory components accept string or number or callback which returns string or number - type StringOrNumberOrCallback = string | number | { (): string | number }; - type NumberOrCallback = { (): number } | number; + type StringOrNumberOrCallback = + | string + | number + | ((datum: any, active: boolean) => string | number); + type NumberOrCallback = ((datum: any, active: boolean) => number) | number; + type VictoryStyleObject = { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; /** * Style interface used in components/themeing */ export interface VictoryStyleInterface { - parent?: React.CSSProperties; - data?: React.CSSProperties; - labels?: React.CSSProperties; - tickLabels?: React.CSSProperties; + parent?: VictoryStyleObject; + data?: VictoryStyleObject; + labels?: VictoryStyleObject; } export interface VictoryAnimationProps { @@ -122,16 +125,19 @@ declare module "victory" { * Event handlers are currently only called with their corresponding events. */ events?: React.DOMAttributes<any>; - /** - * All Victory components will pass a text prop to their label component. - * This defines the content of the label when child nodes are absent. It will be ignored if children are provided. - */ - text?: StringOrNumberOrCallback; /** * The children of this component define the content of the label. * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. */ children?: StringOrNumberOrCallback; + /** + * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. + * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar + * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. + * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label + * placement will be used for cartesian charts. + */ + labelPlacement?: "parallel" | "perpendicular" | "vertical"; /** * The lineHeight prop defines how much space a single line of text should take up. * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, @@ -141,10 +147,31 @@ declare module "victory" { * @default 1 */ lineHeight?: StringOrNumberOrCallback; + /** + * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. + * **This prop should not be set manually.** + */ + origin?: { x: number, y: number }; + /** + * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. + * **This prop should not be set manually.** + */ + polar?: boolean; + /** + * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. + * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. + */ + renderInPortal?: boolean; /** * The style prop applies CSS properties to the rendered `<text>` element. */ style?: React.CSSProperties; + /** + * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, + * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate + * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. + */ + text?: string[] | StringOrNumberOrCallback; /** * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. */ @@ -188,7 +215,7 @@ declare module "victory" { * with a viewBox attribute, or a static container with absolute width and height. * @default true */ - responsive?: boolean + responsive?: boolean; /** * The style prop specifies styles for your VictoryContainer. Any valid inline style properties * will be applied. Height and width should be specified via the height @@ -244,7 +271,7 @@ declare module "victory" { type CursorData = { x: number; y: number; - } + }; export interface VictoryCursorContainerProps extends VictoryContainerProps { /** @@ -294,7 +321,7 @@ declare module "victory" { /** * When the disable prop is set to true, VictoryCursorContainer events will not fire. */ - disable?: boolean + disable?: boolean; /** * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). * When this prop is not specified, the cursor will be a 2-dimensional crosshair. @@ -302,7 +329,7 @@ declare module "victory" { * the cursor will then be a vertical line that will inspect the time value of the current mouse position. * @example onChange={(value, props) => this.setState({cursorValue: value})} */ - onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void + onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void; } export class VictoryCursorContainer extends React.Component<VictoryCursorContainerProps, any> {} @@ -568,10 +595,11 @@ declare module "victory" { /** * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. */ - flyoutStyle?: React.CSSProperties; + flyoutStyle?: VictoryStyleObject; /** * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. - * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. + * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, + * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. * If flyoutComponent is omitted, a default Flyout component will be created with props described above. * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} @@ -590,7 +618,8 @@ declare module "victory" { height?: NumberOrCallback; /** * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. - * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. negative values result in a left orientation and positive values will result in a right orientation by default. + * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. + * negative values result in a left orientation and positive values will result in a right orientation by default. */ horizontal?: boolean; /** @@ -617,11 +646,13 @@ declare module "victory" { */ pointerLength?: NumberOrCallback; /** - * The pointerWidth prop determines the width of the base of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. + * The pointerWidth prop determines the width of the base of the triangular pointer extending from + * the flyout. This prop may be given as a positive number or a function of datum. */ pointerWidth?: NumberOrCallback; /** - * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element within VictoryContainer. Note: This prop should not be set to true when using a custom container element. + * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element + * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. */ renderInPortal?: boolean; /** @@ -636,10 +667,11 @@ declare module "victory" { /** * VictoryAxis uses the standard theme prop. Read about it here * @default VictoryTheme.grayscale - */ + */ theme?: VictoryThemeDefinition; /** - * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. */ width?: NumberOrCallback; /** @@ -652,9 +684,9 @@ declare module "victory" { y?: number; } - /** - * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. + * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label + * component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. * VictoryTooltip renders text as well as a configurable Flyout container. */ export class VictoryTooltip extends React.Component< @@ -735,9 +767,7 @@ declare module "victory" { * Targets may be any valid style namespace for a given component */ target: TTarget; - /** - * - */ + eventKey?: TEventKey; /** * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks @@ -999,65 +1029,67 @@ declare module "victory" { label?: string | { (data: any): string }; } - export interface VictoryAreaProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. - * Since VictoryArea only renders a single element, the eventKey property is not used. - * The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. an area), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @example - * events={[ - * { - * target: "data", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - *}} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; - /** - * The interpolation prop determines how data points should be connected when plotting a line - * @default "linear" - */ - interpolation?: InterpolationPropType; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - * @default 50 - */ - samples?: number; - /** - * The style prop specifies styles for your VictoryArea. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. - * @example {data: {fill: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; + export interface VictoryAreaProps + extends VictoryCommonProps, + VictoryDatableProps, + VictorySingleLabableProps { + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. + * Since VictoryArea only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. an area), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @example + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; + /** + * The interpolation prop determines how data points should be connected when plotting a line + * @default "linear" + */ + interpolation?: InterpolationPropType; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + * @default 50 + */ + samples?: number; + /** + * The style prop specifies styles for your VictoryArea. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; } /** @@ -1143,7 +1175,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; /** @@ -1195,20 +1226,40 @@ declare module "victory" { */ orientation?: "top" | "bottom" | "left" | "right"; /** - * The style prop specifies styles for your VictoryAxis. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. - * @example {axis: {stroke: "#756f6a"}, grid: {stroke: "grey"}, ticks: {stroke: "grey"}, - * tickLabels: {fontSize: 10, padding: 5}, axisLabel: {fontSize: 16, padding: 20}} + * The style prop defines the style of the component. The style prop should be given as an object + * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg + * styles are supported, but width, height, and padding should be specified via props as they + * determine relative layout for components in VictoryChart. Functional styles may be defined for + * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. + * + * note: When a component is rendered as a child of another Victory component, or within a custom + * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. + * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. + * + * note: custom angle and verticalAnchor properties may be included in labels styles. */ style?: { parent?: React.CSSProperties; axis?: React.CSSProperties; axisLabel?: React.CSSProperties; - grid?: React.CSSProperties; - ticks?: React.CSSProperties; - tickLabels?: React.CSSProperties; + grid?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + ticks?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + tickLabels?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; }; /** * The tickComponent prop takes in an entire component which will be used @@ -1251,7 +1302,7 @@ declare module "victory" { * The tickValues prop explicitly specifies which tick values to draw on the axis. * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] */ - tickValues?: any[] + tickValues?: any[]; } /** @@ -1262,12 +1313,41 @@ declare module "victory" { export class VictoryAxis extends React.Component<VictoryAxisProps, any> {} export interface VictoryBarProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { + /** + * The alignment prop specifies how bars should be aligned relative to their data points. + * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, + * bars will have “middle” alignment relative to their data points. + */ + alignment?: "start" | "middle" | "end"; + /** + * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. + * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will + * be used to calculate a default width for each bar given the total number of bars in the data series + * and the overall width of the chart. + */ + barRatio?: number; + /** + * The barWidth prop is used to specify the width of each bar. This prop may be given as + * a number of pixels or as a function that returns a number. When this prop is given as + * a function, it will be evaluated with the arguments datum, and active. When this value + * is not given, a default value will be calculated based on the overall dimensions of + * the chart, and the number of bars. + */ + barWidth?: NumberOrCallback; /** * The cornerRadius prop specifies a radius to apply to each bar. * If this prop is given as a single number, the radius will only be applied to the top of each bar. * When this prop is given as a function, it will be evaluated with the arguments datum, and active. */ - cornerRadius?: NumberOrCallback; + cornerRadius?: NumberOrCallback + | { + top?: number | (NumberOrCallback), + topLeft?: number | (NumberOrCallback), + topRight?: number | (NumberOrCallback), + bottom?: number | (NumberOrCallback), + bottomLeft?: number | (NumberOrCallback), + bottomRight?: number | (NumberOrCallback) + }; /** * The event prop take an array of event objects. Event objects are composed of * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace @@ -1307,8 +1387,7 @@ declare module "victory" { * } * } * ]} - *}} - */ + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally @@ -1331,21 +1410,6 @@ declare module "victory" { * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} */ style?: VictoryStyleInterface; - /** - * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. - * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will - * be used to calculate a default width for each bar given the total number of bars in the data series - * and the overall width of the chart. - */ - barRatio?: number; - /** - * The barWidth prop is used to specify the width of each bar. This prop may be given as - * a number of pixels or as a function that returns a number. When this prop is given as - * a function, it will be evaluated with the arguments datum, and active. When this value - * is not given, a default value will be calculated based on the overall dimensions of - * the chart, and the number of bars. - */ - barWidth?: NumberOrCallback; } /** @@ -1356,16 +1420,16 @@ declare module "victory" { export interface VictoryBoxPlotStyleInterface extends VictoryStyleInterface { - max?: React.CSSProperties; - maxLabels?: React.CSSProperties; - min?: React.CSSProperties; - minLabels?: React.CSSProperties; - median?: React.CSSProperties; - medianLabels?: React.CSSProperties; - q1?: React.CSSProperties; - q1Labels?: React.CSSProperties; - q3?: React.CSSProperties; - q3Labels?: React.CSSProperties; + max?: VictoryStyleObject; + maxLabels?: VictoryStyleObject; + min?: VictoryStyleObject; + minLabels?: VictoryStyleObject; + median?: VictoryStyleObject; + medianLabels?: VictoryStyleObject; + q1?: VictoryStyleObject; + q1Labels?: VictoryStyleObject; + q3?: VictoryStyleObject; + q3Labels?: VictoryStyleObject; } export interface VictoryBoxPlotProps @@ -1432,7 +1496,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; /** @@ -1563,7 +1626,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; /** @@ -1668,8 +1730,7 @@ declare module "victory" { * } * } * ]} - *}} - */ + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally @@ -1688,16 +1749,16 @@ declare module "victory" { * case of groups of bars, this number should be equal to the width of the bar * plus the desired spacing between bars. */ - offset?:number + offset?: number; /** * The style prop specifies styles for your grouped chart. These styles will be * applied to all grouped children */ style?: VictoryStyleInterface; } - + export class VictoryGroup extends React.Component<VictoryGroupProps, any> {} - + export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { /** * The event prop take an array of event objects. Event objects are composed of @@ -1735,8 +1796,7 @@ declare module "victory" { * } * } * ]} - *}} - */ + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; /** * The interpolation prop determines how data points should be connected @@ -1770,13 +1830,13 @@ declare module "victory" { */ style?: VictoryStyleInterface; } - + /** * VictoryLine creates a line based on data. VictoryLine is a composable component, so it does not include an axis. * Check out VictoryChart for easy to use line charts and more. */ export class VictoryLine extends React.Component<VictoryLineProps, any> {} - + export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { /** * The colorScale prop defines a color scale to be applied to each data @@ -1925,14 +1985,14 @@ declare module "victory" { x?: number; y?: number; } - + /** * VictoryLegend renders a chart legend component. */ export class VictoryLegend extends React.Component<VictoryLegendProps, any> {} - + type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; - + export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { /** * The bubbleProperty prop indicates which property of the data object should be used @@ -1978,8 +2038,7 @@ declare module "victory" { * } * } * ]} - *}} - */ + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally @@ -2014,13 +2073,13 @@ declare module "victory" { */ symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; } - + /** * VictoryScatter creates a scatter of points from data. VictoryScatter is a composable component, so it does not include an axis. * Check out VictoryChart for easy to use scatter plots and more. */ export class VictoryScatter extends React.Component<VictoryScatterProps, any> {} - + export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { /** * The categories prop specifies how categorical data for a chart should be ordered. @@ -2096,8 +2155,7 @@ declare module "victory" { * } * } * ]} - *}} - */ + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally @@ -2121,9 +2179,9 @@ declare module "victory" { */ xOffset?: number; } - + export class VictoryStack extends React.Component<VictoryStackProps, any> {} - + export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { /** * The colorScale prop is an optional prop that defines the color scale the pie @@ -2203,8 +2261,7 @@ declare module "victory" { * } * } * ]} - *}} - */ + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally @@ -2212,10 +2269,10 @@ declare module "victory" { */ eventKey?: StringOrNumberOrCallback; /** - * Specifies the radius of the chart. If this property is not provided it is computed - * from width, height, and padding props - * - */ + * Specifies the radius of the chart. If this property is not provided it is computed + * from width, height, and padding props + * + */ radius?: number; /** * When creating a donut chart, this prop determines the number of pixels between @@ -2267,7 +2324,7 @@ declare module "victory" { */ y?: DataGetterPropType; } - + /** * victory-pie draws an SVG pie or donut chart with React. * Styles and data can be customized by passing in your own values as properties to the component. @@ -2275,4 +2332,3 @@ declare module "victory" { */ export class VictoryPie extends React.Component<VictoryPieProps, any> {} } - \ No newline at end of file diff --git a/types/victory/tslint.json b/types/victory/tslint.json index a0357daa61..2fccde6e9b 100644 --- a/types/victory/tslint.json +++ b/types/victory/tslint.json @@ -1,78 +1,14 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, "array-type": false, - "arrow-return-shorthand": false, "ban-types": false, "callable-types": false, - "comment-format": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "strict-export-declare-modifiers": false } } diff --git a/types/victory/victory-tests.tsx b/types/victory/victory-tests.tsx index 0c9992494e..fcd18571e3 100644 --- a/types/victory/victory-tests.tsx +++ b/types/victory/victory-tests.tsx @@ -34,7 +34,7 @@ let test = <VictoryAnimation {(style: AnimationStyle) => <span style={{color: style["color"] as string}}>Hello!</span> } -</VictoryAnimation> +</VictoryAnimation>; // VictoryLabel test test = <VictoryLabel x={50} y={10} @@ -51,7 +51,28 @@ test = <VictoryLabel x={50} y={10} dy={10} lineHeight={1.5}> {"data viz \n is \n fun!"} -</VictoryLabel> +</VictoryLabel>; + +test = ( + <VictoryLabel + text={datum => datum.label} + labelPlacement='perpendicular' + renderInPortal={true} + > + {"data viz \n is \n fun!"} + </VictoryLabel> +); + +test = ( + <VictoryLabel + text={['some', 'text', 'strings']} + labelPlacement='vertical' + renderInPortal={true} + lineHeight={'12'} + > + {"data viz \n is \n fun!"} + </VictoryLabel> +); // VictoryArea test test = ( @@ -91,19 +112,19 @@ test = ( onClick: () => { return { mutation: (props) => { - return { style: { fill: "orange" } } + return { style: { fill: "orange" } }; } - } + }; }, onMouseEnter: () => { return [ { target: "labels", mutation: (props) => { - return { text: "hey" } + return { text: "hey" }; } } - ] + ]; } } } @@ -156,32 +177,37 @@ test = ( test = ( <VictoryAxis style={{ - axis: {stroke: "black"}, - grid: {strokeWidth: 2}, - ticks: {stroke: "red"}, - tickLabels: {fontSize: 12}, - axisLabel: {fontSize: 16} + axis: { stroke: "black" }, + grid: { strokeWidth: 2 }, + ticks: { stroke: "red" }, + tickLabels: { fontSize: 12 }, + axisLabel: { fontSize: 16 } }} label="Planets" tickValues={[ - "Mercury", - "Venus", - "Earth", - "Mars", - "Jupiter" - ]}/> + "Mercury", + "Venus", + "Earth", + "Mars", + "Jupiter" + ]} /> ); test = ( <VictoryAxis scale="time" + style={{ + grid: { strokeWidth: tick => tick.x }, + ticks: { stroke: tick => tick.color }, + tickLabels: { fontSize: tick => tick.y }, + }} tickValues={[ new Date(1980, 1, 1), new Date(1990, 1, 1), new Date(2000, 1, 1), new Date(2010, 1, 1), new Date(2020, 1, 1)]} - tickFormat={(x) => x.getFullYear()}/> + tickFormat={(x) => x.getFullYear()} /> ); test = ( @@ -189,7 +215,7 @@ test = ( dependentAxis padding={{left: 50, top: 20, bottom: 20}} scale="log" - domain={{ x: [new Date(Date.UTC(2016, 0, 1)), new Date()], y: [1,5] }} + domain={{ x: [new Date(Date.UTC(2016, 0, 1)), new Date()], y: [1, 5] }} /> ); @@ -278,6 +304,9 @@ test = ( {x: 4, y: 2}, {x: 5, y: 1} ]} + alignment="start" + barWidth={(datum, active) => active ? datum.x : datum.y} + cornerRadius={{top: 2, bottom: 4}} events={[ { target: "data", @@ -574,12 +603,19 @@ test = ( test = ( <VictoryScatter data={[ - {amount: 1, yield: 1, error: 0.5}, - {amount: 2, yield: 2, error: 1.1}, - {amount: 3, yield: 3, error: 0}, - {amount: 4, yield: 2, error: 0.1}, - {amount: 5, yield: 1, error: 1.5} + { amount: 1, yield: 1, error: 0.5 }, + { amount: 2, yield: 2, error: 1.1 }, + { amount: 3, yield: 3, error: 0 }, + { amount: 4, yield: 2, error: 0.1 }, + { amount: 5, yield: 1, error: 1.5 } ]} + style={{ + data: { + fill: d => d.x, + stroke: (datum, active) => active ? datum.x : datum.y, + strokeWidth: 3 + } + }} x={"amount"} y={(data) => (data.yield + data.error)} /> diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index 62bbf83362..2c2457e3ea 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -3713,6 +3713,21 @@ declare namespace videojs { new (player: Player, options?: ComponentOptions): MouseTimeDisplay }; + enum ReadyState { + HaveNothing = 0, + HaveMetadata = 1, + HaveCurrentData = 2, + HaveFutureData = 3, + HaveEnoughData = 4 + } + + enum NetworkState { + Empty = 0, + Idle = 1, + Loading = 2, + NoSource = 3 + } + /** * An instance of the `Player` class is created when any of the Video.js setup methods * are used to initialize a video. @@ -4249,6 +4264,13 @@ declare namespace videojs { muted(): boolean; + /** + * Returns the current state of network activity for the element + * + * @return The current network state + */ + networkState(): NetworkState; + /** * Pause the video playback * @check @@ -4342,6 +4364,12 @@ declare namespace videojs { */ preload(value?: boolean): string; + /** + * Returns a value that expresses the current state of the element + * with respect to rendering the current playback position. + */ + readyState(): ReadyState; + /** * Calculates how much time is left in the video. Not part * of the native video API. @@ -4609,6 +4637,7 @@ declare namespace videojs { fluid?: boolean; height?: number; html5?: any; + inactivityTimeout?: number; language?: string; languages?: { [code: string]: LanguageTranslations }; loop?: boolean; diff --git a/types/video.js/video.js-tests.ts b/types/video.js/video.js-tests.ts index 378a7150f3..e21d7fe581 100644 --- a/types/video.js/video.js-tests.ts +++ b/types/video.js/video.js-tests.ts @@ -57,8 +57,12 @@ videojs("example_video_1").ready(function() { this.height(480); + const readyState: videojs.ReadyState = this.readyState(); + this.requestFullscreen(); + const networkState: videojs.NetworkState = this.networkState(); + testEvents(this); testComponents(this); diff --git a/types/wait-on/index.d.ts b/types/wait-on/index.d.ts new file mode 100644 index 0000000000..55275a24e0 --- /dev/null +++ b/types/wait-on/index.d.ts @@ -0,0 +1,94 @@ +// Type definitions for wait-on 3.2 +// Project: https://github.com/jeffbski/wait-on#readme +// Definitions by: Ifiok Jr. <https://github.com/ifiokjr> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = waitOn; + +declare function waitOn(options: waitOn.WaitOnOptions): Promise<void>; +declare function waitOn( + options: waitOn.WaitOnOptions, + cb: (err: any) => void, +): void; + +declare namespace waitOn { + interface WaitOnOptions { + /** + * Array of string resources to wait for. prefix determines the type of resource with the default type of file: + */ + resources: string[]; + /** + * Initial delay in ms. + * @default 0 + */ + delay?: number; + /** + * Poll resource interval in ms, + * @default 250ms + */ + interval?: number; + /** + * Flag which outputs to stdout, remaining resources waited on and when complete or any error occurs. + */ + log?: boolean; + /** + * Flag to reverse operation so checks are for resources being NOT available. + * @default false + */ + reverse?: boolean; + /** + * Timeout in ms until it aborts with error. + * @default Infinity + */ + timeout?: number; + /** + * Tcp timeout in ms. + * @default 300 + */ + tcpTimeout?: number; + /** + * Flag which outputs debug output. + * @default false + */ + verbose?: boolean; + /** + * Stabilization time in ms + * Waits this amount of time for file sizes to stabilize or other resource availability to remain unchanged. + * @default 750ms. + */ + window?: number; + + /** + * Https specific option. + * see https:// github.com/request/request#readme for specific details + */ + auth?: WaitOnAuth; + httpSignature?: HttpSignature; + strictSSL?: boolean; + followAllRedirects?: boolean; + followRedirect?: boolean; + headers?: Record<string, any>; + } + + interface HttpSignature { + keyId: string; + key: string; + } + + type WaitOnAuth = + | { + username: string; + password: string; + } + | { + /** + * Alias of username + */ + user: string; + /** + * Alias of password + */ + pass: string; + }; +} diff --git a/types/fastify-static/tsconfig.json b/types/wait-on/tsconfig.json similarity index 87% rename from types/fastify-static/tsconfig.json rename to types/wait-on/tsconfig.json index bdfa7d40c6..c400fad2fe 100644 --- a/types/fastify-static/tsconfig.json +++ b/types/wait-on/tsconfig.json @@ -4,13 +4,13 @@ "lib": ["es6"], "noImplicitAny": true, "noImplicitThis": true, - "strictFunctionTypes": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": ["../"], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, - "files": ["index.d.ts", "fastify-static-tests.ts"] + "files": ["index.d.ts", "wait-on-tests.ts"] } diff --git a/types/wait-on/tslint.json b/types/wait-on/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/wait-on/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/wait-on/wait-on-tests.ts b/types/wait-on/wait-on-tests.ts new file mode 100644 index 0000000000..dea9a9c262 --- /dev/null +++ b/types/wait-on/wait-on-tests.ts @@ -0,0 +1,75 @@ +import waitOn = require('wait-on'); + +const opts = { + resources: [ + 'file1', + 'http://foo.com:8000/bar', + 'https://my.com/cat', + 'http-get://foo.com:8000/bar', + 'https-get://my.com/cat', + 'tcp:foo.com:8000', + 'socket:/my/sock', + 'http://unix:/my/sock:/my/url', + 'http-get://unix:/my/sock:/my/url', + ], + delay: 1000, // initial delay in ms, default 0 + interval: 100, // poll interval in ms, default 250ms + timeout: 30000, // timeout in ms, default Infinity + tcpTimeout: 1000, // tcp timeout in ms, default 300ms + window: 1000, // stabilization time in ms, default 750ms + + // http options + ca: [ + /* strings or binaries */ + ], + cert: [ + /* strings or binaries */ + ], + key: [ + /* strings or binaries */ + ], + passphrase: 'yourpassphrase', + auth: { + user: 'theuser', // or username + pass: 'thepassword', // or password + }, + httpSignature: { + keyId: 'yourKeyId', + key: 'yourKey', + }, + strictSSL: false, + followAllRedirects: true, + followRedirect: true, + headers: { + 'x-custom': 'headers', + }, +}; + +const handleError = (err: any) => undefined; + +// Usage with callback function +waitOn(opts, err => { + if (err) { + return handleError(err); + } + // once here, all resources are available +}); + +// Usage with promises +waitOn(opts) + .then(() => { + // once here, all resources are available + }) + .catch(err => { + handleError(err); + }); + +// Usage with async await +(async () => { + try { + await waitOn(opts); + // once here, all resources are available + } catch (err) { + handleError(err); + } +})(); diff --git a/types/webappsec-credential-management/index.d.ts b/types/webappsec-credential-management/index.d.ts index 4c47ee7cc8..ce3e7ef26c 100644 --- a/types/webappsec-credential-management/index.d.ts +++ b/types/webappsec-credential-management/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for W3C (WebAppSec) Credential Management API Level 1, 0.3 // Project: https://github.com/w3c/webappsec-credential-management // Definitions by: Iain McGinniss <https://github.com/iainmcgin> +// Joao Peixoto <https://github.com/Hartimer> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.7 @@ -493,7 +494,7 @@ interface AuthenticatorAttestationResponse extends AuthenticatorResponse { interface AuthenticatorAssertionResponse extends AuthenticatorResponse { readonly authenticatorData: ArrayBuffer; readonly signature: ArrayBuffer; - readonly userHandle: ArrayBuffer; + readonly userHandle: ArrayBuffer | null; } /** diff --git a/types/webappsec-credential-management/webappsec-credential-management-tests.ts b/types/webappsec-credential-management/webappsec-credential-management-tests.ts index 2afa9f8785..15ae1c6b9e 100644 --- a/types/webappsec-credential-management/webappsec-credential-management-tests.ts +++ b/types/webappsec-credential-management/webappsec-credential-management-tests.ts @@ -5,7 +5,7 @@ function passwordBasedSignInDeprecated() { return; } - navigator.credentials.get({password: true}).then((credential) => { + navigator.credentials.get({ password: true }).then((credential) => { if (!credential) { return; } @@ -117,7 +117,7 @@ function federatedSignIn() { navigator.credentials .get({ password: true, - federated: {providers: ['https://federation.com']} + federated: { providers: ['https://federation.com'] } }) .then((credential) => { if (!credential) return; @@ -141,7 +141,7 @@ function federatedSignIn() { const pwCred = credential as PasswordCredential; fetch( 'https://example.com/loginEndpoint', - {credentials: pwCred, method: 'POST'}); + { credentials: pwCred, method: 'POST' }); } }); } @@ -159,7 +159,7 @@ function passwordPostSignInConfirmation() { const formElem = (e.target as HTMLFormElement); const c = new PasswordCredential(formElem); - fetch(formElem.action, {method: 'POST', credentials: c}).then(r => { + fetch(formElem.action, { method: 'POST', credentials: c }).then(r => { if (r.status === 200) { navigator.credentials!.store(c); } @@ -172,7 +172,7 @@ function passwordPostSignInConfirmation() { function federationPostSignInConfirmation() { if (navigator.credentials) { navigator.credentials.store(new FederatedCredential( - {id: 'username', provider: 'https://federation.com'})); + { id: 'username', provider: 'https://federation.com' })); } } @@ -188,7 +188,7 @@ function existingFormPost(credential: PasswordCredential) { credential.passwordName = 'p'; fetch( 'https://example.com/loginEndpoint', - {credentials: credential, method: 'POST'}); + { credentials: credential, method: 'POST' }); } function additionalDataPost(credential: PasswordCredential, token: string) { @@ -196,14 +196,14 @@ function additionalDataPost(credential: PasswordCredential, token: string) { credential.additionalData.append('csrf', token); fetch( 'https://example.com/loginEndpoint', - {credentials: credential, method: 'POST'}); + { credentials: credential, method: 'POST' }); } function formEncodedPost(credential: PasswordCredential, token: string) { credential.additionalData = new URLSearchParams(); fetch( 'https://example.com/loginEndpoint', - {credentials: credential, method: 'POST'}); + { credentials: credential, method: 'POST' }); } // requireUserMediation example: not included in the spec, but included here @@ -236,7 +236,7 @@ function createPasswordCredential() { } navigator.credentials.create({ - password: {id: 'username', password: 'password'} + password: { id: 'username', password: 'password' } }).then((credential) => { // Credential created! }); @@ -266,7 +266,7 @@ function createFederatedCredential() { } navigator.credentials.create({ - federated: {id: 'username', provider: 'provider'} + federated: { id: 'username', provider: 'provider' } }).then((credential) => { // Credential created! }); @@ -293,7 +293,7 @@ function webauthnRegister() { }, challenge, pubKeyCredParams: [ - {type: 'public-key', alg: -7}, + { type: 'public-key', alg: -7 }, ], excludeCredentials: [ { @@ -329,16 +329,18 @@ function webauthnAuthenticate() { const challenge = new Uint8Array(32); window.crypto.getRandomValues(challenge); - const authPromise = navigator.credentials.get({publicKey: { - challenge, - timeout: 5000, - rpId: document.domain, - allowCredentials: [{ - type: "public-key", - id: credentialID, - transports: ['internal', 'ble', 'nfc', 'usb'] - }], - }}); + const authPromise = navigator.credentials.get({ + publicKey: { + challenge, + timeout: 5000, + rpId: document.domain, + allowCredentials: [{ + type: "public-key", + id: credentialID, + transports: ['internal', 'ble', 'nfc', 'usb'] + }], + } + }); authPromise.then((cred) => { if (cred === null) { @@ -352,3 +354,17 @@ function webauthnAuthenticate() { console.log(e.message); }); } + +function mockAuthenticatorAssertionResponse() { + if (!navigator.credentials) { + return; + } + + const sampleResponse: AuthenticatorAssertionResponse = { + clientDataJSON: new ArrayBuffer(0), + authenticatorData: new ArrayBuffer(0), + signature: new ArrayBuffer(0), + userHandle: null, + }; + sampleResponse.userHandle === undefined; +} diff --git a/types/webpack-dev-server/index.d.ts b/types/webpack-dev-server/index.d.ts index 48abc9a44c..30fd2482e7 100644 --- a/types/webpack-dev-server/index.d.ts +++ b/types/webpack-dev-server/index.d.ts @@ -5,6 +5,7 @@ // Zheyang Song <https://github.com/ZheyangSong> // Alan Agius <https://github.com/alan-agius4> // Artur Androsovych <https://github.com/arturovt> +// Dave Cardwell <https://github.com/davecardwell> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -165,6 +166,8 @@ declare namespace WebpackDevServer { watchContentBase?: boolean; /** Control options related to watching the files. */ watchOptions?: webpack.WatchOptions; + /** Tells devServer to write generated assets to the disk. */ + writeToDisk?: boolean | ((filePath: string) => boolean); } } diff --git a/types/webpack-dev-server/webpack-dev-server-tests.ts b/types/webpack-dev-server/webpack-dev-server-tests.ts index f570dd134e..755245b035 100644 --- a/types/webpack-dev-server/webpack-dev-server-tests.ts +++ b/types/webpack-dev-server/webpack-dev-server-tests.ts @@ -72,6 +72,7 @@ const config: WebpackDevServer.Configuration = { aggregateTimeout: 300, poll: 1000 }, + writeToDisk: true, // It's a required option. publicPath: "/assets/", headers: { "X-Custom-Header": "yes" } @@ -83,6 +84,9 @@ const c2: WebpackDevServer.Configuration = { const c3: WebpackDevServer.Configuration = { stats: "verbose", }; +const c4: WebpackDevServer.Configuration = { + writeToDisk: (filePath: string) => true, +}; // API example server = new WebpackDevServer(compiler, config); diff --git a/types/xrm/index.d.ts b/types/xrm/index.d.ts index 361e33bf92..61362fa208 100644 --- a/types/xrm/index.d.ts +++ b/types/xrm/index.d.ts @@ -4633,7 +4633,7 @@ declare namespace Xrm { * Invokes the device camera to capture an image. * @returns On success, returns Base64 encoded file */ - captureImage(imageOptions: Device.CaptureImageOptions): Async.PromiseLike<Device.CaptureFileResponse>; + captureImage(imageOptions?: Device.CaptureImageOptions): Async.PromiseLike<Device.CaptureFileResponse>; /** * Invokes the device camera to capture video. diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 9f3cb687a2..dc73ae6bd9 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -26,6 +26,7 @@ export function addMethod<T extends Schema<any>>( export function ref(path: string, options?: { contextPrefix: string }): Ref; export function lazy<T>(fn: (value: T) => Schema<T>): Lazy; export function setLocale(customLocale: LocaleObject): void; +export function isSchema(obj: any): obj is Schema<any>; export const mixed: MixedSchemaConstructor; export const string: StringSchemaConstructor; @@ -227,7 +228,7 @@ export interface TestContext { parent: any; schema: Schema<any>; resolve: (value: any) => any; - createError: (params: { path: string; message: string }) => ValidationError; + createError: (params?: { path?: string; message?: string }) => ValidationError; } export interface ValidateOptions { diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index a90a7df25d..c6717e95ad 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -3,6 +3,7 @@ import * as yup from "yup"; // tslint:disable-next-line:no-duplicate-imports import { reach, + isSchema, date, Schema, ObjectSchema, @@ -24,6 +25,10 @@ const schema1 = yup.object().shape({ reach(schema1, "nested.arr.num"); reach(schema1, "nested.arr[].num"); +// isSchema function +const isSchemaResult1: boolean = isSchema(schema1); +const isSchemaResult2: boolean = isSchema({}); + // addMethod function yup.addMethod<NumberSchema>(yup.number, "minimum", function( this, @@ -199,6 +204,12 @@ const testContext = function(this: TestContext) { this.resolve; // $ExpectType ValidationError this.createError({ path: "1", message: "1" }); + // $ExpectType ValidationError + this.createError({ message: "1" }); + // $ExpectType ValidationError + this.createError({ path: "1"}); + // $ExpectType ValidationError + this.createError(); return true; }; mixed.test("with-context", "it uses function context", testContext);