From 4ab95bd255d2c56c04fb52d6e5a0dcec34840238 Mon Sep 17 00:00:00 2001 From: bangbang93 Date: Thu, 5 Jul 2018 11:28:59 +0800 Subject: [PATCH 001/836] fix mockjs.Random.string() mockjs.Random.string() can be called without arguments. --- types/mockjs/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mockjs/index.d.ts b/types/mockjs/index.d.ts index a0ca673b0a..9be645b791 100644 --- a/types/mockjs/index.d.ts +++ b/types/mockjs/index.d.ts @@ -58,7 +58,7 @@ declare namespace mockjs { character(pool?: S): S; // Random.string - string(pool: S | N, min?: N, max?: N): S; + string(pool?: S | N, min?: N, max?: N): S; // Random.range range(start?: N, stop?: N, step?: N): N; From abdca373e90201f817c2b20643e01d03a1eb0697 Mon Sep 17 00:00:00 2001 From: ptrdu Date: Wed, 26 Sep 2018 17:12:52 +0800 Subject: [PATCH 002/836] FEAT: add bucket operations --- types/ali-oss/ali-oss-tests.ts | 3 + types/ali-oss/index.d.ts | 247 +++++++++++++++++++++++++++++++++ types/ali-oss/tsconfig.json | 23 +++ types/ali-oss/tslint.json | 79 +++++++++++ 4 files changed, 352 insertions(+) create mode 100644 types/ali-oss/ali-oss-tests.ts create mode 100644 types/ali-oss/index.d.ts create mode 100644 types/ali-oss/tsconfig.json create mode 100644 types/ali-oss/tslint.json diff --git a/types/ali-oss/ali-oss-tests.ts b/types/ali-oss/ali-oss-tests.ts new file mode 100644 index 0000000000..3cf3229da9 --- /dev/null +++ b/types/ali-oss/ali-oss-tests.ts @@ -0,0 +1,3 @@ +import OSS from "ali-oss"; + +const client = new OSS(); diff --git a/types/ali-oss/index.d.ts b/types/ali-oss/index.d.ts new file mode 100644 index 0000000000..b7c0f35067 --- /dev/null +++ b/types/ali-oss/index.d.ts @@ -0,0 +1,247 @@ +// Type definitions for ali-oss 6.0.1 +// Project: https://github.com/ali-sdk/ali-oss +// Definitions by: Ptrdu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.2.0 + +export type Bucket = { + +} + +export type StorageType = "Standard" | "IA" | "Archive" + +export type ACLType = "public-read-write" | "public-read" | "and private" + +export type RequestOptions = { + // the operation timeout + timeout?: number +} + +export type RuleStatusType = "Enabled" | "Disabled" + +export type LifecycleRule = { + id?: string, // rule id, if not set, OSS will auto create it with random string. + prefix: string, // store prefix + status: RuleStatusType, // rule status, allow values: Enabled or Disabled + days?: number | string, // expire after the days + date: string // expire date, e.g.: 2022-10-11T00:00:00.000Z date and days only set one. +} + +export type CORSRule = { + allowedOrigin: string | Array, // configure for Access-Control-Allow-Origin header + allowedMethod: string | Array, // configure for Access-Control-Allow-Methods header + allowedHeader?: string | Array, // configure for Access-Control-Allow-Headers header + exposeHeader?: string | Array, // configure for Access-Control-Expose-Headers header + maxAgeSeconds?: string | Array, // configure for Access-Control-Max-Age header +} + +export interface NormalSuccessResponse { + //response status + status: number, + // response headers + headers: object, // todo the object in detail + // response size + size: number, + // request total use time (ms) + rt: number +} + +export default class OSS { + /******************************************* the bucket operations *************************************************/ + // base operators + /** + * List buckets in this account. + * @param {{prefix?: string; marker?: string; "max-keys"?: string | number} | null} query - query parameters, default is null + * prefix - search buckets using prefix key + * marker - search start from marker, including marker key + * max-keys - max buckets, default is 100, limit to 1000 + * @param {{timeout?: number}} options - optional parameters + * timeout - the operation timeout + * @return {Promise>} + */ + listBuckets(query: { prefix?: string, marker?: string, 'max-keys'?: string | number } | null, options?: { timeout?: number }): Promise> + + /** + * Create a new bucket. + * @param {string} name - bucket name If bucket exists and not belong to current account, will throw BucketAlreadyExistsError. If bucket not exists, will create a new bucket and set it's ACL. + * @param {{timeout: number; storageClass: StorageType}} options - optional parameters + * timeout - the operation timeout + * StorageClass - the storage type include (Standard,IA,Archive) + * @return { Promise<{ bucket: string, res: NormalSuccessResponse }> } + */ + putBucket(name: string, options?: { timeout: number, storageClass: StorageType }): Promise<{ bucket: string, res: NormalSuccessResponse }> + + /** + * Use the bucket. + * @param {string} name - bucket name + */ + useBucket(name: string) : void + + /** + * Delete an empty bucket. + * @param {string} name - bucket name If bucket is not empty, will throw BucketNotEmptyError. If bucket is not exists, will throw NoSuchBucketError. + * @param {RequestOptions} options + * @return {Promise} + */ + deleteBucket(name: string, options?: RequestOptions): Promise + + /** + * Get bucket information,include CreationDate、ExtranetEndpoint、IntranetEndpoint、Location、Name、StorageClass、 Owner、AccessControlList + * @param {string} name - bucket name + * @return {Promise} // todo the official document miss the return type + */ + getBucketInfo(name: string): Promise + + /** + * Get bucket location + * @param {string} name - bucket name + * @return {Promise} // todo the official document miss the return type + */ + getBucketLocation(name: string): Promise + // ACL operations + /** + * Update the bucket ACL. + * @param {string} name - bucket name + * @param {ACLType} acl - access control list, current available: public-read-write, public-read and private + * @param {RequestOptions} options + * @return {Promise} + */ + putBucketACL(name: string, acl: ACLType, options?: RequestOptions): Promise + + /** + * Get the bucket ACL. + * @param {string} name - bucket name + * @param {RequestOptions} options + * @return {Promise<{ acl: string, res: NormalSuccessResponse }>} + * acl - acl settings string + */ + getBucketACL(name: string, options?: RequestOptions ): Promise<{ acl: string, res: NormalSuccessResponse }> + // logging operations + /** + * Update the bucket logging settings. Log file will create every one hour and name format: -YYYY-mm-DD-HH-MM-SS-UniqueString. + * @param {string} name - bucket name + * @param {string} prefix - prefix path name to store the log files + * @param {RequestOptions} options + * @return {Promise} + */ + putBucketLogging(name: string, prefix?: string, options?: RequestOptions): Promise + + /** + * Get the bucket logging settings. + * @param {string} name + * @param {RequestOptions} options + * @return {Promise<{ enable: boolean, prefix: string | null, res: NormalSuccessResponse }>} + */ + getBucketLogging(name: string, options?: RequestOptions): Promise<{ enable: boolean, prefix: string | null, res: NormalSuccessResponse }> + + /** + * Delete the bucket logging settings. + * @param {string} name - bucket name + * @param {RequestOptions} options + * @return {Promise} + */ + deleteBucketLogging(name: string, options?: RequestOptions) : Promise + // Website operations + /** + * Set the bucket as a static website. + * @param {string} name - bucket name + * @param {{index: string; error?: string}} config + * index - default page, e.g.: index.html + * error - error page, e.g.: 'error.html' + * @return {Promise} + */ + putBucketWebsite(name: string, config: { index: string, error?: string }): Promise + + /** + * Get the bucket website config. + * @param {string} name - bucket name + * @param {RequestOptions} options + * @return {Promise<{ index: string, error: string, res: NormalSuccessResponse }>} + */ + getBucketWebsite(name: string, options?: RequestOptions): Promise<{ index: string, error: string, res: NormalSuccessResponse }> + + /** + * Delete the bucket website config. + * @param {string} name - bucket name + * @param {RequestOptions} options + * @return {Promise} + */ + deleteBucketWebsite(name: string, options?: RequestOptions): Promise + // referer operations + /** + * Set the bucket request Referer white list. + * @param {string} name + * @param {boolean} allowEmpty - allow empty request referer or not + * @param {Array} referers - Referer white list, e.g.: ['https://npm.taobao.org', 'http://cnpmjs.org'] + * @param {RequestOptions} options + * @return {Promise} + */ + putBucketReferer(name: string, allowEmpty: boolean, referers: Array, options?: RequestOptions): Promise + + /** + * Get the bucket request Referer white list. + * @param {string} name - bucket name + * @param {RequestOptions} options + * @return {Promise<{ allowEmpty: boolean, referers: Array, res: NormalSuccessResponse }>} + */ + getBucketReferer(name: string, options?: RequestOptions): Promise<{ allowEmpty: boolean, referers: Array, res: NormalSuccessResponse }> + + /** + * Delete the bucket request Referer white list. + * @param {string} name + * @param {RequestOptions} options + * @return {Promise} + */ + deleteBucketReferer(name: string, options?: RequestOptions): Promise + // lifecycle operations + /** + * Set the bucket object lifecycle. + * @param {string} name + * @param {Array} rules - rule config list + * @param {RequestOptions} options + * @return {Promise} + */ + putBucketLifecycle(name: string, rules: Array, options?: RequestOptions): Promise + + /** + * Get the bucket object lifecycle. + * @param {string} name + * @param {RequestOptions} options + * @return {Promise<{ rules: Array, res: NormalSuccessResponse }>} + */ + getBucketLifecycle(name: string, options?: RequestOptions): Promise<{ rules: Array, res: NormalSuccessResponse }> + + /** + * Delete the bucket object lifecycle. + * @param {string} name + * @param {RequestOptions} options + * @return {Promise} + */ + deleteBucketLifecycle(name: string, options?: RequestOptions): Promise + // CORS operations + /** + * Set CORS rules of the bucket object + * @param {string} name + * @param {Array} rules + * @param {RequestOptions} options + * @return {Promise} + */ + putBucketCORS(name: string, rules: Array, options?: RequestOptions): Promise + + /** + * Get CORS rules of the bucket object. + * @param {string} name + * @return {Promise<{rules: Array; res: NormalSuccessResponse}>} + */ + getBucketCORS(name: string): Promise<{ rules: Array, res: NormalSuccessResponse}> + + /** + * Delete CORS rules of the bucket object. + * @param {string} name + * @return {Promise} + */ + deleteBucketCORS(name: string): Promise + + /********************************************************** Object operations ********************************************/ + +} diff --git a/types/ali-oss/tsconfig.json b/types/ali-oss/tsconfig.json new file mode 100644 index 0000000000..a3e68ada2b --- /dev/null +++ b/types/ali-oss/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ali-oss-tests.ts" + ] +} diff --git a/types/ali-oss/tslint.json b/types/ali-oss/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/ali-oss/tslint.json @@ -0,0 +1,79 @@ +{ + "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 + } +} From 3e6f81d1563df1c7a81548935eec22606469a106 Mon Sep 17 00:00:00 2001 From: ptrdu Date: Thu, 27 Sep 2018 11:14:53 +0800 Subject: [PATCH 003/836] FEAT: add function definition, current at object uploadPartCopy --- types/ali-oss/index.d.ts | 417 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 398 insertions(+), 19 deletions(-) diff --git a/types/ali-oss/index.d.ts b/types/ali-oss/index.d.ts index b7c0f35067..85708838d3 100644 --- a/types/ali-oss/index.d.ts +++ b/types/ali-oss/index.d.ts @@ -4,6 +4,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.2.0 +// general type + export type Bucket = { } @@ -12,6 +14,8 @@ export type StorageType = "Standard" | "IA" | "Archive" export type ACLType = "public-read-write" | "public-read" | "and private" +export type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT"; + export type RequestOptions = { // the operation timeout timeout?: number @@ -35,7 +39,22 @@ export type CORSRule = { maxAgeSeconds?: string | Array, // configure for Access-Control-Max-Age header } -export interface NormalSuccessResponse { +export type OwnerType = { + id: string, + displayName: string +} + +export type ObjectMeta = { + name: string, // object name on oss + lastModified: string, // object last modified GMT date, e.g.: 2015-02-19T08:39:44.000Z + etag: string, // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" + type: string, // object type, e.g.: Normal + size: number, // object size, e.g.: 344606 + storageClass: StorageType, + owner: OwnerType, +} + +export type NormalSuccessResponse = { //response status status: number, // response headers @@ -46,36 +65,215 @@ export interface NormalSuccessResponse { rt: number } +export type UserMeta = { + uid: number, + pid: number +} + +export type ObjectCallback = { + url: string, // After a file is uploaded successfully, the OSS sends a callback request to this URL. + host?: string, // The host header value for initiating callback requests. + body: string, // The value of the request body when a callback is initiated, for example, key=$(key)&etag=$(etag)&my_var=$(x:my_var). + contentType?: string, // The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value. + customValue?: object, + headers?: object // extra headers, detail see RFC 2616 +} + +export type ModifyData = { + lastModified: string, // object last modified GMT string + etag: string // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" +} + +// parameters type +export type ListBucketsQueryType = { + prefix?: string, // search buckets using prefix key + marker?: string, // search start from marker, including marker key + 'max-keys'?: string | number // max buckets, default is 100, limit to 1000 +} + +export type PutBucketOptions = { + timeout: number, + storageClass: StorageType +} + +export type PutBucketWebsiteConfig = { + index: string, // default page, e.g.: index.html + error?: string // error page, e.g.: 'error.html' +} + +export type ListObjectsQuery = { + prefix?: string, // search object using prefix key + marker?: string, // search start from marker, including marker key + delimiter?: string, // delimiter search scope e.g. / only search current dir, not including subdir + 'max-keys': string | number // max objects, default is 100, limit to 1000 +} + +export type ListObjectResult = { + objects: Array, + prefixes: Array, + isTruncated: boolean, + nextMarker: string, + res: NormalSuccessResponse +} + +export type PutObjectOptions = { + timeout?: number, // the operation timeout + mime?: string, // custom mime, will send with Content-Type entity header + meta?: UserMeta, // user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 } + callback: ObjectCallback, +} + +export type PutObjectResult = { + name: string, + data: object, + res: NormalSuccessResponse +} + +export type PutStreamOptions = { + contentLength?: number, // the stream length, chunked encoding will be used if absent + timeout: number, // the operation timeout + mime: string, // custom mime, will send with Content-Type entity header + meta: UserMeta, + callback: ObjectCallback +} + +export type AppendObjectOptions = { + position?: string, // specify the position which is the content length of the latest object + timeout?: number, // the operation timeout + mime?: string, // custom mime, will send with Content-Type entity header + meta?: UserMeta, + headers?: object +} + +export type AppendObjectResult = { + name: string, + url: string, // the url of oss + res: NormalSuccessResponse, + nextAppendPosition: string, // the next position +} + +export type HeadObjectOptions = { + timeout?: number, + headers?: object +} + +export type HeadObjectResult = { + status: number, // response status, maybe 200 or 304 + meta: UserMeta, + res: NormalSuccessResponse +} + +export type GetObjectOptions = { + timeout?: number, + process?: string, // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} + headers?: object +} + +export type GetObjectResult = { + content?: any, // file content buffer if file parameter is null or ignore + res: NormalSuccessResponse +} + +export type GetStreamOptions = { + timeout?: number, + process?: string, // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} + headers?: object +} + +export type GetStreamResult = { + stream?: any, // readable stream instance if response status is not 200, stream will be null. + res: NormalSuccessResponse +} + +export type CopyObjectOptions = { + timeout?: number, + meta?: UserMeta, + headers?: object +} + +export type CopyAndPutMetaResult = { + data: ModifyData, + res: NormalSuccessResponse +} + +export type DeleteMultiOptions = { + quite?: boolean // quiet mode or verbose mode, default is false, verbose mode quiet mode: if all objects delete succes, return emtpy response. otherwise return delete error object results. verbose mode: return all object delete results. + timeout?: number +} + +export type DeleteMultiResult = { + deleted?: Array // deleted object names list + res: NormalSuccessResponse +} + +export type ResponseHeaderType = { + 'content-type'?: string, + 'content-disposition'? :string, + 'cache-control'?: string +} + +export type SignatureUrlOptions = { + expires?: number, // after expires seconds, the url will become invalid, default is 1800 + method?: HTTPMethods, // the HTTP method, default is 'GET' + 'Content-Type'?: string, // set the request content type + process?: string, + response?: ResponseHeaderType, // set the response headers for download + callback?: ObjectCallback +} + +export type GetACLResult = { + acl: ACLType, + res: NormalSuccessResponse +} + +export type InitMultipartUploadOptions = { + timeout?: number, + mime?: string, // Mime file type + meta?: UserMeta, + headers?: object +} + +export type InitMultipartUploadResult = { + res: { status: number, headers: object, size: number, rt: number } + bucket: string, // bucket name + name: string, // object name store on OSS + uploadId: string, // upload id, use for uploadPart, completeMultipart +} + +export type UploadPartResult = { + name: string, + etag: string, + res: NormalSuccessResponse +} + export default class OSS { + // the image client + static ImageClient: any /******************************************* the bucket operations *************************************************/ + // base operators /** * List buckets in this account. - * @param {{prefix?: string; marker?: string; "max-keys"?: string | number} | null} query - query parameters, default is null - * prefix - search buckets using prefix key - * marker - search start from marker, including marker key - * max-keys - max buckets, default is 100, limit to 1000 - * @param {{timeout?: number}} options - optional parameters + * @param {ListBucketsQueryType | null} query - query parameters, default is null + * @param {RequestOptions} options - optional parameters * timeout - the operation timeout * @return {Promise>} */ - listBuckets(query: { prefix?: string, marker?: string, 'max-keys'?: string | number } | null, options?: { timeout?: number }): Promise> + listBuckets(query: ListBucketsQueryType | null, options?: RequestOptions): Promise> /** * Create a new bucket. * @param {string} name - bucket name If bucket exists and not belong to current account, will throw BucketAlreadyExistsError. If bucket not exists, will create a new bucket and set it's ACL. - * @param {{timeout: number; storageClass: StorageType}} options - optional parameters - * timeout - the operation timeout - * StorageClass - the storage type include (Standard,IA,Archive) + * @param {PutBucketOptions} options - optional parameters * @return { Promise<{ bucket: string, res: NormalSuccessResponse }> } */ - putBucket(name: string, options?: { timeout: number, storageClass: StorageType }): Promise<{ bucket: string, res: NormalSuccessResponse }> + putBucket(name: string, options?: PutBucketOptions): Promise<{ bucket: string, res: NormalSuccessResponse }> /** * Use the bucket. * @param {string} name - bucket name */ - useBucket(name: string) : void + useBucket(name: string): void /** * Delete an empty bucket. @@ -98,6 +296,7 @@ export default class OSS { * @return {Promise} // todo the official document miss the return type */ getBucketLocation(name: string): Promise + // ACL operations /** * Update the bucket ACL. @@ -115,7 +314,8 @@ export default class OSS { * @return {Promise<{ acl: string, res: NormalSuccessResponse }>} * acl - acl settings string */ - getBucketACL(name: string, options?: RequestOptions ): Promise<{ acl: string, res: NormalSuccessResponse }> + getBucketACL(name: string, options?: RequestOptions): Promise<{ acl: string, res: NormalSuccessResponse }> + // logging operations /** * Update the bucket logging settings. Log file will create every one hour and name format: -YYYY-mm-DD-HH-MM-SS-UniqueString. @@ -140,17 +340,16 @@ export default class OSS { * @param {RequestOptions} options * @return {Promise} */ - deleteBucketLogging(name: string, options?: RequestOptions) : Promise + deleteBucketLogging(name: string, options?: RequestOptions): Promise + // Website operations /** * Set the bucket as a static website. * @param {string} name - bucket name - * @param {{index: string; error?: string}} config - * index - default page, e.g.: index.html - * error - error page, e.g.: 'error.html' + * @param {PutBucketWebsiteConfig} config * @return {Promise} */ - putBucketWebsite(name: string, config: { index: string, error?: string }): Promise + putBucketWebsite(name: string, config: PutBucketWebsiteConfig): Promise /** * Get the bucket website config. @@ -167,6 +366,7 @@ export default class OSS { * @return {Promise} */ deleteBucketWebsite(name: string, options?: RequestOptions): Promise + // referer operations /** * Set the bucket request Referer white list. @@ -193,6 +393,7 @@ export default class OSS { * @return {Promise} */ deleteBucketReferer(name: string, options?: RequestOptions): Promise + // lifecycle operations /** * Set the bucket object lifecycle. @@ -218,6 +419,7 @@ export default class OSS { * @return {Promise} */ deleteBucketLifecycle(name: string, options?: RequestOptions): Promise + // CORS operations /** * Set CORS rules of the bucket object @@ -233,7 +435,7 @@ export default class OSS { * @param {string} name * @return {Promise<{rules: Array; res: NormalSuccessResponse}>} */ - getBucketCORS(name: string): Promise<{ rules: Array, res: NormalSuccessResponse}> + getBucketCORS(name: string): Promise<{ rules: Array, res: NormalSuccessResponse }> /** * Delete CORS rules of the bucket object. @@ -243,5 +445,182 @@ export default class OSS { deleteBucketCORS(name: string): Promise /********************************************************** Object operations ********************************************/ + /** + * List objects in the bucket. + * @param {ListObjectsQuery | null} query + * @param {RequestOptions} options + * @return {Promise} + */ + list(query: ListObjectsQuery | null, options: RequestOptions): Promise + + /** + * Add an object to the bucket. + * @param {string} name - object name store on OSS + * @param file - {String|Buffer|ReadStream|File(only support Browser)|Blob(only support Browser)} object local path, content buffer or ReadStream content instance use in Node, Blob and html5 File + * @param {PutObjectOptions} options - optional parameters + * @return {Promise} + */ + put(name: string, file: any, options?: PutObjectOptions): Promise + + /** + * Add a stream object to the bucket. + * @param {string} name - object name store on OSS + * @param stream - object ReadStream content instance + * @param {PutStreamOptions} options - optional parameters + * @return {Promise<{name: string; res: NormalSuccessResponse}>} + */ + putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }> + + /** + * Append an object to the bucket, it's almost same as put, but it can add content to existing object rather than override it. + * @param {string} name + * @param file + * @param {AppendObjectOptions} options + * @return {Promise} + */ + append(name: string, file: any, options?: AppendObjectOptions): Promise + + /** + * Get the Object url. If provide baseUrl, will use baseUrl instead the default endpoint. + * @param {string} name + * @param {string} baseUrl + * @return {string} + */ + getObjectUrl(name: string, baseUrl?: string): string + + /** + * Get the Object url. If provide baseUrl, will use baseUrl instead the default bucket and endpoint. Suggest use generateObjectUrl instead of getObjectUrl. + * @param {string} name + * @param {string} baseUrl + * @return {string} + */ + generateObjectUrl(name: string, baseUrl?: string): string + + /** + * Head an object and get the meta info. + * @param {string} name + * @param {HeadObjectOptions} options + * @return {Promise} + */ + head(name: string, options?: HeadObjectOptions): Promise + + /** + * Get an object from the bucket. + * @param {string} name + * @param file - {String|WriteStream} file path or WriteStream instance to store the content If file is null or ignore this parameter, function will return info contains content property. + * @param {GetObjectOptions} options + * @return {Promise} + */ + get(name: string, file?: any, options?: GetObjectOptions): Promise + + /** + * Get an object read stream. + * @param {string} name + * @param {GetStreamOptions} options + * @return {Promise} + */ + getStream(name?: string, options?: GetStreamOptions): Promise + + /** + * Delete an object from the bucket. + * @param {string} name + * @param {RequestOptions} options + * @return {Promise} + */ + delete(name: string, options?: RequestOptions): Promise + + /** + * Copy an object from sourceName to name. + * @param {string} name - object name store on OSS + * @param {string} sourceName - source object name If sourceName start with /, meaning it's a full name contains the bucket name. e.g.: /otherbucket/logo.png meaning copy otherbucket logn.png object to current bucket. + * @param {CopyObjectOptions} options + * @return {Promise} + */ + copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise + + /** + * Set an exists object meta. + * @param {string} name + * @param {UserMeta} meta + * @param {RequestOptions} options + * @return {Promise} + */ + putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise + + /** + * Delete multi objects in one request. + * @param {Array} names - object names, max 1000 objects in once. + * @param {DeleteMultiOptions} options + * @return {Promise} + */ + deleteMulti(names: Array, options?: DeleteMultiOptions): Promise + + /** + * Create a signature url for download or upload object. When you put object with signatureUrl ,you need to pass Content-Type.Please look at the example. + * @param {string} name + * @param {SignatureUrlOptions} options + * @return {string} + */ + signatureUrl(name: string, options?: SignatureUrlOptions): string + + /** + * Set object's ACL. + * @param {string} name + * @param {ACLType} acl + * @param {RequestOptions} options + * @return {Promise} + */ + putACL(name: string, acl: ACLType, options?: RequestOptions): Promise + + /** + * Get object's ACL. + * @param {string} name + * @param {RequestOptions} options + * @return {Promise} + */ + getACL(name:string, options?: RequestOptions): Promise + + /** + * Restore Object. + * @param {string} name + * @param {RequestOptions} options + * @return {Promise} + */ + restore(name: string, options?: RequestOptions): Promise + + /** + * + * @param {string} name + * @param {InitMultipartUploadOptions} options + * @return {Promise} + */ + initMultipartUpload(name: string, options?: InitMultipartUploadOptions): Promise + + /** + * After initiating a Multipart Upload event, you can upload data in parts based on the specified object name and Upload ID. + * @param {string} name - object name + * @param {string} uploadId - get by initMultipartUpload api + * @param {number} partNo - range is 1-10000, If this range is exceeded, OSS returns the InvalidArgument's error code. + * @param file - is File or FileName, the whole file + Multipart Upload requires that the size of any Part other than the last Part is greater than 100KB. + In Node you can use File or FileName, but in browser you only can use File. + * @param {number} start - part start bytes e.g: 102400 + * @param {number} end - part end bytes e.g: 204800 + * @param {RequestOptions} options + * @return {Promise} + */ + uploadPart(name: string, uploadId: string, partNo: number, file: any, start: number, end: number, options?: RequestOptions): Promise + + /** + * Using Upload Part Copy, you can copy data from an existing object and upload a part of the data. When copying a file larger than 1 GB, you must use the Upload Part Copy method. If you want to copy a file smaller than 1 GB, see Copy Object. + * @param {string} name + * @param {string} uploadId + * @param {number} partNo + * @param {string} range + * @param {{sourceKey: string; sourceBucketName: string}} sourceData + * @param {{timeout?: number; headers?: object}} options + * @return {Promise} + */ + uploadPartCopy(name: string, uploadId: string, partNo: number, range: string, sourceData: { sourceKey: string, sourceBucketName: string }, options: { timeout?: number, headers?: object }): Promise } From 5992ddd064ff74c68e9c32c13fc823ca31a51744 Mon Sep 17 00:00:00 2001 From: ptrdu Date: Thu, 27 Sep 2018 15:09:50 +0800 Subject: [PATCH 004/836] FEAT: add object operations definitions --- types/ali-oss/index.d.ts | 165 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 165 insertions(+) diff --git a/types/ali-oss/index.d.ts b/types/ali-oss/index.d.ts index 85708838d3..fc0ff41ae1 100644 --- a/types/ali-oss/index.d.ts +++ b/types/ali-oss/index.d.ts @@ -84,6 +84,28 @@ export type ModifyData = { etag: string // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" } +export type Checkpoint = { + file: any, // The file object selected by the user, if the browser is restarted, it needs the user to manually trigger the settings + name: string, // object key + fileSize: number, + partSize: number, + uploadId: string, + doneParts: Array<{ number: number, etag: string }> +} + +export type ObjectPart = { + PartNumber: number, + LastModified: any, // {Date} Time when a part is uploaded. + ETag: string, + size: number +} + +export type Upload = { + name: string, + uploadId: string, + initiated: any +} + // parameters type export type ListBucketsQueryType = { prefix?: string, // search buckets using prefix key @@ -246,6 +268,89 @@ export type UploadPartResult = { res: NormalSuccessResponse } +export type CompleteMultipartUploadOptions = { + timeout?: number, + callback?: ObjectCallback, + headers?: object +} + +export type CompleteMultipartUploadResult = { + bucket: string, + name: string, + etag: string, + data: object, + res: NormalSuccessResponse +} + +export type MultipartUploadOptions = { + parallel?: number, // the number of parts to be uploaded in parallel + partSize?: number, // the suggested size for each part + progress?: Function, // the progress callback called after each successful upload of one part, it will be given three parameters: (percentage {Number}, checkpoint {Object}, res {Object}) + checkpoint?: Checkpoint, // the checkpoint to resume upload, if this is provided, it will continue the upload from where interrupted, otherwise a new multipart upload will be created. + meta?: UserMeta, + mime?: string, + callback?: ObjectCallback, + headers?: object, + timeout?: number + copyheaders?: object, // {Object} only uploadPartCopy api used, detail +} + +export type MultipartUploadResult = { + bucket: string, + name: string, + etag: string, + data: object, + res: NormalSuccessResponse +} + +export type MultipartUploadCopyResult = { + bucket: string, + name: string, + etag: string, + res: NormalSuccessResponse +} + +export type MultipartUploadCopySourceData = { + sourceKey: string, // the source object name + sourceBucketName: string, // sourceData. the source bucket name + startOffset: number, // data copy start byte offset, e.g: 0 + endOffset: number // data copy end byte offset, e.g: 102400 +} + +export type ListPartsQuery = { + 'max-parts': number, // The maximum part number in the response of the OSS. default value: 1000. + 'part-number-marker': number, // Starting position of a specific list. A part is listed only when the part number is greater than the value of this parameter. + 'encoding-type': string // Specify the encoding of the returned content and the encoding type. Optional value: url +} + +export type ListPartsResult = { + uploadId: string, + bucket: string, + name: string, + PartNumberMarker: number, + nextPartNumberMarker: number, + maxParts: number, + isTruncated: boolean, + parts: Array, + res: NormalSuccessResponse +} + +export type ListUploadsQuery = { + prefix?: string, + 'max-uploads'?: number, + 'key-marker'?: string, + 'upload-id-marker'?: string +} + +export type ListUploadsResult = { + res: NormalSuccessResponse, + bucket: string, + nextKeyMarker: any, + nextUploadIdMarker: any, + isTruncated: boolean, + uploads: Array +} + export default class OSS { // the image client static ImageClient: any @@ -623,4 +728,64 @@ export default class OSS { */ uploadPartCopy(name: string, uploadId: string, partNo: number, range: string, sourceData: { sourceKey: string, sourceBucketName: string }, options: { timeout?: number, headers?: object }): Promise + /** + * After uploading all data parts, you must call the Complete Multipart Upload API to complete Multipart Upload for the entire file. + * @param {string} name + * @param {string} uploadId + * @param {Array<{number: number; etag: string}>} parts + * @param {CompleteMultipartUploadOptions} options + * @return {Promise} + */ + completeMultipartUpload(name: string, uploadId: string, parts: Array<{ number: number, etag: string }>, options?:CompleteMultipartUploadOptions): Promise + + /** + * Upload file with OSS multipart. + * this function contains initMultipartUpload, uploadPart, completeMultipartUpload. When you use multipartUpload api,if you encounter problems with ConnectionTimeoutError, you should handle ConnectionTimeoutError in your business code. + * How to resolve ConnectionTimeoutError, you can decrease partSize size 、 Increase timeout 、Retry request , or give tips in your business code; + * @param {string} name + * @param file + * @param {MultipartUploadOptions} options + * @return {Promise} + */ + multipartUpload(name: string, file: any, options: MultipartUploadOptions): Promise + + /** + * Copy file with OSS multipart. + * this function contains head, initMultipartUpload, uploadPartCopy, completeMultipartUpload. + * When copying a file larger than 1 GB, you should use the Upload Part Copy method. If you want to copy a file smaller than 1 GB, see Copy Object. + * @param {string} name + * @param {MultipartUploadCopySourceData} sourceData + * @param {MultipartUploadOptions} options + * @return {Promise} + */ + multipartUploadCopy(name: string, sourceData: MultipartUploadCopySourceData, options?: MultipartUploadOptions): Promise + + /** + * The ListParts command can be used to list all successfully uploaded parts mapped to a specific upload ID, i.e.: those not completed and not aborted. + * @param {string} name + * @param {string} uploadId + * @param {ListPartsQuery} query + * @param {RequestOptions} options + * @return {Promise} + */ + listParts(name: string, uploadId: string, query?: ListPartsQuery, options?: RequestOptions): Promise + + /** + * List on-going multipart uploads, i.e.: those not completed and not aborted. + * @param {ListUploadsQuery} query + * @param {RequestOptions} options + * @return {Promise} + */ + listUploads(query: ListUploadsQuery, options?: RequestOptions): Promise + + /** + * Abort a multipart upload for object. + * @param {string} name + * @param {string} uploadId + * @param {RequestOptions} options + * @return {Promise} + */ + abortMultipartUpload(name: string, uploadId: string, options?: RequestOptions): Promise + + /************************************************ RTMP Operations *************************************************************/ } From eea11d19fe8fb925d07ef1fd4ed19308a2b43ffc Mon Sep 17 00:00:00 2001 From: ptrdu Date: Thu, 27 Sep 2018 16:30:04 +0800 Subject: [PATCH 005/836] FEATURE: add rtmp operations definition --- types/ali-oss/ali-oss-tests.ts | 8 +- types/ali-oss/index.d.ts | 257 ++++++++++++++++++++++++++------- 2 files changed, 213 insertions(+), 52 deletions(-) diff --git a/types/ali-oss/ali-oss-tests.ts b/types/ali-oss/ali-oss-tests.ts index 3cf3229da9..82941c1e5e 100644 --- a/types/ali-oss/ali-oss-tests.ts +++ b/types/ali-oss/ali-oss-tests.ts @@ -1,3 +1,9 @@ import OSS from "ali-oss"; -const client = new OSS(); +const client = new OSS({ + accessKeyId: 'your access key', + accessKeySecret: 'your access secret', + bucket: 'your bucket name', + region: 'oss-cn-hangzhou' +}); + diff --git a/types/ali-oss/index.d.ts b/types/ali-oss/index.d.ts index fc0ff41ae1..9f5530db71 100644 --- a/types/ali-oss/index.d.ts +++ b/types/ali-oss/index.d.ts @@ -6,7 +6,19 @@ // general type -export type Bucket = { +export interface Options { + accessKeyId: string, // access secret you create + accessKeySecret: string, // access secret you create + stsToken?: string, // used by temporary authorization + bucket?: string, // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. + endpoint?: string, // oss region domain. It takes priority over region. + region?: string, // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou. + internal?: boolean, // access OSS with aliyun internal network or not, default is false. If your servers are running on aliyun too, you can set true to save lot of money. + secure?: boolean, // instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol. + timeout?: string | number // instance level timeout for all operations, default is 60s +} + +export type Bucket = { } @@ -16,14 +28,14 @@ export type ACLType = "public-read-write" | "public-read" | "and private" export type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT"; -export type RequestOptions = { +export interface RequestOptions { // the operation timeout timeout?: number } export type RuleStatusType = "Enabled" | "Disabled" -export type LifecycleRule = { +export interface LifecycleRule { id?: string, // rule id, if not set, OSS will auto create it with random string. prefix: string, // store prefix status: RuleStatusType, // rule status, allow values: Enabled or Disabled @@ -31,7 +43,7 @@ export type LifecycleRule = { date: string // expire date, e.g.: 2022-10-11T00:00:00.000Z date and days only set one. } -export type CORSRule = { +export interface CORSRule { allowedOrigin: string | Array, // configure for Access-Control-Allow-Origin header allowedMethod: string | Array, // configure for Access-Control-Allow-Methods header allowedHeader?: string | Array, // configure for Access-Control-Allow-Headers header @@ -39,12 +51,12 @@ export type CORSRule = { maxAgeSeconds?: string | Array, // configure for Access-Control-Max-Age header } -export type OwnerType = { +export interface OwnerType { id: string, displayName: string } -export type ObjectMeta = { +export interface ObjectMeta { name: string, // object name on oss lastModified: string, // object last modified GMT date, e.g.: 2015-02-19T08:39:44.000Z etag: string, // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" @@ -54,7 +66,7 @@ export type ObjectMeta = { owner: OwnerType, } -export type NormalSuccessResponse = { +export interface NormalSuccessResponse { //response status status: number, // response headers @@ -65,12 +77,12 @@ export type NormalSuccessResponse = { rt: number } -export type UserMeta = { +export interface UserMeta { uid: number, pid: number } -export type ObjectCallback = { +export interface ObjectCallback { url: string, // After a file is uploaded successfully, the OSS sends a callback request to this URL. host?: string, // The host header value for initiating callback requests. body: string, // The value of the request body when a callback is initiated, for example, key=$(key)&etag=$(etag)&my_var=$(x:my_var). @@ -79,12 +91,12 @@ export type ObjectCallback = { headers?: object // extra headers, detail see RFC 2616 } -export type ModifyData = { +export interface ModifyData { lastModified: string, // object last modified GMT string etag: string // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" } -export type Checkpoint = { +export interface Checkpoint { file: any, // The file object selected by the user, if the browser is restarted, it needs the user to manually trigger the settings name: string, // object key fileSize: number, @@ -93,44 +105,58 @@ export type Checkpoint = { doneParts: Array<{ number: number, etag: string }> } -export type ObjectPart = { +export interface ObjectPart { PartNumber: number, LastModified: any, // {Date} Time when a part is uploaded. ETag: string, size: number } -export type Upload = { +export interface Upload { name: string, uploadId: string, initiated: any } +export interface Channel { + Name: string, + Description: string, + Status: string, + LastModified: string, + PublishUrls: Array, + PlayUrls: Array +} + +export interface ChannelHistory { + StartTime: string, // + EndTime: string, + RemoteAddr: string // the remote addr +} // parameters type -export type ListBucketsQueryType = { +export interface ListBucketsQueryType { prefix?: string, // search buckets using prefix key marker?: string, // search start from marker, including marker key 'max-keys'?: string | number // max buckets, default is 100, limit to 1000 } -export type PutBucketOptions = { +export interface PutBucketOptions { timeout: number, storageClass: StorageType } -export type PutBucketWebsiteConfig = { +export interface PutBucketWebsiteConfig { index: string, // default page, e.g.: index.html error?: string // error page, e.g.: 'error.html' } -export type ListObjectsQuery = { +export interface ListObjectsQuery { prefix?: string, // search object using prefix key marker?: string, // search start from marker, including marker key delimiter?: string, // delimiter search scope e.g. / only search current dir, not including subdir 'max-keys': string | number // max objects, default is 100, limit to 1000 } -export type ListObjectResult = { +export interface ListObjectResult { objects: Array, prefixes: Array, isTruncated: boolean, @@ -138,20 +164,20 @@ export type ListObjectResult = { res: NormalSuccessResponse } -export type PutObjectOptions = { +export interface PutObjectOptions { timeout?: number, // the operation timeout mime?: string, // custom mime, will send with Content-Type entity header meta?: UserMeta, // user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 } callback: ObjectCallback, } -export type PutObjectResult = { +export interface PutObjectResult { name: string, data: object, res: NormalSuccessResponse } -export type PutStreamOptions = { +export interface PutStreamOptions { contentLength?: number, // the stream length, chunked encoding will be used if absent timeout: number, // the operation timeout mime: string, // custom mime, will send with Content-Type entity header @@ -159,7 +185,7 @@ export type PutStreamOptions = { callback: ObjectCallback } -export type AppendObjectOptions = { +export interface AppendObjectOptions { position?: string, // specify the position which is the content length of the latest object timeout?: number, // the operation timeout mime?: string, // custom mime, will send with Content-Type entity header @@ -167,74 +193,74 @@ export type AppendObjectOptions = { headers?: object } -export type AppendObjectResult = { +export interface AppendObjectResult { name: string, url: string, // the url of oss res: NormalSuccessResponse, nextAppendPosition: string, // the next position } -export type HeadObjectOptions = { +export interface HeadObjectOptions { timeout?: number, headers?: object } -export type HeadObjectResult = { +export interface HeadObjectResult { status: number, // response status, maybe 200 or 304 meta: UserMeta, res: NormalSuccessResponse } -export type GetObjectOptions = { +export interface GetObjectOptions { timeout?: number, process?: string, // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} headers?: object } -export type GetObjectResult = { +export interface GetObjectResult { content?: any, // file content buffer if file parameter is null or ignore res: NormalSuccessResponse } -export type GetStreamOptions = { +export interface GetStreamOptions { timeout?: number, process?: string, // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} headers?: object } -export type GetStreamResult = { +export interface GetStreamResult { stream?: any, // readable stream instance if response status is not 200, stream will be null. res: NormalSuccessResponse } -export type CopyObjectOptions = { +export interface CopyObjectOptions { timeout?: number, meta?: UserMeta, headers?: object } -export type CopyAndPutMetaResult = { +export interface CopyAndPutMetaResult { data: ModifyData, res: NormalSuccessResponse } -export type DeleteMultiOptions = { +export interface DeleteMultiOptions { quite?: boolean // quiet mode or verbose mode, default is false, verbose mode quiet mode: if all objects delete succes, return emtpy response. otherwise return delete error object results. verbose mode: return all object delete results. timeout?: number } -export type DeleteMultiResult = { +export interface DeleteMultiResult { deleted?: Array // deleted object names list res: NormalSuccessResponse } -export type ResponseHeaderType = { +export interface ResponseHeaderType { 'content-type'?: string, 'content-disposition'? :string, 'cache-control'?: string } -export type SignatureUrlOptions = { +export interface SignatureUrlOptions { expires?: number, // after expires seconds, the url will become invalid, default is 1800 method?: HTTPMethods, // the HTTP method, default is 'GET' 'Content-Type'?: string, // set the request content type @@ -243,38 +269,38 @@ export type SignatureUrlOptions = { callback?: ObjectCallback } -export type GetACLResult = { +export interface GetACLResult { acl: ACLType, res: NormalSuccessResponse } -export type InitMultipartUploadOptions = { +export interface InitMultipartUploadOptions { timeout?: number, mime?: string, // Mime file type meta?: UserMeta, headers?: object } -export type InitMultipartUploadResult = { +export interface InitMultipartUploadResult { res: { status: number, headers: object, size: number, rt: number } bucket: string, // bucket name name: string, // object name store on OSS uploadId: string, // upload id, use for uploadPart, completeMultipart } -export type UploadPartResult = { +export interface UploadPartResult { name: string, etag: string, res: NormalSuccessResponse } -export type CompleteMultipartUploadOptions = { +export interface CompleteMultipartUploadOptions { timeout?: number, callback?: ObjectCallback, headers?: object } -export type CompleteMultipartUploadResult = { +export interface CompleteMultipartUploadResult { bucket: string, name: string, etag: string, @@ -282,7 +308,7 @@ export type CompleteMultipartUploadResult = { res: NormalSuccessResponse } -export type MultipartUploadOptions = { +export interface MultipartUploadOptions { parallel?: number, // the number of parts to be uploaded in parallel partSize?: number, // the suggested size for each part progress?: Function, // the progress callback called after each successful upload of one part, it will be given three parameters: (percentage {Number}, checkpoint {Object}, res {Object}) @@ -295,7 +321,7 @@ export type MultipartUploadOptions = { copyheaders?: object, // {Object} only uploadPartCopy api used, detail } -export type MultipartUploadResult = { +export interface MultipartUploadResult { bucket: string, name: string, etag: string, @@ -303,27 +329,27 @@ export type MultipartUploadResult = { res: NormalSuccessResponse } -export type MultipartUploadCopyResult = { +export interface MultipartUploadCopyResult { bucket: string, name: string, etag: string, res: NormalSuccessResponse } -export type MultipartUploadCopySourceData = { +export interface MultipartUploadCopySourceData { sourceKey: string, // the source object name sourceBucketName: string, // sourceData. the source bucket name startOffset: number, // data copy start byte offset, e.g: 0 endOffset: number // data copy end byte offset, e.g: 102400 } -export type ListPartsQuery = { +export interface ListPartsQuery { 'max-parts': number, // The maximum part number in the response of the OSS. default value: 1000. 'part-number-marker': number, // Starting position of a specific list. A part is listed only when the part number is greater than the value of this parameter. 'encoding-type': string // Specify the encoding of the returned content and the encoding type. Optional value: url } -export type ListPartsResult = { +export interface ListPartsResult { uploadId: string, bucket: string, name: string, @@ -335,14 +361,14 @@ export type ListPartsResult = { res: NormalSuccessResponse } -export type ListUploadsQuery = { +export interface ListUploadsQuery { prefix?: string, 'max-uploads'?: number, 'key-marker'?: string, 'upload-id-marker'?: string } -export type ListUploadsResult = { +export interface ListUploadsResult { res: NormalSuccessResponse, bucket: string, nextKeyMarker: any, @@ -351,9 +377,62 @@ export type ListUploadsResult = { uploads: Array } +export interface PutChannelConf { + Description?: string, + Status?: string, + Target?: { + Type: string, + FragDuration: number, + FragCount: number, + PlaylistName: string + } +} + +export interface PutChannelResult { + publishUrls: Array, + playUrls: Array, + res: NormalSuccessResponse +} + +export interface GetChannelResult { + Status: string, + ConnectedTime?: string, + RemoteAddr?: string, + Video?: object, + Audio?: object, + res: NormalSuccessResponse +} + +export interface ListChannelsQuery { + prefix: string, // the channel id prefix (returns channels with this prefix) + marker: string, // the channle id marker (returns channels after this id) + 'max-keys ': number // max number of channels to return +} + +export interface ListChannelsResult { + channels: Array + nextMarker: string | null, + isTruncated: boolean, + res: NormalSuccessResponse +} + +export interface ChannelHistoryResult { + records: ChannelHistory, + res: NormalSuccessResponse +} + +export interface GetRtmpUrlOptions { + expires?: number, // the expire time in seconds of the url + params?: object, // the additional paramters for url, e.g.: {playlistName: 'play.m3u8'} + timeout?: number // the operation timeout +} + export default class OSS { // the image client static ImageClient: any + + constructor(options: Options) + /******************************************* the bucket operations *************************************************/ // base operators @@ -683,7 +762,7 @@ export default class OSS { * @param {RequestOptions} options * @return {Promise} */ - getACL(name:string, options?: RequestOptions): Promise + getACL(name: string, options?: RequestOptions): Promise /** * Restore Object. @@ -736,7 +815,7 @@ export default class OSS { * @param {CompleteMultipartUploadOptions} options * @return {Promise} */ - completeMultipartUpload(name: string, uploadId: string, parts: Array<{ number: number, etag: string }>, options?:CompleteMultipartUploadOptions): Promise + completeMultipartUpload(name: string, uploadId: string, parts: Array<{ number: number, etag: string }>, options?: CompleteMultipartUploadOptions): Promise /** * Upload file with OSS multipart. @@ -788,4 +867,80 @@ export default class OSS { abortMultipartUpload(name: string, uploadId: string, options?: RequestOptions): Promise /************************************************ RTMP Operations *************************************************************/ + /** + * Create a live channel. + * @param {string} id + * @param {PutChannelConf} conf + * @param {RequestOptions} options + * @return {Promise} + */ + putChannel(id: string, conf: PutChannelConf, options?: RequestOptions): Promise + + /** + * Get live channel info. + * @param {string} id + * @param {RequestOptions} options + * @return {Promise<{data: PutChannelConf; res: NormalSuccessResponse}>} + */ + getChannel(id: string, options?: RequestOptions): Promise<{ data: PutChannelConf, res: NormalSuccessResponse }> + + /** + * Delete a live channel. + * @param {string} id + * @param {RequestOptions} options + * @return {Promise} + */ + deleteChannel(id: string, options?: RequestOptions): Promise + + /** + * Change the live channel status. + * @param {string} id + * @param {string} status + * @param {RequestOptions} options + * @return {Promise} + */ + putChannelStatus(id: string, status?: string, options?: RequestOptions): Promise + + /** + * Get the live channel status. + * @param {string} id + * @param {RequestOptions} options + * @return {Promise} + */ + getChannelStatus(id: string, options?: RequestOptions): Promise + + /** + * List channels. + * @param {ListChannelsQuery} query + * @param {RequestOptions} options + * @return {Promise} + */ + listChannels(query: ListChannelsQuery, options?: RequestOptions): Promise + + /** + * Get the live channel history. + * @param {string} id + * @param {RequestOptions} options + * @return {Promise} + */ + getChannelHistory(id: string, options?: RequestOptions): Promise + + /** + * Create a VOD playlist for the channel. + * @param {string} id + * @param {string} name + * @param {{startTime: number; endTime: number}} time + * @param {RequestOptions} options + * @return {Promise} + */ + createVod(id: string, name: string, time: { startTime: number, endTime: number }, options?: RequestOptions): Promise + + /** + * Get signatured rtmp url for publishing. + * @param {string} channelId + * @param {GetRtmpUrlOptions} options + * @return {string} + */ + getRtmpUrl(channelId?: string, options?: GetRtmpUrlOptions): string } + From 8c7758f7efe942e0f68ffa3a769e67b1b06b8e30 Mon Sep 17 00:00:00 2001 From: ptrdu Date: Sat, 29 Sep 2018 15:50:26 +0800 Subject: [PATCH 006/836] FEAT: add ImageClient and cluster --- types/ali-oss/Cluster.d.ts | 64 ++++++++++++++++++++++ types/ali-oss/ImageClient.d.ts | 99 ++++++++++++++++++++++++++++++++++ types/ali-oss/ali-oss-tests.ts | 9 ++++ types/ali-oss/index.d.ts | 11 +++- types/ali-oss/tsconfig.json | 2 + 5 files changed, 184 insertions(+), 1 deletion(-) create mode 100644 types/ali-oss/Cluster.d.ts create mode 100644 types/ali-oss/ImageClient.d.ts diff --git a/types/ali-oss/Cluster.d.ts b/types/ali-oss/Cluster.d.ts new file mode 100644 index 0000000000..57ab35719b --- /dev/null +++ b/types/ali-oss/Cluster.d.ts @@ -0,0 +1,64 @@ +import { + ACLType, + CopyAndPutMetaResult, + CopyObjectOptions, + DeleteMultiOptions, + DeleteMultiResult, + GetObjectOptions, + GetObjectResult, + GetStreamOptions, + GetStreamResult, + HeadObjectOptions, + HeadObjectResult, + ListObjectResult, + ListObjectsQuery, + NormalSuccessResponse, + PutObjectOptions, + PutObjectResult, + PutStreamOptions, + RequestOptions, + SignatureUrlOptions, + UserMeta +} from "./index"; + +export interface ClusterType { + host: string, + accessKeyId: string, + accessKeySecret: string +} + +export interface ClusterOptions { + clusters: Array, + schedule?: string +} + + +export class Cluster { + constructor(options: ClusterOptions) + + list(query: ListObjectsQuery | null, options: RequestOptions): Promise + + put(name: string, file: any, options?: PutObjectOptions): Promise + + putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }> + + head(name: string, options?: HeadObjectOptions): Promise + + get(name: string, file?: any, options?: GetObjectOptions): Promise + + getStream(name?: string, options?: GetStreamOptions): Promise + + delete(name: string, options?: RequestOptions): Promise + + copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise + + putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise + + deleteMulti(names: Array, options?: DeleteMultiOptions): Promise + + signatureUrl(name: string, options?: SignatureUrlOptions): string + + putACL(name: string, acl: ACLType, options?: RequestOptions): Promise + + restore(name: string, options?: RequestOptions): Promise +} diff --git a/types/ali-oss/ImageClient.d.ts b/types/ali-oss/ImageClient.d.ts new file mode 100644 index 0000000000..ec6ec9b71a --- /dev/null +++ b/types/ali-oss/ImageClient.d.ts @@ -0,0 +1,99 @@ +import {NormalSuccessResponse, RequestOptions} from "./index"; + +export interface Options { + imageHost: string, // your image service domain that binding to a OSS bucket + accessKeyId: string, // access key you create on aliyun console website + accessKeySecret: string, // access secret you create + bucket: string, // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. + region?: string, // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou Current available: oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhen + internal?: boolean, // access OSS with aliyun internal network or not, default is false If your servers are running on aliyun too, you can set true to save lot of money. + timeout?: string | number, // instance level timeout for all operations, default is 60s +} + +export interface ImageGetOptions { + timeout?: number, + headers?: object +} + +export interface StyleData { + Name: string, // style name + Content: string, // style content + CreateTime: string, // style create time + LastModifyTime: string // style last modify time +} +export class Client { + constructor(options: Options) + + /** + * Get an image from the image channel. + * @param {string} name + * @param file - String|WriteStream} file path or WriteStream instance to store the image If file is null or ignore this parameter, function will return info contains content property. + * @param {ImageGetOptions} options + * @return {Promise<{content: any; res: NormalSuccessResponse}>} + */ + get(name: string, file?: any, options?: ImageGetOptions): Promise<{ content: any, res: NormalSuccessResponse }> + + /** + * Get an image read stream. + * @param {string} name + * @param {ImageGetOptions} options + * @return {Promise<{stream: any; res: NormalSuccessResponse}>} + */ + getStream(name: string, options?: ImageGetOptions): Promise<{ stream: any, res: NormalSuccessResponse }> + + /** + * Get a image exif info by image object name from the image channel. + * @param {string} name + * @param {RequestOptions} options + * @return {Promise<{data: object; res: NormalSuccessResponse}>} + */ + getExif(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }> + + /** + * Get a image info and exif info by image object name from the image channel. + * @param {string} name + * @param {RequestOptions} options + * @return {Promise<{data: object; res: NormalSuccessResponse}>} + */ + getInfo(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }> + + /** + * todo + * @param {string} name + * @param {string} style + * @param {RequestOptions} options + * @return {Promise<{data: object; res: NormalSuccessResponse}>} + */ + putStyle(name: string, style: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }> + + /** + * Get a style by name from the image channel. + * @param {string} name + * @param {RequestOptions} options + * @return {Promise<{data: StyleData; res: NormalSuccessResponse}>} + */ + getStyle(name: string, options?: RequestOptions): Promise<{ data: StyleData, res: NormalSuccessResponse}> + + /** + * Get all styles from the image channel. + * @param {RequestOptions} options + * @return {Promise>} + */ + listStyle(options?: RequestOptions): Promise> + + /** + * todo + * @param {string} styleName + * @param {RequestOptions} options + * @return {Promise} + */ + deleteStyle(styleName: string, options?: RequestOptions): Promise + + /** + * Create a signature url for directly download. + * @param {string} name + * @param {{expires?: string; timeout?: string}} options + * @return {string} + */ + signatureUrl(name: string, options?: { expires?: string, timeout?: string }): string +} diff --git a/types/ali-oss/ali-oss-tests.ts b/types/ali-oss/ali-oss-tests.ts index 82941c1e5e..e441e15577 100644 --- a/types/ali-oss/ali-oss-tests.ts +++ b/types/ali-oss/ali-oss-tests.ts @@ -7,3 +7,12 @@ const client = new OSS({ region: 'oss-cn-hangzhou' }); +const ImageClient = OSS.ImageClient({ + imageHost: 'xxxx', + accessKeySecret: "xxxx", + accessKeyId: 'xxxxxx', + bucket: "", + internal: false, + region: "", + timeout: undefined +}) diff --git a/types/ali-oss/index.d.ts b/types/ali-oss/index.d.ts index 9f5530db71..1ced1efaf8 100644 --- a/types/ali-oss/index.d.ts +++ b/types/ali-oss/index.d.ts @@ -6,6 +6,9 @@ // general type +import * as ImageClientDefinition from './ImageClient' +import * as ClusterDefinition from "./Cluster" + export interface Options { accessKeyId: string, // access secret you create accessKeySecret: string, // access secret you create @@ -427,9 +430,14 @@ export interface GetRtmpUrlOptions { timeout?: number // the operation timeout } +export interface ObjectInterface { + +} + export default class OSS { // the image client - static ImageClient: any + public static ImageClient: (options: ImageClientDefinition.Options) => ImageClientDefinition.Client + public static Cluster: (options: ClusterDefinition.ClusterOptions) => ClusterDefinition.Cluster constructor(options: Options) @@ -942,5 +950,6 @@ export default class OSS { * @return {string} */ getRtmpUrl(channelId?: string, options?: GetRtmpUrlOptions): string + } diff --git a/types/ali-oss/tsconfig.json b/types/ali-oss/tsconfig.json index a3e68ada2b..b6f46ae8e8 100644 --- a/types/ali-oss/tsconfig.json +++ b/types/ali-oss/tsconfig.json @@ -18,6 +18,8 @@ }, "files": [ "index.d.ts", + "ImageClient.d.ts", + "Cluster.d.ts", "ali-oss-tests.ts" ] } From c56edf64cc154e9aa4d7efad94f7aa01ee1b585c Mon Sep 17 00:00:00 2001 From: ptrdu Date: Sat, 29 Sep 2018 17:49:53 +0800 Subject: [PATCH 007/836] FEAT: add test --- types/ali-oss/ImageClient.d.ts | 8 ++++---- types/ali-oss/ali-oss-tests.ts | 27 ++++++++++++++++++++++----- types/ali-oss/index.d.ts | 19 +++++++++++-------- 3 files changed, 37 insertions(+), 17 deletions(-) diff --git a/types/ali-oss/ImageClient.d.ts b/types/ali-oss/ImageClient.d.ts index ec6ec9b71a..047077904f 100644 --- a/types/ali-oss/ImageClient.d.ts +++ b/types/ali-oss/ImageClient.d.ts @@ -1,6 +1,6 @@ -import {NormalSuccessResponse, RequestOptions} from "./index"; +import { NormalSuccessResponse, RequestOptions } from "./index"; -export interface Options { +export interface ImageClientOptions { imageHost: string, // your image service domain that binding to a OSS bucket accessKeyId: string, // access key you create on aliyun console website accessKeySecret: string, // access secret you create @@ -21,8 +21,8 @@ export interface StyleData { CreateTime: string, // style create time LastModifyTime: string // style last modify time } -export class Client { - constructor(options: Options) +export class ImageClient { + constructor(options: ImageClientOptions) /** * Get an image from the image channel. diff --git a/types/ali-oss/ali-oss-tests.ts b/types/ali-oss/ali-oss-tests.ts index e441e15577..a9c39ab199 100644 --- a/types/ali-oss/ali-oss-tests.ts +++ b/types/ali-oss/ali-oss-tests.ts @@ -5,14 +5,31 @@ const client = new OSS({ accessKeySecret: 'your access secret', bucket: 'your bucket name', region: 'oss-cn-hangzhou' -}); +}) + const ImageClient = OSS.ImageClient({ - imageHost: 'xxxx', - accessKeySecret: "xxxx", - accessKeyId: 'xxxxxx', + imageHost: 'host', + accessKeySecret: "secret", + accessKeyId: 'id', bucket: "", internal: false, region: "", - timeout: undefined + timeout: 2000 +}) + +const cluster = OSS.Cluster({ + clusters: [ + { + accessKeyId: 'id', + accessKeySecret: 'secret', + host: "" + }, + { + accessKeyId: 'id', + accessKeySecret: 'secret', + host: "" + }, + ], + schedule: 'masterSlave', }) diff --git a/types/ali-oss/index.d.ts b/types/ali-oss/index.d.ts index 1ced1efaf8..0f17bbb142 100644 --- a/types/ali-oss/index.d.ts +++ b/types/ali-oss/index.d.ts @@ -8,6 +8,10 @@ import * as ImageClientDefinition from './ImageClient' import * as ClusterDefinition from "./Cluster" +import {ImageClient} from "./ImageClient"; + +export * from './ImageClient' +export * from './Cluster' export interface Options { accessKeyId: string, // access secret you create @@ -22,7 +26,10 @@ export interface Options { } export type Bucket = { - + name: string, + region: string, + creationDate: string, + StorageClass: StorageType } export type StorageType = "Standard" | "IA" | "Archive" @@ -430,13 +437,9 @@ export interface GetRtmpUrlOptions { timeout?: number // the operation timeout } -export interface ObjectInterface { - -} - export default class OSS { // the image client - public static ImageClient: (options: ImageClientDefinition.Options) => ImageClientDefinition.Client + public static ImageClient: (options: ImageClientDefinition.ImageClientOptions) => ImageClientDefinition.ImageClient public static Cluster: (options: ClusterDefinition.ClusterOptions) => ClusterDefinition.Cluster constructor(options: Options) @@ -455,7 +458,8 @@ export default class OSS { /** * Create a new bucket. - * @param {string} name - bucket name If bucket exists and not belong to current account, will throw BucketAlreadyExistsError. If bucket not exists, will create a new bucket and set it's ACL. + * @param {string} name - bucket name If bucket exists and not belong to current account, will throw BucketAlreadyExistsError. + * If bucket not exists, will create a new bucket and set it's ACL. * @param {PutBucketOptions} options - optional parameters * @return { Promise<{ bucket: string, res: NormalSuccessResponse }> } */ @@ -952,4 +956,3 @@ export default class OSS { getRtmpUrl(channelId?: string, options?: GetRtmpUrlOptions): string } - From 14dda1b33703537649a2e5f019d1de0c74a9148b Mon Sep 17 00:00:00 2001 From: ptrdu Date: Sat, 29 Sep 2018 18:50:18 +0800 Subject: [PATCH 008/836] FIX: fix some used import and the typescript version --- types/ali-oss/index.d.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/types/ali-oss/index.d.ts b/types/ali-oss/index.d.ts index 0f17bbb142..b7eba95d62 100644 --- a/types/ali-oss/index.d.ts +++ b/types/ali-oss/index.d.ts @@ -2,13 +2,10 @@ // Project: https://github.com/ali-sdk/ali-oss // Definitions by: Ptrdu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.2.0 - -// general type +// TypeScript Version: 2.3 import * as ImageClientDefinition from './ImageClient' import * as ClusterDefinition from "./Cluster" -import {ImageClient} from "./ImageClient"; export * from './ImageClient' export * from './Cluster' From 83d5d18ae729119b39a63f5c6ed3d698507fc48d Mon Sep 17 00:00:00 2001 From: ptrdu Date: Sun, 30 Sep 2018 10:17:52 +0800 Subject: [PATCH 009/836] FIX: fix the tsconfig and tslint error --- types/ali-oss/Cluster.d.ts | 37 +- types/ali-oss/ImageClient.d.ts | 72 +-- types/ali-oss/ali-oss-tests.ts | 7 +- types/ali-oss/index.d.ts | 823 +++++++++++++-------------------- types/ali-oss/tsconfig.json | 2 +- types/ali-oss/tslint.json | 78 +--- 6 files changed, 359 insertions(+), 660 deletions(-) diff --git a/types/ali-oss/Cluster.d.ts b/types/ali-oss/Cluster.d.ts index 57ab35719b..60886fca36 100644 --- a/types/ali-oss/Cluster.d.ts +++ b/types/ali-oss/Cluster.d.ts @@ -22,43 +22,42 @@ import { } from "./index"; export interface ClusterType { - host: string, - accessKeyId: string, - accessKeySecret: string + host: string; + accessKeyId: string; + accessKeySecret: string; } export interface ClusterOptions { - clusters: Array, - schedule?: string + clusters: ClusterType[]; + schedule?: string; } - export class Cluster { constructor(options: ClusterOptions) - list(query: ListObjectsQuery | null, options: RequestOptions): Promise + list(query: ListObjectsQuery | null, options: RequestOptions): Promise; - put(name: string, file: any, options?: PutObjectOptions): Promise + put(name: string, file: any, options?: PutObjectOptions): Promise; - putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }> + putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }>; - head(name: string, options?: HeadObjectOptions): Promise + head(name: string, options?: HeadObjectOptions): Promise; - get(name: string, file?: any, options?: GetObjectOptions): Promise + get(name: string, file?: any, options?: GetObjectOptions): Promise; - getStream(name?: string, options?: GetStreamOptions): Promise + getStream(name?: string, options?: GetStreamOptions): Promise; - delete(name: string, options?: RequestOptions): Promise + delete(name: string, options?: RequestOptions): Promise; - copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise + copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise; - putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise + putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise; - deleteMulti(names: Array, options?: DeleteMultiOptions): Promise + deleteMulti(names: string[], options?: DeleteMultiOptions): Promise; - signatureUrl(name: string, options?: SignatureUrlOptions): string + signatureUrl(name: string, options?: SignatureUrlOptions): string; - putACL(name: string, acl: ACLType, options?: RequestOptions): Promise + putACL(name: string, acl: ACLType, options?: RequestOptions): Promise; - restore(name: string, options?: RequestOptions): Promise + restore(name: string, options?: RequestOptions): Promise; } diff --git a/types/ali-oss/ImageClient.d.ts b/types/ali-oss/ImageClient.d.ts index 047077904f..850213083c 100644 --- a/types/ali-oss/ImageClient.d.ts +++ b/types/ali-oss/ImageClient.d.ts @@ -1,99 +1,71 @@ import { NormalSuccessResponse, RequestOptions } from "./index"; export interface ImageClientOptions { - imageHost: string, // your image service domain that binding to a OSS bucket - accessKeyId: string, // access key you create on aliyun console website - accessKeySecret: string, // access secret you create - bucket: string, // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. - region?: string, // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou Current available: oss-cn-hangzhou, oss-cn-qingdao, oss-cn-beijing, oss-cn-hongkong and oss-cn-shenzhen - internal?: boolean, // access OSS with aliyun internal network or not, default is false If your servers are running on aliyun too, you can set true to save lot of money. - timeout?: string | number, // instance level timeout for all operations, default is 60s + imageHost: string; // your image service domain that binding to a OSS bucket + accessKeyId: string; // access key you create on aliyun console website + accessKeySecret: string; // access secret you create + bucket: string; // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. + region?: string; // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou + internal?: boolean; // access OSS with aliyun internal network or not, default is false If your servers are running on aliyun too, you can set true to save lot of money. + timeout?: string | number; // instance level timeout for all operations, default is 60s } export interface ImageGetOptions { - timeout?: number, - headers?: object + timeout?: number; + headers?: object; } export interface StyleData { - Name: string, // style name - Content: string, // style content - CreateTime: string, // style create time - LastModifyTime: string // style last modify time + Name: string; // style name + Content: string; // style content + CreateTime: string; // style create time + LastModifyTime: string; // style last modify time } export class ImageClient { constructor(options: ImageClientOptions) /** * Get an image from the image channel. - * @param {string} name - * @param file - String|WriteStream} file path or WriteStream instance to store the image If file is null or ignore this parameter, function will return info contains content property. - * @param {ImageGetOptions} options - * @return {Promise<{content: any; res: NormalSuccessResponse}>} */ - get(name: string, file?: any, options?: ImageGetOptions): Promise<{ content: any, res: NormalSuccessResponse }> + get(name: string, file?: any, options?: ImageGetOptions): Promise<{ content: any, res: NormalSuccessResponse }>; /** * Get an image read stream. - * @param {string} name - * @param {ImageGetOptions} options - * @return {Promise<{stream: any; res: NormalSuccessResponse}>} */ - getStream(name: string, options?: ImageGetOptions): Promise<{ stream: any, res: NormalSuccessResponse }> + getStream(name: string, options?: ImageGetOptions): Promise<{ stream: any, res: NormalSuccessResponse }>; /** * Get a image exif info by image object name from the image channel. - * @param {string} name - * @param {RequestOptions} options - * @return {Promise<{data: object; res: NormalSuccessResponse}>} */ - getExif(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }> + getExif(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; /** * Get a image info and exif info by image object name from the image channel. - * @param {string} name - * @param {RequestOptions} options - * @return {Promise<{data: object; res: NormalSuccessResponse}>} */ - getInfo(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }> + getInfo(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; /** * todo - * @param {string} name - * @param {string} style - * @param {RequestOptions} options - * @return {Promise<{data: object; res: NormalSuccessResponse}>} */ - putStyle(name: string, style: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }> + putStyle(name: string, style: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; /** * Get a style by name from the image channel. - * @param {string} name - * @param {RequestOptions} options - * @return {Promise<{data: StyleData; res: NormalSuccessResponse}>} */ - getStyle(name: string, options?: RequestOptions): Promise<{ data: StyleData, res: NormalSuccessResponse}> + getStyle(name: string, options?: RequestOptions): Promise<{ data: StyleData, res: NormalSuccessResponse}>; /** * Get all styles from the image channel. - * @param {RequestOptions} options - * @return {Promise>} */ - listStyle(options?: RequestOptions): Promise> + listStyle(options?: RequestOptions): Promise; /** * todo - * @param {string} styleName - * @param {RequestOptions} options - * @return {Promise} */ - deleteStyle(styleName: string, options?: RequestOptions): Promise + deleteStyle(styleName: string, options?: RequestOptions): Promise; /** * Create a signature url for directly download. - * @param {string} name - * @param {{expires?: string; timeout?: string}} options - * @return {string} */ - signatureUrl(name: string, options?: { expires?: string, timeout?: string }): string + signatureUrl(name: string, options?: { expires?: string, timeout?: string }): string; } diff --git a/types/ali-oss/ali-oss-tests.ts b/types/ali-oss/ali-oss-tests.ts index a9c39ab199..96f817cca8 100644 --- a/types/ali-oss/ali-oss-tests.ts +++ b/types/ali-oss/ali-oss-tests.ts @@ -5,8 +5,7 @@ const client = new OSS({ accessKeySecret: 'your access secret', bucket: 'your bucket name', region: 'oss-cn-hangzhou' -}) - +}); const ImageClient = OSS.ImageClient({ imageHost: 'host', @@ -16,7 +15,7 @@ const ImageClient = OSS.ImageClient({ internal: false, region: "", timeout: 2000 -}) +}); const cluster = OSS.Cluster({ clusters: [ @@ -32,4 +31,4 @@ const cluster = OSS.Cluster({ }, ], schedule: 'masterSlave', -}) +}); diff --git a/types/ali-oss/index.d.ts b/types/ali-oss/index.d.ts index b7eba95d62..c3fa0dd10b 100644 --- a/types/ali-oss/index.d.ts +++ b/types/ali-oss/index.d.ts @@ -1,443 +1,443 @@ -// Type definitions for ali-oss 6.0.1 +// Type definitions for ali-oss 6.0 // Project: https://github.com/ali-sdk/ali-oss // Definitions by: Ptrdu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as ImageClientDefinition from './ImageClient' -import * as ClusterDefinition from "./Cluster" +import * as ImageClientDefinition from './ImageClient'; +import * as ClusterDefinition from "./Cluster"; -export * from './ImageClient' -export * from './Cluster' +export * from './ImageClient'; +export * from './Cluster'; export interface Options { - accessKeyId: string, // access secret you create - accessKeySecret: string, // access secret you create - stsToken?: string, // used by temporary authorization - bucket?: string, // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. - endpoint?: string, // oss region domain. It takes priority over region. - region?: string, // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou. - internal?: boolean, // access OSS with aliyun internal network or not, default is false. If your servers are running on aliyun too, you can set true to save lot of money. - secure?: boolean, // instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol. - timeout?: string | number // instance level timeout for all operations, default is 60s + accessKeyId: string; // access secret you create + accessKeySecret: string; // access secret you create + stsToken?: string; // used by temporary authorization + bucket?: string; // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. + endpoint?: string; // oss region domain. It takes priority over region. + region?: string; // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou. + internal?: boolean; // access OSS with aliyun internal network or not, default is false. If your servers are running on aliyun too, you can set true to save lot of money. + secure?: boolean; // instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol. + timeout?: string | number; // instance level timeout for all operations, default is 60s } -export type Bucket = { - name: string, - region: string, - creationDate: string, - StorageClass: StorageType +export interface Bucket { + name: string; + region: string; + creationDate: string; + StorageClass: StorageType; } -export type StorageType = "Standard" | "IA" | "Archive" +export type StorageType = "Standard" | "IA" | "Archive"; -export type ACLType = "public-read-write" | "public-read" | "and private" +export type ACLType = "public-read-write" | "public-read" | "and private"; export type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT"; export interface RequestOptions { // the operation timeout - timeout?: number + timeout?: number; } -export type RuleStatusType = "Enabled" | "Disabled" +export type RuleStatusType = "Enabled" | "Disabled"; export interface LifecycleRule { - id?: string, // rule id, if not set, OSS will auto create it with random string. - prefix: string, // store prefix - status: RuleStatusType, // rule status, allow values: Enabled or Disabled - days?: number | string, // expire after the days - date: string // expire date, e.g.: 2022-10-11T00:00:00.000Z date and days only set one. + id?: string; // rule id, if not set, OSS will auto create it with random string. + prefix: string; // store prefix + status: RuleStatusType; // rule status, allow values: Enabled or Disabled + days?: number | string; // expire after the days + date: string; // expire date, e.g.: 2022-10-11T00:00:00.000Z date and days only set one. } export interface CORSRule { - allowedOrigin: string | Array, // configure for Access-Control-Allow-Origin header - allowedMethod: string | Array, // configure for Access-Control-Allow-Methods header - allowedHeader?: string | Array, // configure for Access-Control-Allow-Headers header - exposeHeader?: string | Array, // configure for Access-Control-Expose-Headers header - maxAgeSeconds?: string | Array, // configure for Access-Control-Max-Age header + allowedOrigin: string | string[]; // configure for Access-Control-Allow-Origin header + allowedMethod: string | string[]; // configure for Access-Control-Allow-Methods header + allowedHeader?: string | string[]; // configure for Access-Control-Allow-Headers header + exposeHeader?: string | string[]; // configure for Access-Control-Expose-Headers header + maxAgeSeconds?: string | string[]; // configure for Access-Control-Max-Age header } export interface OwnerType { - id: string, - displayName: string + id: string; + displayName: string; } export interface ObjectMeta { - name: string, // object name on oss - lastModified: string, // object last modified GMT date, e.g.: 2015-02-19T08:39:44.000Z - etag: string, // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" - type: string, // object type, e.g.: Normal - size: number, // object size, e.g.: 344606 - storageClass: StorageType, - owner: OwnerType, + name: string; // object name on oss + lastModified: string; // object last modified GMT date, e.g.: 2015-02-19T08:39:44.000Z + etag: string; // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" + type: string; // object type, e.g.: Normal + size: number; // object size, e.g.: 344606 + storageClass: StorageType; + owner: OwnerType; } export interface NormalSuccessResponse { - //response status - status: number, + // response status + status: number; // response headers - headers: object, // todo the object in detail + headers: object; // todo the object in detail // response size - size: number, + size: number; // request total use time (ms) - rt: number + rt: number; } export interface UserMeta { - uid: number, - pid: number + uid: number; + pid: number; } export interface ObjectCallback { - url: string, // After a file is uploaded successfully, the OSS sends a callback request to this URL. - host?: string, // The host header value for initiating callback requests. - body: string, // The value of the request body when a callback is initiated, for example, key=$(key)&etag=$(etag)&my_var=$(x:my_var). - contentType?: string, // The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value. - customValue?: object, - headers?: object // extra headers, detail see RFC 2616 + url: string; // After a file is uploaded successfully, the OSS sends a callback request to this URL. + host?: string; // The host header value for initiating callback requests. + body: string; // The value of the request body when a callback is initiated, for example, key=$(key)&etag=$(etag)&my_var=$(x:my_var). + contentType?: string; // The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value. + customValue?: object; + headers?: object; // extra headers, detail see RFC 2616 } export interface ModifyData { - lastModified: string, // object last modified GMT string - etag: string // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" + lastModified: string; // object last modified GMT string + etag: string; // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" } export interface Checkpoint { - file: any, // The file object selected by the user, if the browser is restarted, it needs the user to manually trigger the settings - name: string, // object key - fileSize: number, - partSize: number, - uploadId: string, - doneParts: Array<{ number: number, etag: string }> + file: any; // The file object selected by the user, if the browser is restarted, it needs the user to manually trigger the settings + name: string; // object key + fileSize: number; + partSize: number; + uploadId: string; + doneParts: Array<{ number: number, etag: string }>; } export interface ObjectPart { - PartNumber: number, - LastModified: any, // {Date} Time when a part is uploaded. - ETag: string, - size: number + PartNumber: number; + LastModified: any; // {Date} Time when a part is uploaded. + ETag: string; + size: number; } export interface Upload { - name: string, - uploadId: string, - initiated: any + name: string; + uploadId: string; + initiated: any; } export interface Channel { - Name: string, - Description: string, - Status: string, - LastModified: string, - PublishUrls: Array, - PlayUrls: Array + Name: string; + Description: string; + Status: string; + LastModified: string; + PublishUrls: string[]; + PlayUrls: string[]; } export interface ChannelHistory { - StartTime: string, // - EndTime: string, - RemoteAddr: string // the remote addr + StartTime: string; // + EndTime: string; + RemoteAddr: string; // the remote addr } // parameters type export interface ListBucketsQueryType { - prefix?: string, // search buckets using prefix key - marker?: string, // search start from marker, including marker key - 'max-keys'?: string | number // max buckets, default is 100, limit to 1000 + prefix?: string; // search buckets using prefix key + marker?: string; // search start from marker, including marker key + 'max-keys'?: string | number; // max buckets, default is 100, limit to 1000 } export interface PutBucketOptions { - timeout: number, - storageClass: StorageType + timeout: number; + storageClass: StorageType; } export interface PutBucketWebsiteConfig { - index: string, // default page, e.g.: index.html - error?: string // error page, e.g.: 'error.html' + index: string; // default page, e.g.: index.html + error?: string; // error page, e.g.: 'error.html' } export interface ListObjectsQuery { - prefix?: string, // search object using prefix key - marker?: string, // search start from marker, including marker key - delimiter?: string, // delimiter search scope e.g. / only search current dir, not including subdir - 'max-keys': string | number // max objects, default is 100, limit to 1000 + prefix?: string; // search object using prefix key + marker?: string; // search start from marker, including marker key + delimiter?: string; // delimiter search scope e.g. / only search current dir, not including subdir + 'max-keys': string | number; // max objects, default is 100, limit to 1000 } export interface ListObjectResult { - objects: Array, - prefixes: Array, - isTruncated: boolean, - nextMarker: string, - res: NormalSuccessResponse + objects: ObjectMeta[]; + prefixes: string[]; + isTruncated: boolean; + nextMarker: string; + res: NormalSuccessResponse; } export interface PutObjectOptions { - timeout?: number, // the operation timeout - mime?: string, // custom mime, will send with Content-Type entity header - meta?: UserMeta, // user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 } - callback: ObjectCallback, + timeout?: number; // the operation timeout + mime?: string; // custom mime, will send with Content-Type entity header + meta?: UserMeta; // user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 } + callback: ObjectCallback; } export interface PutObjectResult { - name: string, - data: object, - res: NormalSuccessResponse + name: string; + data: object; + res: NormalSuccessResponse; } export interface PutStreamOptions { - contentLength?: number, // the stream length, chunked encoding will be used if absent - timeout: number, // the operation timeout - mime: string, // custom mime, will send with Content-Type entity header - meta: UserMeta, - callback: ObjectCallback + contentLength?: number; // the stream length, chunked encoding will be used if absent + timeout: number; // the operation timeout + mime: string; // custom mime, will send with Content-Type entity header + meta: UserMeta; + callback: ObjectCallback; } export interface AppendObjectOptions { - position?: string, // specify the position which is the content length of the latest object - timeout?: number, // the operation timeout - mime?: string, // custom mime, will send with Content-Type entity header - meta?: UserMeta, - headers?: object + position?: string; // specify the position which is the content length of the latest object + timeout?: number; // the operation timeout + mime?: string; // custom mime, will send with Content-Type entity header + meta?: UserMeta; + headers?: object; } export interface AppendObjectResult { - name: string, - url: string, // the url of oss - res: NormalSuccessResponse, - nextAppendPosition: string, // the next position + name: string; + url: string; // the url of oss + res: NormalSuccessResponse; + nextAppendPosition: string; // the next position } export interface HeadObjectOptions { - timeout?: number, - headers?: object + timeout?: number; + headers?: object; } export interface HeadObjectResult { - status: number, // response status, maybe 200 or 304 - meta: UserMeta, - res: NormalSuccessResponse + status: number; // response status, maybe 200 or 304 + meta: UserMeta; + res: NormalSuccessResponse; } export interface GetObjectOptions { - timeout?: number, - process?: string, // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} - headers?: object + timeout?: number; + process?: string; // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} + headers?: object; } export interface GetObjectResult { - content?: any, // file content buffer if file parameter is null or ignore - res: NormalSuccessResponse + content?: any; // file content buffer if file parameter is null or ignore + res: NormalSuccessResponse; } export interface GetStreamOptions { - timeout?: number, - process?: string, // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} - headers?: object + timeout?: number; + process?: string; // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} + headers?: object; } export interface GetStreamResult { - stream?: any, // readable stream instance if response status is not 200, stream will be null. - res: NormalSuccessResponse + stream?: any; // readable stream instance if response status is not 200, stream will be null. + res: NormalSuccessResponse; } export interface CopyObjectOptions { - timeout?: number, - meta?: UserMeta, - headers?: object + timeout?: number; + meta?: UserMeta; + headers?: object; } export interface CopyAndPutMetaResult { - data: ModifyData, - res: NormalSuccessResponse + data: ModifyData; + res: NormalSuccessResponse; } export interface DeleteMultiOptions { - quite?: boolean // quiet mode or verbose mode, default is false, verbose mode quiet mode: if all objects delete succes, return emtpy response. otherwise return delete error object results. verbose mode: return all object delete results. - timeout?: number + quite?: boolean; // quiet mode or verbose mode, default is false + timeout?: number; } export interface DeleteMultiResult { - deleted?: Array // deleted object names list - res: NormalSuccessResponse + deleted?: string[]; // deleted object names list + res: NormalSuccessResponse; } export interface ResponseHeaderType { - 'content-type'?: string, - 'content-disposition'? :string, - 'cache-control'?: string + 'content-type'?: string; + 'content-disposition'?: string; + 'cache-control'?: string; } export interface SignatureUrlOptions { - expires?: number, // after expires seconds, the url will become invalid, default is 1800 - method?: HTTPMethods, // the HTTP method, default is 'GET' - 'Content-Type'?: string, // set the request content type - process?: string, - response?: ResponseHeaderType, // set the response headers for download - callback?: ObjectCallback + expires?: number; // after expires seconds, the url will become invalid, default is 1800 + method?: HTTPMethods; // the HTTP method, default is 'GET' + 'Content-Type'?: string; // set the request content type + process?: string; + response?: ResponseHeaderType; // set the response headers for download + callback?: ObjectCallback; } export interface GetACLResult { - acl: ACLType, - res: NormalSuccessResponse + acl: ACLType; + res: NormalSuccessResponse; } export interface InitMultipartUploadOptions { - timeout?: number, - mime?: string, // Mime file type - meta?: UserMeta, - headers?: object + timeout?: number; + mime?: string; // Mime file type + meta?: UserMeta; + headers?: object; } export interface InitMultipartUploadResult { - res: { status: number, headers: object, size: number, rt: number } - bucket: string, // bucket name - name: string, // object name store on OSS - uploadId: string, // upload id, use for uploadPart, completeMultipart + res: { status: number, headers: object, size: number, rt: number }; + bucket: string; // bucket name + name: string; // object name store on OSS + uploadId: string; // upload id, use for uploadPart, completeMultipart } export interface UploadPartResult { - name: string, - etag: string, - res: NormalSuccessResponse + name: string; + etag: string; + res: NormalSuccessResponse; } export interface CompleteMultipartUploadOptions { - timeout?: number, - callback?: ObjectCallback, - headers?: object + timeout?: number; + callback?: ObjectCallback; + headers?: object; } export interface CompleteMultipartUploadResult { - bucket: string, - name: string, - etag: string, - data: object, - res: NormalSuccessResponse + bucket: string; + name: string; + etag: string; + data: object; + res: NormalSuccessResponse; } export interface MultipartUploadOptions { - parallel?: number, // the number of parts to be uploaded in parallel - partSize?: number, // the suggested size for each part - progress?: Function, // the progress callback called after each successful upload of one part, it will be given three parameters: (percentage {Number}, checkpoint {Object}, res {Object}) - checkpoint?: Checkpoint, // the checkpoint to resume upload, if this is provided, it will continue the upload from where interrupted, otherwise a new multipart upload will be created. - meta?: UserMeta, - mime?: string, - callback?: ObjectCallback, - headers?: object, - timeout?: number - copyheaders?: object, // {Object} only uploadPartCopy api used, detail + parallel?: number; // the number of parts to be uploaded in parallel + partSize?: number; // the suggested size for each part + progress?: (...args: any[]) => any; // the progress callback called after each successful upload of one part + checkpoint?: Checkpoint; // the checkpoint to resume upload, if this is provided, it will continue the upload from where interrupted, otherwise a new multipart upload will be created. + meta?: UserMeta; + mime?: string; + callback?: ObjectCallback; + headers?: object; + timeout?: number; + copyheaders?: object; // {Object} only uploadPartCopy api used, detail } export interface MultipartUploadResult { - bucket: string, - name: string, - etag: string, - data: object, - res: NormalSuccessResponse + bucket: string; + name: string; + etag: string; + data: object; + res: NormalSuccessResponse; } export interface MultipartUploadCopyResult { - bucket: string, - name: string, - etag: string, - res: NormalSuccessResponse + bucket: string; + name: string; + etag: string; + res: NormalSuccessResponse; } export interface MultipartUploadCopySourceData { - sourceKey: string, // the source object name - sourceBucketName: string, // sourceData. the source bucket name - startOffset: number, // data copy start byte offset, e.g: 0 - endOffset: number // data copy end byte offset, e.g: 102400 + sourceKey: string; // the source object name + sourceBucketName: string; // sourceData. the source bucket name + startOffset: number; // data copy start byte offset, e.g: 0 + endOffset: number; // data copy end byte offset, e.g: 102400 } export interface ListPartsQuery { - 'max-parts': number, // The maximum part number in the response of the OSS. default value: 1000. - 'part-number-marker': number, // Starting position of a specific list. A part is listed only when the part number is greater than the value of this parameter. - 'encoding-type': string // Specify the encoding of the returned content and the encoding type. Optional value: url + 'max-parts': number; // The maximum part number in the response of the OSS. default value: 1000. + 'part-number-marker': number; // Starting position of a specific list. A part is listed only when the part number is greater than the value of this parameter. + 'encoding-type': string; // Specify the encoding of the returned content and the encoding type. Optional value: url } export interface ListPartsResult { - uploadId: string, - bucket: string, - name: string, - PartNumberMarker: number, - nextPartNumberMarker: number, - maxParts: number, - isTruncated: boolean, - parts: Array, - res: NormalSuccessResponse + uploadId: string; + bucket: string; + name: string; + PartNumberMarker: number; + nextPartNumberMarker: number; + maxParts: number; + isTruncated: boolean; + parts: ObjectPart[]; + res: NormalSuccessResponse; } export interface ListUploadsQuery { - prefix?: string, - 'max-uploads'?: number, - 'key-marker'?: string, - 'upload-id-marker'?: string + prefix?: string; + 'max-uploads'?: number; + 'key-marker'?: string; + 'upload-id-marker'?: string; } export interface ListUploadsResult { - res: NormalSuccessResponse, - bucket: string, - nextKeyMarker: any, - nextUploadIdMarker: any, - isTruncated: boolean, - uploads: Array + res: NormalSuccessResponse; + bucket: string; + nextKeyMarker: any; + nextUploadIdMarker: any; + isTruncated: boolean; + uploads: Upload[]; } export interface PutChannelConf { - Description?: string, - Status?: string, + Description?: string; + Status?: string; Target?: { Type: string, FragDuration: number, FragCount: number, PlaylistName: string - } + }; } export interface PutChannelResult { - publishUrls: Array, - playUrls: Array, - res: NormalSuccessResponse + publishUrls: string[]; + playUrls: string[]; + res: NormalSuccessResponse; } export interface GetChannelResult { - Status: string, - ConnectedTime?: string, - RemoteAddr?: string, - Video?: object, - Audio?: object, - res: NormalSuccessResponse + Status: string; + ConnectedTime?: string; + RemoteAddr?: string; + Video?: object; + Audio?: object; + res: NormalSuccessResponse; } export interface ListChannelsQuery { - prefix: string, // the channel id prefix (returns channels with this prefix) - marker: string, // the channle id marker (returns channels after this id) - 'max-keys ': number // max number of channels to return + prefix: string; // the channel id prefix (returns channels with this prefix) + marker: string; // the channel id marker (returns channels after this id) + 'max-keys ': number; // max number of channels to return } export interface ListChannelsResult { - channels: Array - nextMarker: string | null, - isTruncated: boolean, - res: NormalSuccessResponse + channels: Channel[]; + nextMarker: string | null; + isTruncated: boolean; + res: NormalSuccessResponse; } export interface ChannelHistoryResult { - records: ChannelHistory, - res: NormalSuccessResponse + records: ChannelHistory; + res: NormalSuccessResponse; } export interface GetRtmpUrlOptions { - expires?: number, // the expire time in seconds of the url - params?: object, // the additional paramters for url, e.g.: {playlistName: 'play.m3u8'} - timeout?: number // the operation timeout + expires?: number; // the expire time in seconds of the url + params?: object; // the additional parameters for url, e.g.: {playlistName: 'play.m3u8'} + timeout?: number; // the operation timeout } export default class OSS { // the image client - public static ImageClient: (options: ImageClientDefinition.ImageClientOptions) => ImageClientDefinition.ImageClient - public static Cluster: (options: ClusterDefinition.ClusterOptions) => ClusterDefinition.Cluster + static ImageClient: (options: ImageClientDefinition.ImageClientOptions) => ImageClientDefinition.ImageClient; + static Cluster: (options: ClusterDefinition.ClusterOptions) => ClusterDefinition.Cluster; constructor(options: Options) @@ -446,510 +446,315 @@ export default class OSS { // base operators /** * List buckets in this account. - * @param {ListBucketsQueryType | null} query - query parameters, default is null - * @param {RequestOptions} options - optional parameters - * timeout - the operation timeout - * @return {Promise>} */ - listBuckets(query: ListBucketsQueryType | null, options?: RequestOptions): Promise> + listBuckets(query: ListBucketsQueryType | null, options?: RequestOptions): Promise; /** * Create a new bucket. - * @param {string} name - bucket name If bucket exists and not belong to current account, will throw BucketAlreadyExistsError. - * If bucket not exists, will create a new bucket and set it's ACL. - * @param {PutBucketOptions} options - optional parameters - * @return { Promise<{ bucket: string, res: NormalSuccessResponse }> } */ - putBucket(name: string, options?: PutBucketOptions): Promise<{ bucket: string, res: NormalSuccessResponse }> + putBucket(name: string, options?: PutBucketOptions): Promise<{ bucket: string, res: NormalSuccessResponse }>; /** * Use the bucket. - * @param {string} name - bucket name */ - useBucket(name: string): void + useBucket(name: string): void; /** * Delete an empty bucket. - * @param {string} name - bucket name If bucket is not empty, will throw BucketNotEmptyError. If bucket is not exists, will throw NoSuchBucketError. - * @param {RequestOptions} options - * @return {Promise} */ - deleteBucket(name: string, options?: RequestOptions): Promise + deleteBucket(name: string, options?: RequestOptions): Promise; /** * Get bucket information,include CreationDate、ExtranetEndpoint、IntranetEndpoint、Location、Name、StorageClass、 Owner、AccessControlList - * @param {string} name - bucket name - * @return {Promise} // todo the official document miss the return type */ - getBucketInfo(name: string): Promise + getBucketInfo(name: string): Promise; /** * Get bucket location - * @param {string} name - bucket name - * @return {Promise} // todo the official document miss the return type */ - getBucketLocation(name: string): Promise + getBucketLocation(name: string): Promise; // ACL operations /** * Update the bucket ACL. - * @param {string} name - bucket name - * @param {ACLType} acl - access control list, current available: public-read-write, public-read and private - * @param {RequestOptions} options - * @return {Promise} */ - putBucketACL(name: string, acl: ACLType, options?: RequestOptions): Promise + putBucketACL(name: string, acl: ACLType, options?: RequestOptions): Promise; /** * Get the bucket ACL. - * @param {string} name - bucket name - * @param {RequestOptions} options - * @return {Promise<{ acl: string, res: NormalSuccessResponse }>} * acl - acl settings string */ - getBucketACL(name: string, options?: RequestOptions): Promise<{ acl: string, res: NormalSuccessResponse }> + getBucketACL(name: string, options?: RequestOptions): Promise<{ acl: string, res: NormalSuccessResponse }>; // logging operations /** * Update the bucket logging settings. Log file will create every one hour and name format: -YYYY-mm-DD-HH-MM-SS-UniqueString. - * @param {string} name - bucket name - * @param {string} prefix - prefix path name to store the log files - * @param {RequestOptions} options - * @return {Promise} */ - putBucketLogging(name: string, prefix?: string, options?: RequestOptions): Promise + putBucketLogging(name: string, prefix?: string, options?: RequestOptions): Promise; /** * Get the bucket logging settings. - * @param {string} name - * @param {RequestOptions} options - * @return {Promise<{ enable: boolean, prefix: string | null, res: NormalSuccessResponse }>} */ - getBucketLogging(name: string, options?: RequestOptions): Promise<{ enable: boolean, prefix: string | null, res: NormalSuccessResponse }> + getBucketLogging(name: string, options?: RequestOptions): Promise<{ enable: boolean, prefix: string | null, res: NormalSuccessResponse }>; /** * Delete the bucket logging settings. - * @param {string} name - bucket name - * @param {RequestOptions} options - * @return {Promise} */ - deleteBucketLogging(name: string, options?: RequestOptions): Promise + deleteBucketLogging(name: string, options?: RequestOptions): Promise; // Website operations /** * Set the bucket as a static website. - * @param {string} name - bucket name - * @param {PutBucketWebsiteConfig} config - * @return {Promise} */ - putBucketWebsite(name: string, config: PutBucketWebsiteConfig): Promise + putBucketWebsite(name: string, config: PutBucketWebsiteConfig): Promise; /** * Get the bucket website config. - * @param {string} name - bucket name - * @param {RequestOptions} options - * @return {Promise<{ index: string, error: string, res: NormalSuccessResponse }>} */ - getBucketWebsite(name: string, options?: RequestOptions): Promise<{ index: string, error: string, res: NormalSuccessResponse }> + getBucketWebsite(name: string, options?: RequestOptions): Promise<{ index: string, error: string, res: NormalSuccessResponse }>; /** * Delete the bucket website config. - * @param {string} name - bucket name - * @param {RequestOptions} options - * @return {Promise} */ - deleteBucketWebsite(name: string, options?: RequestOptions): Promise + deleteBucketWebsite(name: string, options?: RequestOptions): Promise; // referer operations /** * Set the bucket request Referer white list. - * @param {string} name - * @param {boolean} allowEmpty - allow empty request referer or not - * @param {Array} referers - Referer white list, e.g.: ['https://npm.taobao.org', 'http://cnpmjs.org'] - * @param {RequestOptions} options - * @return {Promise} */ - putBucketReferer(name: string, allowEmpty: boolean, referers: Array, options?: RequestOptions): Promise + putBucketReferer(name: string, allowEmpty: boolean, referers: string[], options?: RequestOptions): Promise; /** * Get the bucket request Referer white list. - * @param {string} name - bucket name - * @param {RequestOptions} options - * @return {Promise<{ allowEmpty: boolean, referers: Array, res: NormalSuccessResponse }>} */ - getBucketReferer(name: string, options?: RequestOptions): Promise<{ allowEmpty: boolean, referers: Array, res: NormalSuccessResponse }> + getBucketReferer(name: string, options?: RequestOptions): Promise<{ allowEmpty: boolean, referers: string[], res: NormalSuccessResponse }>; /** * Delete the bucket request Referer white list. - * @param {string} name - * @param {RequestOptions} options - * @return {Promise} */ - deleteBucketReferer(name: string, options?: RequestOptions): Promise + deleteBucketReferer(name: string, options?: RequestOptions): Promise; // lifecycle operations /** * Set the bucket object lifecycle. - * @param {string} name - * @param {Array} rules - rule config list - * @param {RequestOptions} options - * @return {Promise} */ - putBucketLifecycle(name: string, rules: Array, options?: RequestOptions): Promise + putBucketLifecycle(name: string, rules: LifecycleRule[], options?: RequestOptions): Promise; /** * Get the bucket object lifecycle. - * @param {string} name - * @param {RequestOptions} options - * @return {Promise<{ rules: Array, res: NormalSuccessResponse }>} */ - getBucketLifecycle(name: string, options?: RequestOptions): Promise<{ rules: Array, res: NormalSuccessResponse }> + getBucketLifecycle(name: string, options?: RequestOptions): Promise<{ rules: LifecycleRule[], res: NormalSuccessResponse }>; /** * Delete the bucket object lifecycle. - * @param {string} name - * @param {RequestOptions} options - * @return {Promise} */ - deleteBucketLifecycle(name: string, options?: RequestOptions): Promise + deleteBucketLifecycle(name: string, options?: RequestOptions): Promise; // CORS operations /** * Set CORS rules of the bucket object - * @param {string} name - * @param {Array} rules - * @param {RequestOptions} options - * @return {Promise} */ - putBucketCORS(name: string, rules: Array, options?: RequestOptions): Promise + putBucketCORS(name: string, rules: CORSRule[], options?: RequestOptions): Promise; /** * Get CORS rules of the bucket object. - * @param {string} name - * @return {Promise<{rules: Array; res: NormalSuccessResponse}>} */ - getBucketCORS(name: string): Promise<{ rules: Array, res: NormalSuccessResponse }> + getBucketCORS(name: string): Promise<{ rules: CORSRule[], res: NormalSuccessResponse }>; /** * Delete CORS rules of the bucket object. - * @param {string} name - * @return {Promise} */ - deleteBucketCORS(name: string): Promise + deleteBucketCORS(name: string): Promise; /********************************************************** Object operations ********************************************/ /** * List objects in the bucket. - * @param {ListObjectsQuery | null} query - * @param {RequestOptions} options - * @return {Promise} */ - list(query: ListObjectsQuery | null, options: RequestOptions): Promise + list(query: ListObjectsQuery | null, options: RequestOptions): Promise; /** * Add an object to the bucket. - * @param {string} name - object name store on OSS - * @param file - {String|Buffer|ReadStream|File(only support Browser)|Blob(only support Browser)} object local path, content buffer or ReadStream content instance use in Node, Blob and html5 File - * @param {PutObjectOptions} options - optional parameters - * @return {Promise} */ - put(name: string, file: any, options?: PutObjectOptions): Promise + put(name: string, file: any, options?: PutObjectOptions): Promise; /** * Add a stream object to the bucket. - * @param {string} name - object name store on OSS - * @param stream - object ReadStream content instance - * @param {PutStreamOptions} options - optional parameters - * @return {Promise<{name: string; res: NormalSuccessResponse}>} */ - putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }> + putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }>; /** * Append an object to the bucket, it's almost same as put, but it can add content to existing object rather than override it. - * @param {string} name - * @param file - * @param {AppendObjectOptions} options - * @return {Promise} */ - append(name: string, file: any, options?: AppendObjectOptions): Promise + append(name: string, file: any, options?: AppendObjectOptions): Promise; /** * Get the Object url. If provide baseUrl, will use baseUrl instead the default endpoint. - * @param {string} name - * @param {string} baseUrl - * @return {string} */ - getObjectUrl(name: string, baseUrl?: string): string + getObjectUrl(name: string, baseUrl?: string): string; /** * Get the Object url. If provide baseUrl, will use baseUrl instead the default bucket and endpoint. Suggest use generateObjectUrl instead of getObjectUrl. - * @param {string} name - * @param {string} baseUrl - * @return {string} */ - generateObjectUrl(name: string, baseUrl?: string): string + generateObjectUrl(name: string, baseUrl?: string): string; /** * Head an object and get the meta info. - * @param {string} name - * @param {HeadObjectOptions} options - * @return {Promise} */ - head(name: string, options?: HeadObjectOptions): Promise + head(name: string, options?: HeadObjectOptions): Promise; /** * Get an object from the bucket. - * @param {string} name - * @param file - {String|WriteStream} file path or WriteStream instance to store the content If file is null or ignore this parameter, function will return info contains content property. - * @param {GetObjectOptions} options - * @return {Promise} */ - get(name: string, file?: any, options?: GetObjectOptions): Promise + get(name: string, file?: any, options?: GetObjectOptions): Promise; /** * Get an object read stream. - * @param {string} name - * @param {GetStreamOptions} options - * @return {Promise} */ - getStream(name?: string, options?: GetStreamOptions): Promise + getStream(name?: string, options?: GetStreamOptions): Promise; /** * Delete an object from the bucket. - * @param {string} name - * @param {RequestOptions} options - * @return {Promise} */ - delete(name: string, options?: RequestOptions): Promise + delete(name: string, options?: RequestOptions): Promise; /** * Copy an object from sourceName to name. - * @param {string} name - object name store on OSS - * @param {string} sourceName - source object name If sourceName start with /, meaning it's a full name contains the bucket name. e.g.: /otherbucket/logo.png meaning copy otherbucket logn.png object to current bucket. - * @param {CopyObjectOptions} options - * @return {Promise} */ - copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise + copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise; /** * Set an exists object meta. - * @param {string} name - * @param {UserMeta} meta - * @param {RequestOptions} options - * @return {Promise} */ - putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise + putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise; /** * Delete multi objects in one request. - * @param {Array} names - object names, max 1000 objects in once. - * @param {DeleteMultiOptions} options - * @return {Promise} */ - deleteMulti(names: Array, options?: DeleteMultiOptions): Promise + deleteMulti(names: string[], options?: DeleteMultiOptions): Promise; /** * Create a signature url for download or upload object. When you put object with signatureUrl ,you need to pass Content-Type.Please look at the example. - * @param {string} name - * @param {SignatureUrlOptions} options - * @return {string} */ - signatureUrl(name: string, options?: SignatureUrlOptions): string + signatureUrl(name: string, options?: SignatureUrlOptions): string; /** * Set object's ACL. - * @param {string} name - * @param {ACLType} acl - * @param {RequestOptions} options - * @return {Promise} */ - putACL(name: string, acl: ACLType, options?: RequestOptions): Promise + putACL(name: string, acl: ACLType, options?: RequestOptions): Promise; /** * Get object's ACL. - * @param {string} name - * @param {RequestOptions} options - * @return {Promise} */ - getACL(name: string, options?: RequestOptions): Promise + getACL(name: string, options?: RequestOptions): Promise; /** * Restore Object. - * @param {string} name - * @param {RequestOptions} options - * @return {Promise} */ - restore(name: string, options?: RequestOptions): Promise + restore(name: string, options?: RequestOptions): Promise; /** - * - * @param {string} name - * @param {InitMultipartUploadOptions} options - * @return {Promise} + * multi upload */ - initMultipartUpload(name: string, options?: InitMultipartUploadOptions): Promise + initMultipartUpload(name: string, options?: InitMultipartUploadOptions): Promise; /** * After initiating a Multipart Upload event, you can upload data in parts based on the specified object name and Upload ID. - * @param {string} name - object name - * @param {string} uploadId - get by initMultipartUpload api - * @param {number} partNo - range is 1-10000, If this range is exceeded, OSS returns the InvalidArgument's error code. - * @param file - is File or FileName, the whole file - Multipart Upload requires that the size of any Part other than the last Part is greater than 100KB. - In Node you can use File or FileName, but in browser you only can use File. - * @param {number} start - part start bytes e.g: 102400 - * @param {number} end - part end bytes e.g: 204800 - * @param {RequestOptions} options - * @return {Promise} */ - uploadPart(name: string, uploadId: string, partNo: number, file: any, start: number, end: number, options?: RequestOptions): Promise + uploadPart(name: string, uploadId: string, partNo: number, file: any, start: number, end: number, options?: RequestOptions): Promise; /** - * Using Upload Part Copy, you can copy data from an existing object and upload a part of the data. When copying a file larger than 1 GB, you must use the Upload Part Copy method. If you want to copy a file smaller than 1 GB, see Copy Object. - * @param {string} name - * @param {string} uploadId - * @param {number} partNo - * @param {string} range - * @param {{sourceKey: string; sourceBucketName: string}} sourceData - * @param {{timeout?: number; headers?: object}} options - * @return {Promise} + * Using Upload Part Copy, you can copy data from an existing object and upload a part of the data. + * When copying a file larger than 1 GB, you must use the Upload Part Copy method. If you want to copy a file smaller than 1 GB, see Copy Object. */ - uploadPartCopy(name: string, uploadId: string, partNo: number, range: string, sourceData: { sourceKey: string, sourceBucketName: string }, options: { timeout?: number, headers?: object }): Promise + uploadPartCopy( + name: string, + uploadId: string, + partNo: number, + range: string, + sourceData: { sourceKey: string, sourceBucketName: string }, + options: { timeout?: number, headers?: object } + ): Promise; /** * After uploading all data parts, you must call the Complete Multipart Upload API to complete Multipart Upload for the entire file. - * @param {string} name - * @param {string} uploadId - * @param {Array<{number: number; etag: string}>} parts - * @param {CompleteMultipartUploadOptions} options - * @return {Promise} */ - completeMultipartUpload(name: string, uploadId: string, parts: Array<{ number: number, etag: string }>, options?: CompleteMultipartUploadOptions): Promise + completeMultipartUpload( + name: string, + uploadId: string, + parts: Array<{ number: number, etag: string }>, + options?: CompleteMultipartUploadOptions + ): Promise; /** * Upload file with OSS multipart. - * this function contains initMultipartUpload, uploadPart, completeMultipartUpload. When you use multipartUpload api,if you encounter problems with ConnectionTimeoutError, you should handle ConnectionTimeoutError in your business code. - * How to resolve ConnectionTimeoutError, you can decrease partSize size 、 Increase timeout 、Retry request , or give tips in your business code; - * @param {string} name - * @param file - * @param {MultipartUploadOptions} options - * @return {Promise} */ - multipartUpload(name: string, file: any, options: MultipartUploadOptions): Promise + multipartUpload(name: string, file: any, options: MultipartUploadOptions): Promise; /** * Copy file with OSS multipart. * this function contains head, initMultipartUpload, uploadPartCopy, completeMultipartUpload. * When copying a file larger than 1 GB, you should use the Upload Part Copy method. If you want to copy a file smaller than 1 GB, see Copy Object. - * @param {string} name - * @param {MultipartUploadCopySourceData} sourceData - * @param {MultipartUploadOptions} options - * @return {Promise} */ - multipartUploadCopy(name: string, sourceData: MultipartUploadCopySourceData, options?: MultipartUploadOptions): Promise + multipartUploadCopy(name: string, sourceData: MultipartUploadCopySourceData, options?: MultipartUploadOptions): Promise; /** * The ListParts command can be used to list all successfully uploaded parts mapped to a specific upload ID, i.e.: those not completed and not aborted. - * @param {string} name - * @param {string} uploadId - * @param {ListPartsQuery} query - * @param {RequestOptions} options - * @return {Promise} */ - listParts(name: string, uploadId: string, query?: ListPartsQuery, options?: RequestOptions): Promise + listParts(name: string, uploadId: string, query?: ListPartsQuery, options?: RequestOptions): Promise; /** * List on-going multipart uploads, i.e.: those not completed and not aborted. - * @param {ListUploadsQuery} query - * @param {RequestOptions} options - * @return {Promise} */ - listUploads(query: ListUploadsQuery, options?: RequestOptions): Promise + listUploads(query: ListUploadsQuery, options?: RequestOptions): Promise; /** * Abort a multipart upload for object. - * @param {string} name - * @param {string} uploadId - * @param {RequestOptions} options - * @return {Promise} */ - abortMultipartUpload(name: string, uploadId: string, options?: RequestOptions): Promise + abortMultipartUpload(name: string, uploadId: string, options?: RequestOptions): Promise; /************************************************ RTMP Operations *************************************************************/ /** * Create a live channel. - * @param {string} id - * @param {PutChannelConf} conf - * @param {RequestOptions} options - * @return {Promise} */ - putChannel(id: string, conf: PutChannelConf, options?: RequestOptions): Promise + putChannel(id: string, conf: PutChannelConf, options?: RequestOptions): Promise; /** * Get live channel info. - * @param {string} id - * @param {RequestOptions} options - * @return {Promise<{data: PutChannelConf; res: NormalSuccessResponse}>} */ - getChannel(id: string, options?: RequestOptions): Promise<{ data: PutChannelConf, res: NormalSuccessResponse }> + getChannel(id: string, options?: RequestOptions): Promise<{ data: PutChannelConf, res: NormalSuccessResponse }>; /** * Delete a live channel. - * @param {string} id - * @param {RequestOptions} options - * @return {Promise} */ - deleteChannel(id: string, options?: RequestOptions): Promise + deleteChannel(id: string, options?: RequestOptions): Promise; /** * Change the live channel status. - * @param {string} id - * @param {string} status - * @param {RequestOptions} options - * @return {Promise} */ - putChannelStatus(id: string, status?: string, options?: RequestOptions): Promise + putChannelStatus(id: string, status?: string, options?: RequestOptions): Promise; /** * Get the live channel status. - * @param {string} id - * @param {RequestOptions} options - * @return {Promise} */ - getChannelStatus(id: string, options?: RequestOptions): Promise + getChannelStatus(id: string, options?: RequestOptions): Promise; /** * List channels. - * @param {ListChannelsQuery} query - * @param {RequestOptions} options - * @return {Promise} */ - listChannels(query: ListChannelsQuery, options?: RequestOptions): Promise + listChannels(query: ListChannelsQuery, options?: RequestOptions): Promise; /** * Get the live channel history. - * @param {string} id - * @param {RequestOptions} options - * @return {Promise} */ - getChannelHistory(id: string, options?: RequestOptions): Promise + getChannelHistory(id: string, options?: RequestOptions): Promise; /** * Create a VOD playlist for the channel. - * @param {string} id - * @param {string} name - * @param {{startTime: number; endTime: number}} time - * @param {RequestOptions} options - * @return {Promise} */ - createVod(id: string, name: string, time: { startTime: number, endTime: number }, options?: RequestOptions): Promise + createVod(id: string, name: string, time: { startTime: number, endTime: number }, options?: RequestOptions): Promise; /** * Get signatured rtmp url for publishing. - * @param {string} channelId - * @param {GetRtmpUrlOptions} options - * @return {string} */ - getRtmpUrl(channelId?: string, options?: GetRtmpUrlOptions): string - + getRtmpUrl(channelId?: string, options?: GetRtmpUrlOptions): string; } diff --git a/types/ali-oss/tsconfig.json b/types/ali-oss/tsconfig.json index b6f46ae8e8..62f030a4fd 100644 --- a/types/ali-oss/tsconfig.json +++ b/types/ali-oss/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/ali-oss/tslint.json b/types/ali-oss/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/ali-oss/tslint.json +++ b/types/ali-oss/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" } From e32ea94e933c8d7d426ef4ad9734fe4a2e8bdbdf Mon Sep 17 00:00:00 2001 From: quas94 Date: Fri, 28 Sep 2018 17:53:41 +1000 Subject: [PATCH 010/836] Add definitions for Dropbox Chooser --- .../dropbox-chooser/dropbox-chooser-tests.ts | 20 ++++++ types/dropbox-chooser/index.d.ts | 66 +++++++++++++++++++ types/dropbox-chooser/tsconfig.json | 24 +++++++ types/dropbox-chooser/tslint.json | 1 + 4 files changed, 111 insertions(+) create mode 100644 types/dropbox-chooser/dropbox-chooser-tests.ts create mode 100644 types/dropbox-chooser/index.d.ts create mode 100644 types/dropbox-chooser/tsconfig.json create mode 100644 types/dropbox-chooser/tslint.json diff --git a/types/dropbox-chooser/dropbox-chooser-tests.ts b/types/dropbox-chooser/dropbox-chooser-tests.ts new file mode 100644 index 0000000000..f0930733f8 --- /dev/null +++ b/types/dropbox-chooser/dropbox-chooser-tests.ts @@ -0,0 +1,20 @@ +// Tests for Dropbox Chooser DefinitelyTyped TS definitions + +const options: DropboxChooserOptions = { + success: (files: ReadonlyArray) => { + console.log('Success, selected files were:', files); + }, +}; + +const Dropbox = window.Dropbox!; +Dropbox.choose(options); + +const sampleFile: DropboxChooserFile = { + id: 'SAMPLE_ID', + name: 'HelloBox.jpg', + link: 'http://localhost/1.png', + bytes: 1024, + icon: 'http://localhost/icons/png.png', + thumbnailLink: 'http://localhost/thumbnails/1.png', + isDir: false, +}; diff --git a/types/dropbox-chooser/index.d.ts b/types/dropbox-chooser/index.d.ts new file mode 100644 index 0000000000..8c9db6f72d --- /dev/null +++ b/types/dropbox-chooser/index.d.ts @@ -0,0 +1,66 @@ +// Type definitions for Dropbox Chooser 1.0 +// Project: https://www.dropbox.com/developers/chooser +// Definitions by: Michael Su +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Dropbox { + interface DropboxChooser { + choose(options: ChooserOptions): void; + } + + interface ChooserOptions { + // alled when a user selects an item in the Chooser + success(files: ReadonlyArray): void; + + // called when the user closes the dialog without selecting a file + cancel?(): void; + + // default: 'preview' + linkType?: 'preview' | 'direct'; + + // default: false + multiselect?: boolean; + + // eg. '.png' + extensions?: string[]; + + // default: false + folderselect?: boolean; + + // any positive number + sizeLimit?: number; + } + + interface File { + // Unique ID for the file, compatible with Dropbox API v2. + id: string; + + // Name of the file. + name: string; + + // URL to access the file, which varies depending on the linkType specified when the + // Chooser was triggered. + link: string; + + // Size of the file in bytes. + bytes: number; + + // URL to a 64x64px icon for the file based on the file's extension. + icon: string; + + // A thumbnail URL generated when the user selects images and videos. + // If the user didn't select an image or video, no thumbnail will be included. + thumbnailLink?: string; + + // whether or not the file is actually a directory + isDir: boolean; + } +} + +type DropboxChooser = Dropbox.DropboxChooser; +type DropboxChooserOptions = Dropbox.ChooserOptions; +type DropboxChooserFile = Dropbox.File; + +interface Window { + Dropbox?: DropboxChooser; +} diff --git a/types/dropbox-chooser/tsconfig.json b/types/dropbox-chooser/tsconfig.json new file mode 100644 index 0000000000..88fb15cc91 --- /dev/null +++ b/types/dropbox-chooser/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dropbox-chooser-tests.ts" + ] +} diff --git a/types/dropbox-chooser/tslint.json b/types/dropbox-chooser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dropbox-chooser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 38728d9cc8d956d6a1c391a2a0e99a8236923699 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomek=20=C5=81aziuk?= Date: Tue, 16 Oct 2018 13:57:01 +0200 Subject: [PATCH 011/836] description --- types/range-parser/index.d.ts | 4 ++-- types/range-parser/tsconfig.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/range-parser/index.d.ts b/types/range-parser/index.d.ts index a1bcf4c9dc..13d331041a 100644 --- a/types/range-parser/index.d.ts +++ b/types/range-parser/index.d.ts @@ -4,11 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** - * Returns `-1` when unsatisfiable and `-2` when syntactically invalid. - * * When ranges are returned, the array has a "type" property which is the type of * range that is required (most commonly, "bytes"). Each array element is an object * with a "start" and "end" property for the portion of the range. + * + * @returns `-1` when unsatisfiable and `-2` when syntactically invalid, ranges otherwise. */ declare function RangeParser(size: number, str: string, options?: RangeParser.Options): RangeParser.Result | RangeParser.Ranges; diff --git a/types/range-parser/tsconfig.json b/types/range-parser/tsconfig.json index 15585886a9..dc6de494bf 100644 --- a/types/range-parser/tsconfig.json +++ b/types/range-parser/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "range-parser-tests.ts" ] -} \ No newline at end of file +} From 6d51909cafaad3b3634ad057bfeb2f7eac011872 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomek=20=C5=81aziuk?= Date: Tue, 16 Oct 2018 14:10:42 +0200 Subject: [PATCH 012/836] --isolatedModules fix --- types/range-parser/index.d.ts | 7 +++---- types/range-parser/range-parser-tests.ts | 4 ++-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/types/range-parser/index.d.ts b/types/range-parser/index.d.ts index 13d331041a..e8e6ae4451 100644 --- a/types/range-parser/index.d.ts +++ b/types/range-parser/index.d.ts @@ -27,10 +27,9 @@ declare namespace RangeParser { */ combine?: boolean; } - const enum Result { - invaild = -2, - unsatisifiable = -1, - } + type ResultUnsatisfiable = -1; + type ResultInvalid = -2; + type Result = ResultUnsatisfiable | ResultInvalid; } export = RangeParser; diff --git a/types/range-parser/range-parser-tests.ts b/types/range-parser/range-parser-tests.ts index ec1ffa6e4e..2c18e3f9dc 100644 --- a/types/range-parser/range-parser-tests.ts +++ b/types/range-parser/range-parser-tests.ts @@ -2,8 +2,8 @@ import RangeParser = require('range-parser'); declare var console: { assert(b: boolean): void }; -console.assert(RangeParser(200, `malformed`) === RangeParser.Result.invaild); -console.assert(RangeParser(200, `bytes=500-20`) === RangeParser.Result.unsatisifiable); +console.assert(RangeParser(200, `malformed`) === -2); +console.assert(RangeParser(200, `bytes=500-20`) === -1); const range = RangeParser(1000, `bytes=0-499`); From 730393928c0de536fc827c64c72609eac92f11fe Mon Sep 17 00:00:00 2001 From: juwar Date: Mon, 22 Oct 2018 09:13:40 -0700 Subject: [PATCH 013/836] Add maxFontSize and minFontSize to series that have it. --- types/highcharts/index.d.ts | 110 +++++++++++++++++++++++++++++++++++- 1 file changed, 108 insertions(+), 2 deletions(-) diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index dcde50413d..d3036a869a 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -4644,6 +4644,14 @@ declare namespace Highcharts { * allows setting a separate color for the line without altering the fillColor. */ lineColor?: string | Gradient; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number; /** * A separate color for the negative part of the area. * @since 3.0 @@ -4742,6 +4750,10 @@ declare namespace Highcharts { * @since 2.3.0 */ grouping?: boolean; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number; /** * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the * columns from becoming too wide when there is a small number of points in the chart. @@ -4749,6 +4761,10 @@ declare namespace Highcharts { * @since 4.1.8 */ maxPointWidth?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number; /** * The minimal height for a column or width for a bar. By default, 0 values are not shown. To visualize a 0 (or * close to zero) point, set the minimal point length to a pixel value like 3. In stacked column charts, @@ -4843,6 +4859,10 @@ declare namespace Highcharts { * @since 3.0 */ displayNegative?: boolean; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number; /** * Maximum bubble size. Bubbles will automatically size between the minSize and maxSize to reflect the z value of * each bubble. Can be either pixels (when no unit is given), or a percentage of the smallest one of the plot width @@ -4851,6 +4871,10 @@ declare namespace Highcharts { * @since 3.0 */ maxSize?: string | number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number; /** * Minimum bubble size. Bubbles will automatically size between the minSize and maxSize to reflect the z value of * each bubble. Can be either pixels (when no unit is given), or a percentage of the smallest one of the plot width @@ -5136,6 +5160,14 @@ declare namespace Highcharts { * Options for the dial or arrow pointer of the gauge. */ dial?: Dial; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number; /** * Allow the dial to overshoot the end of the perimeter axis by this many degrees. Say if the gauge axis goes from 0 * to 60, a value of 100, or 1000, will show 5 degrees beyond the end of the axis. Defaults to 0. @@ -5204,6 +5236,10 @@ declare namespace Highcharts { * @default 50 */ cropTreshold?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number; /** * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the * columns from becoming too wide when there is a small number of points in the chart. @@ -5211,6 +5247,10 @@ declare namespace Highcharts { * @since 4.1.8 */ maxPointWidth?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number; /** * The row size - how many Y axis units each heatmap row should span. * @default 1 @@ -5229,6 +5269,14 @@ declare namespace Highcharts { } interface LineChart extends SeriesChart { + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number; /** * Whether to apply steps to the line. Possible values are left, center and right. Prior to 2.3.5, only left was * supported. @@ -5299,6 +5347,14 @@ declare namespace Highcharts { * @since 2.0 */ innerSize?: number | string; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number; /** * The minimum size for a pie in response to auto margins. The pie will try to shrink to make room for data labels * in side the plot area, but only to this size. @@ -5346,6 +5402,14 @@ declare namespace Highcharts { * @default 0 */ lineWidth?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number; } interface PyramidChart extends SeriesChart { @@ -5420,7 +5484,16 @@ declare namespace Highcharts { width?: number | string; } - interface ScatterChart extends SeriesChart { } + interface ScatterChart extends SeriesChart { + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number; + } /** * A gauge showing values using a filled arc with colors indicating the value. The solid gauge plots values against the @@ -5456,7 +5529,16 @@ declare namespace Highcharts { wrap?: boolean; } - interface SplineChart extends SeriesChart { } + interface SplineChart extends SeriesChart { + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number; + } /** * The size of the point shape is determined by its value relative to its siblings values. Requires the module @@ -5528,6 +5610,10 @@ declare namespace Highcharts { * Set options on specific levels. Takes precedence over series options, but not point options. */ levels?: TreeMapLevel[]; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number; /** * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the * columns from becoming too wide when there is a small number of points in the chart. @@ -5535,6 +5621,10 @@ declare namespace Highcharts { * @since 4.1.8 */ maxPointWidth?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number; /** * The sort index of the point inside the treemap level. * @since 4.1.10 @@ -5599,6 +5689,14 @@ declare namespace Highcharts { * @since 5.0.12 */ exposeElementToA11y?: boolean; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number; /** * This option decides which algorithm is used for placement, and rotation of a word. The choice of algorith is * therefore a crucial part of the resulting layout of the wordcloud. It is possible for users to add their own @@ -5799,6 +5897,14 @@ declare namespace Highcharts { * The sequential index of the series in the legend. */ legendIndex?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number; /** * The name of the series as shown in the legend, tooltip etc. */ From 7cda494c6987dec64f6ceb59dccb14341d3ea49f Mon Sep 17 00:00:00 2001 From: juwar Date: Mon, 22 Oct 2018 09:21:02 -0700 Subject: [PATCH 014/836] Update version at top of file. --- types/highcharts/index.d.ts | 334 +++++++++++++++++++++++++++--------- 1 file changed, 255 insertions(+), 79 deletions(-) diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index d3036a869a..7da3ac752d 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Highcharts 5.0.13 +// Type definitions for Highcharts 5.0.32 // Project: http://www.highcharts.com/ // Definitions by: Damiano Gambarotto // Dan Lewi Harkestad @@ -292,7 +292,7 @@ declare namespace Highcharts { * @default null * @since 2.3 */ - innerRadius?: number | string | null; + innerRadius?: number | string | null; /** * Text labels for the plot bands */ @@ -494,12 +494,12 @@ declare namespace Highcharts { shadow?: | boolean | { - color?: string | Gradient; - offsetX?: number; - offsetY?: number; - opacity?: number; - width?: number; - }; + color?: string | Gradient; + offsetX?: number; + offsetY?: number; + opacity?: number; + width?: number; + }; /** * The name of a symbol to use for the border around the label. Symbols are predefined functions on the Renderer object. * @default "callout" @@ -1294,7 +1294,7 @@ declare namespace Highcharts { * Use this in cases where a linear gradient between a minColor and maxColor is not sufficient. * The stops is an array of tuples, where the first item is a float between 0 and 1 assigning the relative position in the gradient, and the second item is the color. */ - stops?: Array>; + stops?: Array>; /** * The amount of ticks to draw on the axis. This opens up for aligning the ticks of multiple charts or panes within * a chart. This option overrides the tickPixelInterval option. @@ -1859,7 +1859,9 @@ declare namespace Highcharts { interface Gradient { linearGradient?: LinearGradient | number[]; radialGradient?: { - cx: number; cy: number; r: number; + cx: number; + cy: number; + r: number; }; stops?: any[][]; /** @@ -2015,7 +2017,7 @@ declare namespace Highcharts { /** * The button stroke width */ - 'stroke-width'?: number; + "stroke-width"?: number; /** * The border radius */ @@ -3416,7 +3418,7 @@ declare namespace Highcharts { * @default ['50%', '50%'] * @since 2.3.0 */ - center?: Array; + center?: Array; /** * The end angle of the polar X axis or gauge value axis, given in degrees where 0 is north. * @default startAngle + 360 @@ -4033,7 +4035,7 @@ declare namespace Highcharts { halo?: boolean | Halo; } - interface PieStates extends BarStates, LineStates { } + interface PieStates extends BarStates, LineStates {} interface AreaZone { /** @@ -4682,11 +4684,9 @@ declare namespace Highcharts { dataLabels?: RangeDataLabels; } - interface AreaSplineChart extends AreaChart { - } + interface AreaSplineChart extends AreaChart {} - interface AreaSplineRangeChart extends AreaRangeChart { - } + interface AreaSplineRangeChart extends AreaRangeChart {} interface BarChart extends SeriesChart { /** @@ -4925,8 +4925,7 @@ declare namespace Highcharts { zThreshold?: number; } - interface ColumnChart extends BarChart { - } + interface ColumnChart extends BarChart {} /** * The column range is a cartesian series type with higher and lower Y values along an X axis. Requires @@ -5874,7 +5873,14 @@ declare namespace Highcharts { * [3, 7, 8] * */ - data?: Array; + data?: Array< + | number + | [number, number] + | [string, number] + | [string, number, number] + | [number, number, number] + | DataPoint + >; /** * A description of the series to add to the screen reader information about the series. * @since 5.0.0 @@ -5942,31 +5948,73 @@ declare namespace Highcharts { zIndex?: number; } - interface SeriesOptions extends IndividualSeriesOptions, SeriesChart { } + interface SeriesOptions extends IndividualSeriesOptions, SeriesChart {} - interface AreaChartSeriesOptions extends IndividualSeriesOptions, AreaChart { } - interface AreaRangeChartSeriesOptions extends IndividualSeriesOptions, AreaRangeChart { } - interface AreaSplineChartSeriesOptions extends IndividualSeriesOptions, AreaSplineChart { } - interface AreaSplineRangeChartSeriesOptions extends IndividualSeriesOptions, AreaSplineRangeChart { } - interface BarChartSeriesOptions extends IndividualSeriesOptions, BarChart { } - interface BoxPlotChartSeriesOptions extends IndividualSeriesOptions, BoxPlotChart { } - interface BubbleChartSeriesOptions extends IndividualSeriesOptions, BubbleChart { } - interface ColumnChartSeriesOptions extends IndividualSeriesOptions, ColumnChart { } - interface ColumnRangeChartSeriesOptions extends IndividualSeriesOptions, ColumnRangeChart { } - interface ErrorBarChartSeriesOptions extends IndividualSeriesOptions, ErrorBarChart { } - interface FunnelChartSeriesOptions extends IndividualSeriesOptions, FunnelChart { } - interface GaugeChartSeriesOptions extends IndividualSeriesOptions, GaugeChart { } - interface HeatMapSeriesOptions extends IndividualSeriesOptions, HeatMapChart { } - interface LineChartSeriesOptions extends IndividualSeriesOptions, LineChart { } - interface PieChartSeriesOptions extends IndividualSeriesOptions, PieChart { } - interface PolygonChartSeriesOptions extends IndividualSeriesOptions, PolygonChart { } - interface PyramidChartSeriesOptions extends IndividualSeriesOptions, PyramidChart { } - interface ScatterChartSeriesOptions extends IndividualSeriesOptions, ScatterChart { } - interface SolidGaugeChartSeriesOptions extends IndividualSeriesOptions, SolidGaugeChart { } - interface SplineChartSeriesOptions extends IndividualSeriesOptions, SplineChart { } - interface TreeMapChartSeriesOptions extends IndividualSeriesOptions, TreeMapChart { } - interface WaterFallChartSeriesOptions extends IndividualSeriesOptions, WaterFallChart { } - interface WordCloudChartSeriesOptions extends IndividualSeriesOptions, WordCloudChart { } + interface AreaChartSeriesOptions + extends IndividualSeriesOptions, + AreaChart {} + interface AreaRangeChartSeriesOptions + extends IndividualSeriesOptions, + AreaRangeChart {} + interface AreaSplineChartSeriesOptions + extends IndividualSeriesOptions, + AreaSplineChart {} + interface AreaSplineRangeChartSeriesOptions + extends IndividualSeriesOptions, + AreaSplineRangeChart {} + interface BarChartSeriesOptions extends IndividualSeriesOptions, BarChart {} + interface BoxPlotChartSeriesOptions + extends IndividualSeriesOptions, + BoxPlotChart {} + interface BubbleChartSeriesOptions + extends IndividualSeriesOptions, + BubbleChart {} + interface ColumnChartSeriesOptions + extends IndividualSeriesOptions, + ColumnChart {} + interface ColumnRangeChartSeriesOptions + extends IndividualSeriesOptions, + ColumnRangeChart {} + interface ErrorBarChartSeriesOptions + extends IndividualSeriesOptions, + ErrorBarChart {} + interface FunnelChartSeriesOptions + extends IndividualSeriesOptions, + FunnelChart {} + interface GaugeChartSeriesOptions + extends IndividualSeriesOptions, + GaugeChart {} + interface HeatMapSeriesOptions + extends IndividualSeriesOptions, + HeatMapChart {} + interface LineChartSeriesOptions + extends IndividualSeriesOptions, + LineChart {} + interface PieChartSeriesOptions extends IndividualSeriesOptions, PieChart {} + interface PolygonChartSeriesOptions + extends IndividualSeriesOptions, + PolygonChart {} + interface PyramidChartSeriesOptions + extends IndividualSeriesOptions, + PyramidChart {} + interface ScatterChartSeriesOptions + extends IndividualSeriesOptions, + ScatterChart {} + interface SolidGaugeChartSeriesOptions + extends IndividualSeriesOptions, + SolidGaugeChart {} + interface SplineChartSeriesOptions + extends IndividualSeriesOptions, + SplineChart {} + interface TreeMapChartSeriesOptions + extends IndividualSeriesOptions, + TreeMapChart {} + interface WaterFallChartSeriesOptions + extends IndividualSeriesOptions, + WaterFallChart {} + interface WordCloudChartSeriesOptions + extends IndividualSeriesOptions, + WordCloudChart {} interface DataPoint { /** @@ -6321,7 +6369,12 @@ declare namespace Highcharts { * * @default null */ - crosshairs?: boolean | [boolean, boolean] | CrosshairObject | [CrosshairObject, CrosshairObject] | null; + crosshairs?: + | boolean + | [boolean, boolean] + | CrosshairObject + | [CrosshairObject, CrosshairObject] + | null; /** * Enable or disable the tooltip. * @default true @@ -6380,7 +6433,11 @@ declare namespace Highcharts { * The return should be an object containing x and y values, for example { x: 100, y: 100 }. * @since 2.2.4 */ - positioner?(labelWidth: number, labelHeight: number, point: PlotPoint): { x: number; y: number; }; + positioner?( + labelWidth: number, + labelHeight: number, + point: PlotPoint + ): { x: number; y: number }; /** * Whether to apply a drop shadow to the tooltip. * @default true @@ -6751,7 +6808,13 @@ declare namespace Highcharts { * The animation can also be a configuration object with properties duration and easing. * @since 1.2.0 */ - setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | Animation, eventArguments?: any): void; + setExtremes( + min?: number, + max?: number, + redraw?: boolean, + animation?: boolean | Animation, + eventArguments?: any + ): void; /** * Update the title of the axis after render time. * @param title The new title options on the same format as given in xAxis.title. @@ -6800,7 +6863,12 @@ declare namespace Highcharts { * The animation can also be a configuration object with properties duration and easing. * @since 3.0 */ - addAxis(options: AxisOptions, isX?: boolean, redraw?: boolean, animation?: boolean | Animation): AxisObject; + addAxis( + options: AxisOptions, + isX?: boolean, + redraw?: boolean, + animation?: boolean | Animation + ): AxisObject; /** * Set a new credits label for the chart. * @param A configuration object for the credits as defined at credits. @@ -6815,7 +6883,11 @@ declare namespace Highcharts { * @param [boolean] redraw * @since 1.2.0 */ - addSeries(options: T, redraw?: boolean, animation?: boolean | Animation): SeriesObject; + addSeries( + options: T, + redraw?: boolean, + animation?: boolean | Animation + ): SeriesObject; /** * Add a series to the chart as drilldown from a specific point in the parent series. This method is used for async * drilldown, when clicking a point in a series should result in loading and displaying a more high-resolution @@ -6824,7 +6896,10 @@ declare namespace Highcharts { * @param seriesOptions The series options, as documented under plotOptions.series and under the plotOptions for each series type. * @since 3.0.8 */ - addSeriesAsDrilldown(point: PointObject, seriesOptions: IndividualSeriesOptions): void; + addSeriesAsDrilldown( + point: PointObject, + seriesOptions: IndividualSeriesOptions + ): void; chartHeight?: number; chartWidth?: number; /** @@ -6898,7 +6973,10 @@ declare namespace Highcharts { * exported chart. Same as the exportChart params. * @since 2.0 */ - exportChartLocal(options: ExportingOptions, chartOptions: Options): void; + exportChartLocal( + options: ExportingOptions, + chartOptions: Options + ): void; /** * Get an axis, series or point by its id as given in the configuration options. * @param id The id of the axis, series or point to get. @@ -6975,7 +7053,11 @@ declare namespace Highcharts { * @param animation Defaults to true. When true, the resize will be animated with default animation options. * The animation can also be a configuration object with properties duration and easing. */ - setSize(width: number, height: number, animation?: boolean | Animation): void; + setSize( + width: number, + height: number, + animation?: boolean | Animation + ): void; /** * Set a new title or subtitle for the chart * @param title A configuration object for the new title as defined at #title. @@ -6983,7 +7065,11 @@ declare namespace Highcharts { * @param [boolean] redraw Whether to redraw the chart. Defaults to true. * @since 2.1.0 */ - setTitle(title: TitleOptions, subtitle?: SubtitleOptions, redraw?: boolean): void; + setTitle( + title: TitleOptions, + subtitle?: SubtitleOptions, + redraw?: boolean + ): void; /** * Dim the chart's plot area and show a loading label text. Options for the loading screen are defined at * options.loading. A custom text can be given as a parameter for loading. @@ -7015,7 +7101,12 @@ declare namespace Highcharts { * @param [(boolean | AnimationOptions)] animation Whether to apply animation, and optionally animation configuration. * @since 5.0.0 */ - update(options: Options, redraw?: boolean, oneToOne?: boolean, animation?: boolean | AnimationOptions): void; + update( + options: Options, + redraw?: boolean, + oneToOne?: boolean, + animation?: boolean | AnimationOptions + ): void; /** * This method is deprecated as of 2.0.1. Updating the chart position after a move operation is no longer necessary. * @since 1.2.5 @@ -7052,7 +7143,10 @@ declare namespace Highcharts { * and in these cases the chart object will not be finished directly after callingnew Highcharts.Chart(). * s a consequence, code that relies on the newly built Chart object should always run in the callback. Defining a chart.event.load handler is equivalent. */ - new (options: Options, callback: (chart: ChartObject) => void): ChartObject; + new ( + options: Options, + callback: (chart: ChartObject) => void + ): ChartObject; /** * This is the constructor for creating a new chart object. * @param renderTo The id or a reference to a DOM element where the chart should be rendered (since v4.2.0). @@ -7068,7 +7162,11 @@ declare namespace Highcharts { * and in these cases the chart object will not be finished directly after callingnew Highcharts.Chart(). * As a consequence, code that relies on the newly built Chart object should always run in the callback. Defining a chart.event.load handler is equivalent. */ - new (renderTo: string | HTMLElement, options: Options, callback: (chart: ChartObject) => void): ChartObject; + new ( + renderTo: string | HTMLElement, + options: Options, + callback: (chart: ChartObject) => void + ): ChartObject; } /** @@ -7121,7 +7219,7 @@ declare namespace Highcharts { * @return An object containing x, y, width and height values for the element. * @since 2.0 */ - getBBox(): { x: number; y: number; height: number; width: number; }; + getBBox(): { x: number; y: number; height: number; width: number }; /** * Apply an event handler to the element * @param eventType The event type to attach, for example 'click', 'mouseover', 'touch'. @@ -7160,7 +7258,14 @@ declare namespace Highcharts { * @param end The ending angle of the arc in radians, where 0 is to the right and -Math.PI/2 is up. * @since 2.0 */ - arc(centerX: number, centerY: number, outerRadius: number, innerRadius: number, start: number, end: number): ElementObject; + arc( + centerX: number, + centerY: number, + outerRadius: number, + innerRadius: number, + start: number, + end: number + ): ElementObject; /** * Draw circle on the renderer canvas. * @param centerX The x position of the circle's center in the SVG element. @@ -7200,7 +7305,13 @@ declare namespace Highcharts { * @param height The height of the image. * @since 2.0 */ - image(source: string, x: number, y: number, width: number, height: number): ElementObject; + image( + source: string, + x: number, + y: number, + width: number, + height: number + ): ElementObject; /** * Draw a label, which is an extended text element with support for border and background. Highcharts creates a g * element with a text and a path or rect inside, to make it behave somewhat like a HTML div. Border and background @@ -7218,7 +7329,17 @@ declare namespace Highcharts { * @param [string] className A class name for the g element surrounding the label. * @since 2.0 */ - label(str: string, x: number, y: number, shape?: string, anchorX?: number, anchorY?: number, useHTML?: boolean, baseline?: boolean, className?: string): ElementObject; + label( + str: string, + x: number, + y: number, + shape?: string, + anchorX?: number, + anchorY?: number, + useHTML?: boolean, + baseline?: boolean, + className?: string + ): ElementObject; /** * Add a path based on SVG's path commands. In SVG capable browsers all path commands are supported, but in VML only * a subset is supported: absolute moveTo (M), absolute lineTo (L), absolute curveTo (C) and close (Z). @@ -7234,7 +7355,13 @@ declare namespace Highcharts { * @param cornerRadius The corner radius of all the rectangle's corners. * @since 2.0 */ - rect(x: number, y: number, width: number, height: number, cornerRadius: number): ElementObject; + rect( + x: number, + y: number, + width: number, + height: number, + cornerRadius: number + ): ElementObject; /** * Draw text. The text can contain a subset of HTML, like spans and anchors and some basic text styling of these. * For more advanced features like border and background, use label instead. @@ -7262,7 +7389,11 @@ declare namespace Highcharts { } interface Renderer { - new (parentNode: HTMLElement, width: number, height: number): RendererObject; + new ( + parentNode: HTMLElement, + width: number, + height: number + ): RendererObject; } interface Static { @@ -7274,12 +7405,19 @@ declare namespace Highcharts { * As Highcharts.Chart, but without need for the new keyword. * @since 4.2.0 */ - chart(options: Options, callback?: (chart: ChartObject) => void): ChartObject; + chart( + options: Options, + callback?: (chart: ChartObject) => void + ): ChartObject; /** * As Highcharts.Chart, but without need for the new keyword. * @since 4.2.0 */ - chart(renderTo: string | HTMLElement, options: Options, callback?: (chart: ChartObject) => void): ChartObject; + chart( + renderTo: string | HTMLElement, + options: Options, + callback?: (chart: ChartObject) => void + ): ChartObject; /** * An array containing the current chart objects in the page. A chart's position in the array is preserved * throughout the page's lifetime. When a chart is destroyed, the array item becomes undefined. @@ -7318,7 +7456,12 @@ declare namespace Highcharts { * @param decimalPoint The decimal point. Defaults to '.' or to the string specified globally in options.lang.decimalPoint. * @param thousandsSep The thousands separator. Defaults to ' ' or to the string specified globally in options.lang.thousandsSep. */ - numberFormat(value: number, decimals?: number, decimalPoint?: string, thousandsSep?: string): string; + numberFormat( + value: number, + decimals?: number, + decimalPoint?: string, + thousandsSep?: string + ): string; /** * Sets the options globally for all charts created after this has been called. Takes an options JavaScript object * structure as the argument. These options are merged with the default options and the result is returned. @@ -7343,7 +7486,11 @@ declare namespace Highcharts { * @param type The type of behavior you are extending. * @param cb The function that executes when the behavior occurs. */ - wrap(prototype: any, type: string, cb: (proceed: Function, ...args: any[]) => void): void; + wrap( + prototype: any, + type: string, + cb: (proceed: Function, ...args: any[]) => void + ): void; /** * Add an event listener. @@ -7356,9 +7503,11 @@ declare namespace Highcharts { * @param cb The function callback to execute when the event is fired. * @returns A callback function to remove the added event. */ - addEvent(element: HTMLElement | ElementObject | object, - type: string, - cb: (evt: Event) => void): () => void; + addEvent( + element: HTMLElement | ElementObject | object, + type: string, + cb: (evt: Event) => void + ): () => void; /** * Fire an event that was registered with @@ -7370,10 +7519,12 @@ declare namespace Highcharts { * @param eventArguments Custom event arguments that are passed on as an argument to the event handler. * @param defaultFunction The default function to execute if the other listeners haven't returned false. */ - fireEvent(element: HTMLElement | ElementObject | object, - type: string, - eventArguments?: any, - defaultFunction?: () => void): void; + fireEvent( + element: HTMLElement | ElementObject | object, + type: string, + eventArguments?: any, + defaultFunction?: () => void + ): void; distribute(array: any[], value: number): void; @@ -7443,7 +7594,11 @@ declare namespace Highcharts { * The animation can also be a configuration object with properties duration and easing. * @since 1.2.0 */ - slice(sliced?: boolean, redraw?: boolean, animation?: boolean | Animation): void; + slice( + sliced?: boolean, + redraw?: boolean, + animation?: boolean | Animation + ): void; /** * The total of a stack for stacked series, or pie in pie charts. */ @@ -7459,7 +7614,11 @@ declare namespace Highcharts { * The animation can also be a configuration object with properties duration and easing. * @since 1.2.0 */ - update(options: number | [number, number] | DataPoint, redraw?: boolean, animation?: boolean | Animation): void; + update( + options: number | [number, number] | DataPoint, + redraw?: boolean, + animation?: boolean | Animation + ): void; /** * The x value for the point. * @since 1.2.0 @@ -7500,7 +7659,12 @@ declare namespace Highcharts { * Use this option for live charts monitoring a value over time. * @since 1.2.0 */ - addPoint(options: number | [number, number] | DataPoint, redraw?: boolean, shift?: boolean, animation?: boolean | Animation): void; + addPoint( + options: number | [number, number] | DataPoint, + redraw?: boolean, + shift?: boolean, + animation?: boolean | Animation + ): void; /** * Read only. The chart that the series belongs to. * @since 1.2.0 @@ -7544,7 +7708,11 @@ declare namespace Highcharts { * The animation can also be a configuration object with properties duration and easing. * @since 4.1.0 */ - removePoint(index: number, redraw?: boolean, animation?: boolean | Animation): void; + removePoint( + index: number, + redraw?: boolean, + animation?: boolean | Animation + ): void; /** * Select or unselect the series. This means its selected property is set,the checkbox in the legend is toggled and * when selected, the series is returned in the chart.getSelectedSeries() method. @@ -7569,7 +7737,12 @@ declare namespace Highcharts { * This option prevents this, and makes setData behave like it did prior to Highcharts 3.0.10. * @since 1.2.0 */ - setData(data: number[] | number[][] | DataPoint[], redraw?: boolean, animation?: boolean | Animation, updatePoints?: boolean): void; + setData( + data: number[] | number[][] | DataPoint[], + redraw?: boolean, + animation?: boolean | Animation, + updatePoints?: boolean + ): void; /** * A utility function to show or hide the series with an optional redraw. * @param [boolean] visible - Whether to show or hide the series. If undefined, the visibility is toggled. @@ -7656,7 +7829,10 @@ declare global { * @param callback Callback function used to manipulate the constructed chart instance * @return current {JQuery} selector the current JQuery selector */ - highcharts(options: Highcharts.Options, callback: (chart: Highcharts.ChartObject) => void): JQuery; + highcharts( + options: Highcharts.Options, + callback: (chart: Highcharts.ChartObject) => void + ): JQuery; } } From 2083505b395c2742083e085386ea96a503eb70af Mon Sep 17 00:00:00 2001 From: juwar Date: Mon, 22 Oct 2018 09:31:35 -0700 Subject: [PATCH 015/836] Revert the formatting --- types/highcharts/index.d.ts | 332 +++++++++--------------------------- 1 file changed, 78 insertions(+), 254 deletions(-) diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 7da3ac752d..644dc1a169 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -292,7 +292,7 @@ declare namespace Highcharts { * @default null * @since 2.3 */ - innerRadius?: number | string | null; + innerRadius?: number | string | null; /** * Text labels for the plot bands */ @@ -494,12 +494,12 @@ declare namespace Highcharts { shadow?: | boolean | { - color?: string | Gradient; - offsetX?: number; - offsetY?: number; - opacity?: number; - width?: number; - }; + color?: string | Gradient; + offsetX?: number; + offsetY?: number; + opacity?: number; + width?: number; + }; /** * The name of a symbol to use for the border around the label. Symbols are predefined functions on the Renderer object. * @default "callout" @@ -1294,7 +1294,7 @@ declare namespace Highcharts { * Use this in cases where a linear gradient between a minColor and maxColor is not sufficient. * The stops is an array of tuples, where the first item is a float between 0 and 1 assigning the relative position in the gradient, and the second item is the color. */ - stops?: Array>; + stops?: Array>; /** * The amount of ticks to draw on the axis. This opens up for aligning the ticks of multiple charts or panes within * a chart. This option overrides the tickPixelInterval option. @@ -1859,9 +1859,7 @@ declare namespace Highcharts { interface Gradient { linearGradient?: LinearGradient | number[]; radialGradient?: { - cx: number; - cy: number; - r: number; + cx: number; cy: number; r: number; }; stops?: any[][]; /** @@ -2017,7 +2015,7 @@ declare namespace Highcharts { /** * The button stroke width */ - "stroke-width"?: number; + 'stroke-width'?: number; /** * The border radius */ @@ -3418,7 +3416,7 @@ declare namespace Highcharts { * @default ['50%', '50%'] * @since 2.3.0 */ - center?: Array; + center?: Array; /** * The end angle of the polar X axis or gauge value axis, given in degrees where 0 is north. * @default startAngle + 360 @@ -4035,7 +4033,7 @@ declare namespace Highcharts { halo?: boolean | Halo; } - interface PieStates extends BarStates, LineStates {} + interface PieStates extends BarStates, LineStates { } interface AreaZone { /** @@ -4684,9 +4682,11 @@ declare namespace Highcharts { dataLabels?: RangeDataLabels; } - interface AreaSplineChart extends AreaChart {} + interface AreaSplineChart extends AreaChart { + } - interface AreaSplineRangeChart extends AreaRangeChart {} + interface AreaSplineRangeChart extends AreaRangeChart { + } interface BarChart extends SeriesChart { /** @@ -4925,7 +4925,8 @@ declare namespace Highcharts { zThreshold?: number; } - interface ColumnChart extends BarChart {} + interface ColumnChart extends BarChart { + } /** * The column range is a cartesian series type with higher and lower Y values along an X axis. Requires @@ -5873,14 +5874,7 @@ declare namespace Highcharts { * [3, 7, 8] * */ - data?: Array< - | number - | [number, number] - | [string, number] - | [string, number, number] - | [number, number, number] - | DataPoint - >; + data?: Array; /** * A description of the series to add to the screen reader information about the series. * @since 5.0.0 @@ -5948,73 +5942,31 @@ declare namespace Highcharts { zIndex?: number; } - interface SeriesOptions extends IndividualSeriesOptions, SeriesChart {} + interface SeriesOptions extends IndividualSeriesOptions, SeriesChart { } - interface AreaChartSeriesOptions - extends IndividualSeriesOptions, - AreaChart {} - interface AreaRangeChartSeriesOptions - extends IndividualSeriesOptions, - AreaRangeChart {} - interface AreaSplineChartSeriesOptions - extends IndividualSeriesOptions, - AreaSplineChart {} - interface AreaSplineRangeChartSeriesOptions - extends IndividualSeriesOptions, - AreaSplineRangeChart {} - interface BarChartSeriesOptions extends IndividualSeriesOptions, BarChart {} - interface BoxPlotChartSeriesOptions - extends IndividualSeriesOptions, - BoxPlotChart {} - interface BubbleChartSeriesOptions - extends IndividualSeriesOptions, - BubbleChart {} - interface ColumnChartSeriesOptions - extends IndividualSeriesOptions, - ColumnChart {} - interface ColumnRangeChartSeriesOptions - extends IndividualSeriesOptions, - ColumnRangeChart {} - interface ErrorBarChartSeriesOptions - extends IndividualSeriesOptions, - ErrorBarChart {} - interface FunnelChartSeriesOptions - extends IndividualSeriesOptions, - FunnelChart {} - interface GaugeChartSeriesOptions - extends IndividualSeriesOptions, - GaugeChart {} - interface HeatMapSeriesOptions - extends IndividualSeriesOptions, - HeatMapChart {} - interface LineChartSeriesOptions - extends IndividualSeriesOptions, - LineChart {} - interface PieChartSeriesOptions extends IndividualSeriesOptions, PieChart {} - interface PolygonChartSeriesOptions - extends IndividualSeriesOptions, - PolygonChart {} - interface PyramidChartSeriesOptions - extends IndividualSeriesOptions, - PyramidChart {} - interface ScatterChartSeriesOptions - extends IndividualSeriesOptions, - ScatterChart {} - interface SolidGaugeChartSeriesOptions - extends IndividualSeriesOptions, - SolidGaugeChart {} - interface SplineChartSeriesOptions - extends IndividualSeriesOptions, - SplineChart {} - interface TreeMapChartSeriesOptions - extends IndividualSeriesOptions, - TreeMapChart {} - interface WaterFallChartSeriesOptions - extends IndividualSeriesOptions, - WaterFallChart {} - interface WordCloudChartSeriesOptions - extends IndividualSeriesOptions, - WordCloudChart {} + interface AreaChartSeriesOptions extends IndividualSeriesOptions, AreaChart { } + interface AreaRangeChartSeriesOptions extends IndividualSeriesOptions, AreaRangeChart { } + interface AreaSplineChartSeriesOptions extends IndividualSeriesOptions, AreaSplineChart { } + interface AreaSplineRangeChartSeriesOptions extends IndividualSeriesOptions, AreaSplineRangeChart { } + interface BarChartSeriesOptions extends IndividualSeriesOptions, BarChart { } + interface BoxPlotChartSeriesOptions extends IndividualSeriesOptions, BoxPlotChart { } + interface BubbleChartSeriesOptions extends IndividualSeriesOptions, BubbleChart { } + interface ColumnChartSeriesOptions extends IndividualSeriesOptions, ColumnChart { } + interface ColumnRangeChartSeriesOptions extends IndividualSeriesOptions, ColumnRangeChart { } + interface ErrorBarChartSeriesOptions extends IndividualSeriesOptions, ErrorBarChart { } + interface FunnelChartSeriesOptions extends IndividualSeriesOptions, FunnelChart { } + interface GaugeChartSeriesOptions extends IndividualSeriesOptions, GaugeChart { } + interface HeatMapSeriesOptions extends IndividualSeriesOptions, HeatMapChart { } + interface LineChartSeriesOptions extends IndividualSeriesOptions, LineChart { } + interface PieChartSeriesOptions extends IndividualSeriesOptions, PieChart { } + interface PolygonChartSeriesOptions extends IndividualSeriesOptions, PolygonChart { } + interface PyramidChartSeriesOptions extends IndividualSeriesOptions, PyramidChart { } + interface ScatterChartSeriesOptions extends IndividualSeriesOptions, ScatterChart { } + interface SolidGaugeChartSeriesOptions extends IndividualSeriesOptions, SolidGaugeChart { } + interface SplineChartSeriesOptions extends IndividualSeriesOptions, SplineChart { } + interface TreeMapChartSeriesOptions extends IndividualSeriesOptions, TreeMapChart { } + interface WaterFallChartSeriesOptions extends IndividualSeriesOptions, WaterFallChart { } + interface WordCloudChartSeriesOptions extends IndividualSeriesOptions, WordCloudChart { } interface DataPoint { /** @@ -6369,12 +6321,7 @@ declare namespace Highcharts { * * @default null */ - crosshairs?: - | boolean - | [boolean, boolean] - | CrosshairObject - | [CrosshairObject, CrosshairObject] - | null; + crosshairs?: boolean | [boolean, boolean] | CrosshairObject | [CrosshairObject, CrosshairObject] | null; /** * Enable or disable the tooltip. * @default true @@ -6433,11 +6380,7 @@ declare namespace Highcharts { * The return should be an object containing x and y values, for example { x: 100, y: 100 }. * @since 2.2.4 */ - positioner?( - labelWidth: number, - labelHeight: number, - point: PlotPoint - ): { x: number; y: number }; + positioner?(labelWidth: number, labelHeight: number, point: PlotPoint): { x: number; y: number; }; /** * Whether to apply a drop shadow to the tooltip. * @default true @@ -6808,13 +6751,7 @@ declare namespace Highcharts { * The animation can also be a configuration object with properties duration and easing. * @since 1.2.0 */ - setExtremes( - min?: number, - max?: number, - redraw?: boolean, - animation?: boolean | Animation, - eventArguments?: any - ): void; + setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | Animation, eventArguments?: any): void; /** * Update the title of the axis after render time. * @param title The new title options on the same format as given in xAxis.title. @@ -6863,12 +6800,7 @@ declare namespace Highcharts { * The animation can also be a configuration object with properties duration and easing. * @since 3.0 */ - addAxis( - options: AxisOptions, - isX?: boolean, - redraw?: boolean, - animation?: boolean | Animation - ): AxisObject; + addAxis(options: AxisOptions, isX?: boolean, redraw?: boolean, animation?: boolean | Animation): AxisObject; /** * Set a new credits label for the chart. * @param A configuration object for the credits as defined at credits. @@ -6883,11 +6815,7 @@ declare namespace Highcharts { * @param [boolean] redraw * @since 1.2.0 */ - addSeries( - options: T, - redraw?: boolean, - animation?: boolean | Animation - ): SeriesObject; + addSeries(options: T, redraw?: boolean, animation?: boolean | Animation): SeriesObject; /** * Add a series to the chart as drilldown from a specific point in the parent series. This method is used for async * drilldown, when clicking a point in a series should result in loading and displaying a more high-resolution @@ -6896,10 +6824,7 @@ declare namespace Highcharts { * @param seriesOptions The series options, as documented under plotOptions.series and under the plotOptions for each series type. * @since 3.0.8 */ - addSeriesAsDrilldown( - point: PointObject, - seriesOptions: IndividualSeriesOptions - ): void; + addSeriesAsDrilldown(point: PointObject, seriesOptions: IndividualSeriesOptions): void; chartHeight?: number; chartWidth?: number; /** @@ -6973,10 +6898,7 @@ declare namespace Highcharts { * exported chart. Same as the exportChart params. * @since 2.0 */ - exportChartLocal( - options: ExportingOptions, - chartOptions: Options - ): void; + exportChartLocal(options: ExportingOptions, chartOptions: Options): void; /** * Get an axis, series or point by its id as given in the configuration options. * @param id The id of the axis, series or point to get. @@ -7053,11 +6975,7 @@ declare namespace Highcharts { * @param animation Defaults to true. When true, the resize will be animated with default animation options. * The animation can also be a configuration object with properties duration and easing. */ - setSize( - width: number, - height: number, - animation?: boolean | Animation - ): void; + setSize(width: number, height: number, animation?: boolean | Animation): void; /** * Set a new title or subtitle for the chart * @param title A configuration object for the new title as defined at #title. @@ -7065,11 +6983,7 @@ declare namespace Highcharts { * @param [boolean] redraw Whether to redraw the chart. Defaults to true. * @since 2.1.0 */ - setTitle( - title: TitleOptions, - subtitle?: SubtitleOptions, - redraw?: boolean - ): void; + setTitle(title: TitleOptions, subtitle?: SubtitleOptions, redraw?: boolean): void; /** * Dim the chart's plot area and show a loading label text. Options for the loading screen are defined at * options.loading. A custom text can be given as a parameter for loading. @@ -7101,12 +7015,7 @@ declare namespace Highcharts { * @param [(boolean | AnimationOptions)] animation Whether to apply animation, and optionally animation configuration. * @since 5.0.0 */ - update( - options: Options, - redraw?: boolean, - oneToOne?: boolean, - animation?: boolean | AnimationOptions - ): void; + update(options: Options, redraw?: boolean, oneToOne?: boolean, animation?: boolean | AnimationOptions): void; /** * This method is deprecated as of 2.0.1. Updating the chart position after a move operation is no longer necessary. * @since 1.2.5 @@ -7143,10 +7052,7 @@ declare namespace Highcharts { * and in these cases the chart object will not be finished directly after callingnew Highcharts.Chart(). * s a consequence, code that relies on the newly built Chart object should always run in the callback. Defining a chart.event.load handler is equivalent. */ - new ( - options: Options, - callback: (chart: ChartObject) => void - ): ChartObject; + new (options: Options, callback: (chart: ChartObject) => void): ChartObject; /** * This is the constructor for creating a new chart object. * @param renderTo The id or a reference to a DOM element where the chart should be rendered (since v4.2.0). @@ -7162,11 +7068,7 @@ declare namespace Highcharts { * and in these cases the chart object will not be finished directly after callingnew Highcharts.Chart(). * As a consequence, code that relies on the newly built Chart object should always run in the callback. Defining a chart.event.load handler is equivalent. */ - new ( - renderTo: string | HTMLElement, - options: Options, - callback: (chart: ChartObject) => void - ): ChartObject; + new (renderTo: string | HTMLElement, options: Options, callback: (chart: ChartObject) => void): ChartObject; } /** @@ -7219,7 +7121,7 @@ declare namespace Highcharts { * @return An object containing x, y, width and height values for the element. * @since 2.0 */ - getBBox(): { x: number; y: number; height: number; width: number }; + getBBox(): { x: number; y: number; height: number; width: number; }; /** * Apply an event handler to the element * @param eventType The event type to attach, for example 'click', 'mouseover', 'touch'. @@ -7258,14 +7160,7 @@ declare namespace Highcharts { * @param end The ending angle of the arc in radians, where 0 is to the right and -Math.PI/2 is up. * @since 2.0 */ - arc( - centerX: number, - centerY: number, - outerRadius: number, - innerRadius: number, - start: number, - end: number - ): ElementObject; + arc(centerX: number, centerY: number, outerRadius: number, innerRadius: number, start: number, end: number): ElementObject; /** * Draw circle on the renderer canvas. * @param centerX The x position of the circle's center in the SVG element. @@ -7305,13 +7200,7 @@ declare namespace Highcharts { * @param height The height of the image. * @since 2.0 */ - image( - source: string, - x: number, - y: number, - width: number, - height: number - ): ElementObject; + image(source: string, x: number, y: number, width: number, height: number): ElementObject; /** * Draw a label, which is an extended text element with support for border and background. Highcharts creates a g * element with a text and a path or rect inside, to make it behave somewhat like a HTML div. Border and background @@ -7329,17 +7218,7 @@ declare namespace Highcharts { * @param [string] className A class name for the g element surrounding the label. * @since 2.0 */ - label( - str: string, - x: number, - y: number, - shape?: string, - anchorX?: number, - anchorY?: number, - useHTML?: boolean, - baseline?: boolean, - className?: string - ): ElementObject; + label(str: string, x: number, y: number, shape?: string, anchorX?: number, anchorY?: number, useHTML?: boolean, baseline?: boolean, className?: string): ElementObject; /** * Add a path based on SVG's path commands. In SVG capable browsers all path commands are supported, but in VML only * a subset is supported: absolute moveTo (M), absolute lineTo (L), absolute curveTo (C) and close (Z). @@ -7355,13 +7234,7 @@ declare namespace Highcharts { * @param cornerRadius The corner radius of all the rectangle's corners. * @since 2.0 */ - rect( - x: number, - y: number, - width: number, - height: number, - cornerRadius: number - ): ElementObject; + rect(x: number, y: number, width: number, height: number, cornerRadius: number): ElementObject; /** * Draw text. The text can contain a subset of HTML, like spans and anchors and some basic text styling of these. * For more advanced features like border and background, use label instead. @@ -7389,11 +7262,7 @@ declare namespace Highcharts { } interface Renderer { - new ( - parentNode: HTMLElement, - width: number, - height: number - ): RendererObject; + new (parentNode: HTMLElement, width: number, height: number): RendererObject; } interface Static { @@ -7405,19 +7274,12 @@ declare namespace Highcharts { * As Highcharts.Chart, but without need for the new keyword. * @since 4.2.0 */ - chart( - options: Options, - callback?: (chart: ChartObject) => void - ): ChartObject; + chart(options: Options, callback?: (chart: ChartObject) => void): ChartObject; /** * As Highcharts.Chart, but without need for the new keyword. * @since 4.2.0 */ - chart( - renderTo: string | HTMLElement, - options: Options, - callback?: (chart: ChartObject) => void - ): ChartObject; + chart(renderTo: string | HTMLElement, options: Options, callback?: (chart: ChartObject) => void): ChartObject; /** * An array containing the current chart objects in the page. A chart's position in the array is preserved * throughout the page's lifetime. When a chart is destroyed, the array item becomes undefined. @@ -7456,12 +7318,7 @@ declare namespace Highcharts { * @param decimalPoint The decimal point. Defaults to '.' or to the string specified globally in options.lang.decimalPoint. * @param thousandsSep The thousands separator. Defaults to ' ' or to the string specified globally in options.lang.thousandsSep. */ - numberFormat( - value: number, - decimals?: number, - decimalPoint?: string, - thousandsSep?: string - ): string; + numberFormat(value: number, decimals?: number, decimalPoint?: string, thousandsSep?: string): string; /** * Sets the options globally for all charts created after this has been called. Takes an options JavaScript object * structure as the argument. These options are merged with the default options and the result is returned. @@ -7486,11 +7343,7 @@ declare namespace Highcharts { * @param type The type of behavior you are extending. * @param cb The function that executes when the behavior occurs. */ - wrap( - prototype: any, - type: string, - cb: (proceed: Function, ...args: any[]) => void - ): void; + wrap(prototype: any, type: string, cb: (proceed: Function, ...args: any[]) => void): void; /** * Add an event listener. @@ -7503,11 +7356,9 @@ declare namespace Highcharts { * @param cb The function callback to execute when the event is fired. * @returns A callback function to remove the added event. */ - addEvent( - element: HTMLElement | ElementObject | object, - type: string, - cb: (evt: Event) => void - ): () => void; + addEvent(element: HTMLElement | ElementObject | object, + type: string, + cb: (evt: Event) => void): () => void; /** * Fire an event that was registered with @@ -7519,12 +7370,10 @@ declare namespace Highcharts { * @param eventArguments Custom event arguments that are passed on as an argument to the event handler. * @param defaultFunction The default function to execute if the other listeners haven't returned false. */ - fireEvent( - element: HTMLElement | ElementObject | object, - type: string, - eventArguments?: any, - defaultFunction?: () => void - ): void; + fireEvent(element: HTMLElement | ElementObject | object, + type: string, + eventArguments?: any, + defaultFunction?: () => void): void; distribute(array: any[], value: number): void; @@ -7594,11 +7443,7 @@ declare namespace Highcharts { * The animation can also be a configuration object with properties duration and easing. * @since 1.2.0 */ - slice( - sliced?: boolean, - redraw?: boolean, - animation?: boolean | Animation - ): void; + slice(sliced?: boolean, redraw?: boolean, animation?: boolean | Animation): void; /** * The total of a stack for stacked series, or pie in pie charts. */ @@ -7614,11 +7459,7 @@ declare namespace Highcharts { * The animation can also be a configuration object with properties duration and easing. * @since 1.2.0 */ - update( - options: number | [number, number] | DataPoint, - redraw?: boolean, - animation?: boolean | Animation - ): void; + update(options: number | [number, number] | DataPoint, redraw?: boolean, animation?: boolean | Animation): void; /** * The x value for the point. * @since 1.2.0 @@ -7659,12 +7500,7 @@ declare namespace Highcharts { * Use this option for live charts monitoring a value over time. * @since 1.2.0 */ - addPoint( - options: number | [number, number] | DataPoint, - redraw?: boolean, - shift?: boolean, - animation?: boolean | Animation - ): void; + addPoint(options: number | [number, number] | DataPoint, redraw?: boolean, shift?: boolean, animation?: boolean | Animation): void; /** * Read only. The chart that the series belongs to. * @since 1.2.0 @@ -7708,11 +7544,7 @@ declare namespace Highcharts { * The animation can also be a configuration object with properties duration and easing. * @since 4.1.0 */ - removePoint( - index: number, - redraw?: boolean, - animation?: boolean | Animation - ): void; + removePoint(index: number, redraw?: boolean, animation?: boolean | Animation): void; /** * Select or unselect the series. This means its selected property is set,the checkbox in the legend is toggled and * when selected, the series is returned in the chart.getSelectedSeries() method. @@ -7737,12 +7569,7 @@ declare namespace Highcharts { * This option prevents this, and makes setData behave like it did prior to Highcharts 3.0.10. * @since 1.2.0 */ - setData( - data: number[] | number[][] | DataPoint[], - redraw?: boolean, - animation?: boolean | Animation, - updatePoints?: boolean - ): void; + setData(data: number[] | number[][] | DataPoint[], redraw?: boolean, animation?: boolean | Animation, updatePoints?: boolean): void; /** * A utility function to show or hide the series with an optional redraw. * @param [boolean] visible - Whether to show or hide the series. If undefined, the visibility is toggled. @@ -7829,10 +7656,7 @@ declare global { * @param callback Callback function used to manipulate the constructed chart instance * @return current {JQuery} selector the current JQuery selector */ - highcharts( - options: Highcharts.Options, - callback: (chart: Highcharts.ChartObject) => void - ): JQuery; + highcharts(options: Highcharts.Options, callback: (chart: Highcharts.ChartObject) => void): JQuery; } } From 38983e317ac39a234d6bc4106f7f4d0767211800 Mon Sep 17 00:00:00 2001 From: AzSiAz Date: Mon, 22 Oct 2018 19:58:14 +0200 Subject: [PATCH 016/836] Add overloading to `get` method --- types/cheerio/index.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/cheerio/index.d.ts b/types/cheerio/index.d.ts index cb8031705e..7f76146257 100644 --- a/types/cheerio/index.d.ts +++ b/types/cheerio/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Cheerio v0.22.0 // Project: https://github.com/cheeriojs/cheerio -// Definitions by: Bret Little , VILIC VANE , Wayne Maurer , Umar Nizamani , LiJinyao , Chennakrishna +// Definitions by: Bret Little , VILIC VANE , Wayne Maurer , Umar Nizamani , LiJinyao , Chennakrishna , AzSiAz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Cheerio { @@ -112,8 +112,10 @@ interface Cheerio { eq(index: number): Cheerio; get(): string[]; + get(): T[]; get(): CheerioElement[]; get(index: number): CheerioElement; + get(index: number): T; index(): number; index(selector: string): number; From a8b6dfd99e9637403c2204d0f2fe8e53f9c8eed3 Mon Sep 17 00:00:00 2001 From: AzSiAz Date: Mon, 22 Oct 2018 20:10:40 +0200 Subject: [PATCH 017/836] Revert "Add overloading to `get` method" This reverts commit 38983e317ac39a234d6bc4106f7f4d0767211800. --- types/cheerio/index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/cheerio/index.d.ts b/types/cheerio/index.d.ts index 7f76146257..5f8b89fe60 100644 --- a/types/cheerio/index.d.ts +++ b/types/cheerio/index.d.ts @@ -112,10 +112,8 @@ interface Cheerio { eq(index: number): Cheerio; get(): string[]; - get(): T[]; get(): CheerioElement[]; get(index: number): CheerioElement; - get(index: number): T; index(): number; index(selector: string): number; From 023af83ed4d02ef61234532448ac49d8c27dad5b Mon Sep 17 00:00:00 2001 From: AzSiAz Date: Mon, 22 Oct 2018 20:11:22 +0200 Subject: [PATCH 018/836] Add correct overloading to `get` method --- types/cheerio/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/cheerio/index.d.ts b/types/cheerio/index.d.ts index 5f8b89fe60..b04e0f009d 100644 --- a/types/cheerio/index.d.ts +++ b/types/cheerio/index.d.ts @@ -111,6 +111,7 @@ interface Cheerio { eq(index: number): Cheerio; + get(): any[] get(): string[]; get(): CheerioElement[]; get(index: number): CheerioElement; From f482096dc54638fb2211d673d762f3d051fa271e Mon Sep 17 00:00:00 2001 From: Boris Sergeyev Date: Sat, 3 Nov 2018 19:20:07 +0100 Subject: [PATCH 019/836] [react-redux] implemented proper typings for thunk action creators in TDispatchProps --- types/react-redux/index.d.ts | 38 +++++++++++++++++++++---- types/react-redux/react-redux-tests.tsx | 23 +++++++++++++++ 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index 5cbde2e8db..0676941ce9 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-redux 6.0.4 +// Type definitions for react-redux 6.0.5 // Project: https://github.com/reduxjs/react-redux // Definitions by: Qubo , // Kenzie Togami , @@ -11,6 +11,7 @@ // Valentin Descamps // Johann Rakotoharisoa // Anatoli Papirovski +// Boris Sergeyev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -102,7 +103,7 @@ type ConnectedComponentClass = ComponentClass { - >>>( + >>>( component: C ): ConnectedComponentClass, keyof Shared>> & TNeedsProps> } @@ -113,6 +114,19 @@ export interface InferableComponentEnhancerWithProps = InferableComponentEnhancerWithProps +// redux-thunk middleware returns thunk's return value from dispatch call +type WithThunkActionCreators = + TDispatchProps extends object + ? { + [C in keyof TDispatchProps]: C extends (...args: any[]) => any + ? ReturnType extends (...args: any[]) => any + ? ReturnType> + : C + : never + } + : TDispatchProps + + /** * Connects a React component to a Redux store. * @@ -142,12 +156,18 @@ export interface Connect { ( mapStateToProps: null | undefined, mapDispatchToProps: MapDispatchToPropsParam - ): InferableComponentEnhancerWithProps; + ): InferableComponentEnhancerWithProps< + WithThunkActionCreators, + TOwnProps + >; ( mapStateToProps: MapStateToPropsParam, mapDispatchToProps: MapDispatchToPropsParam - ): InferableComponentEnhancerWithProps; + ): InferableComponentEnhancerWithProps< + TStateProps & WithThunkActionCreators, + TOwnProps + >; ( mapStateToProps: MapStateToPropsParam, @@ -185,14 +205,20 @@ export interface Connect { mapDispatchToProps: MapDispatchToPropsParam, mergeProps: null | undefined, options: Options<{}, TStateProps, TOwnProps> - ): InferableComponentEnhancerWithProps; + ): InferableComponentEnhancerWithProps< + WithThunkActionCreators, + TOwnProps + >; ( mapStateToProps: MapStateToPropsParam, mapDispatchToProps: MapDispatchToPropsParam, mergeProps: null | undefined, options: Options - ): InferableComponentEnhancerWithProps; + ): InferableComponentEnhancerWithProps< + TStateProps & WithThunkActionCreators, + TOwnProps + >; ( mapStateToProps: MapStateToPropsParam, diff --git a/types/react-redux/react-redux-tests.tsx b/types/react-redux/react-redux-tests.tsx index 3b25b25843..a5f8c2b4f7 100644 --- a/types/react-redux/react-redux-tests.tsx +++ b/types/react-redux/react-redux-tests.tsx @@ -99,6 +99,29 @@ namespace MapDispatch { const verifyUndefined = } +namespace MapDispatchWithThunkActionCreators { + interface OwnProps { foo: string } + interface DispatchProps { + onClick(): void, + thunkAction(): Promise + } + + class TestComponent extends Component {} + + const mapDispatchToProps = () => ({ + onClick: () => {}, + thunkAction: () => async () => {} + }) + + const Test = connect( + null, + mapDispatchToProps, + )(TestComponent) + + const verify = +} + + namespace MapStateAndDispatchObject { interface ClickPayload { count: number } const onClick: ActionCreator = () => ({ count: 1 }); From 57ba1bcd755c8bc2aac0e74dadc50215d9127bed Mon Sep 17 00:00:00 2001 From: Boris Sergeyev Date: Mon, 5 Nov 2018 23:09:07 +0100 Subject: [PATCH 020/836] [react-redux] fixed error in typings for thunk action creators As noted in https://github.com/DefinitelyTyped/DefinitelyTyped/pull/30255#issuecomment-435814014 the key was used where value was expected. The test didn't catched that because `never` does not interact with `Shared` higher-order type in a way that I've expected. So I've avoided using `never` and edited test a bit. --- types/react-redux/index.d.ts | 20 +++++++++++--------- types/react-redux/react-redux-tests.tsx | 9 ++++----- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index 0676941ce9..d1889b54fe 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -114,17 +114,19 @@ export interface InferableComponentEnhancerWithProps = InferableComponentEnhancerWithProps +type HandleThunkActionCreator = + TActionCreator extends (...args: any[]) => (...args: any[]) => any + ? ReturnType + : TActionCreator + // redux-thunk middleware returns thunk's return value from dispatch call +// https://github.com/reduxjs/redux-thunk#composition type WithThunkActionCreators = - TDispatchProps extends object - ? { - [C in keyof TDispatchProps]: C extends (...args: any[]) => any - ? ReturnType extends (...args: any[]) => any - ? ReturnType> - : C - : never - } - : TDispatchProps + TDispatchProps extends { [key: string]: any } + ? { + [C in keyof TDispatchProps]: HandleThunkActionCreator + } + : TDispatchProps /** diff --git a/types/react-redux/react-redux-tests.tsx b/types/react-redux/react-redux-tests.tsx index a5f8c2b4f7..a2fad70440 100644 --- a/types/react-redux/react-redux-tests.tsx +++ b/types/react-redux/react-redux-tests.tsx @@ -99,14 +99,13 @@ namespace MapDispatch { const verifyUndefined = } + namespace MapDispatchWithThunkActionCreators { - interface OwnProps { foo: string } - interface DispatchProps { + class TestComponent extends Component<{ + foo: string, onClick(): void, thunkAction(): Promise - } - - class TestComponent extends Component {} + }>{} const mapDispatchToProps = () => ({ onClick: () => {}, From c592ba0099f5e689e5cbcd5d610df578633c6ef1 Mon Sep 17 00:00:00 2001 From: Hasan Oezdemir Date: Tue, 6 Nov 2018 11:58:04 +0100 Subject: [PATCH 021/836] redis-rate-limiter: update version to 1.2.0 to provide new options --- types/redis-rate-limiter/index.d.ts | 7 +++++-- types/redis-rate-limiter/redis-rate-limiter-tests.ts | 4 +++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/types/redis-rate-limiter/index.d.ts b/types/redis-rate-limiter/index.d.ts index 6e36f60f3e..45495ad874 100644 --- a/types/redis-rate-limiter/index.d.ts +++ b/types/redis-rate-limiter/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for redis-rate-limiter 1.0.3 +// Type definitions for redis-rate-limiter 1.2.0 // Project: https://github.com/TabDigital/redis-rate-limiter // Definitions by: Seth Westphal +// Hasan Oezdemir // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -20,6 +21,8 @@ declare namespace RedisRateLimiter { window?: number; limit?: number; rate?: string; + deleteImmediatelyIfRaceCondition?: boolean; + onPossibleRaceCondition?: (key: string) => void; } export interface Response { @@ -31,4 +34,4 @@ declare namespace RedisRateLimiter { } } -export = RedisRateLimiter; \ No newline at end of file +export = RedisRateLimiter; diff --git a/types/redis-rate-limiter/redis-rate-limiter-tests.ts b/types/redis-rate-limiter/redis-rate-limiter-tests.ts index a121d28477..98cb34a4e0 100644 --- a/types/redis-rate-limiter/redis-rate-limiter-tests.ts +++ b/types/redis-rate-limiter/redis-rate-limiter-tests.ts @@ -30,7 +30,9 @@ limit(request, function(err, rate) { var middleware = rateLimiter.middleware({ redis: redisClient, key: 'ip', - rate: '100/minute' + rate: '100/minute', + deleteImmediatelyIfRaceCondition: true, + onPossibleRaceCondition: key => console.log(`A race condition has been detected for <${key}>!`) }); var app = express(); From feac0654fa67b2692dfe156420acb0396f98c446 Mon Sep 17 00:00:00 2001 From: Chris O'Toole Date: Wed, 7 Nov 2018 10:09:01 -0500 Subject: [PATCH 022/836] Add "onChildMouseDown" "onChildMouseUp", and "onChildMouseMove" to google-map-react definitions --- package.json | 2 +- types/google-map-react/index.d.ts | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 09fe064d48..2bd57a4c7c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "private": true, "name": "definitely-typed", - "version": "0.0.3", + "version": "0.0.4", "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped", "repository": { "type": "git", diff --git a/types/google-map-react/index.d.ts b/types/google-map-react/index.d.ts index a917ae426e..56686c94c1 100644 --- a/types/google-map-react/index.d.ts +++ b/types/google-map-react/index.d.ts @@ -131,6 +131,9 @@ export interface Props { onChildClick?(hoverKey: any, childProps: any): void; onChildMouseEnter?(hoverKey: any, childProps: any): void; onChildMouseLeave?(hoverKey: any, childProps: any): void; + onChildMouseDown?(childKey: any, childProps: any, mouse: any): void; + onChildMouseUp?(childKey: any, childProps: any, mouse: any): void; + onChildMouseMove?(childKey: any, childProps: any, mouse: any): void; onDrag?(args: any): void; onZoomAnimationStart?(args: any): void; onZoomAnimationEnd?(args: any): void; From 9e043b0469ce0afba60c188fe666d92d7ff87799 Mon Sep 17 00:00:00 2001 From: tzachshabtay Date: Wed, 7 Nov 2018 10:40:10 -0500 Subject: [PATCH 023/836] Update bearer-strategy.d.ts --- types/passport-azure-ad/bearer-strategy.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/passport-azure-ad/bearer-strategy.d.ts b/types/passport-azure-ad/bearer-strategy.d.ts index 30751720f3..6ea48809c1 100644 --- a/types/passport-azure-ad/bearer-strategy.d.ts +++ b/types/passport-azure-ad/bearer-strategy.d.ts @@ -21,7 +21,7 @@ export interface IBearerStrategyOptionWithRequest extends IBearerStrategyOption passReqToCallback: true; } -export class BearerStrategy extends passport.Strategy { +export class BearerStrategy implements passport.Strategy { constructor( options: IBearerStrategyOptionWithRequest, verify: VerifyBearerFunctionWithReq @@ -31,4 +31,4 @@ export class BearerStrategy extends passport.Strategy { name: string; authenticate(req: Request, options?: object): void; -} \ No newline at end of file +} From 66d61a566b42a2e67b397d57f146771f94daed02 Mon Sep 17 00:00:00 2001 From: tzachshabtay Date: Wed, 7 Nov 2018 10:40:41 -0500 Subject: [PATCH 024/836] Update oidc-strategy.d.ts --- types/passport-azure-ad/oidc-strategy.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/passport-azure-ad/oidc-strategy.d.ts b/types/passport-azure-ad/oidc-strategy.d.ts index ac4d984ea2..672694d5a9 100644 --- a/types/passport-azure-ad/oidc-strategy.d.ts +++ b/types/passport-azure-ad/oidc-strategy.d.ts @@ -52,7 +52,7 @@ export type VerifyOIDCFunctionWithReq = ((req: Request, iss: string, sub: string, profile: IProfile, access_token: string, refresh_token: string, params: any, done: VerifyCallback) => void) | ((req: Request, iss: string, sub: string, profile: IProfile, jwtClaims: any, access_token: string, refresh_token: string, params: any, done: VerifyCallback) => void); -export class OIDCStrategy extends passport.Strategy { +export class OIDCStrategy implements passport.Strategy { constructor( options: IOIDCStrategyOptionWithRequest, verify: VerifyOIDCFunction @@ -62,4 +62,4 @@ export class OIDCStrategy extends passport.Strategy { name: string; authenticate(req: Request, options?: object): void; -} \ No newline at end of file +} From 202f4ee2dd0603bc665629d5f6c1c37ae3868dd6 Mon Sep 17 00:00:00 2001 From: Jeff Held Date: Thu, 8 Nov 2018 16:49:37 -0600 Subject: [PATCH 025/836] detox: create tests folder, add test for importing Detox module --- types/detox/detox-tests.ts | 31 -------------- types/detox/tests/detox-globals-tests.ts | 40 ++++++++++++++++++ .../detox/tests/detox-import-modules-tests.ts | 42 +++++++++++++++++++ types/detox/tsconfig.json | 11 ++--- 4 files changed, 86 insertions(+), 38 deletions(-) delete mode 100644 types/detox/detox-tests.ts create mode 100644 types/detox/tests/detox-globals-tests.ts create mode 100644 types/detox/tests/detox-import-modules-tests.ts diff --git a/types/detox/detox-tests.ts b/types/detox/detox-tests.ts deleted file mode 100644 index 58fe5c1912..0000000000 --- a/types/detox/detox-tests.ts +++ /dev/null @@ -1,31 +0,0 @@ -declare var describe: (test: string, callback: () => void) => void; -declare var beforeAll: (callback: () => void) => void; -declare var afterAll: (callback: () => void) => void; -declare var test: (test: string, callback: () => void) => void; - -describe('Test', () => { - beforeAll(async () => { - await device.reloadReactNative(); - }); - - afterAll(async () => { - await element(by.id('element')).clearText(); - }); - - test('Test', async () => { - await element(by.id('element')).replaceText('text'); - await element(by.id('element')).tap(); - await element(by.id('element')).scroll(50, 'down'); - await element(by.id('scrollView')).scrollTo('bottom'); - await expect(element(by.id('element')).atIndex(0)).toNotExist(); - await element(by.id('scrollView')).swipe('down', 'fast'); - await element(by.type('UIPickerView')).setColumnToValue(1, "6"); - - await expect(element(by.id('element').withAncestor(by.id('parent_element')))).toNotExist(); - await expect(element(by.id('element').withDescendant(by.id('child_element')))).toNotExist(); - - await waitFor(element(by.id('element'))).toBeVisible().withTimeout(2000); - await device.pressBack(); - await waitFor(element(by.text('Text5'))).toBeVisible().whileElement(by.id('ScrollView630')).scroll(50, 'down'); - }); -}); diff --git a/types/detox/tests/detox-globals-tests.ts b/types/detox/tests/detox-globals-tests.ts new file mode 100644 index 0000000000..42415c548d --- /dev/null +++ b/types/detox/tests/detox-globals-tests.ts @@ -0,0 +1,40 @@ +declare var describe: (test: string, callback: () => void) => void; +declare var beforeAll: (callback: () => void) => void; +declare var afterAll: (callback: () => void) => void; +declare var test: (test: string, callback: () => void) => void; + +describe("Test", () => { + beforeAll(async () => { + await device.reloadReactNative(); + }); + + afterAll(async () => { + await element(by.id("element")).clearText(); + }); + + test("Test", async () => { + await element(by.id("element")).replaceText("text"); + await element(by.id("element")).tap(); + await element(by.id("element")).scroll(50, "down"); + await element(by.id("scrollView")).scrollTo("bottom"); + await expect(element(by.id("element")).atIndex(0)).toNotExist(); + await element(by.id("scrollView")).swipe("down", "fast"); + await element(by.type("UIPickerView")).setColumnToValue(1, "6"); + + await expect( + element(by.id("element").withAncestor(by.id("parent_element"))) + ).toNotExist(); + await expect( + element(by.id("element").withDescendant(by.id("child_element"))) + ).toNotExist(); + + await waitFor(element(by.id("element"))) + .toBeVisible() + .withTimeout(2000); + await device.pressBack(); + await waitFor(element(by.text("Text5"))) + .toBeVisible() + .whileElement(by.id("ScrollView630")) + .scroll(50, "down"); + }); +}); diff --git a/types/detox/tests/detox-import-modules-tests.ts b/types/detox/tests/detox-import-modules-tests.ts new file mode 100644 index 0000000000..318569c03d --- /dev/null +++ b/types/detox/tests/detox-import-modules-tests.ts @@ -0,0 +1,42 @@ +declare var describe: (test: string, callback: () => void) => void; +declare var beforeAll: (callback: () => void) => void; +declare var afterAll: (callback: () => void) => void; +declare var test: (test: string, callback: () => void) => void; + +import { by, device, element, expect, waitFor } from "detox"; + +describe("Test", () => { + beforeAll(async () => { + await device.reloadReactNative(); + }); + + afterAll(async () => { + await element(by.id("element")).clearText(); + }); + + test("Test", async () => { + await element(by.id("element")).replaceText("text"); + await element(by.id("element")).tap(); + await element(by.id("element")).scroll(50, "down"); + await element(by.id("scrollView")).scrollTo("bottom"); + await expect(element(by.id("element")).atIndex(0)).toNotExist(); + await element(by.id("scrollView")).swipe("down", "fast"); + await element(by.type("UIPickerView")).setColumnToValue(1, "6"); + + await expect( + element(by.id("element").withAncestor(by.id("parent_element"))) + ).toNotExist(); + await expect( + element(by.id("element").withDescendant(by.id("child_element"))) + ).toNotExist(); + + await waitFor(element(by.id("element"))) + .toBeVisible() + .withTimeout(2000); + await device.pressBack(); + await waitFor(element(by.text("Text5"))) + .toBeVisible() + .whileElement(by.id("ScrollView630")) + .scroll(50, "down"); + }); +}); diff --git a/types/detox/tsconfig.json b/types/detox/tsconfig.json index 2d1a22fb79..3eb7524be2 100644 --- a/types/detox/tsconfig.json +++ b/types/detox/tsconfig.json @@ -1,24 +1,21 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6" - ], + "lib": ["es6"], "target": "ES2015", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", - "detox-tests.ts" + "tests/detox-globals-tests.ts", + "tests/detox-import-modules-tests.ts" ] } From 45a0c57ef040ed95fa5994b05a2a5c32778706fc Mon Sep 17 00:00:00 2001 From: Jeff Held Date: Thu, 8 Nov 2018 16:49:42 -0600 Subject: [PATCH 026/836] detox: follow global-modifying dts example --- types/detox/index.d.ts | 821 +++++++++++++++++++++-------------------- 1 file changed, 416 insertions(+), 405 deletions(-) diff --git a/types/detox/index.d.ts b/types/detox/index.d.ts index 7ef085e25d..f9baa99f6e 100644 --- a/types/detox/index.d.ts +++ b/types/detox/index.d.ts @@ -3,418 +3,429 @@ // Definitions by: Tareq El-Masri , Steve Chun // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare const detox: Detox.Detox; -declare const device: Detox.Device; -declare const element: Detox.Element; -declare const waitFor: Detox.WaitFor; -declare const expect: Detox.Expect>; -declare const by: Detox.Matchers; +declare global { + const detox: Detox.Detox; + const device: Detox.Device; + const element: Detox.Element; + const waitFor: Detox.WaitFor; + const expect: Detox.Expect>; + const by: Detox.Matchers; -declare namespace Detox { - interface Detox { - /** - * The setup phase happens inside detox.init(). This is the phase where detox reads its configuration, starts a server, loads its expection library and starts a simulator - * @param config - * @param options - * @example const config = require('../package.json').detox; - * - * before(async () => { - * await detox.init(config); - * }); - */ - init(config: any, options?: DetoxInitOptions): Promise; - /** - * Artifacts currently include only logs from the app process before each task - * @param args - */ - beforeEach(...args: any[]): Promise; - /** - * Artifacts currently include only logs from the app process after each task - * @param args - */ - afterEach(...args: any[]): Promise; - /** - * The cleanup phase should happen after all the tests have finished. This is the phase where detox-server shuts down. - * @example after(async () => { - * await detox.cleanup(); - * }); - */ - cleanup(): Promise; - } - interface Device { - /** - * Launch the app - * @param config - * @example // Terminate the app and launch it again. If set to false, the simulator will try to bring app from background, - * // if the app isn't running, it will launch a new instance. default is false - * await device.launchApp({newInstance: true}); - * // Grant or deny runtime permissions for your application. - * await device.launchApp({permissions: {calendar: 'YES'}}); - * // Mock opening the app from URL to test your app's deep link handling mechanism. - * await device.launchApp({url: url}); - */ - launchApp(config: DeviceLanchAppConfig): Promise; - /** - * By default, terminateApp() with no params will terminate the app - * To terminate another app, specify its bundle id - * @param bundle - * @example await device.terminateApp('other.bundle.id'); - */ - terminateApp(bundle?: string): Promise; - /** - * Send application to background by bringing com.apple.springboard to the foreground. - * Combining sendToHome() with launchApp({newInstance: false}) will simulate app coming back from background. - * @example await device.sendToHome(); - * await device.launchApp({newInstance: false}); - */ - sendToHome(): Promise; - /** - * If this is a React Native app, reload the React Native JS bundle. This action is much faster than device.launchApp(), and can be used if you just need to reset your React Native logic. - * @example await device.reloadReactNative() - */ - reloadReactNative(): Promise; - /** - * By default, installApp() with no params will install the app file defined in the current configuration. - * To install another app, specify its path - * @param path - * @example await device.installApp('path/to/other/app'); - */ - installApp(path?: any): Promise; - /** - * By default, uninstallApp() with no params will uninstall the app defined in the current configuration. - * To uninstall another app, specify its bundle id - * @param bundle - * @example await device.installApp('other.bundle.id'); - */ - uninstallApp(bundle?: string): Promise; - /** - * Mock opening the app from URL. sourceApp is an optional parameter to specify source application bundle id. - * @param url - */ - openURL(url: {url: string, sourceApp?: string}): Promise; - /** - * Mock handling of received user notification when app is in foreground. - * @param params - */ - sendUserNotification(...params: any[]): Promise; - /** - * Mock handling of received user activity when app is in foreground. - * @param params - */ - sendUserActivity(...params: any[]): Promise; - /** - * Takes "portrait" or "landscape" and rotates the device to the given orientation. Currently only available in the iOS Simulator. - * @param orientation - */ - setOrientation(orientation: Orientation): Promise; - /** - * Note: setLocation is dependent on fbsimctl. if fbsimctl is not installed, the command will fail, it must be installed. Sets the simulator location to the given latitude and longitude. - * @param lat - * @param lon - * @example await device.setLocation(32.0853, 34.7818); - */ - setLocation(lat: number, lon: number): Promise; - /** - * Disable EarlGrey's network synchronization mechanism on preffered endpoints. Usful if you want to on skip over synchronizing on certain URLs. - * @param urls - * @example await device.setURLBlacklist(['.*127.0.0.1.*']); - */ - setURLBlacklist(urls: string[]): Promise; - /** - * Enable EarlGrey's synchronization mechanism (enabled by default). This is being reset on every new instance of the app. - * @example await device.enableSynchronization(); - */ - enableSynchronization(): Promise; - /** - * Disable EarlGrey's synchronization mechanism (enabled by default) This is being reset on every new instance of the app. - * @example await device.disableSynchronization(); - */ - disableSynchronization(): Promise; - /** - * Resets the Simulator to clean state (like the Simulator > Reset Content and Settings... menu item), especially removing previously set permissions. - * @example await device.resetContentAndSettings(); - */ - resetContentAndSettings(): Promise; - /** - * Returns the current device, ios or android. - * @example if (device.getPlatform() === 'ios') { - * await expect(loopSwitch).toHaveValue('1'); - * } - */ - getPlatform(): "ios" | "android"; - /** - * Simulate press back button (Android Only) - */ - pressBack(): Promise; - /** - * Simulate shake (iOS Only) - */ - shake(): Promise; - } + namespace Detox { + interface Detox { + /** + * The setup phase happens inside detox.init(). This is the phase where detox reads its configuration, starts a server, loads its expection library and starts a simulator + * @param config + * @param options + * @example const config = require('../package.json').detox; + * + * before(async () => { + * await detox.init(config); + * }); + */ + init(config: any, options?: DetoxInitOptions): Promise; + /** + * Artifacts currently include only logs from the app process before each task + * @param args + */ + beforeEach(...args: any[]): Promise; + /** + * Artifacts currently include only logs from the app process after each task + * @param args + */ + afterEach(...args: any[]): Promise; + /** + * The cleanup phase should happen after all the tests have finished. This is the phase where detox-server shuts down. + * @example after(async () => { + * await detox.cleanup(); + * }); + */ + cleanup(): Promise; + } + interface Device { + /** + * Launch the app + * @param config + * @example // Terminate the app and launch it again. If set to false, the simulator will try to bring app from background, + * // if the app isn't running, it will launch a new instance. default is false + * await device.launchApp({newInstance: true}); + * // Grant or deny runtime permissions for your application. + * await device.launchApp({permissions: {calendar: 'YES'}}); + * // Mock opening the app from URL to test your app's deep link handling mechanism. + * await device.launchApp({url: url}); + */ + launchApp(config: DeviceLanchAppConfig): Promise; + /** + * By default, terminateApp() with no params will terminate the app + * To terminate another app, specify its bundle id + * @param bundle + * @example await device.terminateApp('other.bundle.id'); + */ + terminateApp(bundle?: string): Promise; + /** + * Send application to background by bringing com.apple.springboard to the foreground. + * Combining sendToHome() with launchApp({newInstance: false}) will simulate app coming back from background. + * @example await device.sendToHome(); + * await device.launchApp({newInstance: false}); + */ + sendToHome(): Promise; + /** + * If this is a React Native app, reload the React Native JS bundle. This action is much faster than device.launchApp(), and can be used if you just need to reset your React Native logic. + * @example await device.reloadReactNative() + */ + reloadReactNative(): Promise; + /** + * By default, installApp() with no params will install the app file defined in the current configuration. + * To install another app, specify its path + * @param path + * @example await device.installApp('path/to/other/app'); + */ + installApp(path?: any): Promise; + /** + * By default, uninstallApp() with no params will uninstall the app defined in the current configuration. + * To uninstall another app, specify its bundle id + * @param bundle + * @example await device.installApp('other.bundle.id'); + */ + uninstallApp(bundle?: string): Promise; + /** + * Mock opening the app from URL. sourceApp is an optional parameter to specify source application bundle id. + * @param url + */ + openURL(url: { url: string; sourceApp?: string }): Promise; + /** + * Mock handling of received user notification when app is in foreground. + * @param params + */ + sendUserNotification(...params: any[]): Promise; + /** + * Mock handling of received user activity when app is in foreground. + * @param params + */ + sendUserActivity(...params: any[]): Promise; + /** + * Takes "portrait" or "landscape" and rotates the device to the given orientation. Currently only available in the iOS Simulator. + * @param orientation + */ + setOrientation(orientation: Orientation): Promise; + /** + * Note: setLocation is dependent on fbsimctl. if fbsimctl is not installed, the command will fail, it must be installed. Sets the simulator location to the given latitude and longitude. + * @param lat + * @param lon + * @example await device.setLocation(32.0853, 34.7818); + */ + setLocation(lat: number, lon: number): Promise; + /** + * Disable EarlGrey's network synchronization mechanism on preffered endpoints. Usful if you want to on skip over synchronizing on certain URLs. + * @param urls + * @example await device.setURLBlacklist(['.*127.0.0.1.*']); + */ + setURLBlacklist(urls: string[]): Promise; + /** + * Enable EarlGrey's synchronization mechanism (enabled by default). This is being reset on every new instance of the app. + * @example await device.enableSynchronization(); + */ + enableSynchronization(): Promise; + /** + * Disable EarlGrey's synchronization mechanism (enabled by default) This is being reset on every new instance of the app. + * @example await device.disableSynchronization(); + */ + disableSynchronization(): Promise; + /** + * Resets the Simulator to clean state (like the Simulator > Reset Content and Settings... menu item), especially removing previously set permissions. + * @example await device.resetContentAndSettings(); + */ + resetContentAndSettings(): Promise; + /** + * Returns the current device, ios or android. + * @example if (device.getPlatform() === 'ios') { + * await expect(loopSwitch).toHaveValue('1'); + * } + */ + getPlatform(): "ios" | "android"; + /** + * Simulate press back button (Android Only) + */ + pressBack(): Promise; + /** + * Simulate shake (iOS Only) + */ + shake(): Promise; + } - type DetoxAny = Element & Actions & WaitFor; + type DetoxAny = Element & Actions & WaitFor; - interface Element { - (by: Matchers): DetoxAny; + interface Element { + (by: Matchers): DetoxAny; - /** - * Choose from multiple elements matching the same matcher using index - * @param index - * @example await element(by.text('Product')).atIndex(2); - */ - atIndex(index: number): DetoxAny; - } - interface Matchers { - (by: Matchers): Matchers; + /** + * Choose from multiple elements matching the same matcher using index + * @param index + * @example await element(by.text('Product')).atIndex(2); + */ + atIndex(index: number): DetoxAny; + } + interface Matchers { + (by: Matchers): Matchers; - /** - * by.id will match an id that is given to the view via testID prop. - * @param id - * @example // In a React Native component add testID like so: - * - * // Then match with by.id: - * await element(by.id('tap_me')); - */ - id(id: string): Matchers; - /** - * Find an element by text, useful for text fields, buttons. - * @param text - * @example await element(by.text('Tap Me')); - */ - text(text: string): Matchers; - /** - * Find an element by accessibilityLabel on iOS, or by contentDescription on Android. - * @param label - * @example await element(by.label('Welcome')); - */ - label(label: string): Matchers; - /** - * Find an element by native view type. - * @param nativeViewType - * @example await element(by.type('RCTImageView')); - */ - type(nativeViewType: string): Matchers; - /** - * Find an element with an accessibility trait. (iOS only) - * @example await element(by.traits(['button'])); - */ - traits(traits: string[]): Matchers; - /** - * Find an element by a matcher with a parent matcher - * @param parentBy - * @example await element(by.id('Grandson883').withAncestor(by.id('Son883'))); - */ - withAncestor(parentBy: Matchers): Matchers; - /** - * Find an element by a matcher with a child matcher - * @param childBy - * @example await element(by.id('Son883').withDescendant(by.id('Grandson883'))); - */ - withDescendant(childBy: Matchers): Matchers; - /** - * Find an element by multiple matchers - * @param by - * @example await element(by.text('Product').and(by.id('product_name')); - */ - and(by: Matchers): Matchers; - } - interface Expect { - (element: Element): Expect; - /** - * Expect the view to be at least 75% visible. - * @example await expect(element(by.id('UniqueId204'))).toBeVisible(); - */ - toBeVisible(): R; - /** - * Expect the view to not be visible. - * @example await expect(element(by.id('UniqueId205'))).toBeNotVisible(); - */ - toBeNotVisible(): R; - /** - * Expect the view to exist in the UI hierarchy. - * @example await expect(element(by.id('UniqueId205'))).toExist(); - */ - toExist(): R; - /** - * Expect the view to not exist in the UI hierarchy. - * @example await expect(element(by.id('RandomJunk959'))).toNotExist(); - */ - toNotExist(): R; - /** - * In React Native apps, expect UI component of type to have text. - * In native iOS apps, expect UI elements of type UIButton, UILabel, UITextField or UITextViewIn to have inputText with text. - * @param text - * @example await expect(element(by.id('UniqueId204'))).toHaveText('I contain some text'); - */ - toHaveText(text: string): R; - /** - * It searches by accessibilityLabel on iOS, or by contentDescription on Android. - * In React Native it can be set for both platforms by defining an accessibilityLabel on the view. - * @param label - * @example await expect(element(by.id('UniqueId204'))).toHaveLabel('Done'); - */ - toHaveLabel(label: string): R; - /** - * In React Native apps, expect UI component to have testID with that id. - * In native iOS apps, expect UI element to have accesibilityIdentifier with that id. - * @param id - * @example await expect(element(by.text('I contain some text'))).toHaveId('UniqueId204'); - */ - toHaveId(id: string): R; - /** - * Expect components like a Switch to have a value ('0' for off, '1' for on). - * @param value - * @example await expect(element(by.id('UniqueId533'))).toHaveValue('0'); - */ - toHaveValue(value: any): R; - } - interface WaitFor { - /** - * This API polls using the given expectation continuously until the expectation is met. Use manual synchronization with waitFor only as a last resort. - * NOTE: Every waitFor call must set a timeout using withTimeout(). Calling waitFor without setting a timeout will do nothing. - * @example await waitFor(element(by.id('UniqueId336'))).toExist().withTimeout(2000); - */ - (element: Element): Expect; - /** - * Waits for the condition to be met until the specified time (millis) have elapsed. - * @param millis number - * @example await waitFor(element(by.id('UniqueId336'))).toExist().withTimeout(2000); - */ - withTimeout(millis: number): Promise; - /** - * Performs the action repeatedly on the element until an expectation is met - * @param by - * @example await waitFor(element(by.text('Text5'))).toBeVisible().whileElement(by.id('ScrollView630')).scroll(50, 'down'); - */ - whileElement(by: Matchers): DetoxAny; - } - interface Actions { - /** - * Simulate tap on an element - * @example await element(by.id('tappable')).tap(); - */ - tap(): Promise>; - /** - * Simulate long press on an element - * @example await element(by.id('tappable')).longPress(); - */ - longPress(): Promise>; - /** - * Simulate multiple taps on an element. - * @param times number - * @example await element(by.id('tappable')).multiTap(3); - */ - multiTap(times: number): Promise>; - /** - * Simulate tap at a specific point on an element. - * Note: The point coordinates are relative to the matched element and the element size could changes on different devices or even when changing the device font size. - * @param point - * @example await element(by.id('tappable')).tapAtPoint({ x:5, y:10 }); - */ - tapAtPoint(point: { x: number, y: number }): Promise>; - /** - * Use the builtin keyboard to type text into a text field. - * @param text - * @example await element(by.id('textField')).typeText('passcode'); - */ - typeText(text: string): Promise>; - /** - * Paste text into a text field. - * @param text - * @example await element(by.id('textField')).replaceText('passcode again'); - */ - replaceText(text: string): Promise>; - /** - * Clear text from a text field. - * @example await element(by.id('textField')).clearText(); - */ - clearText(): Promise>; - /** - * - * @param pixels - * @param direction - * @example - * await element(by.id('scrollView')).scroll(100, 'down'); - * await element(by.id('scrollView')).scroll(100, 'up'); - */ - scroll(pixels: number, direction: Direction): Promise>; - /** - * Scroll to edge. - * @param edge - * @example await element(by.id('scrollView')).scrollTo('bottom'); - * await element(by.id('scrollView')).scrollTo('top'); - */ - scrollTo(edge: Direction): Promise>; - /** - * - * @param direction - * @param speed - * @param percentage - * @example await element(by.id('scrollView')).swipe('down'); - * await element(by.id('scrollView')).swipe('down', 'fast'); - * await element(by.id('scrollView')).swipe('down', 'fast', 0.5); - */ - swipe(direction: Direction, speed?: Speed, percentage?: number): Promise>; - /** - * (iOS Only) column - number of datepicker column (starts from 0) value - string value in setted column (must be correct) - * @param column - * @param value - * @example await expect(element(by.type('UIPickerView'))).toBeVisible(); - * await element(by.type('UIPickerView')).setColumnToValue(1,"6"); - * await element(by.type('UIPickerView')).setColumnToValue(2,"34"); - */ - setColumnToValue(column: number, value: string): Promise>; - } + /** + * by.id will match an id that is given to the view via testID prop. + * @param id + * @example // In a React Native component add testID like so: + * + * // Then match with by.id: + * await element(by.id('tap_me')); + */ + id(id: string): Matchers; + /** + * Find an element by text, useful for text fields, buttons. + * @param text + * @example await element(by.text('Tap Me')); + */ + text(text: string): Matchers; + /** + * Find an element by accessibilityLabel on iOS, or by contentDescription on Android. + * @param label + * @example await element(by.label('Welcome')); + */ + label(label: string): Matchers; + /** + * Find an element by native view type. + * @param nativeViewType + * @example await element(by.type('RCTImageView')); + */ + type(nativeViewType: string): Matchers; + /** + * Find an element with an accessibility trait. (iOS only) + * @example await element(by.traits(['button'])); + */ + traits(traits: string[]): Matchers; + /** + * Find an element by a matcher with a parent matcher + * @param parentBy + * @example await element(by.id('Grandson883').withAncestor(by.id('Son883'))); + */ + withAncestor(parentBy: Matchers): Matchers; + /** + * Find an element by a matcher with a child matcher + * @param childBy + * @example await element(by.id('Son883').withDescendant(by.id('Grandson883'))); + */ + withDescendant(childBy: Matchers): Matchers; + /** + * Find an element by multiple matchers + * @param by + * @example await element(by.text('Product').and(by.id('product_name')); + */ + and(by: Matchers): Matchers; + } + interface Expect { + (element: Element): Expect; + /** + * Expect the view to be at least 75% visible. + * @example await expect(element(by.id('UniqueId204'))).toBeVisible(); + */ + toBeVisible(): R; + /** + * Expect the view to not be visible. + * @example await expect(element(by.id('UniqueId205'))).toBeNotVisible(); + */ + toBeNotVisible(): R; + /** + * Expect the view to exist in the UI hierarchy. + * @example await expect(element(by.id('UniqueId205'))).toExist(); + */ + toExist(): R; + /** + * Expect the view to not exist in the UI hierarchy. + * @example await expect(element(by.id('RandomJunk959'))).toNotExist(); + */ + toNotExist(): R; + /** + * In React Native apps, expect UI component of type to have text. + * In native iOS apps, expect UI elements of type UIButton, UILabel, UITextField or UITextViewIn to have inputText with text. + * @param text + * @example await expect(element(by.id('UniqueId204'))).toHaveText('I contain some text'); + */ + toHaveText(text: string): R; + /** + * It searches by accessibilityLabel on iOS, or by contentDescription on Android. + * In React Native it can be set for both platforms by defining an accessibilityLabel on the view. + * @param label + * @example await expect(element(by.id('UniqueId204'))).toHaveLabel('Done'); + */ + toHaveLabel(label: string): R; + /** + * In React Native apps, expect UI component to have testID with that id. + * In native iOS apps, expect UI element to have accesibilityIdentifier with that id. + * @param id + * @example await expect(element(by.text('I contain some text'))).toHaveId('UniqueId204'); + */ + toHaveId(id: string): R; + /** + * Expect components like a Switch to have a value ('0' for off, '1' for on). + * @param value + * @example await expect(element(by.id('UniqueId533'))).toHaveValue('0'); + */ + toHaveValue(value: any): R; + } + interface WaitFor { + /** + * This API polls using the given expectation continuously until the expectation is met. Use manual synchronization with waitFor only as a last resort. + * NOTE: Every waitFor call must set a timeout using withTimeout(). Calling waitFor without setting a timeout will do nothing. + * @example await waitFor(element(by.id('UniqueId336'))).toExist().withTimeout(2000); + */ + (element: Element): Expect; + /** + * Waits for the condition to be met until the specified time (millis) have elapsed. + * @param millis number + * @example await waitFor(element(by.id('UniqueId336'))).toExist().withTimeout(2000); + */ + withTimeout(millis: number): Promise; + /** + * Performs the action repeatedly on the element until an expectation is met + * @param by + * @example await waitFor(element(by.text('Text5'))).toBeVisible().whileElement(by.id('ScrollView630')).scroll(50, 'down'); + */ + whileElement(by: Matchers): DetoxAny; + } + interface Actions { + /** + * Simulate tap on an element + * @example await element(by.id('tappable')).tap(); + */ + tap(): Promise>; + /** + * Simulate long press on an element + * @example await element(by.id('tappable')).longPress(); + */ + longPress(): Promise>; + /** + * Simulate multiple taps on an element. + * @param times number + * @example await element(by.id('tappable')).multiTap(3); + */ + multiTap(times: number): Promise>; + /** + * Simulate tap at a specific point on an element. + * Note: The point coordinates are relative to the matched element and the element size could changes on different devices or even when changing the device font size. + * @param point + * @example await element(by.id('tappable')).tapAtPoint({ x:5, y:10 }); + */ + tapAtPoint(point: { x: number; y: number }): Promise>; + /** + * Use the builtin keyboard to type text into a text field. + * @param text + * @example await element(by.id('textField')).typeText('passcode'); + */ + typeText(text: string): Promise>; + /** + * Paste text into a text field. + * @param text + * @example await element(by.id('textField')).replaceText('passcode again'); + */ + replaceText(text: string): Promise>; + /** + * Clear text from a text field. + * @example await element(by.id('textField')).clearText(); + */ + clearText(): Promise>; + /** + * + * @param pixels + * @param direction + * @example + * await element(by.id('scrollView')).scroll(100, 'down'); + * await element(by.id('scrollView')).scroll(100, 'up'); + */ + scroll(pixels: number, direction: Direction): Promise>; + /** + * Scroll to edge. + * @param edge + * @example await element(by.id('scrollView')).scrollTo('bottom'); + * await element(by.id('scrollView')).scrollTo('top'); + */ + scrollTo(edge: Direction): Promise>; + /** + * + * @param direction + * @param speed + * @param percentage + * @example await element(by.id('scrollView')).swipe('down'); + * await element(by.id('scrollView')).swipe('down', 'fast'); + * await element(by.id('scrollView')).swipe('down', 'fast', 0.5); + */ + swipe( + direction: Direction, + speed?: Speed, + percentage?: number + ): Promise>; + /** + * (iOS Only) column - number of datepicker column (starts from 0) value - string value in setted column (must be correct) + * @param column + * @param value + * @example await expect(element(by.type('UIPickerView'))).toBeVisible(); + * await element(by.type('UIPickerView')).setColumnToValue(1,"6"); + * await element(by.type('UIPickerView')).setColumnToValue(2,"34"); + */ + setColumnToValue( + column: number, + value: string + ): Promise>; + } - type Direction = "left" | "right" | "top" | "bottom" | "up" | "down"; - type Orientation = "portrait" | "landscape"; - type Speed = "fast" | "slow"; + type Direction = "left" | "right" | "top" | "bottom" | "up" | "down"; + type Orientation = "portrait" | "landscape"; + type Speed = "fast" | "slow"; - interface DetoxInitOptions { - /** - * Detox exports device, expect, element, by and waitFor as globals by default, if you want to control their initialization manually, set init detox with initGlobals set to false. - * This is useful when during E2E tests you also need to run regular expectations in node. jest Expect for instance, will not be overriden by Detox when this option is used. - */ - initGlobals?: boolean; - /** - * By default await detox.init(config); will launch the installed app. If you wish to control when your app is launched, add {launchApp: false} param to your init. - */ - launchApp?: boolean; - } + interface DetoxInitOptions { + /** + * Detox exports device, expect, element, by and waitFor as globals by default, if you want to control their initialization manually, set init detox with initGlobals set to false. + * This is useful when during E2E tests you also need to run regular expectations in node. jest Expect for instance, will not be overriden by Detox when this option is used. + */ + initGlobals?: boolean; + /** + * By default await detox.init(config); will launch the installed app. If you wish to control when your app is launched, add {launchApp: false} param to your init. + */ + launchApp?: boolean; + } - interface DeviceLanchAppConfig { - /** - * Restart the app - * Terminate the app and launch it again. If set to false, the simulator will try to bring app from background, if the app isn't running, it will launch a new instance. default is false - */ - newInstance?: boolean; - /** - * Set runtime permissions - * Grant or deny runtime permissions for your application. - */ - permissions?: any; - /** - * Launch from URL - * Mock opening the app from URL to test your app's deep link handling mechanism. - */ - url?: any; - /** - * Launch with user notifications - */ - userNotification?: any; - /** - * Launch with user activity - */ - userActivity?: any; - /** - * Launch into a fresh installation - * A flag that enables relaunching into a fresh installation of the app (it will uninstall and install the binary again), default is false. - */ - delete?: boolean; - /** - * Detox can start the app with additional launch arguments - * The added launchArgs will be passed through the launch command to the device and be accessible via [[NSProcessInfo processInfo] arguments] - */ - launchArgs?: any; + interface DeviceLanchAppConfig { + /** + * Restart the app + * Terminate the app and launch it again. If set to false, the simulator will try to bring app from background, if the app isn't running, it will launch a new instance. default is false + */ + newInstance?: boolean; + /** + * Set runtime permissions + * Grant or deny runtime permissions for your application. + */ + permissions?: any; + /** + * Launch from URL + * Mock opening the app from URL to test your app's deep link handling mechanism. + */ + url?: any; + /** + * Launch with user notifications + */ + userNotification?: any; + /** + * Launch with user activity + */ + userActivity?: any; + /** + * Launch into a fresh installation + * A flag that enables relaunching into a fresh installation of the app (it will uninstall and install the binary again), default is false. + */ + delete?: boolean; + /** + * Detox can start the app with additional launch arguments + * The added launchArgs will be passed through the launch command to the device and be accessible via [[NSProcessInfo processInfo] arguments] + */ + launchArgs?: any; + } } } + +export { by, detox, device, element, expect, waitFor }; From 700298f03a177fd488245bd0d0a77212085cb0d3 Mon Sep 17 00:00:00 2001 From: Jeff Held Date: Thu, 8 Nov 2018 17:11:01 -0600 Subject: [PATCH 027/836] detox: add jest adapter definitions --- types/detox/runners/jest/adapters/index.d.ts | 9 +++++++ types/detox/tests/detox-jest-setup-tests.ts | 28 ++++++++++++++++++++ types/detox/tsconfig.json | 4 ++- 3 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 types/detox/runners/jest/adapters/index.d.ts create mode 100644 types/detox/tests/detox-jest-setup-tests.ts diff --git a/types/detox/runners/jest/adapters/index.d.ts b/types/detox/runners/jest/adapters/index.d.ts new file mode 100644 index 0000000000..ca195ae744 --- /dev/null +++ b/types/detox/runners/jest/adapters/index.d.ts @@ -0,0 +1,9 @@ +interface DetoxJestAdapter { + detox: Detox.Detox; + beforeEach: () => Promise; + afterAll: () => Promise; +} + +declare const adapter: DetoxJestAdapter; + +export default adapter; diff --git a/types/detox/tests/detox-jest-setup-tests.ts b/types/detox/tests/detox-jest-setup-tests.ts new file mode 100644 index 0000000000..002b5605bb --- /dev/null +++ b/types/detox/tests/detox-jest-setup-tests.ts @@ -0,0 +1,28 @@ +declare var beforeAll: (callback: () => void) => void; +declare var beforeEach: (callback: () => void) => void; +declare var afterAll: (callback: () => void) => void; + +import adapter from "detox/runners/jest/adapters"; + +// Normally the Detox configuration from the project's package.json like so: +// const config = require("./package.json").detox; +declare const config: any; + +beforeAll(async () => { + await detox.init(config); + + const initOptions: Detox.DetoxInitOptions = { + initGlobals: false, + launchApp: false, + }; + await detox.init(config, initOptions); +}); + +beforeEach(async () => { + await adapter.beforeEach(); +}); + +afterAll(async () => { + await adapter.afterAll(); + await detox.cleanup(); +}); diff --git a/types/detox/tsconfig.json b/types/detox/tsconfig.json index 3eb7524be2..9440443222 100644 --- a/types/detox/tsconfig.json +++ b/types/detox/tsconfig.json @@ -15,7 +15,9 @@ }, "files": [ "index.d.ts", + "runners/jest/adapters/index.d.ts", "tests/detox-globals-tests.ts", - "tests/detox-import-modules-tests.ts" + "tests/detox-import-modules-tests.ts", + "tests/detox-jest-setup-tests.ts" ] } From f627c9caf605e2c6bd920b79d87b17fd34a21c0b Mon Sep 17 00:00:00 2001 From: Jeff Held Date: Thu, 8 Nov 2018 17:11:13 -0600 Subject: [PATCH 028/836] detox: add mocha adapter definitions --- types/detox/runners/mocha/adapters/index.d.ts | 9 ++++++ .../detox-global-tests.ts} | 0 .../{tests => test}/detox-jest-setup-tests.ts | 0 types/detox/test/detox-mocha-setup-tests.ts | 32 +++++++++++++++++++ .../detox-module-tests.ts} | 0 types/detox/tsconfig.json | 8 +++-- 6 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 types/detox/runners/mocha/adapters/index.d.ts rename types/detox/{tests/detox-globals-tests.ts => test/detox-global-tests.ts} (100%) rename types/detox/{tests => test}/detox-jest-setup-tests.ts (100%) create mode 100644 types/detox/test/detox-mocha-setup-tests.ts rename types/detox/{tests/detox-import-modules-tests.ts => test/detox-module-tests.ts} (100%) diff --git a/types/detox/runners/mocha/adapters/index.d.ts b/types/detox/runners/mocha/adapters/index.d.ts new file mode 100644 index 0000000000..8e13b3bc01 --- /dev/null +++ b/types/detox/runners/mocha/adapters/index.d.ts @@ -0,0 +1,9 @@ +interface DetoxMochaAdapter { + detox: Detox.Detox; + beforeEach: (context: any) => Promise; + afterEach: (context: any) => Promise; +} + +declare const adapter: DetoxMochaAdapter; + +export default adapter; diff --git a/types/detox/tests/detox-globals-tests.ts b/types/detox/test/detox-global-tests.ts similarity index 100% rename from types/detox/tests/detox-globals-tests.ts rename to types/detox/test/detox-global-tests.ts diff --git a/types/detox/tests/detox-jest-setup-tests.ts b/types/detox/test/detox-jest-setup-tests.ts similarity index 100% rename from types/detox/tests/detox-jest-setup-tests.ts rename to types/detox/test/detox-jest-setup-tests.ts diff --git a/types/detox/test/detox-mocha-setup-tests.ts b/types/detox/test/detox-mocha-setup-tests.ts new file mode 100644 index 0000000000..3f502d1391 --- /dev/null +++ b/types/detox/test/detox-mocha-setup-tests.ts @@ -0,0 +1,32 @@ +// tslint:disable:only-arrow-functions + +declare var before: (callback: () => void) => void; +declare var beforeEach: (callback: () => void) => void; +declare var after: (callback: () => void) => void; +declare var afterEach: (callback: () => void) => void; + +import adapter from "detox/runners/mocha/adapters"; + +// Normally the Detox configuration from the project's package.json like so: +// const config = require("./package.json").detox; +declare const config: any; + +// Normally, the beforeEach and afterEach function should take `this` as its argument, +// but `this` cannot be used since it doesn't have a type signature (and therefore always implicltly any) +declare const context: any; + +before(async function() { + await detox.init(config); +}); + +beforeEach(async function() { + await adapter.beforeEach(context); +}); + +afterEach(async function() { + await adapter.afterEach(context); +}); + +after(async function() { + await detox.cleanup(); +}); diff --git a/types/detox/tests/detox-import-modules-tests.ts b/types/detox/test/detox-module-tests.ts similarity index 100% rename from types/detox/tests/detox-import-modules-tests.ts rename to types/detox/test/detox-module-tests.ts diff --git a/types/detox/tsconfig.json b/types/detox/tsconfig.json index 9440443222..7be4d3bb9e 100644 --- a/types/detox/tsconfig.json +++ b/types/detox/tsconfig.json @@ -16,8 +16,10 @@ "files": [ "index.d.ts", "runners/jest/adapters/index.d.ts", - "tests/detox-globals-tests.ts", - "tests/detox-import-modules-tests.ts", - "tests/detox-jest-setup-tests.ts" + "runners/mocha/adapters/index.d.ts", + "test/detox-global-tests.ts", + "test/detox-module-tests.ts", + "test/detox-jest-setup-tests.ts", + "test/detox-mocha-setup-tests.ts" ] } From 53db0897816810df904fbbbbda46fef65a1c1e1a Mon Sep 17 00:00:00 2001 From: Yann Normand Date: Fri, 9 Nov 2018 15:14:19 +1000 Subject: [PATCH 029/836] add a new generic for resource type --- types/react-big-calendar/index.d.ts | 28 +++++++-------- .../react-big-calendar-tests.tsx | 35 ++++++++++++++++--- 2 files changed, 44 insertions(+), 19 deletions(-) diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index bbfd7047ec..eba901bfc9 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -171,19 +171,19 @@ export class DateLocalizer { format(value: FormatInput, format: string, culture: Culture): string; } -export interface BigCalendarProps extends React.Props> { +export interface BigCalendarProps extends React.Props> { localizer: DateLocalizer; date?: stringOrDate; now?: Date; view?: View; - events?: T[]; + events?: TEvent[]; onNavigate?: (newDate: Date, action: Navigate) => void; onView?: (view: View) => void; onDrillDown?: (date: Date, view: View) => void; onSelectSlot?: (slotInfo: { start: stringOrDate, end: stringOrDate, slots: Date[] | string[], action: 'select' | 'click' | 'doubleClick' }) => void; - onDoubleClickEvent?: (event: T, e: React.SyntheticEvent) => void; - onSelectEvent?: (event: T, e: React.SyntheticEvent) => void; + onDoubleClickEvent?: (event: TEvent, e: React.SyntheticEvent) => void; + onSelectEvent?: (event: TEvent, e: React.SyntheticEvent) => void; onSelecting?: (range: { start: stringOrDate, end: stringOrDate }) => boolean | undefined | null; selected?: any; views?: View[] | { @@ -202,7 +202,7 @@ export interface BigCalendarProps extends React.Props { className?: string, style?: React.CSSProperties }; + eventPropGetter?: (event: TEvent, start: stringOrDate, end: stringOrDate, isSelected: boolean) => { className?: string, style?: React.CSSProperties }; slotPropGetter?: (date: Date) => { className?: string, style?: object }; dayPropGetter?: (date: Date) => { className?: string, style?: object }; showMultiDayTimes?: boolean; @@ -213,14 +213,14 @@ export interface BigCalendarProps extends React.Props string); - allDayAccessor?: keyof T | ((event: T) => boolean); - startAccessor?: keyof T | ((event: T) => Date); - endAccessor?: keyof T | ((event: T) => Date); - resourceAccessor?: keyof T | ((event: T) => any); - resources?: any[]; - resourceIdAccessor?: keyof T | ((event: T) => any); - resourceTitleAccessor?: keyof T | ((event: T) => string); + titleAccessor?: keyof TEvent | ((event: TEvent) => string); + allDayAccessor?: keyof TEvent | ((event: TEvent) => boolean); + startAccessor?: keyof TEvent | ((event: TEvent) => Date); + endAccessor?: keyof TEvent | ((event: TEvent) => Date); + resourceAccessor?: keyof TEvent | ((event: TEvent) => any); + resources?: TResource[]; + resourceIdAccessor?: keyof TResource | ((resource: TResource) => any); + resourceTitleAccessor?: keyof TResource | ((resource: TResource) => string); defaultView?: View; defaultDate?: Date; className?: string; @@ -237,7 +237,7 @@ export interface MoveOptions { today: Date; } -export default class BigCalendar extends React.Component> { +export default class BigCalendar extends React.Component> { components: { dateCellWrapper: React.ComponentType, dayWrapper: React.ComponentType, diff --git a/types/react-big-calendar/react-big-calendar-tests.tsx b/types/react-big-calendar/react-big-calendar-tests.tsx index e1b561901e..e50858c546 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -17,13 +17,25 @@ class CalendarEvent { start: Date; end: Date; desc: string; + resourceId?: string; - constructor(_title: string, _start: Date, _end: Date, _allDay?: boolean, _desc?: string) { + constructor(_title: string, _start: Date, _end: Date, _allDay?: boolean, _desc?: string, _resourceId?: string) { this.title = _title; this.allDay = _allDay || false; this.start = _start; this.end = _end; this.desc = _desc || ''; + this.resourceId = _resourceId; + } +} + +class CalendarResource { + title: string; + id: string; + + constructor(id: string, title: string) { + this.id = id; + this.title = title; } } @@ -51,10 +63,10 @@ class CalendarEvent { { // Full API Example Test - based on API Documentation // http://intljusticemission.github.io/react-big-calendar/examples/index.html#api - class FullAPIExample extends React.Component> { + class FullAPIExample extends React.Component> { render() { return ( - {...this.props} date={new Date()} view={'day'} @@ -81,9 +93,9 @@ class CalendarEvent { rtl={true} eventPropGetter={(event, start, end, isSelected) => ({ className: 'some-class' })} titleAccessor={'title'} - allDayAccessor={(event: any) => !!event.allDay} + allDayAccessor={(event: CalendarEvent) => !!event.allDay} startAccessor={'start'} - endAccessor={(event: any) => event.end || event.start} + endAccessor={(event: CalendarEvent) => event.end || event.start} min={new Date()} max={new Date()} scrollToTime={new Date()} @@ -106,6 +118,10 @@ class CalendarEvent { dayPropGetter={customDayPropGetter} slotPropGetter={customSlotPropGetter} defaultDate={new Date()} + resources={getResources()} + resourceAccessor={event => event.resourceId} + resourceIdAccessor={resource => resource.id} + resourceTitleAccessor={resource => resource.title} /> ); } @@ -130,10 +146,19 @@ function getEvents(): CalendarEvent[] { new CalendarEvent('Happy Hour', new Date(2015, 3, 12, 17, 0, 0, 0), new Date(2015, 3, 12, 17, 30, 0, 0), undefined, 'Most important meal of the day'), new CalendarEvent('Dinner', new Date(2015, 3, 12, 20, 0, 0, 0), new Date(2015, 3, 12, 21, 0, 0, 0)), new CalendarEvent('Birthday Party', new Date(2015, 3, 13, 7, 0, 0), new Date(2015, 3, 13, 10, 30, 0)), + new CalendarEvent('Alice\'s break', new Date(2015, 3, 14, 20, 0, 0, 0), new Date(2015, 3, 14, 21, 0, 0, 0), undefined, undefined, "alice"), + new CalendarEvent('Bob\'s break', new Date(2015, 3, 15, 7, 0, 0), new Date(2015, 3, 15, 10, 30, 0), undefined, undefined, "bob"), ]; return events; } +function getResources(): CalendarResource[] { + return [ + new CalendarResource('alice', 'Alice'), + new CalendarResource('bob', 'Bob') + ]; +} + class EventAgenda extends React.Component { render() { // const { label } = this.props; From fe1169f35d5b0b9f577674f6c1ea0e34f58871af Mon Sep 17 00:00:00 2001 From: Yann Normand Date: Fri, 9 Nov 2018 16:30:58 +1000 Subject: [PATCH 030/836] upgrade to TypeScript Version 2.9 --- types/react-big-calendar/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index eba901bfc9..e7faf76ff4 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -6,7 +6,7 @@ // Sebastian Silbermann // Paul Potsides // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 2.9 import { Validator } from 'prop-types'; import * as React from 'react'; From 6ffd9f2bc60165a597b34cc1ea55ee823fccc851 Mon Sep 17 00:00:00 2001 From: Yann Normand Date: Fri, 9 Nov 2018 16:33:24 +1000 Subject: [PATCH 031/836] fix onNavigate function --- types/react-big-calendar/index.d.ts | 2 +- types/react-big-calendar/react-big-calendar-tests.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index e7faf76ff4..0e7da106c2 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -178,7 +178,7 @@ export interface BigCalendarProps void; + onNavigate?: (newDate: Date, view: View, action: Navigate) => void; onView?: (view: View) => void; onDrillDown?: (date: Date, view: View) => void; onSelectSlot?: (slotInfo: { start: stringOrDate, end: stringOrDate, slots: Date[] | string[], action: 'select' | 'click' | 'doubleClick' }) => void; diff --git a/types/react-big-calendar/react-big-calendar-tests.tsx b/types/react-big-calendar/react-big-calendar-tests.tsx index e50858c546..4b80e8a72c 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -71,7 +71,7 @@ class CalendarResource { date={new Date()} view={'day'} events={getEvents()} - onNavigate={(newDate: Date, action: Navigate) => { }} + onNavigate={(newDate: Date, view: View, action: Navigate) => { }} onView={(view: View) => { }} onSelectSlot={(slotInfo) => { const start = slotInfo.start; From 6b5b0a2e98842748c516478c4da99c528481f8e8 Mon Sep 17 00:00:00 2001 From: Ville Saarinen Date: Fri, 9 Nov 2018 09:31:59 +0200 Subject: [PATCH 032/836] Add missing afterVisibleChange and id props --- types/rc-tooltip/index.d.ts | 5 ++++- types/rc-tooltip/rc-tooltip-tests.tsx | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/types/rc-tooltip/index.d.ts b/types/rc-tooltip/index.d.ts index e752404f21..4e07ca484a 100644 --- a/types/rc-tooltip/index.d.ts +++ b/types/rc-tooltip/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for rc-tooltip v3.4.2 +// Type definitions for rc-tooltip v3.7.3 // Project: https://github.com/react-component/tooltip // Definitions by: rhysd // ahstro +// vsaarinen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -24,6 +25,7 @@ declare namespace RCTooltip { prefixCls?: string; transitionName?: string; onVisibleChange?: (visible?: boolean) => void; + afterVisibleChange?: (visible?: boolean) => void; visible?: boolean; defaultVisible?: boolean; placement?: Placement | Object; @@ -33,6 +35,7 @@ declare namespace RCTooltip { arrowContent?: React.ReactNode; getTooltipContainer?: () => Element; destroyTooltipOnHide?: boolean; + id?: string; } } diff --git a/types/rc-tooltip/rc-tooltip-tests.tsx b/types/rc-tooltip/rc-tooltip-tests.tsx index 06b230a55b..7219d8579b 100644 --- a/types/rc-tooltip/rc-tooltip-tests.tsx +++ b/types/rc-tooltip/rc-tooltip-tests.tsx @@ -28,12 +28,14 @@ ReactDOM.render( prefixCls="my-" transitionName="cool-transition" onVisibleChange={() => console.log('visible changed')} + afterVisibleChange={() => console.log('after visible changed')} visible defaultVisible onPopupAlign={(popup, align) => console.log('aligned:', popup, align)} arrowContent={
} getTooltipContainer={() => document.querySelector('.foo')} destroyTooltipOnHide + id="tooltip-id" > hover , From 2da271b8032d72f85f40f04b2f7cf1c79ef56586 Mon Sep 17 00:00:00 2001 From: Alexaner T Date: Fri, 9 Nov 2018 11:59:45 +0200 Subject: [PATCH 033/836] add @types for nise package --- types/nise/index.d.ts | 291 +++++++++++++++++++++++++++++++++++++++ types/nise/nise-tests.ts | 56 ++++++++ types/nise/tsconfig.json | 20 +++ types/nise/tslint.json | 6 + 4 files changed, 373 insertions(+) create mode 100644 types/nise/index.d.ts create mode 100644 types/nise/nise-tests.ts create mode 100644 types/nise/tsconfig.json create mode 100644 types/nise/tslint.json diff --git a/types/nise/index.d.ts b/types/nise/index.d.ts new file mode 100644 index 0000000000..d01ad3303d --- /dev/null +++ b/types/nise/index.d.ts @@ -0,0 +1,291 @@ +// Type definitions for nise 1.4 +// Project: https://github.com/sinonjs/nise#readme +// Definitions by: Alexander T. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +declare namespace Nise { + interface FakeUploadProgress { + eventListeners: { + progress: any[]; + load: any[]; + abort: any[]; + error: any[]; + }; + + addEventListener(event: string, listener: (e: Event) => any): void; + removeEventListener(event: string, listener: (e: Event) => any): void; + dispatchEvent(event: Event): void; + } + + interface FakeXMLHttpRequest { + /** + * The URL set on the request object. + */ + url: string; + /** + * The request method as a string. + */ + method: string; + /** + * An object of all request headers, i.e.: + */ + requestHeaders: any; + /** + * The request body + */ + requestBody: string; + /** + * The request’s status code. + * undefined if the request has not been handled (see respond below) + */ + status: number; + /** + * Only populated if the respond method is called (see below). + */ + statusText: string; + /** + * Whether or not the request is asynchronous. + */ + async: boolean; + /** + * Username, if any. + */ + username: string; + /** + * Password, if any. + */ + password: string; + withCredentials: boolean; + upload: FakeUploadProgress; + /** + * When using respond, this property is populated with a parsed document if response headers indicate as much (see the spec) + */ + responseXML: Document; + /** + * The value of the given response header, if the request has been responded to (see respond). + * @param header + */ + getResponseHeader(header: string): string; + /** + * All response headers as an object. + */ + getAllResponseHeaders(): any; + + /** + * Sets response headers (e.g. { "Content-Type": "text/html", ... }, updates the readyState property and fires onreadystatechange. + * @param headers + */ + setResponseHeaders(headers: any): void; + /** + * Sets the respond body, updates the readyState property and fires onreadystatechange. + * Additionally, populates responseXML with a parsed document if response headers indicate as much. + */ + setResponseBody(body: string): void; + /** + * Calls the above three methods. + */ + respond(status: number, headers?: any, body?: string): void; + autoRespond(ms: number): void; + /** + * Simulates a network error on the request. The onerror handler will be called and the status will be 0. + */ + error(): void; + + onloadstart(e: Event): void; + onprogress(e: Event): void; + ontimeout(e: Event): void; + onloadend(e: Event): void; + onerror(e: Event): void; + onabort(e: Event): void; + onload(e: Event): void; + } + + interface FakeServerOptions { + /** + * When set to true, causes the server to automatically respond to incoming requests after a timeout. + * The default timeout is 10ms but you can control it through the autoRespondAfter property. + * Note that this feature is intended to help during mockup development, and is not suitable for use in tests. + */ + autoRespond: boolean; + /** + * When autoRespond is true, respond to requests after this number of milliseconds. Default is 10. + */ + autoRespondAfter: number; + /** + * If set to true, server will find _method parameter in POST body and recognize that as the actual method. + * Supports a pattern common to Ruby on Rails applications. For custom HTTP method faking, override server.getHTTPMethod(request). + */ + fakeHTTPMethods: boolean; + /** + * If set, the server will respond to every request immediately and synchronously. + * This is ideal for faking the server from within a test without having to call server.respond() after each request made in that test. + * As this is synchronous and immediate, this is not suitable for simulating actual network latency in tests or mockups. + * To simulate network latency with automatic responses, see server.autoRespond and server.autoRespondAfter. + */ + respondImmediately: boolean; + } + + interface FakeServer extends FakeServerOptions { + lastRequest: FakeXMLHttpRequest | undefined; + firstRequest: FakeXMLHttpRequest | undefined; + secondRequest: FakeXMLHttpRequest | undefined; + thirdRequest: FakeXMLHttpRequest | undefined; + + /** + * Used internally to determine the HTTP method used with the provided request. + * By default this method simply returns request.method. + * When server.fakeHTTPMethods is true, the method will return the value of the _method parameter if the method is “POST”. + * This method can be overridden to provide custom behavior. + * @param request + */ + getHTTPMethod(request: FakeXMLHttpRequest): string; + + /** + * You can inspect the server.requests to verify request ordering, find unmatched requests or check that no requests has been done. + * server.requests is an array of all the FakeXMLHttpRequest objects that have been created. + */ + requests: FakeXMLHttpRequest[]; + + /** + * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. + * A String representing the response body + * An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"] + * A Function. + * Default status is 200 and default headers are none. + * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. + * @param body A String representing the response body + */ + respondWith(body: string): void; + /** + * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. + * Default status is 200 and default headers are none. + * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. + * @param response An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"] + */ + respondWith(response: any[]): void; + /** + * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. + * Default status is 200 and default headers are none. + * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. + * @param fn A Function. + */ + respondWith(fn: (xhr: FakeXMLHttpRequest) => void): void; + /** + * Responds to all requests to given URL, e.g. /posts/1. + */ + respondWith(url: string, body: string): void; + /** + * Responds to all requests to given URL, e.g. /posts/1. + */ + respondWith(url: string, response: any[]): void; + /** + * Responds to all requests to given URL, e.g. /posts/1. + */ + respondWith(url: string, fn: (xhr: FakeXMLHttpRequest) => void): void; + /** + * Responds to all method requests to the given URL with the given response. + * method is an HTTP verb. + */ + respondWith(method: string, url: string, body: string): void; + /** + * Responds to all method requests to the given URL with the given response. + * method is an HTTP verb. + */ + respondWith(method: string, url: string, response: any[]): void; + /** + * Responds to all method requests to the given URL with the given response. + * method is an HTTP verb. + */ + respondWith(method: string, url: string, fn: (xhr: FakeXMLHttpRequest) => void): void; + /** + * URL may be a regular expression, e.g. /\\/post\\//\\d+ + * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: + */ + respondWith(url: RegExp, body: string): void; + /** + * URL may be a regular expression, e.g. /\\/post\\//\\d+ + * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: + */ + respondWith(url: RegExp, response: any[]): void; + /** + * URL may be a regular expression, e.g. /\\/post\\//\\d+ + * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: + */ + respondWith(url: RegExp, fn: (xhr: FakeXMLHttpRequest) => void): void; + /** + * Responds to all method requests to URLs matching the regular expression. + */ + respondWith(method: string, url: RegExp, body: string): void; + /** + * Responds to all method requests to URLs matching the regular expression. + */ + respondWith(method: string, url: RegExp, response: any[]): void; + /** + * Responds to all method requests to URLs matching the regular expression. + */ + respondWith(method: string, url: RegExp, fn: (xhr: FakeXMLHttpRequest) => void): void; + respondWith(...args: any[]): void; + + /** + * Causes all queued asynchronous requests to receive a response. + * If none of the responses added through respondWith match, the default response is [404, {}, ""]. + * Synchronous requests are responded to immediately, so make sure to call respondWith upfront. + * If called with arguments, respondWith will be called with those arguments before responding to requests. + */ + respond(): void; + restore(): void; + + getRequest(): FakeXMLHttpRequest | undefined; + reset(): void; + resetBehavior(): void; + resetHistory(): void; + } + + interface FakeXMLHttpRequestStatic { + new(): FakeXMLHttpRequest; + /** + * Default false. + * When set to true, Sinon will check added filters if certain requests should be “unfaked” + */ + useFilters: boolean; + /** + * Add a filter that will decide whether or not to fake a request. + * The filter will be called when xhr.open is called, with the exact same arguments (method, url, async, username, password). + * If the filter returns true, the request will not be faked. + * @param filter + */ + addFilter(filter: (method: string, url: string, async: boolean, username: string, password: string) => boolean): void; + /** + * By assigning a function to the onCreate property of the returned object from useFakeXMLHttpRequest() + * you can subscribe to newly created FakeXMLHttpRequest objects. See below for the fake xhr object API. + * Using this observer means you can still reach objects created by e.g. jQuery.ajax (or other abstractions/frameworks). + * @param xhr + */ + onCreate(xhr: FakeXMLHttpRequest): void; + /** + * Restore original function(s). + */ + restore(): void; + } + + interface FakeServerStatic { + create(options?: Partial): FakeServer; + } + + interface FakeXHR { + useFakeXMLHttpRequest(): FakeXMLHttpRequestStatic; + FakeXMLHttpRequest: FakeXMLHttpRequestStatic; + } + + interface API { + fakeServerWithClock: FakeServerStatic; + fakeServer: FakeServerStatic; + fakeXhr: FakeXHR; + } +} + +declare const Nise: Nise.API; + +export = Nise; +export as namespace nise; diff --git a/types/nise/nise-tests.ts b/types/nise/nise-tests.ts new file mode 100644 index 0000000000..827275fc55 --- /dev/null +++ b/types/nise/nise-tests.ts @@ -0,0 +1,56 @@ +import { fakeXhr, fakeServer, FakeServer, FakeXMLHttpRequest } from 'nise'; + +function testCreateFakeServer() { + fakeServer.create(); + fakeServer.create({ autoRespond: true, autoRespondAfter: 3, fakeHTTPMethods: true, respondImmediately: false }); + fakeServer.create({ autoRespond: true, autoRespondAfter: 3 }); +} + +function testFakeServer() { + const server: FakeServer = fakeServer.create(); + const respondWith = ['GET', 'http://test.com', [200, {}, '']]; + + server.requests; + server.autoRespond = true; + + server.respondWith((xhr: FakeXMLHttpRequest) => xhr.respond(200)); + server.respondWith('body'); + server.respondWith([]); + + server.respondWith('http://test.com', 'body'); + server.respondWith('http://test.com', []); + server.respondWith('http://test.com', (xhr: FakeXMLHttpRequest) => xhr.respond(200)); + + server.respondWith('GET', 'http://test.com', 'body'); + server.respondWith('GET', 'http://test.com', []); + server.respondWith('GET', 'http://test.com', (xhr: FakeXMLHttpRequest) => xhr.respond(200)); + + server.respondWith(/url/, ''); + server.respondWith(/url/, []); + server.respondWith(/url/, (xhr: FakeXMLHttpRequest) => xhr.respond(200)); + + server.respondWith('GET', /url/, ''); + server.respondWith('GET', /url/, []); + server.respondWith('GET', /url/, (xhr: FakeXMLHttpRequest) => xhr.respond(200)); + server.respondWith(...respondWith); + server.respond(); + server.restore(); +} + +function testFakeXMLHttpRequest() { + const xhr = new fakeXhr.FakeXMLHttpRequest(); + const headers = xhr.getAllResponseHeaders(); + const header = xhr.getResponseHeader('test'); + + xhr.setResponseHeaders({ Accept: 'application/json' }); + xhr.setResponseBody('body'); + xhr.respond(200, { Accept: 'application/json' }, 'body'); + xhr.error(); +} + +function testFakeXMLHttpRequestStatic() { + fakeXhr.FakeXMLHttpRequest.useFilters = true; + fakeXhr.FakeXMLHttpRequest.addFilter((method, url, async, user, pass) => true); + fakeXhr.FakeXMLHttpRequest.onCreate = (xhr: FakeXMLHttpRequest) => { }; + fakeXhr.FakeXMLHttpRequest.restore(); +} diff --git a/types/nise/tsconfig.json b/types/nise/tsconfig.json new file mode 100644 index 0000000000..1e535819c3 --- /dev/null +++ b/types/nise/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "noImplicitThis": true, + "noImplicitAny": true, + "module": "commonjs", + "noEmit": true, + "types": [], + "lib": ["es6", "dom"], + "baseUrl": "../", + "typeRoots": ["../"] + }, + + "files": [ + "nise-tests.ts", + "index.d.ts" + ] +} diff --git a/types/nise/tslint.json b/types/nise/tslint.json new file mode 100644 index 0000000000..08b1465cd6 --- /dev/null +++ b/types/nise/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false + } +} From 1343e45412283277fc9b8d6effeee7a76eaee136 Mon Sep 17 00:00:00 2001 From: juwar Date: Fri, 9 Nov 2018 07:30:07 -0800 Subject: [PATCH 034/836] Remove patch version --- types/highcharts/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 644dc1a169..58154954a3 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Highcharts 5.0.32 +// Type definitions for Highcharts 5.0 // Project: http://www.highcharts.com/ // Definitions by: Damiano Gambarotto // Dan Lewi Harkestad From 8f2e78835f3e38c4a5b15a51dd2aa453a2031c47 Mon Sep 17 00:00:00 2001 From: Fellipe Chagas Date: Fri, 9 Nov 2018 15:19:11 -0200 Subject: [PATCH 035/836] Improves react-navigation typings --- types/react-navigation/index.d.ts | 121 +++++++++++++++++------------- 1 file changed, 68 insertions(+), 53 deletions(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 846ea56a9e..512059e29c 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -27,6 +27,7 @@ // Max Davidson // Lachlan Young // Jason Killian +// Fellipe Chagas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -94,6 +95,9 @@ export interface NavigationState { */ index: number; routes: NavigationRoute[]; + isTransitioning: boolean; + key: string; + params: NavigationParams; } export interface DrawerNavigationState extends NavigationState { @@ -129,6 +133,8 @@ export interface NavigationLeafRoute { * e.g. `{ car_id: 123 }` in a route that displays a car. */ params?: Params; + routes: NavigationRoute[]; + isTransitioning: boolean; } export type NavigationStateRoute< @@ -280,28 +286,28 @@ export interface NavigationInitAction extends NavigationInitActionPayload { } export interface NavigationReplaceActionPayload { - key?: string; - newKey?: string; - routeName: string; - params?: NavigationParams; - action?: NavigationNavigateAction; + key?: string; + newKey?: string; + routeName: string; + params?: NavigationParams; + action?: NavigationNavigateAction; } export interface NavigationReplaceAction { - type: 'Navigation/REPLACE'; - key: string; - routeName: string; - params?: NavigationParams; - action?: NavigationNavigateAction; + type: 'Navigation/REPLACE'; + key: string; + routeName: string; + params?: NavigationParams; + action?: NavigationNavigateAction; } export interface NavigationCompleteTransitionActionPayload { - key?: string; + key?: string; } export interface NavigationCompleteTransitionAction { - type: 'Navigation/COMPLETE_TRANSITION'; - key: string; + type: 'Navigation/COMPLETE_TRANSITION'; + key: string; } export interface NavigationResetActionPayload { @@ -343,33 +349,33 @@ export interface NavigationPopToTopAction } export interface NavigationPushActionPayload { - routeName: string; - params?: NavigationParams; - action?: NavigationNavigateAction; - key?: string; + routeName: string; + params?: NavigationParams; + action?: NavigationNavigateAction; + key?: string; } export interface NavigationPushAction { - type: 'Navigation/PUSH'; - routeName: string; - params?: NavigationParams; - action?: NavigationNavigateAction; - key?: string; + type: 'Navigation/PUSH'; + routeName: string; + params?: NavigationParams; + action?: NavigationNavigateAction; + key?: string; } export interface NavigationOpenDrawerAction { - key?: string; - type: 'Navigation/OPEN_DRAWER'; + key?: string; + type: 'Navigation/OPEN_DRAWER'; } export interface NavigationCloseDrawerAction { - key?: string; - type: 'Navigation/CLOSE_DRAWER'; + key?: string; + type: 'Navigation/CLOSE_DRAWER'; } export interface NavigationToggleDrawerAction { - key?: string; - type: 'Navigation/TOGGLE_DRAWER'; + key?: string; + type: 'Navigation/TOGGLE_DRAWER'; } export interface NavigationStackViewConfig { @@ -655,9 +661,12 @@ export interface NavigationScreenProp { pop: (n?: number, params?: { immediate?: boolean }) => boolean; popToTop: (params?: { immediate?: boolean }) => boolean; isFocused: () => boolean; + router?: NavigationRouter; + dangerouslyGetParent: () => NavigationScreenProp | undefined; } export interface NavigationNavigatorProps { + detached?: boolean; navigation?: NavigationProp; screenProps?: { [key: string]: any }; navigationOptions?: O; @@ -728,6 +737,9 @@ export interface NavigationTransitionSpec { easing?: (t: number) => number; // A timing function such as `Animated.timing`. timing?: (value: AnimatedValue, config: any) => any; + friction?: number; + tension?: number; + useNativeDriver?: boolean; } /** @@ -1065,41 +1077,41 @@ export namespace NavigationActions { * DrawerActions */ export namespace DrawerActions { - const OPEN_DRAWER: 'Navigation/OPEN_DRAWER'; - const CLOSE_DRAWER: 'Navigation/CLOSE_DRAWER'; - const TOGGLE_DRAWER: 'Navigation/TOGGLE_DRAWER'; + const OPEN_DRAWER: 'Navigation/OPEN_DRAWER'; + const CLOSE_DRAWER: 'Navigation/CLOSE_DRAWER'; + const TOGGLE_DRAWER: 'Navigation/TOGGLE_DRAWER'; - function openDrawer(): NavigationOpenDrawerAction; - function closeDrawer(): NavigationCloseDrawerAction; - function toggleDrawer(): NavigationToggleDrawerAction; + function openDrawer(): NavigationOpenDrawerAction; + function closeDrawer(): NavigationCloseDrawerAction; + function toggleDrawer(): NavigationToggleDrawerAction; } /** * StackActions */ export namespace StackActions { - const POP: 'Navigation/POP'; - const POP_TO_TOP: 'Navigation/POP_TO_TOP'; - const PUSH: 'Navigation/PUSH'; - const RESET: 'Navigation/RESET'; - const REPLACE: 'Navigation/REPLACE'; - const COMPLETE_TRANSITION: 'Navigation/COMPLETE_TRANSITION'; + const POP: 'Navigation/POP'; + const POP_TO_TOP: 'Navigation/POP_TO_TOP'; + const PUSH: 'Navigation/PUSH'; + const RESET: 'Navigation/RESET'; + const REPLACE: 'Navigation/REPLACE'; + const COMPLETE_TRANSITION: 'Navigation/COMPLETE_TRANSITION'; - function pop(options: NavigationPopActionPayload): NavigationPopAction; - function popToTop( - options: NavigationPopToTopActionPayload - ): NavigationPopToTopAction; + function pop(options: NavigationPopActionPayload): NavigationPopAction; + function popToTop( + options: NavigationPopToTopActionPayload + ): NavigationPopToTopAction; - function push(options: NavigationPushActionPayload): NavigationPushAction; - function reset(options: NavigationResetActionPayload): NavigationResetAction; + function push(options: NavigationPushActionPayload): NavigationPushAction; + function reset(options: NavigationResetActionPayload): NavigationResetAction; - function replace( - options: NavigationReplaceActionPayload - ): NavigationReplaceAction; + function replace( + options: NavigationReplaceActionPayload + ): NavigationReplaceAction; - function completeTransition( - payload: NavigationCompleteTransitionActionPayload - ): NavigationCompleteTransitionAction; + function completeTransition( + payload: NavigationCompleteTransitionActionPayload + ): NavigationCompleteTransitionAction; } /** @@ -1124,6 +1136,7 @@ export interface TransitionerProps { transitionProps: NavigationTransitionProps, prevTransitionProps?: NavigationTransitionProps ) => any; + descriptors: { [key: string]: NavigationDescriptor }; style?: StyleProp; } @@ -1169,11 +1182,13 @@ export interface NavigationDescriptor { state: NavigationLeafRoute | NavigationStateRoute; navigation: NavigationScreenProp; options: NavigationScreenOptions; - getComponent: () => React.ComponentType; + getComponent: () => React.ComponentType & { navigationOptions: N }; } export type NavigationView = React.ComponentType<{ descriptors: { [key: string]: NavigationDescriptor }; + navigationConfig: O; + screenProps?: { [key: string]: any }; } & NavigationInjectedProps>; export function createNavigator( From eea8aaf433a16830c0bb9b99aa0a73b15afb9b79 Mon Sep 17 00:00:00 2001 From: Fellipe Chagas Date: Fri, 9 Nov 2018 15:58:46 -0200 Subject: [PATCH 036/836] Adjusts compilation errors --- types/react-navigation/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 512059e29c..e51629f3af 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -1136,7 +1136,7 @@ export interface TransitionerProps { transitionProps: NavigationTransitionProps, prevTransitionProps?: NavigationTransitionProps ) => any; - descriptors: { [key: string]: NavigationDescriptor }; + descriptors?: { [key: string]: NavigationDescriptor }; style?: StyleProp; } @@ -1182,7 +1182,7 @@ export interface NavigationDescriptor { state: NavigationLeafRoute | NavigationStateRoute; navigation: NavigationScreenProp; options: NavigationScreenOptions; - getComponent: () => React.ComponentType & { navigationOptions: N }; + getComponent: () => React.ComponentType; } export type NavigationView = React.ComponentType<{ From ac84fc6c7f22b49cfe4066d080109e02fdf76db9 Mon Sep 17 00:00:00 2001 From: Lucas Date: Fri, 9 Nov 2018 22:02:35 +0100 Subject: [PATCH 037/836] Add initial definitions for kdbxweb --- types/kdbxweb/index.d.ts | 461 +++++++++++++++++++++++++++++++++ types/kdbxweb/kdbxweb-tests.ts | 18 ++ types/kdbxweb/tsconfig.json | 23 ++ types/kdbxweb/tslint.json | 1 + 4 files changed, 503 insertions(+) create mode 100644 types/kdbxweb/index.d.ts create mode 100644 types/kdbxweb/kdbxweb-tests.ts create mode 100644 types/kdbxweb/tsconfig.json create mode 100644 types/kdbxweb/tslint.json diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts new file mode 100644 index 0000000000..2787ba7a1f --- /dev/null +++ b/types/kdbxweb/index.d.ts @@ -0,0 +1,461 @@ +// Type definitions for kdbxweb 1.2 +// Project: https://github.com/keeweb/kdbxweb#readme +// Definitions by: Roang-zero1 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import Crypto from "crypto"; + +/*~ If this module is a UMD module that exposes a global variable 'myLib' when + *~ loaded outside a module loader environment, declare that global here. + *~ Otherwise, delete this declaration. + */ +export as namespace kdbxweb; + +export interface Settings { + binaries: boolean; + customIcons: boolean; + historyRules: boolean; +} + +export interface ObjectMap { + objects: object[]; + remote: object[]; + deleted: object[]; +} + +export interface editingState { + added: [Date]; + deleted: [Date]; +} + +export interface editingStateDict { + meta: editingState; + [uuid: string]: editingState; +} + +export class Credentials { + constructor( + password: ProtectedValue, + keyFile: string | ArrayBuffer | Uint8Array + ); + + getHash(): Promise; + + setKeyFile(keyFile: ArrayBuffer | Uint8Array | null): Promise; + + setPassword(password: ProtectedValue | null): Promise; + + static createKeyFileWithHash(hash: string): Uint8Array; + + static createRandomKeyFile(): Uint8Array; +} + +export class Int64 { + constructor(lo: number, hi: number); + + valueOf(): number; + + static from(value: number): Int64; +} + +export class Kdbx { + constructor(); + + addDeletedObject(uuid: KdbxUuid, dt: Date): void; + + cleanup(settings: Settings): void; + + createBinary( + value: ProtectedValue | ArrayBuffer + ): Promise; + + createDefaultGroup(): void; + + createEntry(group: Group): Entry; + + createGroup(group: Group, name: string): Group; + + createRecycleBin(): void; + + getDefaultGroup(): Group; + + getGroup(uuid: KdbxUuid | string, parentGroup: Group): Group | undefined; + + getLocalEditState(): editingStateDict; + + merge(remote: Kdbx): void; + + move(object: Entry | Group, toGroup: Group, atIndex: number): void; + + remove(object: Entry | Group): void; + + removeLocalEditState(): void; + + save(): Promise; + + saveXml(): Promise; + + setLocalEditState(editingState: editingStateDict): void; + + upgrade(): void; + + static create(credentials: Credentials, name: string): Kdbx; + + static load(data: ArrayBuffer, credentials: Credentials): Promise; + + static loadXml(data: string, credentials: Credentials): Promise; +} + +export class KdbxError { + constructor(code: number, message: string); + + // Native method; no parameter or return type inference available + toString(): string; +} + +export class KdbxUuid { + constructor(ab: string | ArrayBuffer); + + equals(other: KdbxUuid): boolean; + + toBytes(): Uint8Array | undefined; + + toString(): string; + + valueOf(): string | undefined; + + static random(): KdbxUuid; +} + +export class ProtectedValue { + constructor(value: ArrayBuffer, salt: ArrayBuffer); + + clone(): ProtectedValue; + + getBinary(): Uint8Array; + + getHash(): Promise; + + getText(): string; + + includes(str: string): boolean; + + setSalt(newSalt: ArrayBuffer): void; + + toString(): string; + + static fromBinary(binary: ArrayBuffer): ProtectedValue; + + static fromString(str: string): ProtectedValue; +} + +export class VarDictionary { + constructor(); + + get(key: string): any; + + keys(): string[]; + + remove(key: string): void; + + set(key: string, type: number, value: any): void; + + write(stm: BinaryStream): void; + + static ValueType: { + Bool: number; + Bytes: number; + Int32: number; + Int64: number; + String: number; + UInt32: number; + UInt64: number; + }; + + static read(stm: BinaryStream): VarDictionary; +} + +export const Consts: { + AutoTypeObfuscationOptions: { + None: number; + UseClipboard: number; + }; + CipherId: { + Aes: string; + ChaCha20: string; + }; + CompressionAlgorithm: { + GZip: number; + None: number; + }; + CrsAlgorithm: { + ArcFourVariant: number; + ChaCha20: number; + Null: number; + Salsa20: number; + }; + Defaults: { + HistoryMaxItems: number; + HistoryMaxSize: number; + KeyEncryptionRounds: number; + MntncHistoryDays: number; + RecycleBinName: string; + }; + ErrorCodes: { + BadSignature: string; + FileCorrupt: string; + InvalidArg: string; + InvalidKey: string; + InvalidVersion: string; + MergeError: string; + NotImplemented: string; + Unsupported: string; + }; + Icons: { + Apple: number; + Archive: number; + BlackBerry: number; + Book: number; + CDRom: number; + Certificate: number; + Checked: number; + ClipboardReady: number; + Clock: number; + Configuration: number; + Console: number; + Digicam: number; + Disk: number; + Drive: number; + DriveWindows: number; + EMail: number; + EMailBox: number; + EMailSearch: number; + Energy: number; + EnergyCareful: number; + Expired: number; + Feather: number; + Folder: number; + FolderOpen: number; + FolderPackage: number; + Home: number; + Homebanking: number; + IRCommunication: number; + Identity: number; + Info: number; + Key: number; + List: number; + LockOpen: number; + MarkedDirectory: number; + Memory: number; + Money: number; + Monitor: number; + MultiKeys: number; + NetworkServer: number; + Note: number; + Notepad: number; + Package: number; + PaperFlag: number; + PaperLocked: number; + PaperNew: number; + PaperQ: number; + PaperReady: number; + Parts: number; + Pen: number; + Printer: number; + ProgramIcons: number; + Run: number; + Scanner: number; + Screen: number; + Settings: number; + Star: number; + TerminalEncrypted: number; + Thumbnail: number; + Tool: number; + TrashBin: number; + Tux: number; + UserCommunication: number; + UserKey: number; + Warning: number; + Wiki: number; + World: number; + WorldComputer: number; + WorldSocket: number; + WorldStar: number; + }; + KdfId: { + Aes: string; + Argon2: string; + }; + Signatures: { + FileMagic: number; + Sig2Kdb: number; + Sig2Kdbx: number; + }; +}; + +export namespace ByteUtils { + function arrayBufferEquals(ab1: ArrayBuffer, ab2: ArrayBuffer): boolean; + + function arrayToBuffer(arr: Uint8Array | ArrayBuffer): ArrayBuffer; + + function base64ToBytes(str: string): Uint8Array; + + function bytesToBase64(arr: Uint8Array | ArrayBuffer): string; + + function bytesToHex(arr: Uint8Array | ArrayBuffer): string; + + function bytesToString(arr: Uint8Array | ArrayBuffer): string; + + function hexToBytes(hex: string): Uint8Array; + + function stringToBytes(str: string): Uint8Array; + + function zeroBuffer(buffer: Uint8Array | ArrayBuffer): void; +} + +export namespace CryptoEngine { + const subtle: any; + + const webCrypto: any; + + function argon2( + password: ArrayBuffer, + salt: ArrayBuffer, + memory: number, + iterations: number, + length: number, + parallelism: number, + type: number, + version: number + ): Promise; + + function chacha20( + data: ArrayBuffer, + key: ArrayBuffer, + iv: ArrayBuffer + ): Promise; + + function configure( + newSubtle: SubtleCrypto | null, + newWebCrypto: Crypto | null, + newNodeCrypto: Crypto | null + ): void; + + function createAesCbc(): any; + + function hmacSha256( + key: ArrayBuffer, + data: ArrayBuffer + ): Promise; + + function random(len: number): Uint8Array; + + function sha256(data: ArrayBuffer): Promise; + + function sha512(data: ArrayBuffer): Promise; +} + +export namespace Random { + function getBytes(len: number): Uint8Array; +} + +export class BinaryStream { + constructor(arrayBuffer: ArrayBuffer); + + getByteLength(): number; + + getFloat32(littleEdian?: boolean): number; + + getFloat64(littleEdian?: boolean): number; + + getInt16(littleEdian?: boolean): number; + + getInt32(littleEdian?: boolean): number; + + getInt8(littleEdian?: boolean): number; + + getPos(): number; + + getUint16(littleEdian?: boolean): number; + + getUint32(littleEdian?: boolean): number; + + getUint64(littleEdian?: boolean): number; + + getUint8(littleEdian?: boolean): number; + + getWrittenBytes(): ArrayBuffer; + + readBytes(size: number): ArrayBuffer; + + readBytesNoAdvance(startPos: number, endPos: number): ArrayBuffer; + + readBytesToEnd(): ArrayBuffer; + + setFloat32(value: number, littleEdian?: boolean): void; + + setFloat64(value: number, littleEdian?: boolean): void; + + setInt16(value: number, littleEdian?: boolean): void; + + setInt32(value: number, littleEdian?: boolean): void; + + setInt8(value: number, littleEdian?: boolean): void; + + setUint16(value: number, littleEdian?: boolean): void; + + setUint32(value: number, littleEdian?: boolean): void; + + setUint64(value: number, littleEdian?: boolean): void; + + setUint8(value: number, littleEdian?: boolean): void; + + writeBytes(bytes: ArrayBuffer | Uint8Array): void; +} + +export class Context { + constructor(opts: Kdbx); + + setXmlDate(node: Node, dt: Date): void; +} + +export class Group { + constructor(); + + static create(name: string, parentGroup: Group): Group; + static read(xmlNode: Node, ctx: Context, parentGroup: Group): Group; + + write(parentNode: Node, ctx: Context): void; + forEach( + callback: ( + thisArg: (value: any) => void, + entry: Entry | undefined + ) => void, + thisArg: (value: any) => void + ): void; + merge(objectMap: ObjectMap): void; + copyFrom(group: Group): void; +} + +export class Entry { + constructor(); + + static create(meta: Meta, parentGroup: Group): Entry; + static read(xmlNode: Node, ctx: Context, parentGroup: Group): Entry; + + write(parentNode: Node, ctx: Context): void; + pushHistory(): void; + removeHistory(index: number, count: number): void; + copyFrom(entry: Entry): void; + merge(objectMap: ObjectMap): void; +} + +export class Meta { + constructor(); + + static create(): Meta; + static read(xmlNode: Node, ctx: Context): Meta; + + write(parentNode: Node, ctx: Context): void; + merge(remote: Meta, objectMap: ObjectMap): void; +} diff --git a/types/kdbxweb/kdbxweb-tests.ts b/types/kdbxweb/kdbxweb-tests.ts new file mode 100644 index 0000000000..d667117b6b --- /dev/null +++ b/types/kdbxweb/kdbxweb-tests.ts @@ -0,0 +1,18 @@ +import * as kdbxweb from "kdbxweb"; + +const dataarr = new ArrayBuffer(0); + +const credentials = new kdbxweb.Credentials( + kdbxweb.ProtectedValue.fromString("demo"), + "nFWx&e5SzT" +); + +kdbxweb.Kdbx.load(dataarr, credentials).then(db => db); +kdbxweb.Kdbx.loadXml("data", credentials).then(db => db); + +const newDb = kdbxweb.Kdbx.create(credentials, 'My new db'); +const group = newDb.createGroup(newDb.getDefaultGroup(), 'subgroup'); +const entry = newDb.createEntry(group); + +newDb.save().then(dataAsArrayBuffer => dataAsArrayBuffer); +newDb.saveXml().then(xmlAsString => xmlAsString); diff --git a/types/kdbxweb/tsconfig.json b/types/kdbxweb/tsconfig.json new file mode 100644 index 0000000000..6c6083b077 --- /dev/null +++ b/types/kdbxweb/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", + "kdbxweb-tests.ts" + ] +} diff --git a/types/kdbxweb/tslint.json b/types/kdbxweb/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/kdbxweb/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 2009fc1c826aae33afd1ac1c571707fa57bc328f Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 19:34:31 +0100 Subject: [PATCH 038/836] Add library for dom elements --- types/kdbxweb/tsconfig.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/kdbxweb/tsconfig.json b/types/kdbxweb/tsconfig.json index 6c6083b077..77578b1129 100644 --- a/types/kdbxweb/tsconfig.json +++ b/types/kdbxweb/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, From e9b486b9065591cb640120fbd92e1d1ad9c39159 Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 20:22:08 +0100 Subject: [PATCH 039/836] Remove unnecessary import --- types/kdbxweb/index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index 2787ba7a1f..376e0bafde 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -3,8 +3,6 @@ // Definitions by: Roang-zero1 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import Crypto from "crypto"; - /*~ If this module is a UMD module that exposes a global variable 'myLib' when *~ loaded outside a module loader environment, declare that global here. *~ Otherwise, delete this declaration. From 702978e8c6188eaaa4baf7f2d5e93a4afb94ee4d Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 20:24:01 +0100 Subject: [PATCH 040/836] Add KdbxObject type --- types/kdbxweb/index.d.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index 376e0bafde..c781470283 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -9,6 +9,8 @@ */ export as namespace kdbxweb; +export type KdbxObject = Entry | Group; + export interface Settings { binaries: boolean; customIcons: boolean; @@ -16,9 +18,9 @@ export interface Settings { } export interface ObjectMap { - objects: object[]; - remote: object[]; - deleted: object[]; + objects: KdbxObject[]; + remote: KdbxObject[]; + deleted: KdbxObject[]; } export interface editingState { @@ -59,6 +61,8 @@ export class Int64 { export class Kdbx { constructor(); + deletedObjects: KdbxObject[]; + addDeletedObject(uuid: KdbxUuid, dt: Date): void; cleanup(settings: Settings): void; @@ -83,9 +87,9 @@ export class Kdbx { merge(remote: Kdbx): void; - move(object: Entry | Group, toGroup: Group, atIndex: number): void; + move(object: KdbxObject, toGroup: Group, atIndex?: number): void; - remove(object: Entry | Group): void; + remove(object: KdbxObject): void; removeLocalEditState(): void; From bfbd5e652499e05b03bb2d657b9f462bbe0905c1 Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 20:24:38 +0100 Subject: [PATCH 041/836] Update settings interface --- types/kdbxweb/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index c781470283..9530ad3fa8 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -12,9 +12,9 @@ export as namespace kdbxweb; export type KdbxObject = Entry | Group; export interface Settings { - binaries: boolean; - customIcons: boolean; - historyRules: boolean; + binaries?: boolean; + customIcons?: boolean; + historyRules?: boolean; } export interface ObjectMap { From 4e753b47a47b0417dc9a510f357004290f323d13 Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 20:25:10 +0100 Subject: [PATCH 042/836] Add binaries class --- types/kdbxweb/index.d.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index 9530ad3fa8..3f04965a59 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -23,6 +23,11 @@ export interface ObjectMap { deleted: KdbxObject[]; } +export interface BinaryInforamtion { + ref: string; + value: ProtectedValue | ArrayBuffer; +} + export interface editingState { added: [Date]; deleted: [Date]; @@ -61,6 +66,7 @@ export class Int64 { export class Kdbx { constructor(); + binaries: Binaries; deletedObjects: KdbxObject[]; addDeletedObject(uuid: KdbxUuid, dt: Date): void; @@ -415,6 +421,17 @@ export class BinaryStream { writeBytes(bytes: ArrayBuffer | Uint8Array): void; } +export class Binaries { + constructor(); + + hash(): Promise; + getBinaryHash( + binary: ProtectedValue | ArrayBuffer | Uint8Array + ): Promise; + assignIds(): void; + add(value: ProtectedValue | ArrayBuffer): Promise; +} + export class Context { constructor(opts: Kdbx); From 2224bdf11a6e5420ab6777b22570044af354bd83 Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 20:27:47 +0100 Subject: [PATCH 043/836] Add class properties --- types/kdbxweb/index.d.ts | 93 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index 3f04965a59..0e52af89c0 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -58,6 +58,9 @@ export class Credentials { export class Int64 { constructor(lo: number, hi: number); + lo: number; + hi: number; + valueOf(): number; static from(value: number): Int64; @@ -66,7 +69,12 @@ export class Int64 { export class Kdbx { constructor(); + header: Header; + credentials: Credentials; + meta: Meta; + xml: Document; binaries: Binaries; + groups: Group[]; deletedObjects: KdbxObject[]; addDeletedObject(uuid: KdbxUuid, dt: Date): void; @@ -117,6 +125,10 @@ export class Kdbx { export class KdbxError { constructor(code: number, message: string); + name: "KdbxError"; + code: number; + message: string; + // Native method; no parameter or return type inference available toString(): string; } @@ -124,6 +136,9 @@ export class KdbxError { export class KdbxUuid { constructor(ab: string | ArrayBuffer); + id: string | undefined; + empty: boolean; + equals(other: KdbxUuid): boolean; toBytes(): Uint8Array | undefined; @@ -441,6 +456,22 @@ export class Context { export class Group { constructor(); + uuid: string; + name: string; + notes: string; + icon: number; + customIcon: KdbxUuid; + times: Times; + expanded: boolean; + defaultAutoTypeSeq: string; + enableAutoType: boolean; + enableSearching: boolean; + lastTopVisibleEntry: KdbxUuid; + groups: Group[]; + entries: Entry[]; + parentGroup: Group; + customData: any; + static create(name: string, parentGroup: Group): Group; static read(xmlNode: Node, ctx: Context, parentGroup: Group): Group; @@ -459,6 +490,21 @@ export class Group { export class Entry { constructor(); + uuid: string; + icon: any; + customIcon: any; + fgColor: any; + bgColor: any; + overrideUrl: any; + tags: any[]; + times: Times; + fields: { [name: string]: any }; + binaries: {}; + autoType: any; + history: any[]; + parentGroup: Group; + customData: any; + static create(meta: Meta, parentGroup: Group): Entry; static read(xmlNode: Node, ctx: Context, parentGroup: Group): Entry; @@ -478,3 +524,50 @@ export class Meta { write(parentNode: Node, ctx: Context): void; merge(remote: Meta, objectMap: ObjectMap): void; } + +export class Header { + constructor(); + + compression: number; + crsAlgorithm: number; + dataCipherUuid: KdbxUuid; + encryptionIV: any; + endPos: number; + kdfParameters: VarDictionary; + keyEncryptionRounds: number; + masterSeed: Uint8Array; + protectedStreamKey: any; + publicCustomData: any; + streamStartBytes: any; + transformSeed: any; + versionMajor: number; + versionMinor: number; + + static read(stm: BinaryStream, ctx: Context): Header; + static create(): Header; + + generateSalts(): void; + readInnerHeader(stm: BinaryStream, ctx: Context): void; + upgrade(): void; + write(stm: BinaryStream): void; + writeInnerHeader(stm: BinaryStream, ctx: Context): void; +} + +export class Times { + constructor(); + + creationTime: Date; + lastModTime: Date; + lastAccessTime: Date; + expiryTime: Date; + expires: boolean; + usageCount: number; + locationChanged: Date; + + static create(): Times; + static read(xmlNode: Node): Times; + + clone(): Times; + update(): void; + write(parentNode: Node, ctx: Context): void; +} From 4ea7a5f73578f7230fc6f54e5c3d025a2e74fe7a Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 20:28:07 +0100 Subject: [PATCH 044/836] Update CryptoEngine namespace --- types/kdbxweb/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index 0e52af89c0..f846123cbb 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -337,9 +337,9 @@ export namespace ByteUtils { } export namespace CryptoEngine { - const subtle: any; - - const webCrypto: any; + const subtle: SubtleCrypto | null; + const webCrypto: Crypto | null; + const NodeCrypto: Crypto | null; function argon2( password: ArrayBuffer, From 3902c860b7edf771017802786a9cbcb0168f68c2 Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 20:28:23 +0100 Subject: [PATCH 045/836] Fix getGroup delcaration --- types/kdbxweb/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index f846123cbb..2b5952fa0e 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -95,7 +95,7 @@ export class Kdbx { getDefaultGroup(): Group; - getGroup(uuid: KdbxUuid | string, parentGroup: Group): Group | undefined; + getGroup(uuid: KdbxUuid | string, parentGroup?: Group): Group | undefined; getLocalEditState(): editingStateDict; From 8cb32a28e6b6e0e131325e0ebfcd7f60476bda8d Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 20:36:42 +0100 Subject: [PATCH 046/836] Update Entry properties --- types/kdbxweb/index.d.ts | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index 2b5952fa0e..e7860b1e92 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -490,18 +490,26 @@ export class Group { export class Entry { constructor(); - uuid: string; - icon: any; - customIcon: any; - fgColor: any; - bgColor: any; - overrideUrl: any; - tags: any[]; + uuid: KdbxUuid; + icon: number; + customIcon: KdbxUuid; + fgColor: string; + bgColor: string; + overrideUrl: string; + tags: string[]; times: Times; - fields: { [name: string]: any }; + fields: { [key: string]: any }; binaries: {}; - autoType: any; - history: any[]; + autoType: { + enabled: boolean; + obfuscation: number; + defaultSequence: string; + items: { + windows: string; + keystrokeSequence: string; + }; + }; + history: Entry[]; parentGroup: Group; customData: any; From 13502ed0fd81121e1206821b520f29a1587bfc83 Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 20:49:16 +0100 Subject: [PATCH 047/836] Update header --- types/kdbxweb/index.d.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index e7860b1e92..76f7ad1e88 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -2,11 +2,8 @@ // Project: https://github.com/keeweb/kdbxweb#readme // Definitions by: Roang-zero1 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2' just under the header -/*~ If this module is a UMD module that exposes a global variable 'myLib' when - *~ loaded outside a module loader environment, declare that global here. - *~ Otherwise, delete this declaration. - */ export as namespace kdbxweb; export type KdbxObject = Entry | Group; From f96d6bb925853867ba0df91c29f489fa8037e71d Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 20:50:02 +0100 Subject: [PATCH 048/836] Add types --- types/kdbxweb/index.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index 76f7ad1e88..90aa997fb7 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -172,13 +172,13 @@ export class ProtectedValue { export class VarDictionary { constructor(); - get(key: string): any; + get(key: string): object; keys(): string[]; remove(key: string): void; - set(key: string, type: number, value: any): void; + set(key: string, type: number, value: object): void; write(stm: BinaryStream): void; @@ -467,7 +467,7 @@ export class Group { groups: Group[]; entries: Entry[]; parentGroup: Group; - customData: any; + customData: {}; static create(name: string, parentGroup: Group): Group; static read(xmlNode: Node, ctx: Context, parentGroup: Group): Group; @@ -495,7 +495,7 @@ export class Entry { overrideUrl: string; tags: string[]; times: Times; - fields: { [key: string]: any }; + fields: { [key: string]: ProtectedValue | string }; binaries: {}; autoType: { enabled: boolean; @@ -508,7 +508,7 @@ export class Entry { }; history: Entry[]; parentGroup: Group; - customData: any; + customData: {}; static create(meta: Meta, parentGroup: Group): Entry; static read(xmlNode: Node, ctx: Context, parentGroup: Group): Entry; From 7b887b047d662793ec6bdaaaa799c60cc38b07b3 Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 20:57:43 +0100 Subject: [PATCH 049/836] Update tests --- types/kdbxweb/kdbxweb-tests.ts | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/types/kdbxweb/kdbxweb-tests.ts b/types/kdbxweb/kdbxweb-tests.ts index d667117b6b..dfc8167b4b 100644 --- a/types/kdbxweb/kdbxweb-tests.ts +++ b/types/kdbxweb/kdbxweb-tests.ts @@ -8,11 +8,27 @@ const credentials = new kdbxweb.Credentials( ); kdbxweb.Kdbx.load(dataarr, credentials).then(db => db); -kdbxweb.Kdbx.loadXml("data", credentials).then(db => db); +kdbxweb.Kdbx.loadXml("data", credentials).then(db => db); -const newDb = kdbxweb.Kdbx.create(credentials, 'My new db'); -const group = newDb.createGroup(newDb.getDefaultGroup(), 'subgroup'); +const newDb = kdbxweb.Kdbx.create(credentials, "My new db"); +const defaultGroup = newDb.getDefaultGroup(); +const group = newDb.createGroup(defaultGroup, "subgroup"); +const anotherGroup = newDb.createGroup(group, "subgroup-2"); +const yetAnotherGroup = newDb.createGroup(group, "subgroup-3"); +const deepGroup = defaultGroup.groups[0].groups[0]; + +if (newDb.getGroup(yetAnotherGroup.uuid)){ + newDb.remove(yetAnotherGroup); +} const entry = newDb.createEntry(group); +newDb.move(entry, anotherGroup); +newDb.remove(entry); newDb.save().then(dataAsArrayBuffer => dataAsArrayBuffer); newDb.saveXml().then(xmlAsString => xmlAsString); + +newDb.cleanup({ + customIcons: true +}); + +newDb.upgrade(); From 2fda9144831406ccc783172a7ff14fa049b91287 Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 20:58:38 +0100 Subject: [PATCH 050/836] Fix linting issues --- types/kdbxweb/index.d.ts | 2 +- types/kdbxweb/kdbxweb-tests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index 90aa997fb7..67dbac91f4 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/keeweb/kdbxweb#readme // Definitions by: Roang-zero1 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2' just under the header +// TypeScript Version: 2.2 export as namespace kdbxweb; diff --git a/types/kdbxweb/kdbxweb-tests.ts b/types/kdbxweb/kdbxweb-tests.ts index dfc8167b4b..86a312adb7 100644 --- a/types/kdbxweb/kdbxweb-tests.ts +++ b/types/kdbxweb/kdbxweb-tests.ts @@ -17,7 +17,7 @@ const anotherGroup = newDb.createGroup(group, "subgroup-2"); const yetAnotherGroup = newDb.createGroup(group, "subgroup-3"); const deepGroup = defaultGroup.groups[0].groups[0]; -if (newDb.getGroup(yetAnotherGroup.uuid)){ +if (newDb.getGroup(yetAnotherGroup.uuid)) { newDb.remove(yetAnotherGroup); } const entry = newDb.createEntry(group); From 2a58861813cc188a501116d5220119c558946918 Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 21:36:22 +0100 Subject: [PATCH 051/836] Fix uuid types --- types/kdbxweb/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index 67dbac91f4..0d9e7201fe 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -32,7 +32,7 @@ export interface editingState { export interface editingStateDict { meta: editingState; - [uuid: string]: editingState; + [uuid: KdbxUuid]: editingState; } export class Credentials { @@ -453,7 +453,7 @@ export class Context { export class Group { constructor(); - uuid: string; + uuid: KdbxUuid; name: string; notes: string; icon: number; From bc1b05a692c420e5b0987fbdca6662c0d85fbf83 Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 22:02:51 +0100 Subject: [PATCH 052/836] Update property types --- types/kdbxweb/index.d.ts | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index 0d9e7201fe..ce4892e4f2 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -7,6 +7,7 @@ export as namespace kdbxweb; export type KdbxObject = Entry | Group; +export type StringProtected = ProtectedValue | string; export interface Settings { binaries?: boolean; @@ -86,7 +87,7 @@ export class Kdbx { createEntry(group: Group): Entry; - createGroup(group: Group, name: string): Group; + createGroup(group: Group, name: StringProtected): Group; createRecycleBin(): void; @@ -454,13 +455,13 @@ export class Group { constructor(); uuid: KdbxUuid; - name: string; - notes: string; + name: StringProtected; + notes: StringProtected; icon: number; customIcon: KdbxUuid; times: Times; expanded: boolean; - defaultAutoTypeSeq: string; + defaultAutoTypeSeq: StringProtected; enableAutoType: boolean; enableSearching: boolean; lastTopVisibleEntry: KdbxUuid; @@ -469,7 +470,7 @@ export class Group { parentGroup: Group; customData: {}; - static create(name: string, parentGroup: Group): Group; + static create(name: StringProtected, parentGroup: Group): Group; static read(xmlNode: Node, ctx: Context, parentGroup: Group): Group; write(parentNode: Node, ctx: Context): void; @@ -490,12 +491,12 @@ export class Entry { uuid: KdbxUuid; icon: number; customIcon: KdbxUuid; - fgColor: string; - bgColor: string; - overrideUrl: string; + fgColor: StringProtected; + bgColor: StringProtected; + overrideUrl: StringProtected; tags: string[]; times: Times; - fields: { [key: string]: ProtectedValue | string }; + fields: { [key: string]: StringProtected }; binaries: {}; autoType: { enabled: boolean; From f0e3d17c298fed30e78e03a35e66d7bbcf4645f1 Mon Sep 17 00:00:00 2001 From: Lucas Date: Sat, 10 Nov 2018 22:14:53 +0100 Subject: [PATCH 053/836] Fix index signature parameter --- types/kdbxweb/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/kdbxweb/index.d.ts b/types/kdbxweb/index.d.ts index ce4892e4f2..805a45a2b0 100644 --- a/types/kdbxweb/index.d.ts +++ b/types/kdbxweb/index.d.ts @@ -33,7 +33,7 @@ export interface editingState { export interface editingStateDict { meta: editingState; - [uuid: KdbxUuid]: editingState; + [uuid: string]: editingState; } export class Credentials { From 8b93c6cd5b697a264d1609f86051bb2392c698b8 Mon Sep 17 00:00:00 2001 From: Matt McCutchen Date: Sat, 10 Nov 2018 19:27:38 -0500 Subject: [PATCH 054/836] react-navigation: Make declarations work with strictFunctionTypes. Believed to fix https://stackoverflow.com/q/53154003. This reverts 4464cbbfe725bfc191006e41cbe634dc87b8baaa. I was unable to reproduce the issue that that commit was originally trying to fix. Without reverting it, the BackButtonWithNavigationWithExplicitProps test fails on typescript@next. --- types/react-navigation/index.d.ts | 26 +++++++++---------- .../react-navigation-tests.tsx | 4 +-- types/react-navigation/tsconfig.json | 2 +- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 846ea56a9e..15e72b6b61 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -1248,17 +1248,17 @@ export interface NavigationInjectedProps

{ } // If the wrapped component is a class, we can get a ref to it -export function withNavigation>( - Component: T, -): React.ComponentType, keyof NavigationInjectedProps> & { onRef?: React.Ref> }>; +export function withNavigation

>( + Component: T & React.ComponentClass

, +): React.ComponentType & { onRef?: React.Ref> }>; -export function withNavigation>( - Component: T, -): React.ComponentType, keyof NavigationInjectedProps>>; +export function withNavigation

( + Component: React.ComponentType

, +): React.ComponentType>; // For backwards compatibility export function withNavigation( - Component: React.ComponentType)>, + Component: React.ComponentType>, ): React.ComponentType>> }>; export interface NavigationFocusInjectedProps

extends NavigationInjectedProps

{ @@ -1266,13 +1266,13 @@ export interface NavigationFocusInjectedProps

extends Navi } // If the wrapped component is a class, we can get a ref to it -export function withNavigationFocus>( - Component: T, -): React.ComponentType, keyof NavigationFocusInjectedProps> & { onRef?: React.Ref> }>; +export function withNavigationFocus

>( + Component: T & React.ComponentClass

, +): React.ComponentType & { onRef?: React.Ref> }>; -export function withNavigationFocus>( - Component: T, -): React.ComponentType, keyof NavigationFocusInjectedProps>>; +export function withNavigationFocus

( + Component: React.ComponentType

, +): React.ComponentType>; // For backwards compatibility export function withNavigationFocus( diff --git a/types/react-navigation/react-navigation-tests.tsx b/types/react-navigation/react-navigation-tests.tsx index e568fbed27..ba77442a40 100644 --- a/types/react-navigation/react-navigation-tests.tsx +++ b/types/react-navigation/react-navigation-tests.tsx @@ -383,14 +383,14 @@ class CustomTransitioner extends React.Component /> ); } - _render = (props: NavigationTransitionProps, prevProps: NavigationTransitionProps): React.ReactElement => { + _render = (props: NavigationTransitionProps, prevProps?: NavigationTransitionProps): React.ReactElement => { return ( ); } _configureTransition = ( _transitionProps: NavigationTransitionProps, - _prevTransitionProps: NavigationTransitionProps + _prevTransitionProps?: NavigationTransitionProps ) => { return {}; } diff --git a/types/react-navigation/tsconfig.json b/types/react-navigation/tsconfig.json index b0cf7029db..bc49bee237 100644 --- a/types/react-navigation/tsconfig.json +++ b/types/react-navigation/tsconfig.json @@ -7,7 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "jsx": "react", "typeRoots": [ From e0c287512b36786de0e7390d2bd78d1fa400ca5c Mon Sep 17 00:00:00 2001 From: Simon Schick Date: Sun, 11 Nov 2018 01:46:35 +0100 Subject: [PATCH 055/836] fix(yar): fix cache options --- types/catbox/index.d.ts | 8 +++++--- types/hapi/index.d.ts | 3 +++ types/yar/index.d.ts | 18 ++++++++++++------ types/yar/yar-tests.ts | 4 ++++ 4 files changed, 24 insertions(+), 9 deletions(-) diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index 2a17490dd4..62b99ac5b3 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -118,6 +118,8 @@ export interface ClientOptions { export type PolicyOptionVariants = PolicyOptions | DecoratedPolicyOptions; +export type Id = string | { id: string }; + /** * The Policy object provides a convenient cache interface by setting a * global policy which is automatically applied to every storage action. @@ -138,7 +140,7 @@ export class Policy> { * @param id the unique item identifier (within the policy segment). * Can be a string or an object with the required 'id' key. */ - get(id: string | { id: string }): Promise ? DecoratedResult : T | null>; + get(id: Id): Promise ? DecoratedResult : T | null>; /** * store an item in the cache where: @@ -148,12 +150,12 @@ export class Policy> { * removed from the cache (or is marked invalid). * This should be set to 0 in order to use the caching rules configured when creating the Policy object. */ - set(id: string | { id: string }, value: T, ttl?: number): Promise; + set(id: Id, value: T, ttl?: number): Promise; /** * remove the item from cache where: * @param id the unique item identifier (within the policy segment). */ - drop(id: string | { id: string }): Promise; + drop(id: Id): Promise; /** * given a created timestamp in milliseconds, returns the time-to-live left * based on the configured rules. diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 9bd9a14f41..644c48c5d1 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -2104,6 +2104,9 @@ export interface ServerAuth { } export type CachePolicyOptions = PolicyOptionVariants & { + /** + * @default '_default' + */ cache?: string; segment?: string; }; diff --git a/types/yar/index.d.ts b/types/yar/index.d.ts index e40503c58e..b6c199416d 100644 --- a/types/yar/index.d.ts +++ b/types/yar/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for yar 9.0 +// Type definitions for yar 9.1 // Project: https://github.com/hapijs/yar#readme // Definitions by: Simon Schick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,7 +10,9 @@ import { ServerOptionsCache, Request, Plugin, + CachePolicyOptions, } from 'hapi'; +import { PolicyOptions, Id } from 'catbox'; declare namespace yar { interface YarOptions { /** @@ -41,12 +43,8 @@ declare namespace yar { /** * hapi cache options which includes (among other options): */ - cache?: ServerOptionsCache; + cache?: CachePolicyOptions; - /** - * server-side storage expiration (defaults to 1 day). - */ - expiresIn?: number; /** * the configuration for cookie-specific features: */ @@ -161,6 +159,10 @@ declare namespace yar { */ lazy(enabled: boolean): void; } + + interface ServerYar { + revoke(id: Id): Promise; + } } declare const yar: Plugin; export = yar; @@ -169,4 +171,8 @@ declare module 'hapi' { interface Request { yar: yar.Yar; } + + interface Server { + yar: yar.ServerYar; + } } diff --git a/types/yar/yar-tests.ts b/types/yar/yar-tests.ts index c7e75e0a4b..e7ad2c1c24 100644 --- a/types/yar/yar-tests.ts +++ b/types/yar/yar-tests.ts @@ -10,6 +10,10 @@ async function boot() { password: 'test', isSecure: true, }, + cache: { + cache: 'test', + expiresIn: 123141243, + } }, }); From 7d0a6c9d6797412a73dcd97f21ce29f56002cdd4 Mon Sep 17 00:00:00 2001 From: Shuhei Tsukaomoto Date: Sun, 11 Nov 2018 19:29:21 +0900 Subject: [PATCH 056/836] [react-map-gl]: update to 4.0 --- types/react-map-gl/index.d.ts | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/types/react-map-gl/index.d.ts b/types/react-map-gl/index.d.ts index 136f9352bb..6a215225d7 100644 --- a/types/react-map-gl/index.d.ts +++ b/types/react-map-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-map-gl 3.3 +// Type definitions for react-map-gl 4.0 // Project: https://github.com/uber/react-map-gl#readme // Definitions by: Robert Imig // Fabio Berta @@ -18,7 +18,11 @@ export interface Viewport { } export interface MapError { + error?: { message: string; + status: number; + }; + status: number; } export interface MapRequest { @@ -145,6 +149,17 @@ export interface InteractiveMapProps extends StaticMapProps { onHover?: (event: MapEvent) => void; onClick?: (event: MapEvent) => void; + onDblClick?: (event: MapEvent) => void; + onMouseDown?: (event: MapEvent) => void; + onMouseMove?: (event: MapEvent) => void; + onMouseUp?: (event: MapEvent) => void; + onTouchStart?: (event: MapEvent) => void; + onTouchMove?: (event: MapEvent) => void; + onTouchEnd?: (event: MapEvent) => void; + onMouseEnter?: (event: MapEvent) => void; + onMouseLeave?: (event: MapEvent) => void; + onWheel?: (event: MapEvent) => void; + onMouseOut?: (event: MapEvent) => void; onContextMenu?: (event: MapEvent) => void; @@ -186,6 +201,9 @@ export interface MarkerProps extends BaseControlProps { latitude: number; offsetLeft?: number; offsetTop?: number; + onDrag: (event: any) => void; + onDragStart: (event: any) => void; + onDragEnd: (event: any) => void; } export class Marker extends BaseControl {} @@ -201,6 +219,7 @@ export interface PopupProps extends BaseControlProps { closeOnClick?: boolean; anchor?: 'top' | 'top-left' | 'top-right' | 'bottom' | 'bottom-left' | 'bottom-right' | 'left' | 'right'; dynamicPosition?: boolean; + sortByDepth?: boolean; onClose?: () => void; } @@ -251,8 +270,6 @@ export class SVGOverlay extends BaseControl {} export namespace experimental { interface Options { - // TODO(deprecate): remove this when `onChangeViewport` gets deprecated - onChangeViewport?: (viewport: Viewport) => void; // TODO(deprecate): remove this when `touchZoomRotate` gets deprecated touchZoomRotate?: boolean; From e714e43f06cd24acf7066b41ed0941b2b2a20960 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Santiago=20Aguilar=20Hern=C3=A1ndez?= Date: Mon, 12 Nov 2018 03:36:03 -0500 Subject: [PATCH 057/836] * Renamed property according with docs * Moved types to other file --- types/better-sqlite3/better-sqlite3-tests.ts | 2 + types/better-sqlite3/index.d.ts | 84 +------------------- types/better-sqlite3/tsconfig.json | 1 + types/better-sqlite3/types.d.ts | 80 +++++++++++++++++++ 4 files changed, 86 insertions(+), 81 deletions(-) create mode 100644 types/better-sqlite3/types.d.ts diff --git a/types/better-sqlite3/better-sqlite3-tests.ts b/types/better-sqlite3/better-sqlite3-tests.ts index 34ee6808c3..5d8b95ecf7 100644 --- a/types/better-sqlite3/better-sqlite3-tests.ts +++ b/types/better-sqlite3/better-sqlite3-tests.ts @@ -1,7 +1,9 @@ import Database = require('better-sqlite3'); +import { RunResult } from 'better-sqlite3/types'; const integer = Database.Integer(1); const err = new Database.SqliteError('ok', 'ok'); +const result: RunResult = { changes: 1, lastInsertRowid: 1 }; let db = Database('.'); db = new Database('.', {memory: true}); diff --git a/types/better-sqlite3/index.d.ts b/types/better-sqlite3/index.d.ts index 899a85a2e2..d120209765 100644 --- a/types/better-sqlite3/index.d.ts +++ b/types/better-sqlite3/index.d.ts @@ -1,89 +1,11 @@ -// Type definitions for better-sqlite3 3.1 +// Type definitions for better-sqlite3 5.0 // Project: http://github.com/JoshuaWise/better-sqlite3 // Definitions by: Ben Davies // Mathew Rumsey +// Santiago Aguilar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import Integer = require('integer'); - -interface RunResult { - changes: number; - lastInsertROWID: Integer.IntLike; -} - -declare class Statement { - database: Database; - source: string; - returnsData: boolean; - constructor(db: Database, sources: string[]); - - run(...params: any[]): RunResult; - get(...params: any[]): any; - all(...params: any[]): any[]; - each(params: any, cb: (row: any) => void): void; - each(cb: (row: any) => void): void; - each(...params: any[]): void; - pluck(toggleState?: boolean): this; - bind(...params: any[]): this; - safeIntegers(toggleState?: boolean): this; -} - -declare class Transaction { - database: Database; - source: string; - constructor(db: Database, sources: string[]); - - run(...params: any[]): RunResult; - bind(...params: any[]): this; - safeIntegers(toggleState?: boolean): this; -} - -interface DatabaseOptions { - memory?: boolean; - readonly?: boolean; - fileMustExist?: boolean; -} - -interface RegistrationOptions { - name?: string; - varargs?: boolean; - deterministic?: boolean; - safeIntegers?: boolean; -} - -interface Database { - memory: boolean; - readonly: boolean; - name: string; - open: boolean; - inTransaction: boolean; - - prepare(source: string): Statement; - transaction(sources: string[]): Transaction; - exec(source: string): this; - pragma(source: string, simplify?: boolean): any; - checkpoint(databaseName?: string): this; - register(cb: (...params: any[]) => any): this; - register(options: RegistrationOptions, cb: (...params: any[]) => any): this; - close(): this; - defaultSafeIntegers(toggleState?: boolean): this; -} - -declare class SqliteError implements Error { - name: string; - message: string; - code: string; - constructor(message: string, code: string); -} - -interface DatabaseConstructor { - new(filename: string, options?: DatabaseOptions): Database; - (filename: string, options?: DatabaseOptions): Database; - prototype: Database; - - Integer: typeof Integer; - SqliteError: typeof SqliteError; -} +import { DatabaseConstructor } from "./types"; declare const Database: DatabaseConstructor; export = Database; diff --git a/types/better-sqlite3/tsconfig.json b/types/better-sqlite3/tsconfig.json index 30a480355b..891afa0aad 100644 --- a/types/better-sqlite3/tsconfig.json +++ b/types/better-sqlite3/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "types.d.ts", "better-sqlite3-tests.ts" ] } \ No newline at end of file diff --git a/types/better-sqlite3/types.d.ts b/types/better-sqlite3/types.d.ts new file mode 100644 index 0000000000..61f376b0bf --- /dev/null +++ b/types/better-sqlite3/types.d.ts @@ -0,0 +1,80 @@ +import Integer = require("integer"); + +export interface RunResult { + changes: number; + lastInsertRowid: Integer.IntLike; +} + +export class Statement { + database: Database; + source: string; + returnsData: boolean; + constructor(db: Database, sources: string[]); + + run(...params: any[]): RunResult; + get(...params: any[]): any; + all(...params: any[]): any[]; + each(params: any, cb: (row: any) => void): void; + each(cb: (row: any) => void): void; + each(...params: any[]): void; + pluck(toggleState?: boolean): this; + bind(...params: any[]): this; + safeIntegers(toggleState?: boolean): this; +} + +export class Transaction { + database: Database; + source: string; + constructor(db: Database, sources: string[]); + + run(...params: any[]): RunResult; + bind(...params: any[]): this; + safeIntegers(toggleState?: boolean): this; +} + +export interface DatabaseOptions { + memory?: boolean; + readonly?: boolean; + fileMustExist?: boolean; +} + +export interface RegistrationOptions { + name?: string; + varargs?: boolean; + deterministic?: boolean; + safeIntegers?: boolean; +} + +export interface Database { + memory: boolean; + readonly: boolean; + name: string; + open: boolean; + inTransaction: boolean; + + prepare(source: string): Statement; + transaction(sources: string[]): Transaction; + exec(source: string): this; + pragma(source: string, simplify?: boolean): any; + checkpoint(databaseName?: string): this; + register(cb: (...params: any[]) => any): this; + register(options: RegistrationOptions, cb: (...params: any[]) => any): this; + close(): this; + defaultSafeIntegers(toggleState?: boolean): this; +} + +export class SqliteError implements Error { + name: string; + message: string; + code: string; + constructor(message: string, code: string); +} + +export interface DatabaseConstructor { + new (filename: string, options?: DatabaseOptions): Database; + (filename: string, options?: DatabaseOptions): Database; + prototype: Database; + + Integer: typeof Integer; + SqliteError: typeof SqliteError; +} From 980b86eed1eea61b54c716c67dde90fce38ab7e8 Mon Sep 17 00:00:00 2001 From: Alex Lipatov Date: Mon, 12 Nov 2018 06:16:42 -0500 Subject: [PATCH 058/836] Update middleware callbaback signature to take 4 arguments instead of 2 --- types/swagger-express-middleware/index.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/swagger-express-middleware/index.d.ts b/types/swagger-express-middleware/index.d.ts index acc36d3356..11c4e31c21 100644 --- a/types/swagger-express-middleware/index.d.ts +++ b/types/swagger-express-middleware/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for swagger-express-middleware 1.x // Project: https://github.com/BigstickCarpet/swagger-express-middleware // Definitions by: Alexandre Roba +// Updated by: Tromgy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -39,8 +40,9 @@ declare module "swagger-express-middleware" { (apiDefinitionPathOrObject: string | SwaggerObject, appOrRouter: Application | Router, cb: SwaggerMiddlewareConstructorCallback): SwaggerMiddleware; } interface SwaggerMiddlewareConstructorCallback { - (err: any, middleware: SwaggerMiddleware): void; + (err: any, middleware: SwaggerMiddleware, api: any, parser: any): void; } + export interface SwaggerMiddleware { /** * Annotates the HTTP request (the `req` object) with Swagger metadata. From 11f845bdfc61f1bcee44e37f432f155b881ef408 Mon Sep 17 00:00:00 2001 From: Alex Lipatov Date: Mon, 12 Nov 2018 07:26:41 -0500 Subject: [PATCH 059/836] Update test to use new callback argument. --- .../swagger-express-middleware/PetStore.yaml | 45 +++++++++++++++++++ types/swagger-express-middleware/index.d.ts | 2 +- .../swagger-express-middleware-tests.ts | 17 ++++++- 3 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 types/swagger-express-middleware/PetStore.yaml diff --git a/types/swagger-express-middleware/PetStore.yaml b/types/swagger-express-middleware/PetStore.yaml new file mode 100644 index 0000000000..ae4f16b3b1 --- /dev/null +++ b/types/swagger-express-middleware/PetStore.yaml @@ -0,0 +1,45 @@ +swagger: '2.0' +info: + version: 1.0.0 + title: Swagger Petstore + description: A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification + termsOfService: 'http://swagger.io/terms/' + contact: + name: Swagger API Team + license: + name: MIT +host: petstore.swagger.io +basePath: /api +schemes: + - http +consumes: + - application/json +produces: + - application/json +paths: + /pets: + get: + description: Returns all pets from the system that the user has access to + produces: + - application/json + responses: + '200': + description: A list of pets. + schema: + type: array + items: + $ref: '#/definitions/Pet' +definitions: + Pet: + type: object + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string diff --git a/types/swagger-express-middleware/index.d.ts b/types/swagger-express-middleware/index.d.ts index 11c4e31c21..80d56ae812 100644 --- a/types/swagger-express-middleware/index.d.ts +++ b/types/swagger-express-middleware/index.d.ts @@ -1,7 +1,7 @@ // Type definitions for swagger-express-middleware 1.x // Project: https://github.com/BigstickCarpet/swagger-express-middleware // Definitions by: Alexandre Roba -// Updated by: Tromgy +// Tromgy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/swagger-express-middleware/swagger-express-middleware-tests.ts b/types/swagger-express-middleware/swagger-express-middleware-tests.ts index 1a01d8475d..8717755725 100644 --- a/types/swagger-express-middleware/swagger-express-middleware-tests.ts +++ b/types/swagger-express-middleware/swagger-express-middleware-tests.ts @@ -4,7 +4,7 @@ import SwaggerExpressMiddleware = require("swagger-express-middleware"); let app = express(); let router = express.Router(); -SwaggerExpressMiddleware("PetStore.yaml", app, (err: any, middleware: SwaggerExpressMiddleware.SwaggerMiddleware) => { +SwaggerExpressMiddleware("PetStore.yaml", app, (err: any, middleware: SwaggerExpressMiddleware.SwaggerMiddleware, api) => { let filesOptions: SwaggerExpressMiddleware.FilesOptions = { useBasePath: false, apiPath: "/api-docs/", @@ -30,6 +30,20 @@ SwaggerExpressMiddleware("PetStore.yaml", app, (err: any, middleware: SwaggerExp } + // Demonstrates use of the swagger basePath, it is available from the third argument of the callback + // Complile and run this sample, then do a GET from http://localhost:8000/api/pets + // If for instance you create version 2 of your API, but in this new version "GET pets" implementation + // does not change, you only need to change the basePath to "/api/v2" in the + // swagger YAML file, and this method will still be called. + app.get(`${api.basePath}/pets`, (req, res, next) => { + res.json( + [ + { id: 'pet_1', name: 'Itchy' }, + { id: 'pet_2', name: 'Scratchy' } + ] + ); + }); + app.use( middleware.metadata(router), middleware.CORS(), @@ -991,4 +1005,3 @@ let uberApiDefinition: SwaggerExpressMiddleware.SwaggerObject = } } } - From 1319b54f692bf90f1958f7ab6ca1633b721b295c Mon Sep 17 00:00:00 2001 From: walterh Date: Tue, 13 Nov 2018 10:56:32 +1100 Subject: [PATCH 060/836] react-navigation: add experimental prop transparentCard --- types/react-navigation/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 846ea56a9e..868039a0a4 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -379,6 +379,7 @@ export interface NavigationStackViewConfig { headerTransitionPreset?: 'fade-in-place' | 'uikit'; headerLayoutPreset?: 'left' | 'center'; cardStyle?: StyleProp; + transparentCard?: boolean; transitionConfig?: ( transitionProps: NavigationTransitionProps, prevTransitionProps: NavigationTransitionProps, From 79605fcbf13c7785f3f9409cf29d741721c62bf4 Mon Sep 17 00:00:00 2001 From: Stefano Bourscheid Date: Tue, 13 Nov 2018 14:26:48 +0100 Subject: [PATCH 061/836] Add subs types declaration --- types/react-native-video/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/react-native-video/index.d.ts b/types/react-native-video/index.d.ts index 190d731394..698d919d1c 100644 --- a/types/react-native-video/index.d.ts +++ b/types/react-native-video/index.d.ts @@ -32,6 +32,12 @@ export interface LoadError { }; } +declare const TextTrackType: { + SRT: "application/x-subrip", + TTML: "application/ttml+xml", + VTT: "text/vtt" +} + export interface VideoProperties extends ViewProps { /* Native only */ src?: any; From bb14e16ea403e8e56e38b8b2219f84d091b481e9 Mon Sep 17 00:00:00 2001 From: Stefano Bourscheid Date: Tue, 13 Nov 2018 16:30:56 +0100 Subject: [PATCH 062/836] Add support for 3.1 subs props --- types/react-native-video/index.d.ts | 157 +++++++++++++++------------- 1 file changed, 84 insertions(+), 73 deletions(-) diff --git a/types/react-native-video/index.d.ts b/types/react-native-video/index.d.ts index 698d919d1c..f20cd68664 100644 --- a/types/react-native-video/index.d.ts +++ b/types/react-native-video/index.d.ts @@ -1,13 +1,11 @@ -// Type definitions for react-native-video 2.0 +// Type definitions for react-native-video 2.0 and 3.1 // Project: https://github.com/react-native-community/react-native-video // Definitions by: HuHuanming // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; -import { - ViewProps -} from 'react-native'; +import { ViewProps } from 'react-native'; export interface OnLoadData { canPlayFastForward: boolean; @@ -33,80 +31,93 @@ export interface LoadError { } declare const TextTrackType: { - SRT: "application/x-subrip", - TTML: "application/ttml+xml", - VTT: "text/vtt" -} + SRT: 'application/x-subrip'; + TTML: 'application/ttml+xml'; + VTT: 'text/vtt'; +}; export interface VideoProperties extends ViewProps { - /* Native only */ - src?: any; - seek?: number; - fullscreen?: boolean; - onVideoLoadStart?(): void; - onVideoLoad?(): void; - onVideoBuffer?(): void; - onVideoError?(): void; - onVideoProgress?(): void; - onVideoSeek?(): void; - onVideoEnd?(): void; - onTimedMetadata?(): void; - onVideoFullscreenPlayerWillPresent?(): void; - onVideoFullscreenPlayerDidPresent?(): void; - onVideoFullscreenPlayerWillDismiss?(): void; - onVideoFullscreenPlayerDidDismiss?(): void; + /* Native only */ + src?: any; + seek?: number; + fullscreen?: boolean; + onVideoLoadStart?(): void; + onVideoLoad?(): void; + onVideoBuffer?(): void; + onVideoError?(): void; + onVideoProgress?(): void; + onVideoSeek?(): void; + onVideoEnd?(): void; + onTimedMetadata?(): void; + onVideoFullscreenPlayerWillPresent?(): void; + onVideoFullscreenPlayerDidPresent?(): void; + onVideoFullscreenPlayerWillDismiss?(): void; + onVideoFullscreenPlayerDidDismiss?(): void; - /* Wrapper component */ - // Opaque type returned by require('./video.mp4') - source: { uri?: string } | number; - resizeMode?: string; - poster?: string; - repeat?: boolean; - paused?: boolean; - muted?: boolean; - volume?: number; - rate?: number; - playInBackground?: boolean; - playWhenInactive?: boolean; - ignoreSilentSwitch?: 'ignore' | 'obey'; - disableFocus?: boolean; - controls?: boolean; - currentTime?: number; - progressUpdateInterval?: number; - useTextureView?: boolean; - allowsExternalPlayback?: boolean; - onLoadStart?(): void; - onLoad?(data: OnLoadData): void; - onBuffer?(): void; - onError?(error: LoadError): void; - onProgress?(data: { - currentTime: number; - playableDuration: number; - seekableDuration: number; - }): void; - onSeek?(): void; - onEnd?(): void; - onFullscreenPlayerWillPresent?(): void; - onFullscreenPlayerDidPresent?(): void; - onFullscreenPlayerWillDismiss?(): void; - onFullscreenPlayerDidDismiss?(): void; - onReadyForDisplay?(): void; - onPlaybackStalled?(): void; - onPlaybackResume?(): void; - onPlaybackRateChange?(): void; - onAudioFocusChanged?(): void; - onAudioBecomingNoisy?(): void; + /* Wrapper component */ + // Opaque type returned by require('./video.mp4') + source: { uri?: string } | number; + resizeMode?: string; + poster?: string; + repeat?: boolean; + paused?: boolean; + muted?: boolean; + volume?: number; + rate?: number; + playInBackground?: boolean; + playWhenInactive?: boolean; + ignoreSilentSwitch?: 'ignore' | 'obey'; + disableFocus?: boolean; + controls?: boolean; + currentTime?: number; + progressUpdateInterval?: number; + useTextureView?: boolean; + allowsExternalPlayback?: boolean; - /* Required by react-native */ - scaleX?: number; - scaleY?: number; - translateX?: number; - translateY?: number; - rotation?: number; + onLoadStart?(): void; + onLoad?(data: OnLoadData): void; + onBuffer?(): void; + onError?(error: LoadError): void; + onProgress?(data: { + currentTime: number; + playableDuration: number; + seekableDuration: number; + }): void; + onSeek?(): void; + onEnd?(): void; + onFullscreenPlayerWillPresent?(): void; + onFullscreenPlayerDidPresent?(): void; + onFullscreenPlayerWillDismiss?(): void; + onFullscreenPlayerDidDismiss?(): void; + onReadyForDisplay?(): void; + onPlaybackStalled?(): void; + onPlaybackResume?(): void; + onPlaybackRateChange?(): void; + onAudioFocusChanged?(): void; + onAudioBecomingNoisy?(): void; + + /* 3.0 onwards */ + selectedTextTrack?: { + type: 'system' | 'disabled' | 'title' | 'language' | 'index'; + value?: string | number; + }; + textTracks?: { + title?: string; + language?: string; + type: 'application/x-subrip' | 'application/ttml+xml' | 'text/vtt'; + uri: string; + }[]; + + /* Required by react-native */ + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; + rotation?: number; } export default class Video extends React.Component { - seek(time: number, tolerance?: number): void; - presentFullscreenPlayer(): void; - dismissFullscreenPlayer(): void; + seek(time: number, tolerance?: number): void; + presentFullscreenPlayer(): void; + dismissFullscreenPlayer(): void; } From 136608196335a0b2dfdffbcdb6a818eda82d863f Mon Sep 17 00:00:00 2001 From: Stefano Bourscheid Date: Tue, 13 Nov 2018 16:36:13 +0100 Subject: [PATCH 063/836] Fix CI errors --- types/react-native-video/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/react-native-video/index.d.ts b/types/react-native-video/index.d.ts index f20cd68664..726169caca 100644 --- a/types/react-native-video/index.d.ts +++ b/types/react-native-video/index.d.ts @@ -30,7 +30,7 @@ export interface LoadError { }; } -declare const TextTrackType: { +export const TextTrackType: { SRT: 'application/x-subrip'; TTML: 'application/ttml+xml'; VTT: 'text/vtt'; @@ -101,12 +101,12 @@ export interface VideoProperties extends ViewProps { type: 'system' | 'disabled' | 'title' | 'language' | 'index'; value?: string | number; }; - textTracks?: { + textTracks?: Array<{ title?: string; language?: string; type: 'application/x-subrip' | 'application/ttml+xml' | 'text/vtt'; uri: string; - }[]; + }>; /* Required by react-native */ scaleX?: number; From 9acef5b9dcbda4b7d8c078f8f3384ace6c58c545 Mon Sep 17 00:00:00 2001 From: Mauri Edo Date: Wed, 14 Nov 2018 10:04:41 +1100 Subject: [PATCH 064/836] fixing wrong type for exclusiveMinimum and exclusiveMaximum in BaseSchema --- types/swagger-schema-official/index.d.ts | 4 ++-- .../swagger-schema-official-tests.ts | 6 +++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/types/swagger-schema-official/index.d.ts b/types/swagger-schema-official/index.d.ts index f914e3e394..09d31cc8e7 100644 --- a/types/swagger-schema-official/index.d.ts +++ b/types/swagger-schema-official/index.d.ts @@ -127,9 +127,9 @@ export interface BaseSchema { default?: string|boolean|number|{}; multipleOf?: number; maximum?: number; - exclusiveMaximum?: number; + exclusiveMaximum?: boolean; minimum?: number; - exclusiveMinimum?: number; + exclusiveMinimum?: boolean; maxLength?: number; minLength?: number; pattern?: string; diff --git a/types/swagger-schema-official/swagger-schema-official-tests.ts b/types/swagger-schema-official/swagger-schema-official-tests.ts index d574d055cf..4fb3e55f07 100644 --- a/types/swagger-schema-official/swagger-schema-official-tests.ts +++ b/types/swagger-schema-official/swagger-schema-official-tests.ts @@ -1243,7 +1243,11 @@ const uber: swagger.Spec = { }, "surge_multiplier": { "type": "number", - "description": "Expected surge multiplier. Surge is active if surge_multiplier is greater than 1. Price estimate already factors in the surge multiplier." + "description": "Expected surge multiplier. Surge is active if surge_multiplier is greater than 1. Price estimate already factors in the surge multiplier.", + "minimum": 0, + "exclusiveMinimum": true, + "maximum": 10, + "exclusiveMaximum": true } } }, From f125ffc14e21869c7d8a71a2c5a620b24a978b4c Mon Sep 17 00:00:00 2001 From: Alex Lipatov Date: Tue, 13 Nov 2018 19:10:43 -0500 Subject: [PATCH 065/836] Make more specific type definitions. --- types/swagger-express-middleware/index.d.ts | 7 ++++++- .../swagger-express-middleware-tests.ts | 4 +++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/types/swagger-express-middleware/index.d.ts b/types/swagger-express-middleware/index.d.ts index 80d56ae812..4d83cebfb0 100644 --- a/types/swagger-express-middleware/index.d.ts +++ b/types/swagger-express-middleware/index.d.ts @@ -40,7 +40,7 @@ declare module "swagger-express-middleware" { (apiDefinitionPathOrObject: string | SwaggerObject, appOrRouter: Application | Router, cb: SwaggerMiddlewareConstructorCallback): SwaggerMiddleware; } interface SwaggerMiddlewareConstructorCallback { - (err: any, middleware: SwaggerMiddleware, api: any, parser: any): void; + (err: any, middleware: SwaggerMiddleware, api: SwaggerObject, parser: SwaggerParser): void; } export interface SwaggerMiddleware { @@ -363,6 +363,11 @@ declare module "swagger-express-middleware" { externalDocs?: ExternalDocumentationObject } + export interface SwaggerParser { + $refs: any + schema: SwaggerObject + } + type MimeTypes = string[] export interface InfoObject { diff --git a/types/swagger-express-middleware/swagger-express-middleware-tests.ts b/types/swagger-express-middleware/swagger-express-middleware-tests.ts index 8717755725..37bbf66ec7 100644 --- a/types/swagger-express-middleware/swagger-express-middleware-tests.ts +++ b/types/swagger-express-middleware/swagger-express-middleware-tests.ts @@ -4,7 +4,9 @@ import SwaggerExpressMiddleware = require("swagger-express-middleware"); let app = express(); let router = express.Router(); -SwaggerExpressMiddleware("PetStore.yaml", app, (err: any, middleware: SwaggerExpressMiddleware.SwaggerMiddleware, api) => { +SwaggerExpressMiddleware("PetStore.yaml", app, (err: any, + middleware: SwaggerExpressMiddleware.SwaggerMiddleware, + api: SwaggerExpressMiddleware.SwaggerObject) => { let filesOptions: SwaggerExpressMiddleware.FilesOptions = { useBasePath: false, apiPath: "/api-docs/", From 0218259e41efedfd2253da837ea5cc49988c9ac8 Mon Sep 17 00:00:00 2001 From: Alex Lipatov Date: Tue, 13 Nov 2018 19:28:03 -0500 Subject: [PATCH 066/836] Remove sample swagger file (used in the test) - apparently Travis doesn't know it is actually used. --- .../swagger-express-middleware/PetStore.yaml | 45 ------------------- 1 file changed, 45 deletions(-) delete mode 100644 types/swagger-express-middleware/PetStore.yaml diff --git a/types/swagger-express-middleware/PetStore.yaml b/types/swagger-express-middleware/PetStore.yaml deleted file mode 100644 index ae4f16b3b1..0000000000 --- a/types/swagger-express-middleware/PetStore.yaml +++ /dev/null @@ -1,45 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.0 - title: Swagger Petstore - description: A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification - termsOfService: 'http://swagger.io/terms/' - contact: - name: Swagger API Team - license: - name: MIT -host: petstore.swagger.io -basePath: /api -schemes: - - http -consumes: - - application/json -produces: - - application/json -paths: - /pets: - get: - description: Returns all pets from the system that the user has access to - produces: - - application/json - responses: - '200': - description: A list of pets. - schema: - type: array - items: - $ref: '#/definitions/Pet' -definitions: - Pet: - type: object - required: - - id - - name - properties: - id: - type: integer - format: int64 - name: - type: string - tag: - type: string From 59ab5b3aef80fa55010f7d8385f785514d2e0b1a Mon Sep 17 00:00:00 2001 From: Jessica Date: Wed, 14 Nov 2018 13:14:32 +0900 Subject: [PATCH 067/836] Add more complete support for object styles, tests --- types/styled-components/index.d.ts | 163 ++++++++--------- types/styled-components/test/index.tsx | 237 +++++++++++++++++-------- 2 files changed, 249 insertions(+), 151 deletions(-) diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index 25d006f6f1..6398ee36d5 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -9,10 +9,21 @@ /// -import * as React from 'react'; -import * as CSS from 'csstype'; +import * as React from "react"; +import * as CSS from "csstype"; -export type CSSObject = CSS.Properties; +export type CSSObject = CSS.Properties & + // Index type to allow selector nesting + // This is "[key in string]" and not "[key: string]" to allow CSSObject to be self-referential + { + // we need the CSS.Properties in here too to ensure the index signature doesn't create impossible values + [key in string]: + | CSS.Properties[keyof CSS.Properties< + string | number + >] + | CSSObject + }; +export type CSSKeyframes = object & { [key: string]: CSSObject }; export interface ThemeProps { theme: T; @@ -45,27 +56,25 @@ type StyledComponentPropsWithAs< export type FalseyValue = undefined | null | false; export type Interpolation

= - | FlattenInterpolation

- | ReadonlyArray< - FlattenInterpolation

| ReadonlyArray> - >; -export type FlattenInterpolation

= | InterpolationValue - | InterpolationFunction

; + | InterpolationFunction

+ | FlattenInterpolation

; +// must be an interface to be self-referential +export interface FlattenInterpolation

+ extends ReadonlyArray> {} export type InterpolationValue = | string | number - | Styles | FalseyValue | Keyframes | StyledComponentInterpolation | CSSObject; export type SimpleInterpolation = | InterpolationValue - | ReadonlyArray>; -export interface Styles { - [ruleOrSelector: string]: string | number | Styles; -} + | FlattenSimpleInterpolation; +// must be an interface to be self-referential +interface FlattenSimpleInterpolation + extends ReadonlyArray {} export type InterpolationFunction

= (props: P) => Interpolation

; @@ -76,9 +85,8 @@ type DeprecatedAttrs, T> = { [K in keyof A]: ((props: ThemedStyledProps) => A[K]) | A[K] }; -export type ThemedGlobalStyledClassProps = P & { - suppressMultiMountWarning?: boolean - theme?: T +export type ThemedGlobalStyledClassProps = WithOptionalTheme & { + suppressMultiMountWarning?: boolean; }; export interface GlobalStyleComponent @@ -86,8 +94,8 @@ export interface GlobalStyleComponent // remove the call signature from StyledComponent so Interpolation can still infer InterpolationFunction type StyledComponentInterpolation = Pick< - StyledComponent, - keyof StyledComponent + AnyStyledComponent, + keyof StyledComponentBase >; // abuse Pick to strip the call signature from ForwardRefExoticComponent @@ -101,7 +109,16 @@ export type AnyStyledComponent = | StyledComponent | StyledComponent; -export interface StyledComponent< +export type StyledComponent< + C extends keyof JSX.IntrinsicElements | React.ComponentType, + T extends object, + O extends object = {}, + A extends keyof any = never +> = // the "string" allows this to be used as an object key + // I really want to avoid this if possible but it's the only way to use nesting with object styles... + string & StyledComponentBase; + +export interface StyledComponentBase< C extends keyof JSX.IntrinsicElements | React.ComponentType, T extends object, O extends object = {}, @@ -127,7 +144,7 @@ export interface StyledComponent< * * String types need to be cast to themselves to become literal types (as={'a' as 'a'}). */ - as?: keyof JSX.IntrinsicElements | React.ComponentType + as?: keyof JSX.IntrinsicElements | React.ComponentType; } ): React.ReactElement>; withComponent( @@ -145,34 +162,38 @@ export interface StyledComponent< ): StyledComponent; } +export type ThemedStyledFunctionBase< + C extends keyof JSX.IntrinsicElements | React.ComponentType, + T extends object, + O extends object = {}, + A extends keyof any = never +> = + // at least the first argument is required, whatever it is + ( + first: NonNullable< + Interpolation< + ThemedStyledProps & O & U, T> + > + >, + ...rest: Array< + Interpolation< + ThemedStyledProps & O & U, T> + > + > + ) => StyledComponent; + export interface ThemedStyledFunction< C extends keyof JSX.IntrinsicElements | React.ComponentType, T extends object, O extends object = {}, A extends keyof any = never -> { - ( - strings: TemplateStringsArray, - ...interpolations: Array< - Interpolation< - ThemedStyledProps & O, T> - > - > - ): StyledComponent; - ( - strings: TemplateStringsArray, - ...interpolations: Array< - Interpolation< - ThemedStyledProps & O & U, T> - > - > - ): StyledComponent; +> extends ThemedStyledFunctionBase { // Fun thing: 'attrs' can also provide a polymorphic 'as' prop // My head already hurts enough so maybe later... attrs< U, A extends Partial & U> & { - [others: string]: any + [others: string]: any; } = {} >( attrs: Attrs & U, A, T> @@ -183,7 +204,7 @@ export interface ThemedStyledFunction< attrs< U, A extends Partial & U> & { - [others: string]: any + [others: string]: any; } = {} >( attrs: DeprecatedAttrs & U, A, T> @@ -244,20 +265,11 @@ export type ThemedStyledInterface = ThemedBaseStyledInterface< >; export type StyledInterface = ThemedStyledInterface; -export interface BaseThemedCssFunction { - (cssObject: CSSObject): InterpolationValue[]; - ( - strings: TemplateStringsArray, - ...interpolations: SimpleInterpolation[] - ): InterpolationValue[]; -

( - strings: TemplateStringsArray, - ...interpolations: Array>> - ): Array>>; -

(func: InterpolationFunction>): Array< - FlattenInterpolation> - >; -} +export type BaseThemedCssFunction =

( + first: NonNullable>>, + ...interpolations: Array>> +) => Array>>; + export type ThemedCssFunction = BaseThemedCssFunction< Extract extends never ? any : T >; @@ -266,8 +278,8 @@ export type ThemedCssFunction = BaseThemedCssFunction< type Omit = Pick>; type DiffBetween = Pick> & Pick>; -type WithOptionalTheme

= Omit & { - theme?: T +type WithOptionalTheme

= Omit & { + theme?: T; }; export interface ThemedStyledComponentsModule { @@ -275,20 +287,16 @@ export interface ThemedStyledComponentsModule { css: ThemedCssFunction; - keyframes(cssObject: CSSObject): Keyframes; + // unfortunately keyframes can't interpolate props from the theme keyframes( - strings: TemplateStringsArray, + strings: TemplateStringsArray | CSSKeyframes, ...interpolations: SimpleInterpolation[] ): Keyframes; - createGlobalStyle(cssObject: CSSObject): GlobalStyleComponent<{}, T>; - createGlobalStyle

( - strings: TemplateStringsArray, + createGlobalStyle

( + first: NonNullable>>, ...interpolations: Array>> ): GlobalStyleComponent; - createGlobalStyle

( - func: InterpolationFunction> - ): GlobalStyleComponent; withTheme: WithThemeFnInterface; ThemeProvider: ThemeProviderComponent; @@ -326,33 +334,28 @@ export type BaseThemeProviderComponent = React.ComponentClass< >; export type ThemeProviderComponent< T extends object -> = BaseThemeProviderComponent extends never ? any : T>; +> = BaseThemeProviderComponent< + Extract extends never ? any : T +>; export const ThemeProvider: ThemeProviderComponent; // NOTE: this technically starts as undefined // Also, this cannot be DefaultTheme as it breaks TypedComponents' assignability export const ThemeContext: React.Context; -export const ThemeConsumer: typeof ThemeContext['Consumer']; +export const ThemeConsumer: typeof ThemeContext["Consumer"]; export interface Keyframes { getName(): string; } -export function keyframes(cssObject: CSSObject): Keyframes; export function keyframes( - strings: TemplateStringsArray, + strings: TemplateStringsArray | CSSKeyframes, ...interpolations: SimpleInterpolation[] ): Keyframes; -export function createGlobalStyle( - cssObject: CSSObject -): GlobalStyleComponent<{}, DefaultTheme>; -export function createGlobalStyle

( - strings: TemplateStringsArray, +export function createGlobalStyle

( + first: NonNullable>>, ...interpolations: Array>> ): GlobalStyleComponent; -export function createGlobalStyle

( - func: InterpolationFunction> -): GlobalStyleComponent; export function isStyledComponent( target: any @@ -373,12 +376,12 @@ export class ServerStyleSheet { type StyleSheetManagerProps = | { - sheet: ServerStyleSheet - target?: never + sheet: ServerStyleSheet; + target?: never; } | { - sheet?: never - target: HTMLElement + sheet?: never; + target: HTMLElement; }; export class StyleSheetManager extends React.Component< diff --git a/types/styled-components/test/index.tsx b/types/styled-components/test/index.tsx index 64e0f447ba..7ce9e59fa2 100644 --- a/types/styled-components/test/index.tsx +++ b/types/styled-components/test/index.tsx @@ -1,6 +1,6 @@ -import * as React from 'react'; -import * as ReactDOM from 'react-dom'; -import * as ReactDOMServer from 'react-dom/server'; +import * as React from "react"; +import * as ReactDOM from "react-dom"; +import * as ReactDOMServer from "react-dom/server"; import styled, { css, @@ -14,7 +14,8 @@ import styled, { withTheme, ThemeConsumer, StyledComponent, -} from 'styled-components'; + ThemedStyledComponentsModule +} from "styled-components"; /** * general usage @@ -72,8 +73,8 @@ const TomatoButton = styled(MyButton)` const CustomizableButton = styled(MyButton)` /* Adapt the colors based on primary prop */ - background: ${props => (props.primary ? 'palevioletred' : 'white')}; - color: ${props => (props.primary ? 'white' : 'palevioletred')}; + background: ${props => (props.primary ? "palevioletred" : "white")}; + color: ${props => (props.primary ? "white" : "palevioletred")}; font-size: 1em; margin: 1em; @@ -86,7 +87,7 @@ const example = css` font-size: 1.5em; text-align: center; color: ${props => props.theme.primary}; - border-color: ${'red'}; + border-color: ${"red"}; `; const fadeIn = keyframes` @@ -99,15 +100,15 @@ const fadeIn = keyframes` `; const animationRule = css` - ${fadeIn} 1s infinite alternate; + ${fadeIn} 1s infinite alternate; `; const ComponentWithKeyframe = styled.div` - animation: ${animationRule}; + animation: ${animationRule}; `; const theme = { - main: 'mediumseagreen', + main: "mediumseagreen" }; const ExampleGlobalStyle = createGlobalStyle` @@ -130,7 +131,7 @@ class Example extends React.Component { Hello World, this is my first styled component! - + @@ -143,13 +144,13 @@ class Example extends React.Component { // css which only uses simple interpolations without functions const cssWithValues1 = css` - font-size: ${14} ${'pt'}; + font-size: ${14} ${"pt"}; `; // css which uses other simple interpolations without functions const cssWithValues2 = css` ${cssWithValues1} ${[cssWithValues1, cssWithValues1]} - font-weight: ${'bold'}; + font-weight: ${"bold"}; `; // css which uses function interpolations with common props @@ -168,7 +169,7 @@ const styledButton = styled.button` ${() => [cssWithFunc1, cssWithFunc2]} `; -const name = 'hey'; +const name = "hey"; const ThemedMyButton = withTheme(MyButton); @@ -216,7 +217,7 @@ const ComposedLink = () => ( // Create a react component that renders an which is // centered, palevioletred and sized at 1.5em -const LinkFromString = styled('a')` +const LinkFromString = styled("a")` font-size: 1.5em; text-align: center; color: palevioletred; @@ -235,10 +236,10 @@ interface LinkProps { canClick: boolean; } -const LinkFromStringWithProps = styled('a')` +const LinkFromStringWithProps = styled("a")` font-size: 1.5em; text-align: center; - color: ${(a: LinkProps) => (a.canClick ? 'palevioletred' : 'gray')}; + color: ${(a: LinkProps) => (a.canClick ? "palevioletred" : "gray")}; `; // A LinkFromStringWithProps instance should be backed by an HTMLAnchorElement @@ -251,10 +252,10 @@ const MyOtherComponentWithProps = () => ( // Create a react component that renders an // which takes extra props passed as a generic type argument -const LinkFromStringWithPropsAndGenerics = styled('a')` +const LinkFromStringWithPropsAndGenerics = styled("a")` font-size: 1.5em; text-align: center; - color: ${a => (a.canClick ? 'palevioletred' : 'gray')}; + color: ${a => (a.canClick ? "palevioletred" : "gray")}; `; // A LinkFromStringWithPropsAndGenerics instance should be backed by an HTMLAnchorElement @@ -274,19 +275,19 @@ interface ObjectStyleProps { } const functionReturningStyleObject = (props: ObjectStyleProps) => ({ - padding: props.size === 'big' ? '10px' : 2, + padding: props.size === "big" ? "10px" : 2 }); const ObjectStylesBox = styled.div` ${functionReturningStyleObject} ${{ - backgroundColor: 'red', + backgroundColor: "red", // Supports nested objects (pseudo selectors, media queries, etc) - '@media screen and (min-width: 800px)': { - backgroundColor: 'blue', + "@media screen and (min-width: 800px)": { + backgroundColor: "blue" }, - fontSize: 2, + fontSize: 2 }}; `; @@ -298,11 +299,11 @@ const ObjectStylesBox = styled.div` const AttrsInput = styled.input.attrs({ // we can define static props - type: 'password', + type: "password", // or we can define dynamic ones - margin: (props: any) => (props.size as string) || '1em', - padding: (props: any) => (props.size as string) || '1em', + margin: (props: any) => (props.size as string) || "1em", + padding: (props: any) => (props.size as string) || "1em" })` color: palevioletred; font-size: 1em; @@ -315,9 +316,9 @@ const AttrsInput = styled.input.attrs({ `; // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/30042 -const AttrsWithOnlyNewProps = styled.h2.attrs({ as: 'h1' })` - color: ${props => props.as === 'h1' ? 'red' : 'blue'}; - font-size: ${props => props.as === 'h1' ? 2 : 1}; +const AttrsWithOnlyNewProps = styled.h2.attrs({ as: "h1" })` + color: ${props => (props.as === "h1" ? "red" : "blue")}; + font-size: ${props => (props.as === "h1" ? 2 : 1)}; `; /** @@ -356,14 +357,14 @@ const ThemedButton = styled.button` // Define our `fg` and `bg` on the theme const theme2 = { - fg: 'palevioletred', - bg: 'white', + fg: "palevioletred", + bg: "white" }; // This theme swaps `fg` and `bg` const invertTheme = ({ fg, bg }: { fg: string; bg: string }) => ({ fg: bg, - bg: fg, + bg: fg }); const MyApp = ( @@ -386,7 +387,7 @@ class MyComponent extends React.Component> { render() { const { theme } = this.props; - console.log('Current theme: ', theme); + console.log("Current theme: ", theme); return

Hello

; } @@ -400,7 +401,7 @@ const ThemedMyComponent = withTheme(MyComponent); // ref; // }}/>; const themedRef = React.createRef(); -; +; interface WithThemeProps { theme: { @@ -415,12 +416,10 @@ const Component = (props: WithThemeProps) => ( const ComponentWithTheme = withTheme(Component); -; // ok -; // ok +; // ok +; // ok - - {(theme) => } -; +{theme => }; /** * isStyledComponent utility @@ -439,7 +438,7 @@ class ClassComponent extends React.Component { isStyledComponent(StyledComponent); isStyledComponent(StatelessComponent); isStyledComponent(ClassComponent); -isStyledComponent('div'); +isStyledComponent("div"); /** * server side rendering @@ -470,7 +469,7 @@ const css2 = sheet2.getStyleElement(); const sheet3 = new ServerStyleSheet(); const appStream = ReactDOMServer.renderToNodeStream(Hello world); const wrappedCssStream: NodeJS.ReadableStream = sheet3.interleaveWithNodeStream( - appStream, + appStream ); /** @@ -511,10 +510,10 @@ class Random extends React.Component { } } -const WithComponentH2 = WithComponentH1.withComponent('h2'); -const WithComponentAbbr = WithComponentH1.withComponent('abbr'); +const WithComponentH2 = WithComponentH1.withComponent("h2"); +const WithComponentAbbr = WithComponentH1.withComponent("abbr"); -const WithComponentAnchor = WithComponentH1.withComponent('a'); +const WithComponentAnchor = WithComponentH1.withComponent("a"); const AnchorContainer = () => ( withComponent Anchor @@ -524,37 +523,41 @@ const AnchorContainer = () => ( const WithComponentRandomHeading = WithComponentH1.withComponent(Random); const WithComponentCompA: React.SFC<{ a: number; className?: string }> = ({ - className, + className }) =>
; const WithComponentCompB: React.SFC<{ b: number; className?: string }> = ({ - className, + className }) =>
; const WithComponentStyledA = styled(WithComponentCompA)` color: ${(props: { color: string }) => props.color}; `; const WithComponentFirstStyledA = styled(WithComponentStyledA).attrs({ - a: 1, + a: 1 })``; const WithComponentFirstStyledB = WithComponentFirstStyledA.withComponent( - WithComponentCompB, + WithComponentCompB ); -const WithComponentFirstStyledANew = styled(WithComponentStyledA).attrs(props => ({ a: 1 }))``; +const WithComponentFirstStyledANew = styled(WithComponentStyledA).attrs( + props => ({ a: 1 }) +)``; const test = () => [ - , - , - , + , + , + ]; -const WithComponentRequired = styled((props: { to: string }) => )``; +const WithComponentRequired = styled((props: { to: string }) => ( + +))``; // These tests pass in tsservice, but they fail in dtslint. I do not know why. // ; // $ExpectError // ; -const WithComponentRequired2 = WithComponentRequired.withComponent('a'); +const WithComponentRequired2 = WithComponentRequired.withComponent("a"); // These tests pass in tsservice, but they fail in dtslint. I do not know why. // ; // ; // $ExpectError @@ -569,7 +572,7 @@ const asTest = ( ); interface TestContainerProps { - size: 'big' | 'small'; + size: "big" | "small"; test?: boolean; } const TestContainer = ({ size, test }: TestContainerProps) => { @@ -581,7 +584,7 @@ const StyledTestContainer = styled(TestContainer)` `; interface Test2ContainerProps { - type: 'foo' | 'bar'; + type: "foo" | "bar"; } class Test2Container extends React.Component { render() { @@ -592,28 +595,120 @@ class Test2Container extends React.Component { const containerTest = ( // TODO (TypeScript 3.2): once the polymorphic overload is un-commented-out this should be the correct test // - + ); // 4.0 refs -const divFnRef = (ref: HTMLDivElement|null) => { /* empty */ }; +const divFnRef = (ref: HTMLDivElement | null) => { + /* empty */ +}; const divRef = React.createRef(); const StyledDiv = styled.div``; -; -; -; // $ExpectError +; +; +; // $ExpectError const StyledStyledDiv = styled(StyledDiv)``; -; -; -; // $ExpectError +; +; +; // $ExpectError -const StyledA = StyledDiv.withComponent('a'); -; // $ExpectError - { - // $ExpectType HTMLAnchorElement | null - ref; -}}/>; +const StyledA = StyledDiv.withComponent("a"); +; // $ExpectError + { + // $ExpectType HTMLAnchorElement | null + ref; + }} +/>; + +async function typedThemes() { + const theme = { + color: "green" + }; + + // abuse "await import(...)" to be able to reference the styled-components namespace + // without actually doing a top level namespace import + const { + default: styled, + css, + createGlobalStyle, + ThemeProvider, + ThemeConsumer + } = (await import("styled-components")) as ThemedStyledComponentsModule< + typeof theme + >; + + const ThemedDiv = styled.div` + background: ${props => { + // $ExpectType string + props.theme.color; + // $ExpectType number | undefined + props.tabIndex; + return props.theme.color; + }}; + `; + const ThemedDiv2 = styled.div(props => { + // $ExpectType string + props.theme.color; + // $ExpectType number | undefined + props.tabIndex; + + return { + background: props.theme.color + }; + }); + const ThemedDiv3 = styled.div(props => { + // $ExpectType string + props.theme.color; + // $ExpectType number | undefined + props.tabIndex; + + return css` + background: ${props.theme.color}; + `; + }); + const themedCss = css` + background: ${props => { + // $ExpectType string + props.theme.color; + // $ExpectType "theme" + type Keys = keyof typeof props; + return props.theme.color; + }}; + `; + const ThemedDiv4 = styled.div(themedCss); + + const themedCssWithNesting = css(props => ({ + color: props.theme.color, + [ThemedDiv3]: { + color: "green" + } + })); + + const Global = createGlobalStyle` + ${themedCssWithNesting} + `; + + return ( + + <> + + + + + + + {theme => { + // $ExpectType string + theme.color; + return theme.color; + }} + + + + ); +} From 160c4de7df14c392722aed3fcdd931f53dbc4dd7 Mon Sep 17 00:00:00 2001 From: Jessica Date: Wed, 14 Nov 2018 17:25:01 +0900 Subject: [PATCH 068/836] Use a helper for the Extract stuff, support DefaultTheme in ThemeConsumer --- types/styled-components/index.d.ts | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index 6398ee36d5..c04de160b0 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -261,7 +261,7 @@ export interface ThemedBaseStyledInterface } export type ThemedStyledInterface = ThemedBaseStyledInterface< - Extract extends never ? any : T + AnyIfEmpty >; export type StyledInterface = ThemedStyledInterface; @@ -271,16 +271,15 @@ export type BaseThemedCssFunction =

( ) => Array>>; export type ThemedCssFunction = BaseThemedCssFunction< - Extract extends never ? any : T + AnyIfEmpty >; // Helper type operators type Omit = Pick>; -type DiffBetween = Pick> & - Pick>; type WithOptionalTheme

= Omit & { theme?: T; }; +type AnyIfEmpty = keyof T extends never ? any : T; export interface ThemedStyledComponentsModule { default: ThemedStyledInterface; @@ -318,7 +317,7 @@ export type BaseWithThemeFnInterface = < WithOptionalTheme, T> >; export type WithThemeFnInterface = BaseWithThemeFnInterface< - Extract extends never ? any : T + AnyIfEmpty >; export const withTheme: WithThemeFnInterface; @@ -334,13 +333,10 @@ export type BaseThemeProviderComponent = React.ComponentClass< >; export type ThemeProviderComponent< T extends object -> = BaseThemeProviderComponent< - Extract extends never ? any : T ->; -export const ThemeProvider: ThemeProviderComponent; -// NOTE: this technically starts as undefined -// Also, this cannot be DefaultTheme as it breaks TypedComponents' assignability -export const ThemeContext: React.Context; +> = BaseThemeProviderComponent>; +export const ThemeProvider: ThemeProviderComponent>; +// NOTE: this technically starts as undefined, but allowing undefined is unhelpful when used correctly +export const ThemeContext: React.Context>; export const ThemeConsumer: typeof ThemeContext["Consumer"]; export interface Keyframes { From 9a4b5d4d34c079b80117f4c3758afce64a506e49 Mon Sep 17 00:00:00 2001 From: Jessica Date: Wed, 14 Nov 2018 17:37:42 +0900 Subject: [PATCH 069/836] Document DefaultTheme, test ThemedStyledComponentsModule shape --- types/styled-components/index.d.ts | 12 ++++++++++++ types/styled-components/test/index.tsx | 14 ++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index c04de160b0..2ad44e7e57 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -301,6 +301,12 @@ export interface ThemedStyledComponentsModule { ThemeProvider: ThemeProviderComponent; ThemeConsumer: React.Consumer; ThemeContext: React.Context; + + // This could be made to assert `target is StyledComponent` instead, but that feels not type safe + isStyledComponent: typeof isStyledComponent; + + ServerStyleSheet: typeof ServerStyleSheet; + StyleSheetManager: typeof StyleSheetManager; } declare const styled: StyledInterface; @@ -321,6 +327,12 @@ export type WithThemeFnInterface = BaseWithThemeFnInterface< >; export const withTheme: WithThemeFnInterface; +/** + * This interface can be augmented by users to add types to `styled-components`' default theme + * without needing to reexport `ThemedStyledComponentsModule`. + */ +// Unfortunately, there is no way to write tests for this +// as any augmentation will break the tests for the default case (not augmented). // tslint:disable-next-line:no-empty-interface export interface DefaultTheme {} diff --git a/types/styled-components/test/index.tsx b/types/styled-components/test/index.tsx index 7ce9e59fa2..628a294a48 100644 --- a/types/styled-components/test/index.tsx +++ b/types/styled-components/test/index.tsx @@ -712,3 +712,17 @@ async function typedThemes() { ); } + +async function reexportCompatibility() { + const sc = await import("styled-components"); + const themed = sc as ThemedStyledComponentsModule; + + let { ...scExports } = sc; + let { ...themedExports } = themed; + // both branches must be assignable to each other + if (Math.random()) { + scExports = themedExports; + } else { + themedExports = scExports; + } +} From 9e6ea6abc62b5e8e0fe73c3b60e57460f153975c Mon Sep 17 00:00:00 2001 From: Jessica Date: Wed, 14 Nov 2018 18:53:20 +0900 Subject: [PATCH 070/836] Add a way to declare a ThemeProvider is augmenting another ThemeProvider --- types/styled-components/index.d.ts | 23 +++++++++------ types/styled-components/test/index.tsx | 41 ++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 9 deletions(-) diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index 2ad44e7e57..b915040c7e 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -281,7 +281,10 @@ type WithOptionalTheme

= Omit & { }; type AnyIfEmpty = keyof T extends never ? any : T; -export interface ThemedStyledComponentsModule { +export interface ThemedStyledComponentsModule< + T extends object, + U extends object = T +> { default: ThemedStyledInterface; css: ThemedCssFunction; @@ -298,7 +301,7 @@ export interface ThemedStyledComponentsModule { ): GlobalStyleComponent; withTheme: WithThemeFnInterface; - ThemeProvider: ThemeProviderComponent; + ThemeProvider: ThemeProviderComponent; ThemeConsumer: React.Consumer; ThemeContext: React.Context; @@ -336,16 +339,18 @@ export const withTheme: WithThemeFnInterface; // tslint:disable-next-line:no-empty-interface export interface DefaultTheme {} -export interface ThemeProviderProps { +export interface ThemeProviderProps { children?: React.ReactChild; // only one child is allowed, goes through React.Children.only - theme: T | ((theme: T) => T); + theme: T | ((theme: U) => T); } -export type BaseThemeProviderComponent = React.ComponentClass< - ThemeProviderProps ->; +export type BaseThemeProviderComponent< + T extends object, + U extends object = T +> = React.ComponentClass>; export type ThemeProviderComponent< - T extends object -> = BaseThemeProviderComponent>; + T extends object, + U extends object = T +> = BaseThemeProviderComponent, AnyIfEmpty>; export const ThemeProvider: ThemeProviderComponent>; // NOTE: this technically starts as undefined, but allowing undefined is unhelpful when used correctly export const ThemeContext: React.Context>; diff --git a/types/styled-components/test/index.tsx b/types/styled-components/test/index.tsx index 628a294a48..0e9fec66a1 100644 --- a/types/styled-components/test/index.tsx +++ b/types/styled-components/test/index.tsx @@ -726,3 +726,44 @@ async function reexportCompatibility() { themedExports = scExports; } } + +async function themeAugmentation() { + interface BaseTheme { + background: string; + } + interface ExtraTheme extends BaseTheme { + accent: string; + } + + const base = (await import("styled-components")) as ThemedStyledComponentsModule< + BaseTheme + >; + const extra = (await import("styled-components")) as ThemedStyledComponentsModule< + ExtraTheme, + BaseTheme + >; + + return ( + + <> + base} // $ExpectError + > + {() => null} + + ({ + ...base, + accent: "blue" + })} + > + {() => null} + + + + ); +} From a0df8f39a019eeded79d2a5c6abf1a90fd5b0f7a Mon Sep 17 00:00:00 2001 From: Mihai Dinculescu Date: Thu, 15 Nov 2018 12:07:20 +0000 Subject: [PATCH 071/836] redux-immutable-state-invariant: redux 4 support. --- types/redux-immutable-state-invariant/index.d.ts | 4 ++-- types/redux-immutable-state-invariant/package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/redux-immutable-state-invariant/index.d.ts b/types/redux-immutable-state-invariant/index.d.ts index 6ad2a0e588..64c3fa6851 100644 --- a/types/redux-immutable-state-invariant/index.d.ts +++ b/types/redux-immutable-state-invariant/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for redux-immutable-state-invariant v2.0.0 +// Type definitions for redux-immutable-state-invariant v2.1.0 // Project: https://github.com/leoasis/redux-immutable-state-invariant -// Definitions by: Remo H. Jansen , Ben Rogers +// Definitions by: Remo H. Jansen , Ben Rogers , Mihai Dinculescu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as Redux from "redux"; diff --git a/types/redux-immutable-state-invariant/package.json b/types/redux-immutable-state-invariant/package.json index 6d68bf2f9b..998f8e9b38 100644 --- a/types/redux-immutable-state-invariant/package.json +++ b/types/redux-immutable-state-invariant/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "redux": "^3.6.0" + "redux": "^3.6.0 || ^4.0.0" } } From 1d5101593cc01612f67c9bbd07f814f01c94a67b Mon Sep 17 00:00:00 2001 From: Mihai Dinculescu Date: Thu, 15 Nov 2018 12:20:14 +0000 Subject: [PATCH 072/836] Add TypeScript version. --- types/redux-immutable-state-invariant/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/redux-immutable-state-invariant/index.d.ts b/types/redux-immutable-state-invariant/index.d.ts index 64c3fa6851..502f7e65bf 100644 --- a/types/redux-immutable-state-invariant/index.d.ts +++ b/types/redux-immutable-state-invariant/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/leoasis/redux-immutable-state-invariant // Definitions by: Remo H. Jansen , Ben Rogers , Mihai Dinculescu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as Redux from "redux"; From c700743bc387d8df7a99711e448d1b6f7388f103 Mon Sep 17 00:00:00 2001 From: Brian Caruso Date: Thu, 15 Nov 2018 15:37:48 -0800 Subject: [PATCH 073/836] Update detect-browser to v3.0 --- types/detect-browser/detect-browser-tests.ts | 63 +++++++++++++++++++- types/detect-browser/index.d.ts | 28 ++++++--- 2 files changed, 80 insertions(+), 11 deletions(-) diff --git a/types/detect-browser/detect-browser-tests.ts b/types/detect-browser/detect-browser-tests.ts index 48abb964f8..7453ed044a 100644 --- a/types/detect-browser/detect-browser-tests.ts +++ b/types/detect-browser/detect-browser-tests.ts @@ -1,7 +1,64 @@ -import { detect } from 'detect-browser'; +import { BrowserName, BrowserInfo, detect } from 'detect-browser'; const browser = detect(); if (browser) { - const name: string = browser.name; - const version: string = browser.version; + const name: string | undefined = browser.name; + const version: string | undefined = browser.version; + const os: string | undefined | null = browser.os; + const bot: true | undefined = browser.bot; } + +const browserInfos: BrowserInfo[] = []; + +// Those that can happen when 'detect' hits on a browser + +browserInfos.push( + { + name: "chrome", + version: "1.2.3", + os: null + } +); + +browserInfos.push( + { + name: "edge", + version: "24.5.3", + os: "Sun OS" + } +); + +browserInfos.push( + { + name: "edge", + version: "13.0", + os: "Windows 10", + bot: true + } +); + +// Those that could be returned when it's a bot + +browserInfos.push( + { + name: "facebook", + version: "1.0.2", + os: "Linux", + bot: true + } +); + +browserInfos.push( + { + name: "crios", + version: "2.9.4", + os: undefined, + bot: true + } +); + +browserInfos.push( + { + bot: true + } +); diff --git a/types/detect-browser/index.d.ts b/types/detect-browser/index.d.ts index 22d6bf9c17..943484b013 100644 --- a/types/detect-browser/index.d.ts +++ b/types/detect-browser/index.d.ts @@ -1,30 +1,42 @@ -// Type definitions for detect-browser 2.0 +// Type definitions for detect-browser 3.0 // Project: https://github.com/DamonOehlman/detect-browser // Definitions by: Rogier Schouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Brian Caruso +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export {}; export type BrowserName = + "aol" | "android" | "bb10" | "chrome" | "crios" | "edge" | + "facebook" | "firefox" | "fxios" | "ie" | + "instagram" | "ios" | + "ios-webview" | "kakaotalk" | + "node" | "opera" | "phantomjs" | "safari" | + "samsung" | "vivaldi" | - "yandexbrowser" | - "node"; + "yandexbrowser"; export interface BrowserInfo { - name: BrowserName; - version: string; - os: string; + name?: string; + version?: string; + os?: string | null; + bot?: true; } -export function detect(): null | BrowserInfo; +export function detect(): null | false | BrowserInfo; +export function detectOS(userAgentString: string): null | string; +export function parseUserAgent(userAgentString: string): null | BrowserInfo; +export function getNodeVersion(): false | BrowserInfo; From e4b6fecfdc601e8a9b85bb567171c0806d82c344 Mon Sep 17 00:00:00 2001 From: Hiroshi Ioka Date: Fri, 16 Nov 2018 08:35:26 +0900 Subject: [PATCH 074/836] @types/koa-bodyparser: use any for Request.body Also, fix Request.rawBody and library version. --- types/koa-bodyparser/index.d.ts | 10 ++++++---- types/koa-bodyparser/koa-bodyparser-tests.ts | 1 + 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/types/koa-bodyparser/index.d.ts b/types/koa-bodyparser/index.d.ts index deb1eb04e9..9687f15ff9 100644 --- a/types/koa-bodyparser/index.d.ts +++ b/types/koa-bodyparser/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for koa-bodyparser 5.0 +// Type definitions for koa-bodyparser 4.2 // Project: https://github.com/koajs/bodyparser -// Definitions by: Jerry Chin , Anup Kishore +// Definitions by: Jerry Chin +// Anup Kishore +// Hiroshi Ioka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -18,8 +20,8 @@ import * as Koa from "koa"; declare module "koa" { interface Request { - body: {} | null | undefined; - rawBody: {} | null | undefined; + body: any; + rawBody: string; } } diff --git a/types/koa-bodyparser/koa-bodyparser-tests.ts b/types/koa-bodyparser/koa-bodyparser-tests.ts index e38eb112dd..6b14693914 100644 --- a/types/koa-bodyparser/koa-bodyparser-tests.ts +++ b/types/koa-bodyparser/koa-bodyparser-tests.ts @@ -7,6 +7,7 @@ app.use(bodyParser({ strict: false })); app.use((ctx) => { console.log(ctx.request.body); + console.log(ctx.request.body.ok); console.log(ctx.request.rawBody); }); From 2ee57c7d32b0ef6af3d7d5197a924fc8763c7365 Mon Sep 17 00:00:00 2001 From: Jessica Date: Fri, 16 Nov 2018 10:54:52 +0900 Subject: [PATCH 075/836] Fix return type of css``, tweak overloads --- types/styled-components/index.d.ts | 89 +++++++++++++++++++++--------- 1 file changed, 62 insertions(+), 27 deletions(-) diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index b915040c7e..4a86aa245f 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -9,8 +9,8 @@ /// -import * as React from "react"; import * as CSS from "csstype"; +import * as React from "react"; export type CSSObject = CSS.Properties & // Index type to allow selector nesting @@ -30,7 +30,7 @@ export interface ThemeProps { } export type ThemedStyledProps = P & ThemeProps; -export type StyledProps

= ThemedStyledProps; +export type StyledProps

= ThemedStyledProps>; export type StyledComponentProps< // The Component from whose props are derived @@ -57,8 +57,8 @@ type StyledComponentPropsWithAs< export type FalseyValue = undefined | null | false; export type Interpolation

= | InterpolationValue - | InterpolationFunction

- | FlattenInterpolation

; + | FlattenInterpolation

+ | InterpolationFunction

; // must be an interface to be self-referential export interface FlattenInterpolation

extends ReadonlyArray> {} @@ -93,10 +93,15 @@ export interface GlobalStyleComponent extends React.ComponentClass> {} // remove the call signature from StyledComponent so Interpolation can still infer InterpolationFunction -type StyledComponentInterpolation = Pick< - AnyStyledComponent, - keyof StyledComponentBase ->; +type StyledComponentInterpolation = + | Pick< + StyledComponentBase, + keyof StyledComponentBase + > + | Pick< + StyledComponentBase, + keyof StyledComponentBase + >; // abuse Pick to strip the call signature from ForwardRefExoticComponent type ForwardRefExoticBase

= Pick< @@ -162,25 +167,45 @@ export interface StyledComponentBase< ): StyledComponent; } -export type ThemedStyledFunctionBase< +export interface ThemedStyledFunctionBase< C extends keyof JSX.IntrinsicElements | React.ComponentType, T extends object, O extends object = {}, A extends keyof any = never -> = +> { + ( + first: + | TemplateStringsArray + | NonNullable< + Interpolation< + ThemedStyledProps & O, T> + > + >, + ...rest: Array< + Interpolation< + ThemedStyledProps & O, T> + > + > + ): StyledComponent; // at least the first argument is required, whatever it is ( - first: NonNullable< - Interpolation< - ThemedStyledProps & O & U, T> - > - >, + first: + | TemplateStringsArray + | NonNullable< + Interpolation< + ThemedStyledProps< + StyledComponentPropsWithRef & O & U, + T + > + > + >, ...rest: Array< Interpolation< ThemedStyledProps & O & U, T> > > - ) => StyledComponent; + ): StyledComponent; +} export interface ThemedStyledFunction< C extends keyof JSX.IntrinsicElements | React.ComponentType, @@ -243,17 +268,13 @@ type StyledComponentInnerAttrs< export interface ThemedBaseStyledInterface extends ThemedStyledComponentFactories { - (tag: TTag): ThemedStyledFunction< - TTag, - T - >; (component: C): ThemedStyledFunction< StyledComponentInnerComponent, T, StyledComponentInnerOtherProps, StyledComponentInnerAttrs >; - >( + >( // unfortunately using a conditional type to validate that it can receive a `theme?: Theme` // causes tests to fail in TS 3.1 component: C @@ -265,10 +286,20 @@ export type ThemedStyledInterface = ThemedBaseStyledInterface< >; export type StyledInterface = ThemedStyledInterface; -export type BaseThemedCssFunction =

( - first: NonNullable>>, - ...interpolations: Array>> -) => Array>>; +export interface BaseThemedCssFunction { + ( + first: + | TemplateStringsArray + | NonNullable>>, + ...interpolations: Array>> + ): FlattenInterpolation>; +

( + first: + | TemplateStringsArray + | NonNullable>>, + ...interpolations: Array>> + ): FlattenInterpolation>; +} export type ThemedCssFunction = BaseThemedCssFunction< AnyIfEmpty @@ -296,7 +327,9 @@ export interface ThemedStyledComponentsModule< ): Keyframes; createGlobalStyle

( - first: NonNullable>>, + first: + | TemplateStringsArray + | NonNullable>>, ...interpolations: Array>> ): GlobalStyleComponent; @@ -366,7 +399,9 @@ export function keyframes( ): Keyframes; export function createGlobalStyle

( - first: NonNullable>>, + first: + | TemplateStringsArray + | NonNullable>>, ...interpolations: Array>> ): GlobalStyleComponent; From 7c2cd7f5d26dcbfffaf80d43f85da7258d056dd4 Mon Sep 17 00:00:00 2001 From: Pine Mizune Date: Fri, 16 Nov 2018 12:36:38 +0900 Subject: [PATCH 076/836] Fix the contributor name and url --- types/js-url/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/js-url/index.d.ts b/types/js-url/index.d.ts index d5bf93257d..69583e1553 100644 --- a/types/js-url/index.d.ts +++ b/types/js-url/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for url v1.8.6 // Project: https://github.com/websanova/js-url -// Definitions by: MIZUNE Pine +// Definitions by: Pine Mizune // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface UrlStatic { From 9fd098392c06110c6235db8687be9267c3604bfb Mon Sep 17 00:00:00 2001 From: Sutrisno Suryajaya Date: Fri, 16 Nov 2018 11:49:09 +0800 Subject: [PATCH 077/836] Proper type definition for Relay connection args In the graphql-relay implementation (https://github.com/graphql/graphql-relay-js/blob/da2801ab9e64006b1e41bcdb28c889799ee5c170/src/connection/connection.js#L30-L59) `forwardConnectionArgs`, `backwardConnectionArgs` and `connectionArgs` refer to the argument's GraphQL schema definition instead of the argument structured when used in a GraphQL query. --- types/graphql-relay/graphql-relay-tests.ts | 18 ++++++++++-------- types/graphql-relay/index.d.ts | 19 ++++++------------- 2 files changed, 16 insertions(+), 21 deletions(-) diff --git a/types/graphql-relay/graphql-relay-tests.ts b/types/graphql-relay/graphql-relay-tests.ts index cebc90e2ca..e490329b65 100644 --- a/types/graphql-relay/graphql-relay-tests.ts +++ b/types/graphql-relay/graphql-relay-tests.ts @@ -11,6 +11,7 @@ import { GraphQLInputFieldConfigMap, GraphQLNonNull, GraphQLID, + GraphQLInt } from "graphql"; import { // Connections @@ -30,18 +31,19 @@ import { // Mutations mutationWithClientMutationId, } from "graphql-relay"; + // Connections // connectionArgs returns the arguments that fields should provide when they return a connection type that supports bidirectional pagination. -connectionArgs.first = 10; -connectionArgs.after = "a"; -connectionArgs.before = "b"; -connectionArgs.last = 10; +connectionArgs.first = { type: GraphQLInt }; +connectionArgs.after = { type: GraphQLString }; +connectionArgs.before = { type: GraphQLString }; +connectionArgs.last = { type: GraphQLInt }; // forwardConnectionArgs returns the arguments that fields should provide when they return a connection type that only supports forward pagination. -forwardConnectionArgs.after = "a"; -forwardConnectionArgs.first = 10; +forwardConnectionArgs.after = { type: GraphQLString }; +forwardConnectionArgs.first = { type: GraphQLInt }; // backwardConnectionArgs returns the arguments that fields should provide when they return a connection type that only supports backward pagination. -backwardConnectionArgs.before = "b"; -backwardConnectionArgs.last = 10; +backwardConnectionArgs.before = { type: GraphQLString }; +backwardConnectionArgs.last = { type: GraphQLInt }; // connectionDefinitions returns a connectionType and its associated edgeType, given a node type. const resolve: GraphQLFieldResolver = (source, args, context, info) => { context.flag = "f"; diff --git a/types/graphql-relay/index.d.ts b/types/graphql-relay/index.d.ts index d4bba06948..67edfa3df0 100644 --- a/types/graphql-relay/index.d.ts +++ b/types/graphql-relay/index.d.ts @@ -34,27 +34,20 @@ import { * whose return type is a connection type with forward pagination. */ export interface ForwardConnectionArgs { - after?: ConnectionCursor | null; - first?: number | null; + after: { type: GraphQLScalarType }; + first: { type: GraphQLScalarType }; } -export const forwardConnectionArgs: GraphQLFieldConfigArgumentMap & { - after?: ConnectionCursor | null; - first?: number | null; -}; +export const forwardConnectionArgs: GraphQLFieldConfigArgumentMap & ForwardConnectionArgs; /** * Returns a GraphQLFieldConfigArgumentMap appropriate to include on a field * whose return type is a connection type with backward pagination. */ export interface BackwardConnectionArgs { - before?: ConnectionCursor | null; - last?: number | null; + before: { type: GraphQLScalarType }; + last: { type: GraphQLScalarType }; } -export const backwardConnectionArgs: GraphQLFieldConfigArgumentMap & { - before?: ConnectionCursor | null; - last?: number | null; -}; - +export const backwardConnectionArgs: GraphQLFieldConfigArgumentMap & BackwardConnectionArgs; /** * Returns a GraphQLFieldConfigArgumentMap appropriate to include on a field * whose return type is a connection type with bidirectional pagination. From a0a99124e9c77cac8e3985001a3865f47d6bf6fa Mon Sep 17 00:00:00 2001 From: Jessica Date: Fri, 16 Nov 2018 16:54:58 +0900 Subject: [PATCH 078/836] Preserve optionality of parent StyledComponent .attrs --- types/styled-components/index.d.ts | 12 ++++++------ types/styled-components/test/index.tsx | 4 ++++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index 4a86aa245f..a842c94c63 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -217,23 +217,23 @@ export interface ThemedStyledFunction< // My head already hurts enough so maybe later... attrs< U, - A extends Partial & U> & { + NewA extends Partial & U> & { [others: string]: any; } = {} >( - attrs: Attrs & U, A, T> - ): ThemedStyledFunction; + attrs: Attrs & U, NewA, T> + ): ThemedStyledFunction; // Only this overload is deprecated // tslint:disable:unified-signatures /** @deprecated Prefer using the new single function style, to be removed in v5 */ attrs< U, - A extends Partial & U> & { + NewA extends Partial & U> & { [others: string]: any; } = {} >( - attrs: DeprecatedAttrs & U, A, T> - ): ThemedStyledFunction; + attrs: DeprecatedAttrs & U, NewA, T> + ): ThemedStyledFunction; // tslint:enable:unified-signatures } diff --git a/types/styled-components/test/index.tsx b/types/styled-components/test/index.tsx index 0e9fec66a1..e435d90011 100644 --- a/types/styled-components/test/index.tsx +++ b/types/styled-components/test/index.tsx @@ -321,6 +321,10 @@ const AttrsWithOnlyNewProps = styled.h2.attrs({ as: "h1" })` font-size: ${props => (props.as === "h1" ? 2 : 1)}; `; +const AttrsInputExtra = styled(AttrsInput).attrs({ autoComplete: "off" })``; + +; + /** * component type */ From ea77585d48502609a9f71c1d832247ab05485c7b Mon Sep 17 00:00:00 2001 From: carl-coolblue Date: Fri, 16 Nov 2018 09:24:23 +0100 Subject: [PATCH 079/836] Add missing `data` prop type to `Option` --- types/react-select/lib/components/Option.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/react-select/lib/components/Option.d.ts b/types/react-select/lib/components/Option.d.ts index defe37711a..c6113aa934 100644 --- a/types/react-select/lib/components/Option.d.ts +++ b/types/react-select/lib/components/Option.d.ts @@ -32,6 +32,8 @@ export type OptionProps = PropsWithStyles & /* Type is used by the menu to determine whether this is an option or a group. In the case of option this is always `option`. */ type: 'option', + /* The data of the selected option. */ + data: any, }; export function optionCSS(state: State): React.CSSProperties; From 8320760d0170eefbd1029391263ebcc06a3c46ac Mon Sep 17 00:00:00 2001 From: Mihail Novikov Date: Fri, 16 Nov 2018 12:11:29 +0300 Subject: [PATCH 080/836] [react-table] Add overridden components --- types/react-table/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/react-table/index.d.ts b/types/react-table/index.d.ts index 2e9c14980c..fd7681d3b3 100644 --- a/types/react-table/index.d.ts +++ b/types/react-table/index.d.ts @@ -342,6 +342,10 @@ export interface ComponentProps { TdComponent: React.ReactType; TfootComponent: React.ReactType; ExpanderComponent: React.ReactType; + AggregatedComponent: React.ReactType, + PivotValueComponent: React.ReactType, + PivotComponent: React.ReactType, + FilterComponent: React.ReactType, PaginationComponent: React.ReactType; PreviousComponent: React.ReactType; NextComponent: React.ReactType; From 3634a3943538a5270c1b2722b4592dd077645842 Mon Sep 17 00:00:00 2001 From: Mihail Novikov Date: Fri, 16 Nov 2018 12:18:31 +0300 Subject: [PATCH 081/836] [react-table] Add overridden components (fix errors) --- types/react-table/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/react-table/index.d.ts b/types/react-table/index.d.ts index fd7681d3b3..d6b1679edd 100644 --- a/types/react-table/index.d.ts +++ b/types/react-table/index.d.ts @@ -342,10 +342,10 @@ export interface ComponentProps { TdComponent: React.ReactType; TfootComponent: React.ReactType; ExpanderComponent: React.ReactType; - AggregatedComponent: React.ReactType, - PivotValueComponent: React.ReactType, - PivotComponent: React.ReactType, - FilterComponent: React.ReactType, + AggregatedComponent: React.ReactType; + PivotValueComponent: React.ReactType; + PivotComponent: React.ReactType; + FilterComponent: React.ReactType; PaginationComponent: React.ReactType; PreviousComponent: React.ReactType; NextComponent: React.ReactType; From b5e51f206129d6ee3780ba22fe85e1ddd6687cf0 Mon Sep 17 00:00:00 2001 From: Mihail Novikov Date: Fri, 16 Nov 2018 13:43:49 +0300 Subject: [PATCH 082/836] [react-table] Fix tests --- types/react-table/test/select-table-tests.tsx | 2 -- types/react-table/test/tree-table-tests.tsx | 2 -- 2 files changed, 4 deletions(-) diff --git a/types/react-table/test/select-table-tests.tsx b/types/react-table/test/select-table-tests.tsx index 1a29ed07c1..1a1b231292 100644 --- a/types/react-table/test/select-table-tests.tsx +++ b/types/react-table/test/select-table-tests.tsx @@ -6,8 +6,6 @@ import selectTableHOC, { SelectTableAdditionalProps } from 'react-table/lib/hoc/selectTable'; -import 'react-table/react-table.css'; - const SelectTable = selectTableHOC(ReactTable); const selectTableAdditionalProps: SelectTableAdditionalProps = { diff --git a/types/react-table/test/tree-table-tests.tsx b/types/react-table/test/tree-table-tests.tsx index 14ad8265de..a099124c61 100644 --- a/types/react-table/test/tree-table-tests.tsx +++ b/types/react-table/test/tree-table-tests.tsx @@ -4,8 +4,6 @@ import * as ReactDOM from 'react-dom'; import ReactTable, { Column } from 'react-table'; import treeTableHOC from 'react-table/lib/hoc/treeTable'; -import 'react-table/react-table.css'; - const SelectTable = treeTableHOC(ReactTable); const data = [{ id: 1, name: 'Foo' }, { id: 2, name: 'Bar' }]; From fa930bcc17a0461d1d0c42233321f3d8beb84b6d Mon Sep 17 00:00:00 2001 From: Mihail Novikov Date: Fri, 16 Nov 2018 13:52:27 +0300 Subject: [PATCH 083/836] [react-table] Fix test --- types/react-table/react-table-tests.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/types/react-table/react-table-tests.tsx b/types/react-table/react-table-tests.tsx index fdc3870733..de7eea0bc7 100644 --- a/types/react-table/react-table-tests.tsx +++ b/types/react-table/react-table-tests.tsx @@ -3,7 +3,6 @@ import * as ReactDOM from 'react-dom'; // Import React Table import ReactTable, { Column, FinalState, Instance } from "react-table"; -import "react-table/react-table.css"; interface Data { firstName: string; From f18851bea8e67645232633c8c88321add78a1822 Mon Sep 17 00:00:00 2001 From: Bryan Smith Date: Fri, 16 Nov 2018 10:35:29 -0800 Subject: [PATCH 084/836] Add onBeforeInput form events. --- types/react/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 332d3ac640..2a1c7baf7b 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -808,6 +808,8 @@ declare namespace React { // Form Events onChange?: FormEventHandler; onChangeCapture?: FormEventHandler; + onBeforeInput?: FormEventHandler; + onBeforeInputCapture?: FormEventHandler; onInput?: FormEventHandler; onInputCapture?: FormEventHandler; onReset?: FormEventHandler; From 7364d8937f28c0460ff0eefd3ee1a3e7bd6393e3 Mon Sep 17 00:00:00 2001 From: HokieGeek Date: Fri, 16 Nov 2018 15:30:20 -0500 Subject: [PATCH 085/836] @types/lunr: Updated Builder functions to add new optional arguments --- types/lunr/index.d.ts | 17 +++++++++++++---- types/lunr/lunr-tests.ts | 7 +++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/types/lunr/index.d.ts b/types/lunr/index.d.ts index da87ae95d8..415c7c1d8f 100644 --- a/types/lunr/index.d.ts +++ b/types/lunr/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for lunr.js 2.1 +// Type definitions for lunr.js 2.3 // Project: https://github.com/olivernn/lunr.js -// Definitions by: Sean Tan +// Definitions by: Sean Tan , Andrés Pérez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -127,9 +127,14 @@ declare namespace lunr { * All fields should be added before adding documents to the index. Adding fields after * a document has been indexed will have no effect on already indexed documents. * + * Fields can be boosted at build time. This allows terms within that field to have more + * importance when ranking search results. Use a field boost to specify that matches + * within one field are more important than other fields. + * * @param field - The name of a field to index in all documents. + * @param attributes - Optional attributes associated with this field. */ - field(field: string): void; + field(field: string, attributes?: object): void; /** * A parameter to tune the amount of field length normalisation that is applied when @@ -160,9 +165,13 @@ declare namespace lunr { * it should have all fields defined for indexing, though null or undefined values will not * cause errors. * + * Entire documents can be boosted at build time. Applying a boost to a document indicates that + * this document should rank higher in search results than other documents. + * * @param doc - The document to add to the index. + * @param attributes - Optional attributes associated with this document. */ - add(doc: object): void; + add(doc: object, attributes?: object): void; /** * Builds the index, creating an instance of lunr.Index. diff --git a/types/lunr/lunr-tests.ts b/types/lunr/lunr-tests.ts index ade45cae64..a14fd1947f 100644 --- a/types/lunr/lunr-tests.ts +++ b/types/lunr/lunr-tests.ts @@ -4,11 +4,18 @@ function basic_test() { const index = lunr(function() { this.field("title"); this.field("body"); + this.field("content", { + boost: 2, + extractor: (doc: object) => "oof" + }); this.ref("id"); this.add({ id: 1, title: "Foo", body: "Foo foo foo!" + }, + { + boost: 2 }); this.add({ id: 2, From 1e5d13c5544fc148545dba075306ecc49aee0c1f Mon Sep 17 00:00:00 2001 From: Christophe Hurpeau Date: Fri, 16 Nov 2018 21:43:44 +0100 Subject: [PATCH 086/836] webpack: NormalModuleReplacementPlugin doesnt seems deprecated doc here: https://webpack.js.org/plugins/normal-module-replacement-plugin/ --- types/webpack/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index 357c63e330..f5beb1dc63 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -1394,7 +1394,6 @@ declare namespace webpack { constructor(); } - /** @deprecated use webpack.NoEmitOnErrorsPlugin */ class NormalModuleReplacementPlugin extends Plugin { constructor(resourceRegExp: any, newResource: any); } From 95b71e55e54883aaf6bffa5bdc2dd1a24ec0bb8e Mon Sep 17 00:00:00 2001 From: Jeroen Vervaeke Date: Sat, 17 Nov 2018 00:22:54 +0100 Subject: [PATCH 087/836] Improved DrawerItems --- types/react-navigation/index.d.ts | 36 +++++++++++++++++-- .../react-navigation-tests.tsx | 13 +++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 4e81a26c88..92f3daa0e6 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -27,6 +27,7 @@ // Max Davidson // Lachlan Young // Jason Killian +// Jeroen Vervaeke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -876,7 +877,38 @@ export function createSwitchNavigator( ): NavigationContainer; // DrawerItems -export const DrawerItems: React.ReactType; +export const DrawerItems: React.ComponentType; + +export interface DrawerItemsProps { + navigation: NavigationScreenProp, + items: Array, + activeItemKey?: string, + activeTintColor?: string, + activeBackgroundColor?: string, + inactiveTintColor?: string, + inactiveBackgroundColor?: string, + getLabel: (scene: DrawerScene) => React.ReactNode | string, + renderIcon: (scene: DrawerScene) => React.ReactNode, + onItemPress: (info: DrawerItem) => void, + itemsContainerForceInset?: Object, + itemsContainerStyle?: StyleProp, + itemStyle?: StyleProp, + labelStyle?: StyleProp, + activeLabelStyle?: StyleProp, + inactiveLabelStyle?: StyleProp, + iconContainerStyle?: StyleProp, + drawerPosition: 'left' | 'right', +} +declare type DrawerScene = { + route: NavigationRoute, + focused: boolean, + index: number, + tintColor?: string, +}; +declare type DrawerItem = { + route: NavigationRoute, + focused: boolean, +}; /** * Drawer Navigator @@ -885,7 +917,7 @@ export interface DrawerViewConfig { drawerBackgroundColor?: string; drawerWidth?: number; drawerPosition?: 'left' | 'right'; - contentComponent?: React.ReactType; + contentComponent?: React.ComponentType; contentOptions?: any; style?: StyleProp; } diff --git a/types/react-navigation/react-navigation-tests.tsx b/types/react-navigation/react-navigation-tests.tsx index 66bcf13c3c..43cadcde76 100644 --- a/types/react-navigation/react-navigation-tests.tsx +++ b/types/react-navigation/react-navigation-tests.tsx @@ -8,6 +8,8 @@ import { import { createDrawerNavigator, createBottomTabNavigator, + DrawerItems, + DrawerItemsProps, DrawerNavigatorConfig, NavigationAction, NavigationActions, @@ -331,6 +333,17 @@ const BasicDrawerNavigator = createDrawerNavigator( stackNavigatorConfig, ); +const Drawer = (props: DrawerItemsProps) => ( + +); + +const DrawerNavigatorWithCustomDrawer = createDrawerNavigator( + routeConfigMap, + { + contentComponent: Drawer, + } +); + function renderBasicDrawerNavigator(): JSX.Element { return ( Date: Sat, 17 Nov 2018 00:45:18 +0100 Subject: [PATCH 088/836] Ran 'npm run lint package-name' --- types/react-navigation/index.d.ts | 55 +++++++++++++++---------------- 1 file changed, 27 insertions(+), 28 deletions(-) diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 92f3daa0e6..593500e585 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -880,35 +880,34 @@ export function createSwitchNavigator( export const DrawerItems: React.ComponentType; export interface DrawerItemsProps { - navigation: NavigationScreenProp, - items: Array, - activeItemKey?: string, - activeTintColor?: string, - activeBackgroundColor?: string, - inactiveTintColor?: string, - inactiveBackgroundColor?: string, - getLabel: (scene: DrawerScene) => React.ReactNode | string, - renderIcon: (scene: DrawerScene) => React.ReactNode, - onItemPress: (info: DrawerItem) => void, - itemsContainerForceInset?: Object, - itemsContainerStyle?: StyleProp, - itemStyle?: StyleProp, - labelStyle?: StyleProp, - activeLabelStyle?: StyleProp, - inactiveLabelStyle?: StyleProp, - iconContainerStyle?: StyleProp, - drawerPosition: 'left' | 'right', + navigation: NavigationScreenProp; + items: NavigationRoute[]; + activeItemKey?: string; + activeTintColor?: string; + activeBackgroundColor?: string; + inactiveTintColor?: string; + inactiveBackgroundColor?: string; + getLabel: (scene: DrawerScene) => React.ReactNode | string; + renderIcon: (scene: DrawerScene) => React.ReactNode; + onItemPress: (info: DrawerItem) => void; + itemsContainerStyle?: StyleProp; + itemStyle?: StyleProp; + labelStyle?: StyleProp; + activeLabelStyle?: StyleProp; + inactiveLabelStyle?: StyleProp; + iconContainerStyle?: StyleProp; + drawerPosition: 'left' | 'right'; +} +export interface DrawerScene { + route: NavigationRoute; + focused: boolean; + index: number; + tintColor?: string; +} +export interface DrawerItem { + route: NavigationRoute; + focused: boolean; } -declare type DrawerScene = { - route: NavigationRoute, - focused: boolean, - index: number, - tintColor?: string, -}; -declare type DrawerItem = { - route: NavigationRoute, - focused: boolean, -}; /** * Drawer Navigator From a7e72529b207c1529dd2ad7707f154ac0e359b86 Mon Sep 17 00:00:00 2001 From: robbywashere Date: Fri, 16 Nov 2018 22:16:01 -0500 Subject: [PATCH 089/836] Update to types/recompose package withStateHandler to give stateUpdaters typed arguments rather than --- types/recompose/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index 6f61888954..edb8ef9415 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -151,7 +151,7 @@ declare module 'recompose' { [updaterName: string]: StateHandler; }; type StateUpdaters = { - [updaterName in keyof TUpdaters]: (state: TState, props: TOutter) => StateHandler; + [updaterName in keyof TUpdaters]: (state: TState, props: TOutter) => TUpdaters[updaterName]; }; export function withStateHandlers, TOutter = {}>( createProps: TState | mapper, From cd38ae33dea2dd375ae01a31399d85eeb1f219a6 Mon Sep 17 00:00:00 2001 From: islishude Date: Sat, 17 Nov 2018 12:41:11 +0800 Subject: [PATCH 090/836] [node]: add props to repl.Context --- types/node/index.d.ts | 4 +++- types/node/node-tests.ts | 6 ++++++ types/node/v9/index.d.ts | 4 +++- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index fdda9e948a..221dd5baad 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -2501,7 +2501,9 @@ declare module "readline" { } declare module "vm" { - interface Context { } + interface Context { + [key: string]: any; + } interface BaseOptions { /** * Specifies the filename used in stack traces produced by this script. diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 20159c70d9..0ae3866a8a 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -3675,6 +3675,12 @@ import * as p from "process"; function test() { throw new repl.Recoverable(new Error("test")); } + + _server.context.key0 = 1; + _server.context.key1 = "string"; + _server.context.key2 = true; + _server.context.key3 = []; + _server.context.key4 = {}; } } diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 4678c59c74..b620ac9ce1 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -2390,7 +2390,9 @@ declare module "readline" { } declare module "vm" { - export interface Context { } + export interface Context { + [key: string]: any; + } export interface ScriptOptions { filename?: string; lineOffset?: number; From 8e0be6712ba2c19b495ffc32b8ffb37ff8eb21f6 Mon Sep 17 00:00:00 2001 From: denis Date: Sat, 17 Nov 2018 11:05:38 +0100 Subject: [PATCH 091/836] Fix no-angle-bracket-type-assertion --- types/d3-brush/d3-brush-tests.ts | 2 +- types/d3-drag/d3-drag-tests.ts | 6 +++--- types/d3-selection/d3-selection-tests.ts | 2 +- types/d3-selection/tslint.json | 1 - types/d3-zoom/d3-zoom-tests.ts | 8 ++++---- types/d3-zoom/tslint.json | 1 - types/d3kit/d3kit-tests.ts | 4 ++-- 7 files changed, 11 insertions(+), 13 deletions(-) diff --git a/types/d3-brush/d3-brush-tests.ts b/types/d3-brush/d3-brush-tests.ts index dc2c9a0dc8..c5a287b562 100644 --- a/types/d3-brush/d3-brush-tests.ts +++ b/types/d3-brush/d3-brush-tests.ts @@ -48,7 +48,7 @@ brush = brush.extent(function(d, i, group) { // chainable brush = brush.filter(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - const e = > event; + const e = event as d3Brush.D3BrushEvent; console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement return e.sourceEvent.type !== 'zoom' || !d.filterZoomEvent; // datum type is BrushDatum (as propagated to SVGGElement with brush event attached) diff --git a/types/d3-drag/d3-drag-tests.ts b/types/d3-drag/d3-drag-tests.ts index cf5428e7e2..5e376c003b 100644 --- a/types/d3-drag/d3-drag-tests.ts +++ b/types/d3-drag/d3-drag-tests.ts @@ -134,7 +134,7 @@ touchableFn = circleDrag.touchable(); circleCustomDrag.subject(function(d, i, g) { // Cast event type for completeness, otherwise event is of type any. - const e = > event; + const e = event as d3Drag.D3DragEvent; const that: SVGCircleElement = this; const datum: CircleDatum = d; const index: number = i; @@ -163,14 +163,14 @@ subjectAccessor = circleCustomDrag.subject(); function dragstarted(this: SVGCircleElement, d: CircleDatum) { // cast d3 event to drag event. Otherwise, d3 event is currently defined as type 'any' - const e = > event; + const e = event as d3Drag.D3DragEvent; e.sourceEvent.stopPropagation(); select(this).classed('dragging', true); } function dragged(this: SVGCircleElement, d: CircleDatum) { // cast d3 event to drag event. Otherwise, d3 event is currently defined as type 'any' - const e = > event; + const e = event as d3Drag.D3DragEvent; select(this).attr('cx', d.x = e.x).attr('cy', d.y = e.y); } diff --git a/types/d3-selection/d3-selection-tests.ts b/types/d3-selection/d3-selection-tests.ts index bafc1aeb11..092e8bfa5a 100644 --- a/types/d3-selection/d3-selection-tests.ts +++ b/types/d3-selection/d3-selection-tests.ts @@ -1060,7 +1060,7 @@ interface SuccessEvent { const successEvent = { type: 'wonEuro2016', team: 'Island' }; function customListener(this: HTMLBodyElement | null, finalOpponent: string): string { - const e = d3Selection.event; + const e = d3Selection.event as SuccessEvent; return `${e.team} defeated ${finalOpponent} in the EURO 2016 Cup. Who would have thought!!!`; } diff --git a/types/d3-selection/tslint.json b/types/d3-selection/tslint.json index c89636b4b7..26ee29cf50 100644 --- a/types/d3-selection/tslint.json +++ b/types/d3-selection/tslint.json @@ -2,7 +2,6 @@ "extends": "dtslint/dt.json", "rules": { // TODO - "no-angle-bracket-type-assertion": false, "no-this-assignment": false, "unified-signatures": false, "no-unnecessary-generics": false diff --git a/types/d3-zoom/d3-zoom-tests.ts b/types/d3-zoom/d3-zoom-tests.ts index 19a16930d6..c758e83448 100644 --- a/types/d3-zoom/d3-zoom-tests.ts +++ b/types/d3-zoom/d3-zoom-tests.ts @@ -91,7 +91,7 @@ interface GroupDatum { function zoomedCanvas(this: HTMLCanvasElement, d: CanvasDatum) { // Cast d3 event to D3ZoomEvent to be used in zoom event handler - const e = > event; + const e = event as d3Zoom.D3ZoomEvent; if (context) { context.save(); context.clearRect(0, 0, this.width, this.height); // this element @@ -112,7 +112,7 @@ canvasZoom = d3Zoom.zoom() function zoomedSVGOverlay(this: SVGRectElement) { // Cast d3 event to D3ZoomEvent to be used in zoom event handler - const e = > event; + const e = event as d3Zoom.D3ZoomEvent; g.attr('transform', e.transform.toString()); } @@ -146,7 +146,7 @@ constraintFn = svgZoom.constrain(); // chainable svgZoom = svgZoom.filter(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - const e = > event; + const e = event as d3Zoom.D3ZoomEvent; console.log('Overlay Rectangle width: ', this.width.baseVal.value); // this typing is SVGRectElement return e.sourceEvent.type !== 'brush' || !d.filterBrushEvent; // datum type is SVGDatum (as propagated to SVGRectElement with zoom event attached) @@ -178,7 +178,7 @@ touchableFn = svgZoom.touchable(); // chainable svgZoom = svgZoom.wheelDelta(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - const e = event; + const e = event as WheelEvent; const that: SVGRectElement = this; const datum: SVGDatum = d; const index: number = i; diff --git a/types/d3-zoom/tslint.json b/types/d3-zoom/tslint.json index c89636b4b7..26ee29cf50 100644 --- a/types/d3-zoom/tslint.json +++ b/types/d3-zoom/tslint.json @@ -2,7 +2,6 @@ "extends": "dtslint/dt.json", "rules": { // TODO - "no-angle-bracket-type-assertion": false, "no-this-assignment": false, "unified-signatures": false, "no-unnecessary-generics": false diff --git a/types/d3kit/d3kit-tests.ts b/types/d3kit/d3kit-tests.ts index ec3b2de1ce..705b9fcc59 100644 --- a/types/d3kit/d3kit-tests.ts +++ b/types/d3kit/d3kit-tests.ts @@ -304,7 +304,7 @@ function test_svg_chart() { * Test plate functions */ plate = new d3kit.SvgPlate(); - plate = chart.addPlate('a-plate', plate, true); // with doNotAppend + plate = chart.addPlate('a-plate', plate, true) as d3kit.SvgPlate; // with doNotAppend chart = chart.addPlate('a-plate', plate); // without doNotAppend chart = chart.removePlate('a-plate'); @@ -381,7 +381,7 @@ function test_hybrid_chart() { * Test plate functions */ plate = new d3kit.SvgPlate(); - plate = chart.addPlate('a-plate', plate, true); // with doNotAppend + plate = chart.addPlate('a-plate', plate, true) as d3kit.SvgPlate; // with doNotAppend chart = chart.addPlate('a-plate', plate); // without doNotAppend chart = chart.removePlate('a-plate'); From 25c1531d1cf4b4e6ebc0d708b65529b7be89d0a9 Mon Sep 17 00:00:00 2001 From: loveky Date: Sat, 17 Nov 2018 23:08:51 +0800 Subject: [PATCH 092/836] Update definition for webpack-chain to match version 5.0 --- types/webpack-chain/index.d.ts | 4 ++-- types/webpack-chain/webpack-chain-tests.ts | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/types/webpack-chain/index.d.ts b/types/webpack-chain/index.d.ts index 033ef9951f..d821d13417 100644 --- a/types/webpack-chain/index.d.ts +++ b/types/webpack-chain/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for webpack-chain 4.8 +// Type definitions for webpack-chain 5.0 // Project: https://github.com/mozilla-neutrino/webpack-chain // Definitions by: Eirikur Nilsson , Paul Sachs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -209,7 +209,7 @@ declare namespace Config { flagIncludedChunks(value: boolean): this; mergeDuplicateChunks(value: boolean): this; minimize(value: boolean): this; - minimizer(value: webpack.Plugin[]): this; + minimizer(name: string): Plugin; namedChunks(value: boolean): this; namedModules(value: boolean): this; nodeEnv(value: boolean | string): this; diff --git a/types/webpack-chain/webpack-chain-tests.ts b/types/webpack-chain/webpack-chain-tests.ts index f1d0daa5e2..b655df07ea 100644 --- a/types/webpack-chain/webpack-chain-tests.ts +++ b/types/webpack-chain/webpack-chain-tests.ts @@ -173,7 +173,9 @@ config .flagIncludedChunks(true) .mergeDuplicateChunks(true) .minimize(true) - .minimizer([]) + .minimizer('foo') + .use(webpack.DefinePlugin) + .end() .namedChunks(true) .namedModules(true) .nodeEnv(true) From 1acadfde0d9c5f18226c73c45b4c80a1a39c501a Mon Sep 17 00:00:00 2001 From: Jeroen Vervaeke Date: Sat, 17 Nov 2018 16:43:21 +0100 Subject: [PATCH 093/836] Removed trailing whitespace --- types/react-navigation/react-navigation-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-navigation/react-navigation-tests.tsx b/types/react-navigation/react-navigation-tests.tsx index 43cadcde76..fe6a939a61 100644 --- a/types/react-navigation/react-navigation-tests.tsx +++ b/types/react-navigation/react-navigation-tests.tsx @@ -336,10 +336,10 @@ const BasicDrawerNavigator = createDrawerNavigator( const Drawer = (props: DrawerItemsProps) => ( ); - + const DrawerNavigatorWithCustomDrawer = createDrawerNavigator( routeConfigMap, - { + { contentComponent: Drawer, } ); From c6b16d03af70d28b26eccdf2a452984f14d10b5f Mon Sep 17 00:00:00 2001 From: Shuhei Tsukaomoto Date: Sun, 18 Nov 2018 16:24:48 +0900 Subject: [PATCH 094/836] update: add MjolnirEvent. --- types/react-map-gl/index.d.ts | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/types/react-map-gl/index.d.ts b/types/react-map-gl/index.d.ts index 6a215225d7..7f59244154 100644 --- a/types/react-map-gl/index.d.ts +++ b/types/react-map-gl/index.d.ts @@ -78,6 +78,22 @@ export interface MapEvent { features: Array<{}>; } +export interface MjolnirEvent { + type: string; + offsetCenter: {x: number, y: number}; + deltaX: number; + deltaY: number; + delta: number; + scale: number; + rotation: number; + pointerType: string; + metaKey: boolean; + rightButton: boolean; + stopPropagation: () => void; + preventDefault: () => void; + srcEvent: any; +} + export interface Center { x: number; y: number; @@ -201,9 +217,9 @@ export interface MarkerProps extends BaseControlProps { latitude: number; offsetLeft?: number; offsetTop?: number; - onDrag: (event: any) => void; - onDragStart: (event: any) => void; - onDragEnd: (event: any) => void; + onDrag: (event: MjolnirEvent) => void; + onDragStart: (event: MjolnirEvent) => void; + onDragEnd: (event: MjolnirEvent) => void; } export class Marker extends BaseControl {} From 43ced3fe679143e0e60eb966d1d03db48991925a Mon Sep 17 00:00:00 2001 From: Fabio Berta Date: Sun, 18 Nov 2018 12:58:37 +0100 Subject: [PATCH 095/836] update for 4.0 --- types/react-map-gl/index.d.ts | 269 ++++++++++++---------- types/react-map-gl/react-map-gl-tests.tsx | 18 +- 2 files changed, 150 insertions(+), 137 deletions(-) diff --git a/types/react-map-gl/index.d.ts b/types/react-map-gl/index.d.ts index 7f59244154..4522ddf729 100644 --- a/types/react-map-gl/index.d.ts +++ b/types/react-map-gl/index.d.ts @@ -9,12 +9,13 @@ import * as React from 'react'; import * as MapboxGL from 'mapbox-gl'; import * as GeoJSON from 'geojson'; -export interface Viewport { +export interface ViewState { latitude: number; longitude: number; zoom: number; bearing?: number; pitch?: number; + altitude?: number; } export interface MapError { @@ -31,31 +32,37 @@ export interface MapRequest { credentials?: string; } -export interface MapboxProps extends Partial { - container?: {}; +export interface MapboxProps extends Partial { + container?: object; + gl?: object; mapboxApiAccessToken?: string; attributionControl?: boolean; preserveDrawingBuffer?: boolean; + reuseMaps?: boolean; + transformRequest?: (url?: string, resourceType?: string) => MapRequest; + mapOptions?: object; + mapStyle?: string | object; + visible?: boolean; onLoad?: () => void; onError?: (e: MapError) => void; - reuseMaps?: boolean; reuseMap?: boolean; - transformRequest?: (url?: string, resourceType?: string) => MapRequest; - - mapStyle?: string | {}; - - width: number; - height: number; - - viewState?: Viewport; - - altitude?: number; // Note: Non-public API, see https://github.com/mapbox/mapbox-gl-js/issues/1137 + width: number | string; + height: number | string; + viewState?: ViewState; } export interface StaticMapProps extends MapboxProps { + onResize?: (dimensions: { width: number; height: number }) => void; preventStyleDiffing?: boolean; - visible?: boolean; + disableTokenWarning?: boolean; className?: string; + style?: object; + visibilityConstraints?: { + minZoom?: number; + maxZoom?: number; + minPitch?: number; + maxPitch?: number; + }; } export interface QueryRenderedFeaturesParams { @@ -68,30 +75,71 @@ export class StaticMap extends React.Component { queryRenderedFeatures(geometry?: MapboxGL.PointLike | MapboxGL.PointLike[], parameters?: QueryRenderedFeaturesParams): Array>; } -export interface InteractiveMapState { +export interface ExtraState { isDragging: boolean; isHovering: boolean; } -export interface MapEvent { - lngLat: [number, number]; - features: Array<{}>; +export interface PositionInput { + pos: [number, number]; } -export interface MjolnirEvent { - type: string; - offsetCenter: {x: number, y: number}; - deltaX: number; - deltaY: number; - delta: number; - scale: number; - rotation: number; - pointerType: string; - metaKey: boolean; - rightButton: boolean; - stopPropagation: () => void; - preventDefault: () => void; - srcEvent: any; +export interface MapControllerOptions { + onViewportChange?: (viewState: ViewState) => void; + onStateChange?: (state: MapState) => void; + eventManager?: any; + isInteractive: boolean; + scrollZoom?: boolean; + dragPan?: boolean; + dragRotate?: boolean; + doubleClickZoom?: boolean; + touchZoom?: boolean; + touchRotate?: boolean; + keyboard?: boolean; +} + +export interface ViewportProps { + width: number; + height: number; + latitude: number; + longitude: number; + zoom: number; + bearing: number; + pitch: number; + altitude: number; + maxZoom: number; + minZoom: number; + maxPitch: number; + minPitch: number; + transitionDuration?: number; + transitionInterpolator?: TransitionInterpolator; + transitionInterruption?: TRANSITION_EVENTS; + transitionEasing?: EasingFunction; +} + +export interface InteractiveState { + startPanLngLat?: [number, number]; + startZoomLngLat?: [number, number]; + startBearing?: number; + startPitch?: number; + startZoom?: number; +} + +export type MapStateProps = Partial; + +export class MapState { + constructor(props: MapStateProps); + getViewportProps(): ViewportProps; + getInteractiveState(): InteractiveState; + panStart(input: PositionInput): MapState; + pan(input: PositionInput & { startPos?: [number, number] }): MapState; + panEnd(): MapState; + rotateStart(input: PositionInput): MapState; + rotate(input: { deltaScaleX?: number; deltaScaleY?: number }): MapState; + rotateEnd(): MapState; + zoomStart(input: PositionInput): MapState; + zoom(input: PositionInput & { scale: number; startPos?: [number, number] }): MapState; + zoomEnd(): MapState; } export interface Center { @@ -113,11 +161,30 @@ export interface MapControlEvent { delta?: number; } -export interface BaseMapControls { +export interface BaseMapController { events: string[]; handleEvent(event: MapControlEvent): void; } +export class MapController implements BaseMapController { + events: string[]; + handleEvent(event: MapControlEvent): void; + getMapState(overrides: Partial): MapState; + setOptions(options: MapControllerOptions): void; + setState(newState: MapState): void; + updateViewport(newMapState: MapState, extraProps: any, extraState: ExtraState): void; +} + +export interface PointerEvent { + type: string; + point: [number, number]; + lngLat: [number, number]; + target: any; + srcEvent: any; + // backward compatibility: v3 interface + features: any[]; +} + export type EasingFunction = (t: number) => number; export enum TRANSITION_EVENTS { @@ -135,7 +202,7 @@ export class LinearInterpolator extends TransitionInterpolator { export class FlyToInterpolator extends TransitionInterpolator {} export interface ViewStateChangeInfo { - viewState: Viewport; + viewState: ViewState; } export interface InteractiveMapProps extends StaticMapProps { @@ -143,10 +210,9 @@ export interface InteractiveMapProps extends StaticMapProps { minZoom?: number; maxPitch?: number; minPitch?: number; - - onViewportChange?: (viewport: Viewport) => void; onViewStateChange?: (info: ViewStateChangeInfo) => void; - + onViewportChange?: (viewState: ViewState) => void; + onInteractionStateChange?: (state: ExtraState) => void; transitionDuration?: number; transitionInterpolator?: TransitionInterpolator; transitionInterruption?: TRANSITION_EVENTS; @@ -154,7 +220,6 @@ export interface InteractiveMapProps extends StaticMapProps { onTransitionStart?: () => void; onTransitionInterrupt?: () => void; onTransitionEnd?: () => void; - scrollZoom?: boolean; dragPan?: boolean; dragRotate?: boolean; @@ -162,37 +227,25 @@ export interface InteractiveMapProps extends StaticMapProps { touchZoom?: boolean; touchRotate?: boolean; keyboard?: boolean; - - onHover?: (event: MapEvent) => void; - onClick?: (event: MapEvent) => void; - onDblClick?: (event: MapEvent) => void; - onMouseDown?: (event: MapEvent) => void; - onMouseMove?: (event: MapEvent) => void; - onMouseUp?: (event: MapEvent) => void; - onTouchStart?: (event: MapEvent) => void; - onTouchMove?: (event: MapEvent) => void; - onTouchEnd?: (event: MapEvent) => void; - onMouseEnter?: (event: MapEvent) => void; - onMouseLeave?: (event: MapEvent) => void; - onWheel?: (event: MapEvent) => void; - onMouseOut?: (event: MapEvent) => void; - - onContextMenu?: (event: MapEvent) => void; - + onHover?: (event: PointerEvent) => void; + onClick?: (event: PointerEvent) => void; + onDblClick?: (event: PointerEvent) => void; + onContextMenu?: (event: PointerEvent) => void; + onMouseDown?: (event: PointerEvent) => void; + onMouseMove?: (event: PointerEvent) => void; + onMouseUp?: (event: PointerEvent) => void; + onTouchStart?: (event: PointerEvent) => void; + onTouchMove?: (event: PointerEvent) => void; + onTouchEnd?: (event: PointerEvent) => void; + onMouseEnter?: (event: PointerEvent) => void; + onMouseLeave?: (event: PointerEvent) => void; + onMouseOut?: (event: PointerEvent) => void; + onWheel?: (event: PointerEvent) => void; touchAction?: string; - clickRadius?: number; - - getCursor?: (state: InteractiveMapState) => void; - - visibilityConstraints?: { - minZoom?: number; - maxZoom?: number; - minPitch?: number; - maxPitch?: number; - }; - - mapControls?: BaseMapControls; + interactiveLayerIds?: string[]; + getCursor?: (state: ExtraState) => void; + controller?: MapController; } export class InteractiveMap extends React.Component { @@ -211,15 +264,21 @@ export interface BaseControlProps { export class BaseControl extends React.Component {} +export interface DragEvent { + lngLat: [number, number]; + [key: string]: any; +} + export interface MarkerProps extends BaseControlProps { className?: string; longitude: number; latitude: number; offsetLeft?: number; offsetTop?: number; - onDrag: (event: MjolnirEvent) => void; - onDragStart: (event: MjolnirEvent) => void; - onDragEnd: (event: MjolnirEvent) => void; + draggable?: boolean; + onDrag?: (event: DragEvent) => void; + onDragEnd?: (event: DragEvent) => void; + onDragStart?: (event: DragEvent) => void; } export class Marker extends BaseControl {} @@ -228,6 +287,7 @@ export interface PopupProps extends BaseControlProps { className?: string; longitude: number; latitude: number; + altitude?: number; offsetLeft?: number; offsetTop?: number; tipSize?: number; @@ -244,13 +304,22 @@ export class Popup extends BaseControl {} export interface NavigationControlProps extends BaseControlProps { className?: string; onViewStateChange: (info: ViewStateChangeInfo) => void; - onViewportChange: (viewport: Viewport) => void; + onViewportChange: (viewport: ViewState) => void; showCompass?: boolean; showZoom?: boolean; } export class NavigationControl extends BaseControl {} +export interface DraggableControlProps extends BaseControlProps { + draggable?: boolean; + onDrag?: (event: DragEvent) => void; + onDragEnd?: (event: DragEvent) => void; + onDragStart?: (event: DragEvent) => void; +} + +export class DraggableControl extends BaseControl {} + export interface HTMLRedrawOptions { width: number; height: number; @@ -283,59 +352,3 @@ export interface SVGOverlayProps extends BaseControlProps { } export class SVGOverlay extends BaseControl {} - -export namespace experimental { - interface Options { - // TODO(deprecate): remove this when `touchZoomRotate` gets deprecated - touchZoomRotate?: boolean; - - onViewStateChange?: (info: ViewStateChangeInfo) => void; - onViewportChange?: (viewport: Viewport) => void; - onStateChange?: (state: MapState) => void; - eventManager?: any; - scrollZoom?: boolean; - dragPan?: boolean; - dragRotate?: boolean; - doubleClickZoom?: boolean; - touchZoom?: boolean; - touchRotate?: boolean; - keyboard?: boolean; - } - - class MapState implements Viewport { - width: number; - height: number; - latitude: number; - longitude: number; - zoom: number; - bearing?: number; - pitch?: number; - altitude?: number; - - maxZoom?: number; - minZoom?: number; - maxPitch?: number; - minPitch?: number; - - transitionDuration?: number; - transitionInterpolator?: TransitionInterpolator; - transitionInterruption?: TRANSITION_EVENTS; - transitionEasing?: EasingFunction; - - startPanLngLat?: [number, number]; - startZoomLngLat?: [number, number]; - startBearing?: number; - startPitch?: number; - startZoom?: number; - } - - class MapControls implements BaseMapControls { - events: string[]; - - handleEvent(event: MapControlEvent): void; - getMapState(overrides: Partial): MapState; - setOptions(options: Options): void; - setState(newState: MapState): void; - updateViewport(newMapState: MapState, extraProps: any, extraState: InteractiveMapState): void; - } -} diff --git a/types/react-map-gl/react-map-gl-tests.tsx b/types/react-map-gl/react-map-gl-tests.tsx index 7eb5bfd590..c9024287c9 100644 --- a/types/react-map-gl/react-map-gl-tests.tsx +++ b/types/react-map-gl/react-map-gl-tests.tsx @@ -1,6 +1,6 @@ import * as React from "react"; import { - Viewport, + ViewState, InteractiveMap, CanvasOverlay, SVGOverlay, @@ -13,12 +13,12 @@ import { import * as MapboxGL from "mapbox-gl"; interface State { - viewport: Viewport; + viewState: ViewState; } class MyMap extends React.Component<{}, State> { readonly state: State = { - viewport: { + viewState: { bearing: 0, latitude: 0, longitude: 0, @@ -31,14 +31,14 @@ class MyMap extends React.Component<{}, State> { return (

{ + redraw={opts => { const { ctx, height, @@ -51,7 +51,7 @@ class MyMap extends React.Component<{}, State> { }} /> {}} + redraw={opts => {}} captureScroll={true} captureDrag={true} captureClick={true} @@ -61,7 +61,7 @@ class MyMap extends React.Component<{}, State> { redraw={() => {}} /> { + redraw={opts => { const { height, project, @@ -79,7 +79,7 @@ class MyMap extends React.Component<{}, State> { redraw={() => {}} /> { + redraw={opts => { const { height, project, @@ -98,7 +98,7 @@ class MyMap extends React.Component<{}, State> { /> Date: Sun, 18 Nov 2018 21:55:59 +0100 Subject: [PATCH 096/836] types for dinero.js --- types/dinero.js/dinero.js-tests.ts | 71 +++++++++++++++++++++++++++ types/dinero.js/index.d.ts | 78 ++++++++++++++++++++++++++++++ types/dinero.js/tsconfig.json | 23 +++++++++ types/dinero.js/tslint.json | 1 + 4 files changed, 173 insertions(+) create mode 100644 types/dinero.js/dinero.js-tests.ts create mode 100644 types/dinero.js/index.d.ts create mode 100644 types/dinero.js/tsconfig.json create mode 100644 types/dinero.js/tslint.json diff --git a/types/dinero.js/dinero.js-tests.ts b/types/dinero.js/dinero.js-tests.ts new file mode 100644 index 0000000000..803184c3db --- /dev/null +++ b/types/dinero.js/dinero.js-tests.ts @@ -0,0 +1,71 @@ +import Dinero = require("dinero.js"); + +Dinero.globalExchangeRatesApi = { + endpoint: "https://yourexchangerates.api/latest?base={{from}}", + propertyPath: "data.rates.{{to}}", + headers: { + "user-key": "xxxxxxxxx", + }, +}; +Dinero.globalExchangeRatesApi = { + endpoint: "https://yourexchangerates.api/latest?base={{from}}", + propertyPath: "data.rates.{{to}}", + roundingMode: "HALF_UP", +}; + +Dinero(); +Dinero({ amount: 1 }); +Dinero({ currency: "USD" }); +Dinero({ precision: 2 }); + +let number: number; +let string: string; +let boolean: boolean; + +let dinero: Dinero.Dinero = Dinero(); +let dineroArr: Dinero.Dinero[]; +let dineroObject: Dinero.DineroObject; + +number = dinero.getAmount(); +string = dinero.getCurrency(); +string = dinero.setLocale("fr-FR").getLocale(); +number = dinero.convertPrecision(4).getPrecision(); +dinero = dinero.add(Dinero({ amount: 104545, precision: 4 })); +dinero = dinero.subtract(Dinero({ amount: 104545, precision: 4 })); +dinero = dinero.multiply(2.00125); +dinero = dinero.multiply(2.00125, "HALF_UP"); +dinero = dinero.divide(2); +dinero = dinero.divide(2, "HALF_UP"); +dinero = dinero.percentage(50); +dineroArr = dinero.allocate([50, 50]); +dinero.convert("EUR").then(d => (dinero = d)); +dinero.convert("XBT", { + endpoint: "https://yourexchangerates.api/latest?base={{from}}", + propertyPath: "data.rates.{{to}}", + headers: { + "user-key": "xxxxxxxxx", + }, + roundingMode: "HALF_UP", +}); +boolean = dinero.equalsTo(Dinero({ amount: 500, currency: "EUR" })); +boolean = dinero.lessThan(Dinero({ amount: 800 })); +boolean = dinero.lessThanOrEqual(Dinero({ amount: 800 })); +boolean = dinero.greaterThan(Dinero({ amount: 800 })); +boolean = dinero.greaterThanOrEqual(Dinero({ amount: 800 })); +boolean = dinero.isZero(); +boolean = dinero.isPositive(); +boolean = dinero.isNegative(); +boolean = dinero.hasSubUnits(); +boolean = dinero.hasCents(); +boolean = dinero.hasSameCurrency(Dinero({ amount: 1000, currency: "EUR" })); +boolean = dinero.hasSameAmount(Dinero({ amount: 1000, currency: "EUR" })); +string = dinero.toFormat("0,0 dollar"); +string = dinero.toFormat("0,0 dollar", "HALF_EVEN"); +number = dinero.toUnit(); +number = dinero.toRoundedUnit(1); +number = dinero.toRoundedUnit(1, "HALF_EVEN"); +dineroObject = dinero.toObject(); +dineroArr = Dinero.normalizePrecision([ + Dinero({ amount: 100, precision: 2 }), + Dinero({ amount: 1000, precision: 3 }), +]); diff --git a/types/dinero.js/index.d.ts b/types/dinero.js/index.d.ts new file mode 100644 index 0000000000..82a5026380 --- /dev/null +++ b/types/dinero.js/index.d.ts @@ -0,0 +1,78 @@ +// Type definitions for dinero.js 1.4 +// Project: https://sarahdayan.github.io/dinero.js +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export as namespace Dinero; + +export = DineroFactory; + +declare function DineroFactory(options?: Dinero.Options): DineroFactory.Dinero; + +declare namespace DineroFactory { + let globalExchangeRatesApi: ExchangeRatesApiOptions; + function normalizePrecision(objects: Dinero[]): Dinero[]; + + interface Options { + amount?: number; + currency?: string; + precision?: number; + } + + interface Dinero { + getAmount(): number; + getCurrency(): string; + getLocale(): string; + setLocale(newLocale: string): Dinero; + getPrecision(): number; + convertPrecision(newPrecision: number): Dinero; + add(addend: Dinero): Dinero; + subtract(subtrahend: Dinero): Dinero; + multiply(multiplier: number, roundingMode?: RoundingMode): Dinero; + divide(divisor: number, roundingMode?: RoundingMode): Dinero; + percentage(percentage: number): Dinero; + allocate(ratios: number[]): Dinero[]; + convert(currency: string, options?: ExchangeRatesApiOptions): Promise; + equalsTo(comparator: Dinero): boolean; + lessThan(comparator: Dinero): boolean; + lessThanOrEqual(comparator: Dinero): boolean; + greaterThan(comparator: Dinero): boolean; + greaterThanOrEqual(comparator: Dinero): boolean; + isZero(): boolean; + isPositive(): boolean; + isNegative(): boolean; + hasSubUnits(): boolean; + /** + * @deprecated since version 2.0 + */ + hasCents(): boolean; + hasSameCurrency(comparator: Dinero): boolean; + hasSameAmount(comparator: Dinero): boolean; + toFormat(format?: string, roundingMode?: RoundingMode): string; + toUnit(): number; + toRoundedUnit(digits: number, roundingMode?: RoundingMode): number; + toObject(): DineroObject; + } + + type RoundingMode = + | "HALF_ODD" + | "HALF_EVEN" + | "HALF_UP" + | "HALF_DOWN" + | "HALF_TOWARDS_ZERO" + | "HALF_AWAY_FROM_ZERO"; + + interface ExchangeRatesApiOptions { + endpoint: string; + propertyPath: string; + headers?: { [header: string]: string }; + roundingMode?: RoundingMode; + } + + interface DineroObject { + amount: number; + currency: string; + precision: number; + } +} diff --git a/types/dinero.js/tsconfig.json b/types/dinero.js/tsconfig.json new file mode 100644 index 0000000000..2b306e0676 --- /dev/null +++ b/types/dinero.js/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", + "dinero.js-tests.ts" + ] +} diff --git a/types/dinero.js/tslint.json b/types/dinero.js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dinero.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 67b864b0bd89d3ffd1b89d75ccdc5c0f8b05149f Mon Sep 17 00:00:00 2001 From: islishude Date: Mon, 19 Nov 2018 11:09:15 +0800 Subject: [PATCH 097/836] chore: styling code --- types/node/index.d.ts | 2 +- types/node/node-tests.ts | 10 +++++----- types/node/v9/index.d.ts | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 221dd5baad..66c319c895 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -2501,7 +2501,7 @@ declare module "readline" { } declare module "vm" { - interface Context { + interface Context { [key: string]: any; } interface BaseOptions { diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 0ae3866a8a..7e3c491802 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -3676,11 +3676,11 @@ import * as p from "process"; throw new repl.Recoverable(new Error("test")); } - _server.context.key0 = 1; - _server.context.key1 = "string"; - _server.context.key2 = true; - _server.context.key3 = []; - _server.context.key4 = {}; + _server.context['key0'] = 1; + _server.context['key1'] = ""; + _server.context['key2'] = true; + _server.context['key3'] = []; + _server.context['key4'] = {}; } } diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index b620ac9ce1..3660d87725 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -2390,7 +2390,7 @@ declare module "readline" { } declare module "vm" { - export interface Context { + export interface Context { [key: string]: any; } export interface ScriptOptions { From a0b3d80a77fe1ad8f136388e17d117d70081911f Mon Sep 17 00:00:00 2001 From: Jan Bevers Date: Mon, 19 Nov 2018 08:54:51 +0100 Subject: [PATCH 098/836] [react-big-calendar] Added props declartion for Toolbar and Eventwrapper components --- types/react-big-calendar/index.d.ts | 62 +++++++++++++++---- .../react-big-calendar-tests.tsx | 28 ++++++++- 2 files changed, 77 insertions(+), 13 deletions(-) diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index bbfd7047ec..9d9b62881c 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -5,14 +5,23 @@ // Krzysztof Bezrąk // Sebastian Silbermann // Paul Potsides +// janb87 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { Validator } from 'prop-types'; import * as React from 'react'; +export type DayPropGetter = (date: Date) => { className?: string, style?: object }; +export type EventPropGetter = (event: T, start: stringOrDate, end: stringOrDate, isSelected: boolean) => { className?: string, style?: React.CSSProperties }; +export type SlotPropGetter = (date: Date) => { className?: string, style?: object }; export type stringOrDate = string | Date; export type ViewKey = 'MONTH' | 'WEEK' | 'WORK_WEEK' | 'DAY' | 'AGENDA'; export type View = 'month' | 'week' | 'work_week' | 'day' | 'agenda'; +export type Views = View[] | { + month: boolean | React.SFC | React.Component, + week: boolean | React.SFC | React.Component, + myweek: boolean | React.SFC | React.Component, +}; export type Navigate = 'PREV' | 'NEXT' | 'TODAY' | 'DATE'; export type Event = object; @@ -70,7 +79,7 @@ export interface Formats { /** * Toolbar header format for the Agenda view, e.g. "4/1/2015 — 5/1/2015" */ - agendaHeaderFormat?: DateFormat; + agendaHeaderFormat?: DateRangeFormatFunction; /** * A time range format for selecting time slots, e.g "8:00am — 2:00pm" @@ -105,14 +114,14 @@ export interface HeaderProps { export interface Components { event?: React.SFC | React.Component | React.ComponentClass | JSX.Element; - eventWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + eventWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dayWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dateCellWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; /** * component used as a header for each column in the TimeGridHeader */ header?: React.ComponentType; - toolbar?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + toolbar?: React.SFC | React.Component | React.ComponentClass | JSX.Element; agenda?: { date?: React.SFC | React.Component | React.ComponentClass | JSX.Element; time?: React.SFC | React.Component | React.ComponentClass | JSX.Element; @@ -133,6 +142,41 @@ export interface Components { }; } +export interface ToolbarProps { + date: Date; + view: View; + views: Views; + label: string; + localizer: { messages: Messages }; + onNavigate: (navigate: Navigate, date?: Date) => void; + onView: (view: View) => void; + children?: React.ReactNode; +} + +export interface EventWrapperProps { + style?: React.CSSProperties & { xOffset: number }; + className: string; + event: T; + isRtl: boolean; + getters: { + eventProp?: EventPropGetter; + slotProp?: SlotPropGetter; + dayProp?: DayPropGetter; + }; + onClick: (e: React.MouseEvent) => void; + onDoubleClick: (e: React.MouseEvent) => void; + accessors: { + title?: (event: T) => string; + tooltip?: (event: T) => string; + end?: (event: T) => Date; + start?: (event: T) => Date; + }; + selected: boolean; + label: string; + continuesEarlier: boolean; + continuesLater: boolean; +} + export interface Messages { date?: string; time?: string; @@ -186,11 +230,7 @@ export interface BigCalendarProps extends React.Props) => void; onSelecting?: (range: { start: stringOrDate, end: stringOrDate }) => boolean | undefined | null; selected?: any; - views?: View[] | { - month: boolean | React.SFC | React.Component, - week: boolean | React.SFC | React.Component, - myweek: boolean | React.SFC | React.Component, - }; + views?: Views; drilldownView?: View | null; getDrilldownView?: ((targetDate: Date, currentViewName: View, configuredViewNames: View[]) => void) | null; length?: number; @@ -202,9 +242,9 @@ export interface BigCalendarProps extends React.Props { className?: string, style?: React.CSSProperties }; - slotPropGetter?: (date: Date) => { className?: string, style?: object }; - dayPropGetter?: (date: Date) => { className?: string, style?: object }; + eventPropGetter?: EventPropGetter; + slotPropGetter?: SlotPropGetter; + dayPropGetter?: DayPropGetter; showMultiDayTimes?: boolean; min?: stringOrDate; max?: stringOrDate; diff --git a/types/react-big-calendar/react-big-calendar-tests.tsx b/types/react-big-calendar/react-big-calendar-tests.tsx index e1b561901e..321327e8e7 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -1,6 +1,6 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; -import BigCalendar, { BigCalendarProps, Navigate, View, DateRange, DateLocalizer } from "react-big-calendar"; +import BigCalendar, { BigCalendarProps, Navigate, View, DateRange, DateLocalizer, ToolbarProps, EventWrapperProps } from "react-big-calendar"; // Don't want to add this as a dependency, because it is only used for tests. declare const globalize: any; @@ -101,7 +101,9 @@ class CalendarEvent { event: Event, agenda: { event: EventAgenda - } + }, + toolbar: Toolbar, + eventWrapper: EventWrapper, }} dayPropGetter={customDayPropGetter} slotPropGetter={customSlotPropGetter} @@ -172,3 +174,25 @@ function Event(event: any) { ); } + +class EventWrapper extends React.Component { + render() { + const { continuesEarlier, label, accessors = {}, style } = this.props; + return ( +
+
{continuesEarlier}-{label}-{accessors.title && event && accessors.title(event)}}
+
+ ); + } +} + +class Toolbar extends React.Component { + render() { + const { date, label, view } = this.props; + return ( +
+
{date.toJSON()}-{label}-{view}}
+
+ ); + } +} From ead05a22eb89d1a00082c4eb62e8f6393c58399c Mon Sep 17 00:00:00 2001 From: Esteban Ibarra Date: Mon, 19 Nov 2018 08:19:12 -0500 Subject: [PATCH 099/836] Fix children type for react-native-dialog (#1) * Fix children type for react-native-dialog --- types/react-native-dialog/index.d.ts | 4 +++- .../react-native-dialog-tests.tsx | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/types/react-native-dialog/index.d.ts b/types/react-native-dialog/index.d.ts index 10e977f420..14d7458140 100644 --- a/types/react-native-dialog/index.d.ts +++ b/types/react-native-dialog/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for react-native-dialog 4.0 // Project: https://github.com/mmazzarolo/react-native-dialog // Definitions by: MrLuje +// Stack Builders +// Esteban Ibarra // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -32,7 +34,7 @@ interface ButtonProps { interface ContainerProps { blurComponentIOS?: ReactNode; - children: JSX.Element[]; + children: React.ReactNode[]; /** * default: false */ diff --git a/types/react-native-dialog/react-native-dialog-tests.tsx b/types/react-native-dialog/react-native-dialog-tests.tsx index 151ee14af5..544025051c 100644 --- a/types/react-native-dialog/react-native-dialog-tests.tsx +++ b/types/react-native-dialog/react-native-dialog-tests.tsx @@ -2,6 +2,24 @@ import Dialog from "react-native-dialog"; import { createRef, Component } from "react"; class Example extends Component { + dynamicButtons() { + const buttonFunc = () => console.log('click'); + const buttons = [ + { label: 'Button 1', action: buttonFunc }, + { label: 'Button 2', action: buttonFunc }, + ]; + return buttons.map(({ label , action }) => + + ); + } + + singleButton() { + return ( null} />); + } + render() { const ref = createRef(); @@ -23,6 +41,8 @@ class Example extends Component { label="Validate" onPress={() => console.log("test")} /> + {this.dynamicButtons()} + {this.singleButton()} ); } From 1bc50af06d237a0e9dad12339213bf6290383cae Mon Sep 17 00:00:00 2001 From: Adam Binford Date: Mon, 19 Nov 2018 12:01:59 -0500 Subject: [PATCH 100/836] Added types for react-leaflet-markercluster --- types/react-leaflet-markercluster/index.d.ts | 13 ++++++++ .../react-leaflet-markercluster-tests.tsx | 30 +++++++++++++++++++ .../react-leaflet-markercluster/tsconfig.json | 24 +++++++++++++++ types/react-leaflet-markercluster/tslint.json | 1 + 4 files changed, 68 insertions(+) create mode 100644 types/react-leaflet-markercluster/index.d.ts create mode 100644 types/react-leaflet-markercluster/react-leaflet-markercluster-tests.tsx create mode 100644 types/react-leaflet-markercluster/tsconfig.json create mode 100644 types/react-leaflet-markercluster/tslint.json diff --git a/types/react-leaflet-markercluster/index.d.ts b/types/react-leaflet-markercluster/index.d.ts new file mode 100644 index 0000000000..989605f27c --- /dev/null +++ b/types/react-leaflet-markercluster/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for react-leaflet-markercluster 2.0 +// Project: https://github.com/YUzhva/react-leaflet-markercluster +// Definitions by: Adam Binford +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import 'leaflet.markercluster'; +import * as Leaflet from 'leaflet'; +import * as ReactLeaflet from 'react-leaflet'; + +export type MarkerClusterGroupProps = ReactLeaflet.MapLayerProps & Leaflet.MarkerClusterGroupOptions; + +export default class MarkerClusterGroup

extends ReactLeaflet.MapLayer

-​ - -​ - - -``` - */ - namespace: string; - /** - * The last value returned by an event handler that was triggered by this event, unless the value was undefined. - * @see \`{@link https://api.jquery.com/event.result/ }\` - * @since 1.3 - * @example ​ ````Display previous handler's return value -```html - - - - - event.result demo - - - -​ - -

-​ - -​ - - -``` - */ - result: any; /** * The difference in milliseconds between the time the browser created the event and January 1, 1970. * @see \`{@link https://api.jquery.com/event.timeStamp/ }\` @@ -4297,59 +4327,6 @@ $( "a" ).click(function( event ) { ``` */ type: string; - /** - * For key or mouse events, this property indicates the specific key or button that was pressed. - * @see \`{@link https://api.jquery.com/event.which/ }\` - * @since 1.1.3 - * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. - * @example ​ ````Log which key was depressed. -```html - - - - - event.which demo - - - -​ - -
-​ - -​ - - -``` - * @example ​ ````Log which mouse button was depressed. -```html - - - - - event.which demo - - - -​ - -
-​ - -​ - - -``` - */ - which: number; /** * Returns whether event.preventDefault() was ever called on this event object. * @see \`{@link https://api.jquery.com/event.isDefaultPrevented/ }\` @@ -4542,11 +4519,17 @@ $( "p" ).click(function( event ) { stopPropagation(): void; } - // Generic members - interface Event< - TTarget = EventTarget, - TData = null - > { + // #endregion + + /** + * Base type for jQuery events that have been triggered (including events triggered on plain objects). + */ + interface TriggeredEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends Event { /** * The current DOM element within the event bubbling phase. * @see \`{@link https://api.jquery.com/event.currentTarget/ }\` @@ -4557,51 +4540,8 @@ $( "p" ).click(function( event ) { alert( event.currentTarget === this ); // true }); ``` - */ - currentTarget: TTarget; - /** - * An optional object of data passed to an event method when the current executing handler is bound. - * @see \`{@link https://api.jquery.com/event.data/ }\` - * @since 1.1 - * @example ​ ````Within a for loop, pass the value of i to the .on() method so that the current iteration's value is preserved. -```html - - - - - event.data demo - - - -​ - - - - - -​ -
-​ - -​ - - -``` - */ - data: TData; + */ + currentTarget: TCurrentTarget; /** * The element where the currently-called jQuery event handler was attached. * @see \`{@link https://api.jquery.com/event.delegateTarget/ }\` @@ -4612,21 +4552,8 @@ $( ".box" ).on( "click", "button", function( event ) { $( event.delegateTarget ).css( "background-color", "red" ); }); ``` - */ - delegateTarget: TTarget; - originalEvent: _Event; - /** - * The other DOM element involved in the event, if any. - * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` - * @since 1.1.4 - * @example ​ ````On mouseout of anchors, alert the element type being entered. -```javascript -$( "a" ).mouseout(function( event ) { - alert( event.relatedTarget.nodeName ); // "DIV" -}); -``` - */ - relatedTarget: TTarget | null; + */ + delegateTarget: TDelegateTarget; /** * The DOM element that initiated the event. * @see \`{@link https://api.jquery.com/event.target/ }\` @@ -4704,17 +4631,173 @@ $( "ul" ).click( handler ).find( "ul" ).hide(); ``` - */ + */ target: TTarget; + + /** + * An optional object of data passed to an event method when the current executing handler is bound. + * @see \`{@link https://api.jquery.com/event.data/ }\` + * @since 1.1 + * @example ​ ````Within a for loop, pass the value of i to the .on() method so that the current iteration's value is preserved. +```html + + + + + event.data demo + + + +​ + + + + + +​ +
+​ + +​ + + +``` + */ + data: TData; + + /** + * The namespace specified when the event was triggered. + * @see \`{@link https://api.jquery.com/event.namespace/ }\` + * @since 1.4.3 + * @example ​ ````Determine the event namespace used. +```html + + + + + event.namespace demo + + + +​ + +

+​ + +​ + + +``` + */ + namespace?: string; + /** + * The last value returned by an event handler that was triggered by this event, unless the value was undefined. + * @see \`{@link https://api.jquery.com/event.result/ }\` + * @since 1.3 + * @example ​ ````Display previous handler's return value +```html + + + + + event.result demo + + + +​ + +

+​ + +​ + + +``` + */ + result?: any; } - // #endregion - - interface EventHandler extends EventHandlerBase> { } + interface TypeToTriggeredEventMap< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget + > { + [type: string]: TriggeredEvent; + } // Extra parameters can be passed from trigger() type EventHandlerBase = (this: TContext, t: T, ...args: any[]) => any; + type EventHandler< + TCurrentTarget, + TData = undefined + > = EventHandlerBase>; + + type TypeEventHandler< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget, + TContext, + TType extends keyof TypeToTriggeredEventMap + > = EventHandlerBase[TType]>; + + interface TypeEventHandlers< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget, + TContext + > extends _TypeEventHandlers { + // No idea why it's necessary to include `object` in the union but otherwise TypeScript complains that + // derived types of Event are not assignable to Event. + [type: string]: TypeEventHandler | + false | + undefined | + object; + } + + type _TypeEventHandlers< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget, + TContext + > = { + [TType in keyof TypeToTriggeredEventMap]?: + TypeEventHandler | + false | + object; + }; + // region Event extensions // #region Event extensions @@ -4791,13 +4874,13 @@ $( "ul" ).click( handler ).find( "ul" ).hide(); * The trigger hook is called early in the process of triggering an event, just after the `jQuery.Event` object is constructed and before any handlers have been called. It can process the triggered event in any way, for example by calling `event.stopPropagation()` or `event.preventDefault()` before returning. If the hook returns `false`, jQuery does not perform any further event triggering actions and returns immediately. Otherwise, it performs the normal trigger processing, calling any event handlers for the element and bubbling the event (unless propagation is stopped in advance or `noBubble` was specified for the special event) to call event handlers attached to parent elements. * @see \`{@link https://learn.jquery.com/events/event-extensions/#trigger-function-event-jquery-event-data-object }\` */ - trigger(this: TTarget, event: Event, data: TData): void | false; + trigger(this: TTarget, event: Event, data: TData): void | false; } | { /** * When the `.trigger()` method finishes running all the event handlers for an event, it also looks for and runs any method on the target object by the same name unless of the handlers called `event.preventDefault()`. So, `.trigger( "submit" )` will execute the `submit()` method on the element if one exists. When a `_default` hook is specified, the hook is called just prior to checking for and executing the element's default method. If this hook returns the value `false` the element's default method will be called; otherwise it is not. * @see \`{@link https://learn.jquery.com/events/event-extensions/#_default-function-event-jquery-event-data-object }\` */ - _default(event: Event, data: TData): void | false; + _default(event: TriggeredEvent, data: TData): void | false; } | { /** * jQuery calls a handle hook when the event has occurred and jQuery would normally call the user's event handler specified by `.on()` or another event binding method. If the hook exists, jQuery calls it _instead_ of that event handler, passing it the event and any data passed from `.trigger()` if it was not a native event. The `this` keyword is the DOM element being handled, and `event.handleObj` property has the detailed event information. @@ -4805,11 +4888,11 @@ $( "ul" ).click( handler ).find( "ul" ).hide(); * Based in the information it has, the handle hook should decide whether to call the original handler function which is in `event.handleObj.handler`. It can modify information in the event object before calling the original handler, but _must restore_ that data before returning or subsequent unrelated event handlers may act unpredictably. In most cases, the handle hook should return the result of the original handler, but that is at the discretion of the hook. The handle hook is unique in that it is the only special event function hook that is called under its original special event name when the type is mapped using `bindType` and `delegateType`. For that reason, it is almost always an error to have anything other than a handle hook present if the special event defines a `bindType` and `delegateType`, since those other hooks will never be called. * @see \`{@link https://learn.jquery.com/events/event-extensions/#handle-function-event-jquery-event-data-object }\` */ - handle(this: TTarget, event: Event & { handleObj: HandleObject; }, ...data: TData[]): void; + handle(this: TTarget, event: TriggeredEvent & { handleObj: HandleObject; }, ...data: TData[]): void; } | { - preDispatch(this: TTarget, event: Event): false | void; + preDispatch(this: TTarget, event: Event): false | void; } | { - postDispatch(this: TTarget, event: Event): void; + postDispatch(this: TTarget, event: Event): void; } | { [key: string]: never; }; @@ -4901,7 +4984,6 @@ $( "ul" ).click( handler ).find( "ul" ).hide(); declare const jQuery: JQueryStatic; declare const $: JQueryStatic; -// Used by JQuery.Event type _Event = Event; // region ES5 compatibility diff --git a/types/jquery/test/example-tests.ts b/types/jquery/test/example-tests.ts index 7ecb1733a7..673e549c31 100644 --- a/types/jquery/test/example-tests.ts +++ b/types/jquery/test/example-tests.ts @@ -384,7 +384,7 @@ function examples() { } function bind_2() { - function handler(event: JQuery.Event) { + function handler(event: JQuery.TriggeredEvent) { alert(event.data.foo); } @@ -830,7 +830,7 @@ function examples() { var len = kids.addClass('hilite').length; $('#results span:first').text(len); - $('#results span:last').text(event.target.tagName); + $('#results span:last').text((event.target as Element).tagName); event.preventDefault(); }); @@ -1614,12 +1614,12 @@ function examples() { function event_target_0() { $('body').click(function(event) { - $('#log').html('clicked: ' + event.target.nodeName); + $('#log').html('clicked: ' + (event.target as Node).nodeName); }); } function event_target_1() { - function handler(event: JQuery.Event) { + function handler(event: JQuery.TriggeredEvent) { var target = $(event.target); if (target.is('li')) { target.children().toggle(); @@ -3018,10 +3018,10 @@ function examples() { function jQuery_proxy_0() { var me = { type: 'zombie', - test: function(event: JQuery.Event) { + test: function(event: JQuery.TriggeredEvent) { // Without proxy, `this` would refer to the event target // use event.target to reference that element. - var element = event.target; + var element = event.target as Element; $(element).css('background-color', 'red'); // With proxy, `this` refers to the me object encapsulating @@ -3033,7 +3033,7 @@ function examples() { var you = { type: 'person', - test: function(event: JQuery.Event) { + test: function(event: JQuery.TriggeredEvent) { $('#log').append(this.type + ' '); }, }; @@ -3075,7 +3075,7 @@ function examples() { type: 'dog', // Note that event comes *after* one and two - test: function(one: typeof you, two: typeof they, event: JQuery.Event) { + test: function(one: typeof you, two: typeof they, event: JQuery.TriggeredEvent) { $('#log') // `one` maps to `you`, the 1st additional @@ -3796,7 +3796,7 @@ function examples() { } function on_1() { - function myHandler(event: JQuery.Event) { + function myHandler(event: JQuery.TriggeredEvent) { alert(event.data.foo); } diff --git a/types/jquery/test/learn-tests.ts b/types/jquery/test/learn-tests.ts index 523385b644..b1a0353b4e 100644 --- a/types/jquery/test/learn-tests.ts +++ b/types/jquery/test/learn-tests.ts @@ -35,7 +35,7 @@ function special() { bindType: "click", handle(event) { const handleObj = event.handleObj; - const targetData = jQuery.data(event.target); + const targetData = jQuery.data(event.target as Element); let ret = null; // If a multiple of the click count, run the handler diff --git a/types/jquery/test/longdesc-tests.ts b/types/jquery/test/longdesc-tests.ts index bb3bb4c83c..f3cf559638 100644 --- a/types/jquery/test/longdesc-tests.ts +++ b/types/jquery/test/longdesc-tests.ts @@ -538,7 +538,7 @@ function longdesc() { $('#foo').slideUp(300).delay(800).fadeIn(400); } - function delegate_0(elements: HTMLElement[], selector: string, events: any, data: any, handler: JQuery.EventHandler) { + function delegate_0(elements: HTMLElement[], selector: string, events: string, data: any, handler: JQuery.TypeEventHandler) { // jQuery 1.4.3+ $(elements).delegate(selector, events, data, handler); // jQuery 1.7+ @@ -2016,7 +2016,7 @@ function longdesc() { } function on_3() { - function greet(event: JQuery.Event) { + function greet(event: JQuery.TriggeredEvent) { alert('Hello ' + event.data.name); } From 00c546398c4d3d98655a4bce525a077dd52c83c1 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Wed, 24 Oct 2018 10:26:51 -0400 Subject: [PATCH 245/836] [jquery] Add support for event types that have shorthand methods. --- types/jquery/JQuery.d.ts | 136 ++-- types/jquery/jquery-tests.ts | 197 ++++-- types/jquery/misc.d.ts | 1282 ++++++++++++++++++++++++++++++++++ 3 files changed, 1515 insertions(+), 100 deletions(-) diff --git a/types/jquery/JQuery.d.ts b/types/jquery/JQuery.d.ts index f9a06328e7..83e27c6754 100644 --- a/types/jquery/JQuery.d.ts +++ b/types/jquery/JQuery.d.ts @@ -1521,7 +1521,7 @@ $( "div.test" ).bind({ * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ blur(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -1537,7 +1537,8 @@ $( "div.test" ).bind({ $( "p" ).blur(); ``` */ - blur(handler?: JQuery.EventHandler | false): this; + blur(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "change" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -1551,7 +1552,7 @@ $( "p" ).blur(); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ change(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "change" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -1610,7 +1611,8 @@ $( "input[type='text']" ).change(function() { }); ``` */ - change(handler?: JQuery.EventHandler | false): this; + change(handler?: JQuery.TypeEventHandler | + false): this; /** * Get the children of each element in the set of matched elements, optionally filtered by a selector. * @param selector A string containing a selector expression to match elements against. @@ -1863,7 +1865,7 @@ $( "#stop" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ click(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "click" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -1913,7 +1915,8 @@ $( "p" ).click(function() { $( "p" ).click(); ``` */ - click(handler?: JQuery.EventHandler | false): this; + click(handler?: JQuery.TypeEventHandler | + false): this; /** * Create a deep copy of the set of matched elements. * @param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The @@ -2101,7 +2104,7 @@ $( "#frameDemo" ).contents().find( "a" ).css( "background-color", "#BADA55" ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ contextmenu(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "contextmenu" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -2155,7 +2158,8 @@ div.contextmenu(function() { ``` */ - contextmenu(handler?: JQuery.EventHandler | false): this; + contextmenu(handler?: JQuery.TypeEventHandler | + false): this; /** * Set one or more CSS properties for the set of matched elements. * @param propertyName A CSS property name. @@ -2616,7 +2620,7 @@ $( "button" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ dblclick(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -2670,7 +2674,8 @@ divdbl.dblclick(function() { ``` */ - dblclick(handler?: JQuery.EventHandler | false): this; + dblclick(handler?: JQuery.TypeEventHandler | + false): this; /** * Set a timer to delay execution of subsequent items in the queue. * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. @@ -4293,7 +4298,7 @@ $( "p span" ).first().addClass( "highlight" ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focus(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focus" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -4345,7 +4350,8 @@ $( document ).ready(function() { }); ``` */ - focus(handler?: JQuery.EventHandler | false): this; + focus(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "focusin" event. * @param eventData An object containing data that will be passed to the event handler. @@ -4359,7 +4365,7 @@ $( document ).ready(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focusin(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focusin" event. * @param handler A function to execute each time the event is triggered. @@ -4399,7 +4405,8 @@ $( "p" ).focusin(function() { ``` */ - focusin(handler?: JQuery.EventHandler | false): this; + focusin(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "focusout" JavaScript event. * @param eventData An object containing data that will be passed to the event handler. @@ -4413,7 +4420,7 @@ $( "p" ).focusin(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focusout(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focusout" JavaScript event. * @param handler A function to execute each time the event is triggered. @@ -4474,7 +4481,8 @@ $( "p" ) ``` */ - focusout(handler?: JQuery.EventHandler | false): this; + focusout(handler?: JQuery.TypeEventHandler | + false): this; /** * Retrieve one of the elements matched by the jQuery object. * @param index A zero-based integer indicating which element to retrieve. @@ -4917,12 +4925,11 @@ $( "button" ).click(function() { */ hide(duration_complete_options?: JQuery.Duration | ((this: TElement) => void) | JQuery.EffectsOptions): this; /** - * Bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. - * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. + * @param handlerIn A function to execute when the mouse pointer enters the element. * @param handlerOut A function to execute when the mouse pointer leaves the element. * @see \`{@link https://api.jquery.com/hover/ }\` * @since 1.0 - * @since 1.4 * @deprecated ​ Deprecated. * * **Cause**: The `.hover()` method is a shorthand for the use of the `mouseover`/`mouseout` events. It is often a poor user interface choice because it does not allow for any small amounts of delay between when the mouse enters or exits an area and when the event fires. This can make it quite difficult to use with UI widgets such as drop-down menus. For more information on the problems of hovering, see the \`{@link http://cherne.net/brian/resources/jquery.hoverIntent.html hoverIntent plugin}\`. @@ -4990,6 +4997,21 @@ $( "td" ).hover( ```javascript $( "td" ).off( "mouseenter mouseleave" ); ``` + */ + hover(handlerIn: JQuery.TypeEventHandler | + false, + handlerOut: JQuery.TypeEventHandler | + false): this; + /** + * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. + * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + * @see \`{@link https://api.jquery.com/hover/ }\` + * @since 1.4 + * @deprecated ​ Deprecated. + * + * **Cause**: The `.hover()` method is a shorthand for the use of the `mouseover`/`mouseout` events. It is often a poor user interface choice because it does not allow for any small amounts of delay between when the mouse enters or exits an area and when the event fires. This can make it quite difficult to use with UI widgets such as drop-down menus. For more information on the problems of hovering, see the \`{@link http://cherne.net/brian/resources/jquery.hoverIntent.html hoverIntent plugin}\`. + * + * **Solution**: Review uses of `.hover()` to determine if they are appropriate, and consider use of plugins such as `hoverIntent` as an alternative. The direct replacement for `.hover(fn1, fn2)`, is `.on("mouseenter", fn1).on("mouseleave", fn2)`. * @example ​ ````Slide the next sibling LI up or down on hover, and toggle a class. ```html @@ -5045,10 +5067,8 @@ $( "li" ) ``` */ - // HACK: The type parameter T is not used but ensures the 'event' callback parameter is typed correctly. - // tslint:disable-next-line:no-unnecessary-generics - hover(handlerInOut: JQuery.EventHandler | false, - handlerOut?: JQuery.EventHandler | false): this; + hover(handlerInOut: JQuery.TypeEventHandler | + false): this; /** * Set the HTML contents of each element in the set of matched elements. * @param htmlString_function _@param_ `htmlString_function` @@ -5862,7 +5882,7 @@ $( "li" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keydown(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -5934,7 +5954,8 @@ $( "#other" ).click(function() { ``` */ - keydown(handler?: JQuery.EventHandler | false): this; + keydown(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -5948,7 +5969,7 @@ $( "#other" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keypress(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6020,7 +6041,8 @@ $( "#other" ).click(function() { ``` */ - keypress(handler?: JQuery.EventHandler | false): this; + keypress(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6034,7 +6056,7 @@ $( "#other" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keyup(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6107,7 +6129,8 @@ $( "#other").click(function() { ``` */ - keyup(handler?: JQuery.EventHandler | false): this; + keyup(handler?: JQuery.TypeEventHandler | + false): this; /** * Reduce the set of matched elements to the final one in the set. * @see \`{@link https://api.jquery.com/last/ }\` @@ -6396,7 +6419,7 @@ $( "input" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mousedown(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6434,7 +6457,8 @@ $( "p" ) ``` */ - mousedown(handler?: JQuery.EventHandler | false): this; + mousedown(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6448,7 +6472,7 @@ $( "p" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseenter(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. * @param handler A function to execute each time the event is triggered. @@ -6529,7 +6553,8 @@ $( "div.enterleave" ) ``` */ - mouseenter(handler?: JQuery.EventHandler | false): this; + mouseenter(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6543,7 +6568,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseleave(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. * @param handler A function to execute each time the event is triggered. @@ -6622,7 +6647,8 @@ $( "div.enterleave" ) ``` */ - mouseleave(handler?: JQuery.EventHandler | false): this; + mouseleave(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6636,7 +6662,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mousemove(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6700,7 +6726,8 @@ $( "div" ).mousemove(function( event ) { ``` */ - mousemove(handler?: JQuery.EventHandler | false): this; + mousemove(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6714,7 +6741,7 @@ $( "div" ).mousemove(function( event ) { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseout(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6795,7 +6822,8 @@ $( "div.enterleave" ) ``` */ - mouseout(handler?: JQuery.EventHandler | false): this; + mouseout(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6809,7 +6837,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseover(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6890,7 +6918,8 @@ $( "div.enterleave" ) ``` */ - mouseover(handler?: JQuery.EventHandler | false): this; + mouseover(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6904,7 +6933,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseup(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6942,7 +6971,8 @@ $( "p" ) ``` */ - mouseup(handler?: JQuery.EventHandler | false): this; + mouseup(handler?: JQuery.TypeEventHandler | + false): this; /** * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. * @param selector A string containing a selector expression to match elements against. @@ -9970,7 +10000,7 @@ $( "button" ).on( "click", function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ resize(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "resize" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -9988,7 +10018,8 @@ $( window ).resize(function() { }); ``` */ - resize(handler?: JQuery.EventHandler | false): this; + resize(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -10002,7 +10033,7 @@ $( window ).resize(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ scroll(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -10052,7 +10083,8 @@ $( window ).scroll(function() { ``` */ - scroll(handler?: JQuery.EventHandler | false): this; + scroll(handler?: JQuery.TypeEventHandler | + false): this; /** * Set the current horizontal position of the scroll bar for each of the set of matched elements. * @param value An integer indicating the new position to set the scroll bar to. @@ -10226,7 +10258,7 @@ $( "p:last" ).text( "scrollTop:" + p.scrollTop() ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ select(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "select" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -10275,7 +10307,8 @@ $( ":input" ).select(function() { $( "input" ).select(); ``` */ - select(handler?: JQuery.EventHandler | false): this; + select(handler?: JQuery.TypeEventHandler | + false): this; /** * Encode a set of form elements as a string for submission. * @see \`{@link https://api.jquery.com/serialize/ }\` @@ -11246,7 +11279,7 @@ $( "#toggle" ).on( "click", function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ submit(eventData: TData, - handler: JQuery.EventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "submit" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -11315,7 +11348,8 @@ $( "form" ).submit(function() { $( "form:first" ).submit(); ``` */ - submit(handler?: JQuery.EventHandler | false): this; + submit(handler?: JQuery.TypeEventHandler | + false): this; /** * Set the content of each element in the set of matched elements to the specified text. * @param text_function _@param_ `text_function` diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index b08b48d0b0..069e8613d6 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -3916,6 +3916,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ClickEvent + event; } }); } @@ -3948,6 +3954,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType any + this; + // $ExpectType ClickEvent + event; } }); } @@ -4139,6 +4151,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType any + this; + // $ExpectType ClickEvent + event; } }, 'td', 'myData'); @@ -4150,6 +4168,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ClickEvent + event; } }, null, 'myData'); @@ -4161,6 +4185,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ClickEvent + event; } }, undefined, 'myData'); @@ -4172,6 +4202,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType any + this; + // $ExpectType ClickEvent + event; } }, 'td'); @@ -4183,6 +4219,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ClickEvent + event; } }, 3); @@ -4194,6 +4236,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ClickEvent + event; } }); } @@ -4261,6 +4309,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType any + this; + // $ExpectType ClickEvent + event; } }, 'td', 'myData'); @@ -4272,6 +4326,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ClickEvent + event; } }, null, 'myData'); @@ -4283,6 +4343,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ClickEvent + event; } }, undefined, 'myData'); @@ -4294,6 +4360,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType any + this; + // $ExpectType ClickEvent + event; } }, 'td'); @@ -4305,6 +4377,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ClickEvent + event; } }, 3); @@ -4316,6 +4394,12 @@ function JQuery() { this; // $ExpectType TriggeredEvent event; + }, + click(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ClickEvent + event; } }); } @@ -4445,7 +4529,7 @@ function JQuery() { $('p').blur('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType BlurEvent event; }); @@ -4453,7 +4537,7 @@ function JQuery() { $('p').blur(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType BlurEvent event; }); @@ -4469,7 +4553,7 @@ function JQuery() { $('p').change('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ChangeEvent event; }); @@ -4477,7 +4561,7 @@ function JQuery() { $('p').change(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ChangeEvent event; }); @@ -4493,7 +4577,7 @@ function JQuery() { $('p').click('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; }); @@ -4501,7 +4585,7 @@ function JQuery() { $('p').click(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; }); @@ -4517,7 +4601,7 @@ function JQuery() { $('p').contextmenu('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ContextMenuEvent event; }); @@ -4525,7 +4609,7 @@ function JQuery() { $('p').contextmenu(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ContextMenuEvent event; }); @@ -4541,7 +4625,7 @@ function JQuery() { $('p').dblclick('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType DoubleClickEvent event; }); @@ -4549,7 +4633,7 @@ function JQuery() { $('p').dblclick(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType DoubleClickEvent event; }); @@ -4565,7 +4649,7 @@ function JQuery() { $('p').focus('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType FocusEvent event; }); @@ -4573,7 +4657,7 @@ function JQuery() { $('p').focus(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType FocusEvent event; }); @@ -4589,7 +4673,7 @@ function JQuery() { $('p').focusin('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType FocusInEvent event; }); @@ -4597,7 +4681,7 @@ function JQuery() { $('p').focusin(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType FocusInEvent event; }); @@ -4613,7 +4697,7 @@ function JQuery() { $('p').focusout('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType FocusOutEvent event; }); @@ -4621,7 +4705,7 @@ function JQuery() { $('p').focusout(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType FocusOutEvent event; }); @@ -4637,7 +4721,7 @@ function JQuery() { $('p').keydown('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType KeyDownEvent event; }); @@ -4645,7 +4729,7 @@ function JQuery() { $('p').keydown(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType KeyDownEvent event; }); @@ -4661,7 +4745,7 @@ function JQuery() { $('p').keypress('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType KeyPressEvent event; }); @@ -4669,7 +4753,7 @@ function JQuery() { $('p').keypress(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType KeyPressEvent event; }); @@ -4685,7 +4769,7 @@ function JQuery() { $('p').keyup('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType KeyUpEvent event; }); @@ -4693,7 +4777,7 @@ function JQuery() { $('p').keyup(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType KeyUpEvent event; }); @@ -4709,7 +4793,7 @@ function JQuery() { $('p').mousedown('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseDownEvent event; }); @@ -4717,7 +4801,7 @@ function JQuery() { $('p').mousedown(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseDownEvent event; }); @@ -4733,7 +4817,7 @@ function JQuery() { $('p').mouseenter('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }); @@ -4741,7 +4825,7 @@ function JQuery() { $('p').mouseenter(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }); @@ -4757,7 +4841,7 @@ function JQuery() { $('p').mouseleave('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -4765,7 +4849,7 @@ function JQuery() { $('p').mouseleave(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -4781,7 +4865,7 @@ function JQuery() { $('p').mousemove('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseMoveEvent event; }); @@ -4789,7 +4873,7 @@ function JQuery() { $('p').mousemove(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseMoveEvent event; }); @@ -4805,7 +4889,7 @@ function JQuery() { $('p').mouseout('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseOutEvent event; }); @@ -4813,7 +4897,7 @@ function JQuery() { $('p').mouseout(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseOutEvent event; }); @@ -4829,7 +4913,7 @@ function JQuery() { $('p').mouseover('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseOverEvent event; }); @@ -4837,7 +4921,7 @@ function JQuery() { $('p').mouseover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseOverEvent event; }); @@ -4853,7 +4937,7 @@ function JQuery() { $('p').mouseup('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseUpEvent event; }); @@ -4861,7 +4945,7 @@ function JQuery() { $('p').mouseup(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseUpEvent event; }); @@ -4877,7 +4961,7 @@ function JQuery() { $('p').resize('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ResizeEvent event; }); @@ -4885,7 +4969,7 @@ function JQuery() { $('p').resize(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ResizeEvent event; }); @@ -4901,7 +4985,7 @@ function JQuery() { $('p').scroll('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ScrollEvent event; }); @@ -4909,7 +4993,7 @@ function JQuery() { $('p').scroll(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ScrollEvent event; }); @@ -4925,7 +5009,7 @@ function JQuery() { $('p').select('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType SelectEvent event; }); @@ -4933,7 +5017,7 @@ function JQuery() { $('p').select(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType SelectEvent event; }); @@ -4949,7 +5033,7 @@ function JQuery() { $('p').submit('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType SubmitEvent event; }); @@ -4957,7 +5041,7 @@ function JQuery() { $('p').submit(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType SubmitEvent event; }); @@ -4973,12 +5057,12 @@ function JQuery() { $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -4986,7 +5070,7 @@ function JQuery() { $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }, false); @@ -4994,7 +5078,7 @@ function JQuery() { $('p').hover(false, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5005,8 +5089,23 @@ function JQuery() { $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseEnterEvent | MouseLeaveEvent event; + + switch (event.type) { + case 'mouseover': + // $ExpectType MouseEnterEvent + event; + break; + case 'mouseout': + // $ExpectType MouseLeaveEvent + event; + break; + default: + // $ExpectType never + event; + break; + } }); // $ExpectType JQuery diff --git a/types/jquery/misc.d.ts b/types/jquery/misc.d.ts index d966f1b787..24979fb620 100644 --- a/types/jquery/misc.d.ts +++ b/types/jquery/misc.d.ts @@ -4744,12 +4744,1290 @@ $( "button" ).click(function( event ) { result?: any; } + // region Event + // #region Event + + interface EventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TriggeredEvent { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: undefined; + + // Event + + bubbles: boolean; + cancelable: boolean; + eventPhase: number; + + // UIEvent + + detail: undefined; + view: undefined; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: undefined; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: undefined; + ctrlKey: undefined; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: undefined; + shiftKey: undefined; + + originalEvent?: _Event; + } + + interface ChangeEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'change'; + } + + interface ResizeEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'resize'; + } + + interface ScrollEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'scroll'; + } + + interface SelectEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'select'; + } + + interface SubmitEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'submit'; + } + + // #endregion + + // region UIEvent + // #region UIEvent + + interface UIEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TriggeredEvent { + // Event + + bubbles: boolean; + cancelable: boolean; + eventPhase: number; + + // UIEvent + + detail: number; + view: Window; + + originalEvent?: _UIEvent; + } + + // region MouseEvent + // #region MouseEvent + + interface MouseEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: EventTarget | null; + + // MouseEvent + + button: number; + buttons: number; + clientX: number; + clientY: number; + offsetX: number; + offsetY: number; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: number; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: number; + screenX: number; + screenY: number; + /** @deprecated */ + toElement: Element; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: number; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: boolean; + ctrlKey: boolean; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: boolean; + shiftKey: boolean; + + originalEvent?: _MouseEvent; + } + + interface ClickEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'click'; + } + + interface ContextMenuEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'contextmenu'; + } + + interface DoubleClickEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'dblclick'; + } + + interface MouseDownEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'mousedown'; + } + + interface MouseEnterEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + // Special handling by jQuery. + type: 'mouseover'; + } + + interface MouseLeaveEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + // Special handling by jQuery. + type: 'mouseout'; + } + + interface MouseMoveEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'mousemove'; + } + + interface MouseOutEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + type: 'mouseout'; + } + + interface MouseOverEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + type: 'mouseover'; + } + + interface MouseUpEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'mouseup'; + } + + // #endregion + + // region KeyboardEvent + // #region KeyboardEvent + + interface KeyboardEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: undefined; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: string | undefined; + /** @deprecated */ + charCode: number; + key: string; + /** @deprecated */ + keyCode: number; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: number; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: boolean; + ctrlKey: boolean; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: boolean; + shiftKey: boolean; + + originalEvent?: _KeyboardEvent; + } + + interface KeyDownEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends KeyboardEventBase { + type: 'keydown'; + } + + interface KeyPressEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends KeyboardEventBase { + type: 'keypress'; + } + + interface KeyUpEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends KeyboardEventBase { + type: 'keyup'; + } + + // #endregion + + // region FocusEvent + // #region FocusEvent + + interface FocusEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: EventTarget | null; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: undefined; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: undefined; + ctrlKey: undefined; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: undefined; + shiftKey: undefined; + + originalEvent?: _FocusEvent; + } + + interface BlurEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'blur'; + } + + interface FocusEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'focus'; + } + + interface FocusInEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'focusin'; + } + + interface FocusOutEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'focusout'; + } + + // #endregion + + // #endregion + interface TypeToTriggeredEventMap< TDelegateTarget, TData, TCurrentTarget, TTarget > { + // Event + + change: ChangeEvent; + resize: ResizeEvent; + scroll: ScrollEvent; + select: SelectEvent; + submit: SubmitEvent; + + // UIEvent + + // MouseEvent + + click: ClickEvent; + contextmenu: ContextMenuEvent; + dblclick: DoubleClickEvent; + mousedown: MouseDownEvent; + mouseenter: MouseEnterEvent; + mouseleave: MouseLeaveEvent; + mousemove: MouseMoveEvent; + mouseout: MouseOutEvent; + mouseover: MouseOverEvent; + mouseup: MouseUpEvent; + + // KeyboardEvent + + keydown: KeyDownEvent; + keypress: KeyPressEvent; + keyup: KeyUpEvent; + + // FocusEvent + + blur: BlurEvent; + focus: FocusEvent; + focusin: FocusInEvent; + focusout: FocusOutEvent; + [type: string]: TriggeredEvent; } @@ -4985,6 +6263,10 @@ declare const jQuery: JQueryStatic; declare const $: JQueryStatic; type _Event = Event; +type _UIEvent = UIEvent; +type _MouseEvent = MouseEvent; +type _KeyboardEvent = KeyboardEvent; +type _FocusEvent = FocusEvent; // region ES5 compatibility // #region ES5 compatibility From acc34c5a2347ae1d58bda9dd72fe22c9f56ad959 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sun, 28 Oct 2018 10:50:28 -0400 Subject: [PATCH 246/836] [angular] Update merging tests for jQuery Events API changes. --- types/angular/test/jquery3-merging-tests.ts | 210 +------------------- 1 file changed, 10 insertions(+), 200 deletions(-) diff --git a/types/angular/test/jquery3-merging-tests.ts b/types/angular/test/jquery3-merging-tests.ts index 507c58b67e..da61a6f0bc 100644 --- a/types/angular/test/jquery3-merging-tests.ts +++ b/types/angular/test/jquery3-merging-tests.ts @@ -94,8 +94,6 @@ function JQuery() { } function bind() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').bind('myEvent', 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -104,14 +102,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('p').bind('myEvent', 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('p').bind('myEvent', function(event) { // TODO: $ExpectType HTMLElement @@ -120,14 +110,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('p').bind('myEvent', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('p').bind('myEvent', false); @@ -139,12 +121,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }); @@ -164,27 +140,15 @@ function JQuery() { } function off() { - function defaultContext_defaultData(this: HTMLElement, event: JQueryEventObject) { } + function defaultData(this: HTMLElement, event: JQueryEventObject) { } - function defaultContext_customData(this: HTMLElement, event: JQueryEventObject) { } - - function customContext_defaultData(this: I1, event: JQueryEventObject) { } - - function customContext_customData(this: I1, event: JQueryEventObject) { } - - interface I1 { kind: 'I1'; } + function customData(this: HTMLElement, event: JQueryEventObject) { } // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_defaultData); + $('table').off('myEvent', 'td', defaultData); // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_customData); - - // $ExpectType JQuery - $('table').off('myEvent', 'td', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', 'td', customContext_customData); + $('table').off('myEvent', 'td', customData); // $ExpectType JQuery $('table').off('myEvent', 'td', false); @@ -193,16 +157,10 @@ function JQuery() { $('table').off('myEvent', 'td'); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_defaultData); + $('table').off('myEvent', defaultData); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_customData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_customData); + $('table').off('myEvent', customData); // $ExpectType JQuery $('table').off('myEvent', false); @@ -213,19 +171,15 @@ function JQuery() { // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }, 'td'); // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }); // $ExpectType JQuery @@ -236,8 +190,6 @@ function JQuery() { } function on() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('table').on('myEvent', 'td', 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -246,14 +198,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', 'td', 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', null, 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -262,14 +206,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', null, 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', 'td', function(event) { // TODO: $ExpectType HTMLElement @@ -278,14 +214,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', 'td', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', 'td', false); @@ -297,14 +225,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', 3, function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', function(event) { // TODO: $ExpectType HTMLElement @@ -313,14 +233,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', false); @@ -332,12 +244,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td', 'myData'); @@ -349,12 +255,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, null, 'myData'); @@ -366,12 +266,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td'); @@ -383,12 +277,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 3); @@ -400,19 +288,11 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }); } function one() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('table').one('myEvent', 'td', 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -421,14 +301,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', 'td', 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', null, 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -437,14 +309,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', null, 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', 'td', function(event) { // TODO: $ExpectType HTMLElement @@ -453,14 +317,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', 'td', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', 'td', false); @@ -472,14 +328,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', 3, function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', function(event) { // TODO: $ExpectType HTMLElement @@ -488,14 +336,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', false); @@ -507,12 +347,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td', 'myData'); @@ -524,12 +358,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, null, 'myData'); @@ -541,12 +369,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td'); @@ -558,12 +380,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 3); @@ -575,12 +391,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }); } From 68c38a850c846788505bc8fd34398e19136983e0 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sun, 28 Oct 2018 11:45:11 -0400 Subject: [PATCH 247/836] [backbone] Fix test failure in `backbone.marionette` due to changes in jQuery Events API. --- types/backbone/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index ca36541735..a881284c8f 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -92,7 +92,7 @@ declare namespace Backbone { } interface EventsHash { - [selector: string]: string | {(eventObject: JQueryEventObject): void}; + [selector: string]: string | {(eventObject: JQuery.TriggeredEvent): void}; } export const Events: Events; From b6bb6a64fd214d0f25711c6e79572cf35ad1f07c Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sun, 28 Oct 2018 11:01:29 -0400 Subject: [PATCH 248/836] [bootstrap] Update API for jQuery Events API changes. --- types/bootstrap/index.d.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/types/bootstrap/index.d.ts b/types/bootstrap/index.d.ts index 8a815bccd5..9744731237 100755 --- a/types/bootstrap/index.d.ts +++ b/types/bootstrap/index.d.ts @@ -322,7 +322,7 @@ export interface TooltipOption { // Events // -------------------------------------------------------------------------------------- -export interface CarouselEventHandler extends JQuery.Event { +export interface CarouselEventHandler extends JQuery.TriggeredEvent { /** * The direction in which the carousel is sliding. */ @@ -339,6 +339,10 @@ export interface CarouselEventHandler extends JQuery.Event extends JQuery.TriggeredEvent { + relatedTarget: HTMLElement; +} + export type AlertEvent = "close.bs.alert" | "closed.bs.alert"; export type CarouselEvent = "slide.bs.carousel" | "slid.bs.carousel"; export type CollapseEvent = "show.bs.collapse" | "shown.bs.collapse" | "hide.bs.collapse" | "hidden.bs.collapse"; @@ -383,9 +387,10 @@ declare global { tooltip(options?: TooltipOption): this; on(events: CarouselEvent, handler: JQuery.EventHandlerBase>): this; + on(events: TapEvent, handler: JQuery.EventHandlerBase>): this; on(events: AlertEvent | CollapseEvent | DropdownEvent | ModalEvent | - PopoverEvent | ScrollspyEvent | TapEvent | TooltipEvent, + PopoverEvent | ScrollspyEvent | TooltipEvent, handler: JQuery.EventHandler): this; } } From 5f6b28023b302f089330ef5bb86ac8d805df5b75 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sun, 28 Oct 2018 11:03:13 -0400 Subject: [PATCH 249/836] [bootstrap-slider] Fix test failure due to jQuery Events API changes. --- types/bootstrap-slider/bootstrap-slider-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/bootstrap-slider/bootstrap-slider-tests.ts b/types/bootstrap-slider/bootstrap-slider-tests.ts index 9b2a1a2014..d3ffdeedeb 100644 --- a/types/bootstrap-slider/bootstrap-slider-tests.ts +++ b/types/bootstrap-slider/bootstrap-slider-tests.ts @@ -42,7 +42,7 @@ $(() => { $('#ex7').slider(); - $('#ex7-enabled').click(function(this: HTMLInputElement) { + $('#ex7-enabled').click(function() { if (this.checked) { // With JQuery $('#ex7').slider('enable'); From c1ce5ef2c241a4fdcfc4b181428a1f6500dcaa0d Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sun, 28 Oct 2018 11:04:44 -0400 Subject: [PATCH 250/836] [jquery-focus-exit] Update API for jQuery Events API changes. --- types/jquery-focus-exit/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/jquery-focus-exit/index.d.ts b/types/jquery-focus-exit/index.d.ts index 8787136a4e..d4da0a1f18 100644 --- a/types/jquery-focus-exit/index.d.ts +++ b/types/jquery-focus-exit/index.d.ts @@ -14,7 +14,7 @@ export interface FocusElements { declare global { interface JQuery { focusExit(options?: { debug: boolean }): JQuery; - on(event: 'focusExit', handler: ((event: JQuery.Event, data: FocusElements) => void)): JQuery; - one(event: 'focusin', handler: ((event: JQuery.Event) => void)): JQuery; + on(event: 'focusExit', handler: ((event: JQuery.TriggeredEvent, data: FocusElements) => void)): JQuery; + one(event: 'focusin', handler: ((event: JQuery.TriggeredEvent) => void)): JQuery; } } From 8914a468a462141bd3817bbbccaa2f0ecb947436 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sun, 28 Oct 2018 11:05:22 -0400 Subject: [PATCH 251/836] [jquery-mouse-exit] Update API for jQuery Events API changes. --- types/jquery-mouse-exit/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/jquery-mouse-exit/index.d.ts b/types/jquery-mouse-exit/index.d.ts index f0ba17996e..651a7b3f85 100644 --- a/types/jquery-mouse-exit/index.d.ts +++ b/types/jquery-mouse-exit/index.d.ts @@ -18,6 +18,6 @@ export type FocusElements = Partial<{ declare global { interface JQuery { mouseExit(options?: Options): JQuery; - on(event: 'mouseExit', handler: ((event: JQuery.Event, data: FocusElements) => void)): JQuery; + on(event: 'mouseExit', handler: ((event: JQuery.TriggeredEvent, data: FocusElements) => void)): JQuery; } } From e1d3c4aba92261ee7d9090f713524243fa5433b6 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sun, 28 Oct 2018 11:07:58 -0400 Subject: [PATCH 252/836] [semantic-ui-form] Update API for jQuery Events API changes. --- types/semantic-ui-form/global.d.ts | 2 +- types/semantic-ui-form/semantic-ui-form-tests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/semantic-ui-form/global.d.ts b/types/semantic-ui-form/global.d.ts index 8e5b2c20b8..1f3294c8d6 100644 --- a/types/semantic-ui-form/global.d.ts +++ b/types/semantic-ui-form/global.d.ts @@ -212,7 +212,7 @@ declare namespace SemanticUI { /** * Callback if a form is all valid */ - onSuccess(this: JQuery, event: JQuery.Event, fields: any): void; + onSuccess(this: JQuery, event: JQuery.TriggeredEvent, fields: any): void; /** * Callback if any form field is invalid */ diff --git a/types/semantic-ui-form/semantic-ui-form-tests.ts b/types/semantic-ui-form/semantic-ui-form-tests.ts index f17ca33112..d481cb00ad 100644 --- a/types/semantic-ui-form/semantic-ui-form-tests.ts +++ b/types/semantic-ui-form/semantic-ui-form-tests.ts @@ -144,7 +144,7 @@ function test_form() { }, onSuccess(event, fields) { this; // $ExpectType JQuery - event; // $ExpectType Event + event; // $ExpectType TriggeredEvent fields; // $ExpectType any }, onFailure(formErrors, fields) { From 8f46997efa62f7e42f8c87a3efde06e7ec69ec7e Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sun, 28 Oct 2018 11:28:43 -0400 Subject: [PATCH 253/836] [sharepoint] Fix test failure due to jQuery Events API changes. --- types/sharepoint/sharepoint-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/sharepoint/sharepoint-tests.ts b/types/sharepoint/sharepoint-tests.ts index e76536cd18..d3bbe1f808 100644 --- a/types/sharepoint/sharepoint-tests.ts +++ b/types/sharepoint/sharepoint-tests.ts @@ -2038,7 +2038,7 @@ namespace _ { // do is retrieve a reference to the term set with the same ID as the div, and // then add the term that belong to that term set under the div that was clicked. - function showTerms(event: JQuery.Event, groupID: SP.Guid, termSetID: SP.Guid) { + function showTerms(event: JQuery.ClickEvent, groupID: SP.Guid, termSetID: SP.Guid) { // First, cancel the bubble so that the group div click handler does not also fire // because that removes all term set divs and we don't want that here. event.originalEvent.cancelBubble = true; From 3a54bad0684cc88f91cfeac115d57554fc494c62 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sun, 28 Oct 2018 11:26:51 -0400 Subject: [PATCH 254/836] [jquery] Add support for touch events. Fixes test failures in `viewporter` due to changes in jQuery Events API. --- types/jquery/misc.d.ts | 271 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 271 insertions(+) diff --git a/types/jquery/misc.d.ts b/types/jquery/misc.d.ts index 24979fb620..dd05435043 100644 --- a/types/jquery/misc.d.ts +++ b/types/jquery/misc.d.ts @@ -5716,6 +5716,269 @@ $( "#checkMetaKey" ).click(function( event ) { // #endregion + // region TouchEvent + // #region TouchEvent + + interface TouchEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: undefined; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: TouchList; + targetTouches: TouchList; + touches: TouchList; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: undefined; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: boolean; + ctrlKey: boolean; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: boolean; + shiftKey: boolean; + + originalEvent?: _TouchEvent; + } + + interface TouchCancelEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any + > extends TouchEventBase { + type: 'touchcancel'; + } + + interface TouchEndEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any + > extends TouchEventBase { + type: 'touchend'; + } + + interface TouchMoveEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any + > extends TouchEventBase { + type: 'touchmove'; + } + + interface TouchStartEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any + > extends TouchEventBase { + type: 'touchstart'; + } + + // #endregion + // region FocusEvent // #region FocusEvent @@ -6021,6 +6284,13 @@ $( "#checkMetaKey" ).click(function( event ) { keypress: KeyPressEvent; keyup: KeyUpEvent; + // TouchEvent + + touchcancel: TouchCancelEvent; + touchend: TouchEndEvent; + touchmove: TouchMoveEvent; + touchstart: TouchStartEvent; + // FocusEvent blur: BlurEvent; @@ -6266,6 +6536,7 @@ type _Event = Event; type _UIEvent = UIEvent; type _MouseEvent = MouseEvent; type _KeyboardEvent = KeyboardEvent; +type _TouchEvent = TouchEvent; type _FocusEvent = FocusEvent; // region ES5 compatibility From db83bc720086e202f8b24e37a71cab14a65db456 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Wed, 31 Oct 2018 11:38:35 -0400 Subject: [PATCH 255/836] [jquery] Don't use a separate type parameter for the type of `this` in event handlers. A separate type parameter is unnecessary as `this` and `currentTarget` reference the same object. --- types/jquery/JQuery.d.ts | 158 ++++++++++++++-------------- types/jquery/misc.d.ts | 15 ++- types/jquery/test/longdesc-tests.ts | 2 +- 3 files changed, 86 insertions(+), 89 deletions(-) diff --git a/types/jquery/JQuery.d.ts b/types/jquery/JQuery.d.ts index 83e27c6754..123fad3b34 100644 --- a/types/jquery/JQuery.d.ts +++ b/types/jquery/JQuery.d.ts @@ -1347,7 +1347,7 @@ $( "p" ).before( $( "b" ) ); TData>( eventType: TType, eventData: TData, - handler: JQuery.TypeEventHandler + handler: JQuery.TypeEventHandler ): this; /** * Attach a handler to an event for the elements. @@ -1477,7 +1477,7 @@ $( "button" ).click(function() { */ bind( eventType: TType, - handler_preventBubble: JQuery.TypeEventHandler | + handler_preventBubble: JQuery.TypeEventHandler | false | null | undefined @@ -1507,7 +1507,7 @@ $( "div.test" ).bind({ }); ``` */ - bind(events: JQuery.TypeEventHandlers): this; + bind(events: JQuery.TypeEventHandlers): this; /** * Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -1521,7 +1521,7 @@ $( "div.test" ).bind({ * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ blur(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -1537,7 +1537,7 @@ $( "div.test" ).bind({ $( "p" ).blur(); ``` */ - blur(handler?: JQuery.TypeEventHandler | + blur(handler?: JQuery.TypeEventHandler | false): this; /** * Bind an event handler to the "change" JavaScript event, or trigger that event on an element. @@ -1552,7 +1552,7 @@ $( "p" ).blur(); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ change(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "change" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -1611,7 +1611,7 @@ $( "input[type='text']" ).change(function() { }); ``` */ - change(handler?: JQuery.TypeEventHandler | + change(handler?: JQuery.TypeEventHandler | false): this; /** * Get the children of each element in the set of matched elements, optionally filtered by a selector. @@ -1865,7 +1865,7 @@ $( "#stop" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ click(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "click" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -1915,7 +1915,7 @@ $( "p" ).click(function() { $( "p" ).click(); ``` */ - click(handler?: JQuery.TypeEventHandler | + click(handler?: JQuery.TypeEventHandler | false): this; /** * Create a deep copy of the set of matched elements. @@ -2104,7 +2104,7 @@ $( "#frameDemo" ).contents().find( "a" ).css( "background-color", "#BADA55" ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ contextmenu(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "contextmenu" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -2158,7 +2158,7 @@ div.contextmenu(function() { ``` */ - contextmenu(handler?: JQuery.TypeEventHandler | + contextmenu(handler?: JQuery.TypeEventHandler | false): this; /** * Set one or more CSS properties for the set of matched elements. @@ -2620,7 +2620,7 @@ $( "button" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ dblclick(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -2674,7 +2674,7 @@ divdbl.dblclick(function() { ``` */ - dblclick(handler?: JQuery.TypeEventHandler | + dblclick(handler?: JQuery.TypeEventHandler | false): this; /** * Set a timer to delay execution of subsequent items in the queue. @@ -2745,7 +2745,7 @@ $( "button" ).click(function() { selector: JQuery.Selector, eventType: TType, eventData: TData, - handler: JQuery.TypeEventHandler + handler: JQuery.TypeEventHandler ): this; /** * Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. @@ -2861,7 +2861,7 @@ $( "button" ).click(function() { delegate( selector: JQuery.Selector, eventType: TType, - handler: JQuery.TypeEventHandler | + handler: JQuery.TypeEventHandler | false ): this; /** @@ -2877,7 +2877,7 @@ $( "button" ).click(function() { * **Solution**: Change the method call to use `.on()` or `.off()`, the documentation for the old methods include specific instructions. In general, the `.bind()` and `.unbind()` methods can be renamed directly to `.on()` and `.off()` respectively since the argument orders are identical. */ delegate(selector: JQuery.Selector, - events: JQuery.TypeEventHandlers + events: JQuery.TypeEventHandlers ): this; /** * Execute the next function on the queue for the matched elements. @@ -4298,7 +4298,7 @@ $( "p span" ).first().addClass( "highlight" ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focus(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focus" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -4350,7 +4350,7 @@ $( document ).ready(function() { }); ``` */ - focus(handler?: JQuery.TypeEventHandler | + focus(handler?: JQuery.TypeEventHandler | false): this; /** * Bind an event handler to the "focusin" event. @@ -4365,7 +4365,7 @@ $( document ).ready(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focusin(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focusin" event. * @param handler A function to execute each time the event is triggered. @@ -4405,7 +4405,7 @@ $( "p" ).focusin(function() { ``` */ - focusin(handler?: JQuery.TypeEventHandler | + focusin(handler?: JQuery.TypeEventHandler | false): this; /** * Bind an event handler to the "focusout" JavaScript event. @@ -4420,7 +4420,7 @@ $( "p" ).focusin(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focusout(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focusout" JavaScript event. * @param handler A function to execute each time the event is triggered. @@ -4481,7 +4481,7 @@ $( "p" ) ``` */ - focusout(handler?: JQuery.TypeEventHandler | + focusout(handler?: JQuery.TypeEventHandler | false): this; /** * Retrieve one of the elements matched by the jQuery object. @@ -4998,9 +4998,9 @@ $( "td" ).hover( $( "td" ).off( "mouseenter mouseleave" ); ``` */ - hover(handlerIn: JQuery.TypeEventHandler | + hover(handlerIn: JQuery.TypeEventHandler | false, - handlerOut: JQuery.TypeEventHandler | + handlerOut: JQuery.TypeEventHandler | false): this; /** * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. @@ -5067,7 +5067,7 @@ $( "li" ) ``` */ - hover(handlerInOut: JQuery.TypeEventHandler | + hover(handlerInOut: JQuery.TypeEventHandler | false): this; /** * Set the HTML contents of each element in the set of matched elements. @@ -5882,7 +5882,7 @@ $( "li" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keydown(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -5954,7 +5954,7 @@ $( "#other" ).click(function() { ``` */ - keydown(handler?: JQuery.TypeEventHandler | + keydown(handler?: JQuery.TypeEventHandler | false): this; /** * Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element. @@ -5969,7 +5969,7 @@ $( "#other" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keypress(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6041,7 +6041,7 @@ $( "#other" ).click(function() { ``` */ - keypress(handler?: JQuery.TypeEventHandler | + keypress(handler?: JQuery.TypeEventHandler | false): this; /** * Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element. @@ -6056,7 +6056,7 @@ $( "#other" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keyup(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6129,7 +6129,7 @@ $( "#other").click(function() { ``` */ - keyup(handler?: JQuery.TypeEventHandler | + keyup(handler?: JQuery.TypeEventHandler | false): this; /** * Reduce the set of matched elements to the final one in the set. @@ -6419,7 +6419,7 @@ $( "input" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mousedown(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6457,7 +6457,7 @@ $( "p" ) ``` */ - mousedown(handler?: JQuery.TypeEventHandler | + mousedown(handler?: JQuery.TypeEventHandler | false): this; /** * Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. @@ -6472,7 +6472,7 @@ $( "p" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseenter(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. * @param handler A function to execute each time the event is triggered. @@ -6553,7 +6553,7 @@ $( "div.enterleave" ) ``` */ - mouseenter(handler?: JQuery.TypeEventHandler | + mouseenter(handler?: JQuery.TypeEventHandler | false): this; /** * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. @@ -6568,7 +6568,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseleave(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. * @param handler A function to execute each time the event is triggered. @@ -6647,7 +6647,7 @@ $( "div.enterleave" ) ``` */ - mouseleave(handler?: JQuery.TypeEventHandler | + mouseleave(handler?: JQuery.TypeEventHandler | false): this; /** * Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element. @@ -6662,7 +6662,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mousemove(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6726,7 +6726,7 @@ $( "div" ).mousemove(function( event ) { ``` */ - mousemove(handler?: JQuery.TypeEventHandler | + mousemove(handler?: JQuery.TypeEventHandler | false): this; /** * Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element. @@ -6741,7 +6741,7 @@ $( "div" ).mousemove(function( event ) { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseout(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6822,7 +6822,7 @@ $( "div.enterleave" ) ``` */ - mouseout(handler?: JQuery.TypeEventHandler | + mouseout(handler?: JQuery.TypeEventHandler | false): this; /** * Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element. @@ -6837,7 +6837,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseover(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6918,7 +6918,7 @@ $( "div.enterleave" ) ``` */ - mouseover(handler?: JQuery.TypeEventHandler | + mouseover(handler?: JQuery.TypeEventHandler | false): this; /** * Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element. @@ -6933,7 +6933,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseup(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6971,7 +6971,7 @@ $( "p" ) ``` */ - mouseup(handler?: JQuery.TypeEventHandler | + mouseup(handler?: JQuery.TypeEventHandler | false): this; /** * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. @@ -7306,7 +7306,7 @@ $( "body" ).off( "click", "p", foo ); */ off(events: string, selector: JQuery.Selector, - handler: JQuery.TypeEventHandler | + handler: JQuery.TypeEventHandler | false): this; /** * Remove an event handler. @@ -7339,7 +7339,7 @@ $( "form" ).off( ".validator" ); */ off(events: string, selector_handler?: JQuery.Selector | - JQuery.TypeEventHandler | + JQuery.TypeEventHandler | false): this; /** * Remove an event handler. @@ -7349,7 +7349,7 @@ $( "form" ).off( ".validator" ); * @see \`{@link https://api.jquery.com/off/ }\` * @since 1.7 */ - off(events: JQuery.TypeEventHandlers, + off(events: JQuery.TypeEventHandlers, selector?: JQuery.Selector): this; /** * Remove an event handler. @@ -7539,7 +7539,7 @@ $( "*", document.body ).click(function( event ) { events: TType, selector: JQuery.Selector, data: TData, - handler: JQuery.TypeEventHandler + handler: JQuery.TypeEventHandler ): this; /** * Attach an event handler function for one or more events to the selected elements. @@ -7556,7 +7556,7 @@ $( "*", document.body ).click(function( event ) { events: TType, selector: null | undefined, data: TData, - handler: JQuery.TypeEventHandler + handler: JQuery.TypeEventHandler ): this; /** * Attach an event handler function for one or more events to the selected elements. @@ -7636,7 +7636,7 @@ $( "body" ).on( "click", "a", function( event ) { on( events: TType, selector: JQuery.Selector, - handler: JQuery.TypeEventHandler | + handler: JQuery.TypeEventHandler | false ): this; /** @@ -7658,7 +7658,7 @@ $( "p" ).on( "click", { foo: "bar" }, myHandler ); TData>( events: TType, data: TData, - handler: JQuery.TypeEventHandler + handler: JQuery.TypeEventHandler ): this; /** * Attach an event handler function for one or more events to the selected elements. @@ -7826,7 +7826,7 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { */ on( events: TType, - handler: JQuery.TypeEventHandler | + handler: JQuery.TypeEventHandler | false ): this; /** @@ -7933,7 +7933,7 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { * @since 1.7 */ on( - events: JQuery.TypeEventHandlers, + events: JQuery.TypeEventHandlers, selector: JQuery.Selector, data: TData ): this; @@ -7948,7 +7948,7 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { * @since 1.7 */ on( - events: JQuery.TypeEventHandlers, + events: JQuery.TypeEventHandlers, selector: null | undefined, data: TData ): this; @@ -7961,7 +7961,7 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: JQuery.TypeEventHandlers, + on(events: JQuery.TypeEventHandlers, selector: JQuery.Selector ): this; /** @@ -7973,7 +7973,7 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { * @since 1.7 */ on( - events: JQuery.TypeEventHandlers, + events: JQuery.TypeEventHandlers, data: TData ): this; /** @@ -8024,7 +8024,7 @@ $( "div.test" ).on({ ``` */ - on(events: JQuery.TypeEventHandlers): this; + on(events: JQuery.TypeEventHandlers): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -8040,7 +8040,7 @@ $( "div.test" ).on({ events: TType, selector: JQuery.Selector, data: TData, - handler: JQuery.TypeEventHandler + handler: JQuery.TypeEventHandler ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. @@ -8057,7 +8057,7 @@ $( "div.test" ).on({ events: TType, selector: null | undefined, data: TData, - handler: JQuery.TypeEventHandler + handler: JQuery.TypeEventHandler ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. @@ -8072,7 +8072,7 @@ $( "div.test" ).on({ one( events: TType, selector: JQuery.Selector, - handler: JQuery.TypeEventHandler | + handler: JQuery.TypeEventHandler | false ): this; /** @@ -8087,7 +8087,7 @@ $( "div.test" ).on({ TData>( events: TType, data: TData, - handler: JQuery.TypeEventHandler + handler: JQuery.TypeEventHandler ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. @@ -8179,7 +8179,7 @@ $(".target").one("click mouseenter", function() { */ one( events: TType, - handler: JQuery.TypeEventHandler| + handler: JQuery.TypeEventHandler| false ): this; /** @@ -8193,7 +8193,7 @@ $(".target").one("click mouseenter", function() { * @since 1.7 */ one( - events: JQuery.TypeEventHandlers, + events: JQuery.TypeEventHandlers, selector: JQuery.Selector, data: TData ): this; @@ -8208,7 +8208,7 @@ $(".target").one("click mouseenter", function() { * @since 1.7 */ one( - events: JQuery.TypeEventHandlers, + events: JQuery.TypeEventHandlers, selector: null | undefined, data: TData ): this; @@ -8221,7 +8221,7 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.TypeEventHandlers, + one(events: JQuery.TypeEventHandlers, selector: JQuery.Selector): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. @@ -8232,7 +8232,7 @@ $(".target").one("click mouseenter", function() { * @since 1.7 */ one( - events: JQuery.TypeEventHandlers, + events: JQuery.TypeEventHandlers, data: TData ): this; /** @@ -8242,7 +8242,7 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.TypeEventHandlers): this; + one(events: JQuery.TypeEventHandlers): this; /** * Set the CSS outer height of each element in the set of matched elements. * @param value_function _@param_ `value_function` @@ -10000,7 +10000,7 @@ $( "button" ).on( "click", function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ resize(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "resize" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -10018,7 +10018,7 @@ $( window ).resize(function() { }); ``` */ - resize(handler?: JQuery.TypeEventHandler | + resize(handler?: JQuery.TypeEventHandler | false): this; /** * Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. @@ -10033,7 +10033,7 @@ $( window ).resize(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ scroll(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -10083,7 +10083,7 @@ $( window ).scroll(function() { ``` */ - scroll(handler?: JQuery.TypeEventHandler | + scroll(handler?: JQuery.TypeEventHandler | false): this; /** * Set the current horizontal position of the scroll bar for each of the set of matched elements. @@ -10258,7 +10258,7 @@ $( "p:last" ).text( "scrollTop:" + p.scrollTop() ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ select(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "select" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -10307,7 +10307,7 @@ $( ":input" ).select(function() { $( "input" ).select(); ``` */ - select(handler?: JQuery.TypeEventHandler | + select(handler?: JQuery.TypeEventHandler | false): this; /** * Encode a set of form elements as a string for submission. @@ -11279,7 +11279,7 @@ $( "#toggle" ).on( "click", function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ submit(eventData: TData, - handler: JQuery.TypeEventHandler): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "submit" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -11348,7 +11348,7 @@ $( "form" ).submit(function() { $( "form:first" ).submit(); ``` */ - submit(handler?: JQuery.TypeEventHandler | + submit(handler?: JQuery.TypeEventHandler | false): this; /** * Set the content of each element in the set of matched elements to the specified text. @@ -11969,7 +11969,7 @@ $( "p" ).unbind( "click", foo ); // ... foo will no longer be called. ``` */ unbind(event: string, - handler: JQuery.TypeEventHandler | + handler: JQuery.TypeEventHandler | false ): this; /** @@ -12064,7 +12064,7 @@ $( "body" ).undelegate( "p", "click", foo ); */ undelegate(selector: JQuery.Selector, eventType: string, - handler: JQuery.TypeEventHandler | + handler: JQuery.TypeEventHandler | false ): this; /** @@ -12085,7 +12085,7 @@ $( "body" ).undelegate( "p", "click", foo ); */ undelegate(selector: JQuery.Selector, eventType_events: string | - JQuery.TypeEventHandlers): this; + JQuery.TypeEventHandlers): this; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. * @param namespace A selector which will be used to filter the event results. diff --git a/types/jquery/misc.d.ts b/types/jquery/misc.d.ts index dd05435043..553f3a58ed 100644 --- a/types/jquery/misc.d.ts +++ b/types/jquery/misc.d.ts @@ -6314,20 +6314,18 @@ $( "#checkMetaKey" ).click(function( event ) { TData, TCurrentTarget, TTarget, - TContext, TType extends keyof TypeToTriggeredEventMap - > = EventHandlerBase[TType]>; + > = EventHandlerBase[TType]>; interface TypeEventHandlers< TDelegateTarget, TData, TCurrentTarget, - TTarget, - TContext - > extends _TypeEventHandlers { + TTarget + > extends _TypeEventHandlers { // No idea why it's necessary to include `object` in the union but otherwise TypeScript complains that // derived types of Event are not assignable to Event. - [type: string]: TypeEventHandler | + [type: string]: TypeEventHandler | false | undefined | object; @@ -6337,11 +6335,10 @@ $( "#checkMetaKey" ).click(function( event ) { TDelegateTarget, TData, TCurrentTarget, - TTarget, - TContext + TTarget > = { [TType in keyof TypeToTriggeredEventMap]?: - TypeEventHandler | + TypeEventHandler | false | object; }; diff --git a/types/jquery/test/longdesc-tests.ts b/types/jquery/test/longdesc-tests.ts index f3cf559638..8c5382f904 100644 --- a/types/jquery/test/longdesc-tests.ts +++ b/types/jquery/test/longdesc-tests.ts @@ -538,7 +538,7 @@ function longdesc() { $('#foo').slideUp(300).delay(800).fadeIn(400); } - function delegate_0(elements: HTMLElement[], selector: string, events: string, data: any, handler: JQuery.TypeEventHandler) { + function delegate_0(elements: HTMLElement[], selector: string, events: string, data: any, handler: JQuery.TypeEventHandler) { // jQuery 1.4.3+ $(elements).delegate(selector, events, data, handler); // jQuery 1.7+ From 33c6e58f6e3d5d1bcc9d02710d7f7d634645337e Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Thu, 1 Nov 2018 10:01:29 -0400 Subject: [PATCH 256/836] [jquery] Add missing `TTarget` type parameter to touch events. --- types/jquery/misc.d.ts | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/types/jquery/misc.d.ts b/types/jquery/misc.d.ts index 553f3a58ed..481b79e037 100644 --- a/types/jquery/misc.d.ts +++ b/types/jquery/misc.d.ts @@ -5722,8 +5722,9 @@ $( "#checkMetaKey" ).click(function( event ) { interface TouchEventBase< TDelegateTarget = any, TData = any, - TCurrentTarget = any - > extends UIEventBase { + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { /** * The other DOM element involved in the event, if any. * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` @@ -5948,32 +5949,36 @@ $( "#checkMetaKey" ).click(function( event ) { interface TouchCancelEvent< TDelegateTarget = any, TData = any, - TCurrentTarget = any - > extends TouchEventBase { + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { type: 'touchcancel'; } interface TouchEndEvent< TDelegateTarget = any, TData = any, - TCurrentTarget = any - > extends TouchEventBase { + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { type: 'touchend'; } interface TouchMoveEvent< TDelegateTarget = any, TData = any, - TCurrentTarget = any - > extends TouchEventBase { + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { type: 'touchmove'; } interface TouchStartEvent< TDelegateTarget = any, TData = any, - TCurrentTarget = any - > extends TouchEventBase { + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { type: 'touchstart'; } @@ -6286,10 +6291,10 @@ $( "#checkMetaKey" ).click(function( event ) { // TouchEvent - touchcancel: TouchCancelEvent; - touchend: TouchEndEvent; - touchmove: TouchMoveEvent; - touchstart: TouchStartEvent; + touchcancel: TouchCancelEvent; + touchend: TouchEndEvent; + touchmove: TouchMoveEvent; + touchstart: TouchStartEvent; // FocusEvent From e573d98516efcf5da8773cc97d337475405dc291 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Thu, 1 Nov 2018 10:39:42 -0400 Subject: [PATCH 257/836] [jquery] Add tests for `JQuery.TypeEventHandlers`. --- types/jquery/jquery-tests.ts | 161 +++++++++++++++++++++++++++++++++++ 1 file changed, 161 insertions(+) diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 069e8613d6..c533f1b235 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -7862,6 +7862,167 @@ function JQuery_Event() { } } +function JQuery_TypeEventHandlers() { + const events: JQuery.TypeEventHandlers = { + change(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ChangeEvent + event; + }, + resize(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ResizeEvent + event; + }, + scroll(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ScrollEvent + event; + }, + select(event) { + // $ExpectType HTMLElement + this; + // $ExpectType SelectEvent + event; + }, + submit(event) { + // $ExpectType HTMLElement + this; + // $ExpectType SubmitEvent + event; + }, + click(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ClickEvent + event; + }, + contextmenu(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ContextMenuEvent + event; + }, + dblclick(event) { + // $ExpectType HTMLElement + this; + // $ExpectType DoubleClickEvent + event; + }, + mousedown(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseDownEvent + event; + }, + mouseenter(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseEnterEvent + event; + }, + mouseleave(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseLeaveEvent + event; + }, + mousemove(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseMoveEvent + event; + }, + mouseout(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseOutEvent + event; + }, + mouseover(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseOverEvent + event; + }, + mouseup(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseUpEvent + event; + }, + keydown(event) { + // $ExpectType HTMLElement + this; + // $ExpectType KeyDownEvent + event; + }, + keypress(event) { + // $ExpectType HTMLElement + this; + // $ExpectType KeyPressEvent + event; + }, + keyup(event) { + // $ExpectType HTMLElement + this; + // $ExpectType KeyUpEvent + event; + }, + touchcancel(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchCancelEvent + event; + }, + touchend(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchEndEvent + event; + }, + touchmove(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchMoveEvent + event; + }, + touchstart(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchStartEvent + event; + }, + blur(event) { + // $ExpectType HTMLElement + this; + // $ExpectType BlurEvent + event; + }, + focus(event) { + // $ExpectType HTMLElement + this; + // $ExpectType FocusEvent + event; + }, + focusin(event) { + // $ExpectType HTMLElement + this; + // $ExpectType FocusInEvent + event; + }, + focusout(event) { + // $ExpectType HTMLElement + this; + // $ExpectType FocusOutEvent + event; + } + }; +} + function JQuery_EventExtensions() { function special() { jQuery.event.special.multiclick = { From bf2beee34cc2b64128bbbde858a476fcaba976e2 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sat, 24 Nov 2018 09:45:54 -0500 Subject: [PATCH 258/836] [jquery] Fix no-angle-bracket-type-assertion violations. --- types/jquery/test/example-tests.ts | 2 +- types/jquery/test/longdesc-tests.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/jquery/test/example-tests.ts b/types/jquery/test/example-tests.ts index 673e549c31..77d412f8e1 100644 --- a/types/jquery/test/example-tests.ts +++ b/types/jquery/test/example-tests.ts @@ -1578,7 +1578,7 @@ function examples() { function event_related_target_0() { $('a').mouseout(function(event) { - alert(( event.relatedTarget).nodeName); // "DIV" + alert((event.relatedTarget as HTMLElement).nodeName); // "DIV" }); } diff --git a/types/jquery/test/longdesc-tests.ts b/types/jquery/test/longdesc-tests.ts index 8c5382f904..e1ee36a575 100644 --- a/types/jquery/test/longdesc-tests.ts +++ b/types/jquery/test/longdesc-tests.ts @@ -886,7 +886,7 @@ function longdesc() { var currentRequests: JQuery.PlainObject = {}; $.ajaxPrefilter(function(options, originalOptions, jqXHR) { - if (( options).abortOnRetry) { + if ((options as any).abortOnRetry) { if (currentRequests[options.url!]) { currentRequests[options.url!].abort(); } @@ -1297,7 +1297,7 @@ function longdesc() { return $.css(elem, borderRadius!); }, set: function(elem, value) { - ( elem.style)[borderRadius!] = value; + (elem.style as any)[borderRadius!] = value; }, }; } From e067afd74c6a54eb618b82b92f195b9a21b7f0d8 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Sat, 24 Nov 2018 10:22:29 -0500 Subject: [PATCH 259/836] Disable no-angle-bracket-type-assertion rule. --- types/angular-agility/tslint.json | 3 ++- types/angular-locker/tslint.json | 3 ++- types/angular-odata-resources/tslint.json | 3 ++- types/angular-ui-tree/tslint.json | 3 ++- types/angularfire/tslint.json | 3 ++- types/bootstrap-slider/tslint.json | 5 ++++- types/datatables.net/tslint.json | 7 ++++++- types/devexpress-web/v172/tslint.json | 3 ++- types/devexpress-web/v181/tslint.json | 3 ++- types/ej.web.all/tslint.json | 3 ++- types/gridstack/tslint.json | 3 ++- types/highcharts/tslint.json | 3 ++- types/intl-tel-input/v13/tslint.json | 3 ++- types/jquery.colorpicker/tslint.json | 3 ++- types/jquery.fancytree/tslint.json | 3 ++- types/jquery.pjax/tslint.json | 3 ++- types/kendo-ui/tslint.json | 3 ++- types/ng-cordova/tslint.json | 3 ++- types/ng-flow/tslint.json | 3 ++- types/ng-grid/tslint.json | 3 ++- types/openui5/tslint.json | 3 ++- types/q/tslint.json | 3 ++- types/q/v0/tslint.json | 3 ++- types/qtip2/tslint.json | 3 ++- types/sammy/tslint.json | 3 ++- types/segment-analytics/tslint.json | 3 ++- types/selectize/tslint.json | 3 ++- types/space-pen/tslint.json | 3 ++- types/toastr/tslint.json | 3 ++- 29 files changed, 64 insertions(+), 29 deletions(-) diff --git a/types/angular-agility/tslint.json b/types/angular-agility/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-agility/tslint.json +++ b/types/angular-agility/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular-locker/tslint.json b/types/angular-locker/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-locker/tslint.json +++ b/types/angular-locker/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular-odata-resources/tslint.json b/types/angular-odata-resources/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-odata-resources/tslint.json +++ b/types/angular-odata-resources/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular-ui-tree/tslint.json b/types/angular-ui-tree/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-ui-tree/tslint.json +++ b/types/angular-ui-tree/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angularfire/tslint.json b/types/angularfire/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angularfire/tslint.json +++ b/types/angularfire/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/bootstrap-slider/tslint.json b/types/bootstrap-slider/tslint.json index f93cf8562a..1c36270d47 100644 --- a/types/bootstrap-slider/tslint.json +++ b/types/bootstrap-slider/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } } diff --git a/types/datatables.net/tslint.json b/types/datatables.net/tslint.json index 3db14f85ea..2b6ccb9109 100644 --- a/types/datatables.net/tslint.json +++ b/types/datatables.net/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } +} \ No newline at end of file diff --git a/types/devexpress-web/v172/tslint.json b/types/devexpress-web/v172/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/devexpress-web/v172/tslint.json +++ b/types/devexpress-web/v172/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/devexpress-web/v181/tslint.json b/types/devexpress-web/v181/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/devexpress-web/v181/tslint.json +++ b/types/devexpress-web/v181/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ej.web.all/tslint.json b/types/ej.web.all/tslint.json index 35e3f27cc8..0615bdcb0e 100644 --- a/types/ej.web.all/tslint.json +++ b/types/ej.web.all/tslint.json @@ -37,6 +37,7 @@ "radix": false, "prefer-for-of": false, "one-line": false, - "no-unnecessary-type-assertion": false + "no-unnecessary-type-assertion": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/gridstack/tslint.json b/types/gridstack/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/gridstack/tslint.json +++ b/types/gridstack/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/highcharts/tslint.json b/types/highcharts/tslint.json index cfc8218eab..c663b9324a 100644 --- a/types/highcharts/tslint.json +++ b/types/highcharts/tslint.json @@ -9,6 +9,7 @@ "no-declare-current-package": false, "no-object-literal-type-assertion": false, "no-self-import": false, - "no-unnecessary-generics": false + "no-unnecessary-generics": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/intl-tel-input/v13/tslint.json b/types/intl-tel-input/v13/tslint.json index b6afb8acee..d2632b3e92 100644 --- a/types/intl-tel-input/v13/tslint.json +++ b/types/intl-tel-input/v13/tslint.json @@ -75,6 +75,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/jquery.colorpicker/tslint.json b/types/jquery.colorpicker/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/jquery.colorpicker/tslint.json +++ b/types/jquery.colorpicker/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/jquery.fancytree/tslint.json b/types/jquery.fancytree/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/jquery.fancytree/tslint.json +++ b/types/jquery.fancytree/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/jquery.pjax/tslint.json b/types/jquery.pjax/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/jquery.pjax/tslint.json +++ b/types/jquery.pjax/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/kendo-ui/tslint.json b/types/kendo-ui/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/kendo-ui/tslint.json +++ b/types/kendo-ui/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ng-cordova/tslint.json b/types/ng-cordova/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/ng-cordova/tslint.json +++ b/types/ng-cordova/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ng-flow/tslint.json b/types/ng-flow/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/ng-flow/tslint.json +++ b/types/ng-flow/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ng-grid/tslint.json b/types/ng-grid/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/ng-grid/tslint.json +++ b/types/ng-grid/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/openui5/tslint.json b/types/openui5/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/openui5/tslint.json +++ b/types/openui5/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/q/tslint.json b/types/q/tslint.json index 0bded8e292..4af8abbc8d 100644 --- a/types/q/tslint.json +++ b/types/q/tslint.json @@ -7,6 +7,7 @@ "no-unnecessary-type-assertion": false, "prefer-declare-function": false, "strict-export-declare-modifiers": false, - "unified-signatures": false + "unified-signatures": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/q/v0/tslint.json b/types/q/v0/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/q/v0/tslint.json +++ b/types/q/v0/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/qtip2/tslint.json b/types/qtip2/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/qtip2/tslint.json +++ b/types/qtip2/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/sammy/tslint.json b/types/sammy/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/sammy/tslint.json +++ b/types/sammy/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/segment-analytics/tslint.json b/types/segment-analytics/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/segment-analytics/tslint.json +++ b/types/segment-analytics/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/selectize/tslint.json b/types/selectize/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/selectize/tslint.json +++ b/types/selectize/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/space-pen/tslint.json b/types/space-pen/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/space-pen/tslint.json +++ b/types/space-pen/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/toastr/tslint.json b/types/toastr/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/toastr/tslint.json +++ b/types/toastr/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } From 035abe6ab2d244ae4df8a01f9e0938a2283e9d06 Mon Sep 17 00:00:00 2001 From: Clark Stevenson Date: Sat, 24 Nov 2018 17:37:34 +0000 Subject: [PATCH 260/836] Minor Update to Pixi.js - Fixes missing `animations` and incorrect type - Renames Filter param `uniforms` to `uniformData` --- types/pixi.js/index.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/types/pixi.js/index.d.ts b/types/pixi.js/index.d.ts index 7c05701e75..4d86533fed 100644 --- a/types/pixi.js/index.d.ts +++ b/types/pixi.js/index.d.ts @@ -1585,7 +1585,7 @@ declare namespace PIXI { constructor( vertexSrc?: string, fragmentSrc?: string, - uniforms?: UniformDataMap + uniformData?: UniformDataMap ); protected _blendMode: number; @@ -2312,7 +2312,7 @@ declare namespace PIXI { ); baseTexture: BaseTexture; - animations: { [key: string]: Texture }; + animations: { [key: string]: Texture[] }; textures: { [key: string]: Texture }; data: any; resolution: number; @@ -3346,6 +3346,7 @@ declare namespace PIXI { spineAtlas: any; spineData: any; textures?: TextureDictionary; + spritesheet?: Spritesheet; } const shared: Loader; } From 5b221ee794c64ee920db8e9b21b5c677faf1f715 Mon Sep 17 00:00:00 2001 From: Simon Schick Date: Sat, 24 Nov 2018 09:30:07 -0800 Subject: [PATCH 261/836] feat(hapi): 17.8 --- types/hapi/index.d.ts | 56 +++++++++++++++++--- types/hapi/test/server/server-auth-api.ts | 12 +++-- types/hapi/test/server/server-auth-test.ts | 8 ++- types/hapi/test/server/server-auth-verify.ts | 26 +++++++++ types/hapi/test/server/server-plugins.ts | 17 ++++-- types/hapi/tsconfig.json | 1 + 6 files changed, 104 insertions(+), 16 deletions(-) create mode 100644 types/hapi/test/server/server-auth-verify.ts diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 644c48c5d1..3e323f8c44 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for hapi 17.6 +// Type definitions for hapi 17.8 // Project: https://github.com/hapijs/hapi // Definitions by: Rafael Souza Fijalkowski // Justin Simms @@ -42,6 +42,18 @@ import { PolicyOptionVariants, EnginePrototypeOrObject, PolicyOptions, EnginePro + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +/** + * one of + * a single plugin name string. + * an array of plugin name strings. + * an object where each key is a plugin name and each matching value is a + * {@link https://www.npmjs.com/package/semver version range string} which must match the registered + * plugin version. + */ +export type Dependencies = string | string[] | { + [key: string]: string; +}; + /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) */ @@ -126,7 +138,16 @@ export interface PluginBase { multiple?: boolean; /** (optional) a string or an array of strings indicating a plugin dependency. Same as setting dependencies via server.dependency(). */ - dependencies?: string | string[]; + dependencies?: Dependencies; + + /** + * Allows defining semver requirements for node and hapi. + * @default Allows all. + */ + requirements?: { + node?: string; + hapi?: string; + }; /** once - (optional) if true, will only register the plugin once per server. If set, overrides the once option passed to server.register(). Defaults to no override. */ once?: boolean; @@ -2013,6 +2034,15 @@ export interface ServerAuthSchemeObject { */ response?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + /** + * a method used to verify the authentication credentials provided + * are still valid (e.g. not expired or revoked after the initial authentication). + * the method throws an `Error` when the credentials passed are no longer valid (e.g. expired or + * revoked). Note that the method does not have access to the original request, only to the + * credentials and artifacts produced by the `authenticate()` method. + */ + verify?(auth: RequestAuth): Promise; + /** * An object with the following keys: * * payload @@ -2040,7 +2070,7 @@ export interface ServerAuth { * returned from its implementation function. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi) */ - api: Util.Dictionary; + api: Util.Dictionary; /** * Contains the default authentication configuration is a default strategy was set via @@ -2100,7 +2130,19 @@ export interface ServerAuth { * include verifying scope, entity, or other route properties. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) */ - test(strategy: string, request: Request): Promise; + test(strategy: string, request: Request): Promise; + + /** + * Verify a request's authentication credentials against an authentication strategy. + * Returns nothing if verification was successful, otherwise throws an error. + * + * Note that the `verify()` method does not take into account the route authentication configuration + * or any other information from the request other than the `request.auth` object. It also does not + * perform payload authentication. It is limited to verifying that the previously valid credentials + * are still valid (e.g. have not been revoked or expired). It does not include verifying scope, + * entity, or other route properties. + */ + verify(request: Request): Promise; } export type CachePolicyOptions = PolicyOptionVariants & { @@ -3302,7 +3344,7 @@ export class Server { /** * Server Auth: properties and methods */ - auth: ServerAuth; + readonly auth: ServerAuth; /** * Links another server to the initialize/start/stop state of the current server by calling the @@ -3542,7 +3584,7 @@ export class Server { /** * Used within a plugin to declare a required dependency on other plugins where: - * @param dependencies - a single string or an array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is + * @param dependencies - plugins which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is * initialized or started. * @param after - (optional) a function that is called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is * initialized or started. The function signature is async function(server) where: server - the server the dependency() method was called on. @@ -3552,7 +3594,7 @@ export class Server { * The method does not provide version dependency which should be implemented using npm peer dependencies. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after) */ - dependency(dependencies: string | string[], after?: ((server: Server) => Promise)): void; + dependency(dependencies: Dependencies, after?: ((server: Server) => Promise)): void; /** * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where: diff --git a/types/hapi/test/server/server-auth-api.ts b/types/hapi/test/server/server-auth-api.ts index f1b51bda8c..4508c641c9 100644 --- a/types/hapi/test/server/server-auth-api.ts +++ b/types/hapi/test/server/server-auth-api.ts @@ -1,14 +1,18 @@ // https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi import { - Request, - ResponseToolkit, Server, ServerAuthScheme, - ServerAuthSchemeObject, - ServerAuthSchemeOptions } from "hapi"; import * as Boom from "boom"; +declare module 'hapi' { + interface ServerAuthSchemeObjectApi { + settings: { + x: number; + }; + } +} + const scheme: ServerAuthScheme = (server, options) => { return { api: { diff --git a/types/hapi/test/server/server-auth-test.ts b/types/hapi/test/server/server-auth-test.ts index 5103d11c7e..4e2a175e1a 100644 --- a/types/hapi/test/server/server-auth-test.ts +++ b/types/hapi/test/server/server-auth-test.ts @@ -3,6 +3,12 @@ import { Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions } from "hapi"; import * as Boom from "boom"; +declare module 'hapi' { + interface AuthCredentials { + name?: string; + } +} + const server = new Server({ port: 8000, }); @@ -15,7 +21,7 @@ const scheme: ServerAuthScheme = (server, options) => { if (!authorization) { throw Boom.unauthorized(null, 'Custom'); } - return h.authenticated({ credentials: { user: { a: 1} } }); + return h.authenticated({ credentials: { name: 'john', } }); } }; }; diff --git a/types/hapi/test/server/server-auth-verify.ts b/types/hapi/test/server/server-auth-verify.ts new file mode 100644 index 0000000000..ec788fcb59 --- /dev/null +++ b/types/hapi/test/server/server-auth-verify.ts @@ -0,0 +1,26 @@ +import { Request, Server, RequestAuth } from "hapi"; +import * as Boom from "boom"; + +const server = new Server({ + port: 8000, +}); + +server.auth.scheme('custom', () => ({ + authenticate() { + throw Boom.unauthorized(null, 'hurr'); + }, + async verify(_auth: RequestAuth) { + throw Boom.unauthorized(null, 'durr'); + } +})); +server.auth.strategy('default', 'custom'); + +server.route({ + method: 'GET', + path: '/', + async handler(request: Request) { + request.server.auth.verify(request); + } +}); + +server.start(); diff --git a/types/hapi/test/server/server-plugins.ts b/types/hapi/test/server/server-plugins.ts index 8de3fdc24f..03a3c76907 100644 --- a/types/hapi/test/server/server-plugins.ts +++ b/types/hapi/test/server/server-plugins.ts @@ -33,22 +33,31 @@ const plugin1: Plugin = { server.plugins.example.other = 'other'; console.log(server.plugins.example.key); // 'value' console.log(server.plugins.example.other); // 'other' - } + }, }; const plugin2: Plugin = { name: 'plugin2', - register: async (server: Server, options: Plugin2) => {} + register: async (server: Server, options: Plugin2) => {}, + dependencies: { + plugin1: '*', + }, + requirements: { + node: '>=8', + hapi: '>=1337', + }, }; const plugin3: Plugin = { name: 'plugin3', - register: async (server: Server, options: Plugin3) => {} + register: async (server: Server, options: Plugin3) => {}, + dependencies: ['plugin2'], }; const plugin4: Plugin = { name: 'plugin4', - register: (server: Server, options: Plugin4) => {} + register: (server: Server, options: Plugin4) => {}, + dependencies: 'plugin3', }; const server = new Server({ diff --git a/types/hapi/tsconfig.json b/types/hapi/tsconfig.json index 2804e84871..9df329c575 100644 --- a/types/hapi/tsconfig.json +++ b/types/hapi/tsconfig.json @@ -41,6 +41,7 @@ "test/server/server-auth-api.ts", "test/server/server-auth-default.ts", "test/server/server-auth-test.ts", + "test/server/server-auth-verify.ts", "test/server/server-bind.ts", "test/server/server-cache-provision.ts", "test/server/server-cache.ts", From 942d03b7421428db4d37aa6f3bdff683ebf1ba5f Mon Sep 17 00:00:00 2001 From: Clark Stevenson Date: Sat, 24 Nov 2018 17:53:33 +0000 Subject: [PATCH 262/836] Fixed TSLint Error --- types/pixi.js/pixi.js-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/pixi.js/pixi.js-tests.ts b/types/pixi.js/pixi.js-tests.ts index 48581e67fe..c311c1281b 100644 --- a/types/pixi.js/pixi.js-tests.ts +++ b/types/pixi.js/pixi.js-tests.ts @@ -1508,7 +1508,7 @@ function filters() { maggot.scale.set(1 + Math.random() * 0.3); //tslint:disable-next-line:whitespace - maggot.original = (maggot.scale).clone(); + maggot.original = (maggot.scale as PIXI.Point).clone(); this.maggots.push(maggot); } From d4183853313482fea63ce3e2ef8c3157509d81a9 Mon Sep 17 00:00:00 2001 From: Christian Chown Date: Sat, 24 Nov 2018 18:02:24 +0000 Subject: [PATCH 263/836] Extend typings to include the Enhanced Default Functionality --- types/react-infinite-calendar/index.d.ts | 34 ++++++++++++++----- .../react-infinite-calendar-tests.tsx | 13 ++++++- 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/types/react-infinite-calendar/index.d.ts b/types/react-infinite-calendar/index.d.ts index 2110d4dbd0..3f0c827ed9 100644 --- a/types/react-infinite-calendar/index.d.ts +++ b/types/react-infinite-calendar/index.d.ts @@ -6,16 +6,18 @@ import * as React from 'react'; +export type DateType = Date | string | number; + export interface ReactInfiniteCalendarProps { - selected?: Date | boolean; - width?: number | 'auto'; + selected?: DateType | false | { start: DateType; end: DateType }; + width?: number | 'auto' | '100%'; height?: number | 'auto'; - min?: Date; - max?: Date; - minDate?: Date; - maxDate?: Date; + min?: DateType; + max?: DateType; + minDate?: DateType; + maxDate?: DateType; disabledDays?: Array<0 | 1 | 2 | 3 | 4 | 5 | 6>; - disabledDates?: Date[]; + disabledDates?: DateType[]; display?: 'days' | 'years'; displayOptions?: { hideYearsOnSelect?: boolean; @@ -55,12 +57,28 @@ export interface ReactInfiniteCalendarProps { weekdayColor?: string; }; className?: string; - onSelect?: (date: string) => void; + onSelect?: (date: string | { eventType: EVENT_TYPE; start: Date; end: Date }) => void; onScroll?: (scrollTop: number) => void; onScrollEnd?: (scrollTop: number) => void; rowHeight?: number; autoFocus?: boolean; tabIndex?: number; + Component?: CalendarClass; +} + +export class Calendar extends React.Component {} +export type CalendarClass = React.ComponentClass; + +export function withRange(component: CalendarClass): CalendarClass; +export function withDateSelection(component: CalendarClass): CalendarClass; +export function withMultipleDates(component: CalendarClass): CalendarClass; +export function withKeyboardSupport(component: CalendarClass): CalendarClass; +export function defaultMultipleDateInterpolation(component: CalendarClass): CalendarClass; + +export enum EVENT_TYPE { + START = 1, + HOVER, + END } export default class ReactInfiniteCalendar extends React.Component {} diff --git a/types/react-infinite-calendar/react-infinite-calendar-tests.tsx b/types/react-infinite-calendar/react-infinite-calendar-tests.tsx index ff1918d539..ba4b6a0ec7 100644 --- a/types/react-infinite-calendar/react-infinite-calendar-tests.tsx +++ b/types/react-infinite-calendar/react-infinite-calendar-tests.tsx @@ -1,5 +1,11 @@ import * as React from 'react'; -import ReactInfiniteCalendar from 'react-infinite-calendar'; +import ReactInfiniteCalendar, { + Calendar, + withRange, + withKeyboardSupport, + withMultipleDates, + withDateSelection +} from 'react-infinite-calendar'; const test: React.SFC = () => ( ( tabIndex={1} /> ); + +const testWithRange = withRange(Calendar); +const testWithDateSelection = withDateSelection(Calendar); +const testWithKeyboardSupport = withKeyboardSupport(Calendar); +const testWithMultipleDate = withMultipleDates(Calendar); From 0f79f9e451ad86718cf3baaca65b5c229bab7593 Mon Sep 17 00:00:00 2001 From: Albert Kurniawan Date: Wed, 14 Nov 2018 21:16:39 +0000 Subject: [PATCH 264/836] Remove morcerf from codeowners --- .github/CODEOWNERS | 6 +++--- types/connect-redis/index.d.ts | 1 - types/react/index.d.ts | 1 - types/react/v15/index.d.ts | 1 - 4 files changed, 3 insertions(+), 6 deletions(-) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index df45a8a9e7..0305e57c9b 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -644,7 +644,7 @@ /types/connect-mongo/ @Syati /types/connect-mongodb-session/ @NattapongSiri /types/connect-pg-simple/ @pasieronen -/types/connect-redis/ @xstoudi @morcerf +/types/connect-redis/ @xstoudi /types/connect-slashes/ @samherrmann /types/connect-timeout/ @cyrilschumacher /types/consola/ @Jungwoo-An @@ -3691,8 +3691,8 @@ /types/rdflib/ @cenotelie /types/re-base/ @jordandrako /types/reach__router/ @kingdaro -/types/react/v15/ @bbenezech @pzavolinsky @digiguru @ericanderson @morcerf @tkrotoff @DovydasNavickas @onigoetz -/types/react/ @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @morcerf @tkrotoff @DovydasNavickas @onigoetz @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @hotell @franklixuefei +/types/react/v15/ @bbenezech @pzavolinsky @digiguru @ericanderson @tkrotoff @DovydasNavickas @onigoetz +/types/react/ @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @tkrotoff @DovydasNavickas @onigoetz @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @hotell @franklixuefei /types/react-adal/ @dkorolev1 /types/react-albus/ @sseppola @conradreuter @kuirak /types/react-alert/v2/ @ssyrell diff --git a/types/connect-redis/index.d.ts b/types/connect-redis/index.d.ts index 5675512795..c5a26de73a 100644 --- a/types/connect-redis/index.d.ts +++ b/types/connect-redis/index.d.ts @@ -1,7 +1,6 @@ // Type definitions for connect-redis // Project: https://npmjs.com/package/connect-redis // Definitions by: Xavier Stouder -// Albert Kurniawan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 25f3c710ae..ebcb097eda 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -8,7 +8,6 @@ // Patricio Zavolinsky // Digiguru // Eric Anderson -// Albert Kurniawan // Tanguy Krotoff // Dovydas Navickas // Stéphane Goetz diff --git a/types/react/v15/index.d.ts b/types/react/v15/index.d.ts index 78ec7d8951..ce2a523123 100644 --- a/types/react/v15/index.d.ts +++ b/types/react/v15/index.d.ts @@ -8,7 +8,6 @@ // Patricio Zavolinsky // Digiguru // Eric Anderson -// Albert Kurniawan // Tanguy Krotoff // Dovydas Navickas // Stéphane Goetz From 55aca0b31c103ca32fed346e63532cee17b00834 Mon Sep 17 00:00:00 2001 From: Ehab Khaireldin Date: Sat, 24 Nov 2018 19:58:45 +0100 Subject: [PATCH 265/836] johnny-five LCD class types --- types/johnny-five/index.d.ts | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/types/johnny-five/index.d.ts b/types/johnny-five/index.d.ts index 6a00952153..a770cd2126 100644 --- a/types/johnny-five/index.d.ts +++ b/types/johnny-five/index.d.ts @@ -365,22 +365,22 @@ export declare class LCD { rows: number; cols: number; - print(message: string): void; - useChar(char: string): void; - clear(): void; - cursor(row: number, col: number): void; - home(): void; - on(): void; - off(): void; - display(): void; - noDisplay(): void; - blink(): void; - noBlink(): void; - autoscroll(): void; - noAutoscroll(): void; - bgColor(color: any): void; - noBacklight(): void; - backlight(): void; + print(message: string): this; + useChar(char: string): this; + clear(): this; + cursor(row: number, col: number): this; + home(): this; + on(): this; + off(): this; + display(): this; + noDisplay(): this; + blink(): this; + noBlink(): this; + autoscroll(): this; + noAutoscroll(): this; + bgColor(color: any): this; + noBacklight(): this; + backlight(): this; } export interface LedOption { From dcda399637f7d78d7a7dd1c6ed1f5ccf01693a28 Mon Sep 17 00:00:00 2001 From: BamButz Date: Sun, 25 Nov 2018 12:25:56 +0100 Subject: [PATCH 266/836] Adding types for "hyper-aws4" --- types/hyper-aws4/hyper-aws4-tests.ts | 12 ++++++++++++ types/hyper-aws4/index.d.ts | 25 +++++++++++++++++++++++++ types/hyper-aws4/tsconfig.json | 23 +++++++++++++++++++++++ types/hyper-aws4/tslint.json | 1 + 4 files changed, 61 insertions(+) create mode 100644 types/hyper-aws4/hyper-aws4-tests.ts create mode 100644 types/hyper-aws4/index.d.ts create mode 100644 types/hyper-aws4/tsconfig.json create mode 100644 types/hyper-aws4/tslint.json diff --git a/types/hyper-aws4/hyper-aws4-tests.ts b/types/hyper-aws4/hyper-aws4-tests.ts new file mode 100644 index 0000000000..14caa34a9f --- /dev/null +++ b/types/hyper-aws4/hyper-aws4-tests.ts @@ -0,0 +1,12 @@ +import { sign, Request } from "hyper-aws4"; + +const signOption: Request = { + url: "https://us-west-1.hyper.sh/version", + method: "GET", + credential: { + accessKey: "6DPLADBPWYXDUVXLX34EJXBL", + secretKey: "2ldD1Yz0nzATl9vvagBwYTjglXBjVOWU8gV8aMm5" + } +}; + +sign(signOption); diff --git a/types/hyper-aws4/index.d.ts b/types/hyper-aws4/index.d.ts new file mode 100644 index 0000000000..bf2a0fafa8 --- /dev/null +++ b/types/hyper-aws4/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for hyper-aws4 1.1 +// Project: https://github.com/Tim-Zhang/hyper-aws4#readme +// Definitions by: BamButz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Credentials { + accessKey: string; + secretKey: string; +} + +export interface Header { + [header: string]: string; +} + +export type HttpMethods = "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; + +export interface Request { + url: string; + method?: HttpMethods; + body?: string; + headers?: Header; + credential?: Credentials; +} + +export function sign(request: Request, credential?: Credentials): Header; diff --git a/types/hyper-aws4/tsconfig.json b/types/hyper-aws4/tsconfig.json new file mode 100644 index 0000000000..6df2d811c1 --- /dev/null +++ b/types/hyper-aws4/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", + "hyper-aws4-tests.ts" + ] +} diff --git a/types/hyper-aws4/tslint.json b/types/hyper-aws4/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hyper-aws4/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 02da4b8731282cb35ed274cc337fcc64fd53f619 Mon Sep 17 00:00:00 2001 From: izmhr Date: Sun, 25 Nov 2018 20:40:27 +0900 Subject: [PATCH 267/836] Completely new definitions for SkyWay@1.1.17 and TypeScript@3.0 --- types/skyway/index.d.ts | 327 ++++++++++++++++------------------- types/skyway/skyway-tests.ts | 51 +++--- 2 files changed, 171 insertions(+), 207 deletions(-) diff --git a/types/skyway/index.d.ts b/types/skyway/index.d.ts index eb73937178..8cdbec4a8e 100644 --- a/types/skyway/index.d.ts +++ b/types/skyway/index.d.ts @@ -1,185 +1,154 @@ -// Type definitions for SkyWay -// Project: http://nttcom.github.io/skyway/ +// Type definitions for SkyWay@1.1.17 +// Project: https://github.com/skyway/skyway-js-sdk +// Based on Documentation for skyway-js-doc: https://github.com/skyway/skyway-js-sdk-doc // Definitions by: Toshiya Nakakura +// Atsushi Izumihara // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 -/// - -declare namespace PeerJs{ - interface PeerJSOption{ - key?: string; - host?: string; - port?: number; - path?: string; - secure?: boolean; - turn?: boolean; - config?: RTCPeerConnectionConfig; - debug?: number; - } - - interface PeerConnectOption{ - label?: string; - metadata?: any; - serialization?: string; - reliable?: boolean; - } - - interface DataConnection{ - send(data: any): void; - close(): void; - on(event: string, cb: ()=>void): void; - on(event: 'data', cb: (data: any)=>void): void; - on(event: 'open', cb: ()=>void): void; - on(event: 'close', cb: ()=>void): void; - on(event: 'error', cb: (err: any)=>void): void; - off(event: string, fn: Function, once?: boolean): void; - bufferSize: number; - dataChannel: RTCDataChannel; - label: string; - metadata: any; - open: boolean; - peerConnection: any; - peer: string; - reliable: boolean; - serialization: string; - type: string; - } - - interface MediaConnection{ - answer(stream?: any): void; - close(): void; - on(event: string, cb: ()=>void): void; - on(event: 'stream', cb: (stream: any)=>void): void; - on(event: 'close', cb: ()=>void): void; - on(event: 'error', cb: (err: any)=>void): void; - off(event: string, fn: Function, once?: boolean): void; - open: boolean; - metadata: any; - peer: string; - type: string; - } - - interface utilSupportsObj { - audioVideo: boolean; - data: boolean; - binary: boolean; - reliable: boolean; - } - - interface util{ - browser: string; - supports: utilSupportsObj; - } - - export interface Peer{ - /** - * - * @param id The brokering ID of the remote peer (their peer.id). - * @param options for specifying details about Peer Connection - */ - connect(id: string, options?: PeerJs.PeerConnectOption): PeerJs.DataConnection; - /** - * Connects to the remote peer specified by id and returns a data connection. - * @param id The brokering ID of the remote peer (their peer.id). - * @param stream The caller's media stream - */ - call(id: string, stream: any): PeerJs.MediaConnection; - /** - * Calls the remote peer specified by id and returns a media connection. - * @param event Event name - * @param cb Callback Function - */ - on(event: string, cb: ()=>void): void; - /** - * Emitted when a connection to the PeerServer is established. - * @param event Event name - * @param cb id is the brokering ID of the peer - */ - on(event: 'open', cb: (id: string)=>void): void; - /** - * Emitted when a new data connection is established from a remote peer. - * @param event Event name - * @param cb Callback Function - */ - on(event: 'connection', cb: (dataConnection: PeerJs.DataConnection)=>void): void; - /** - * Emitted when a remote peer attempts to call you. - * @param event Event name - * @param cb Callback Function - */ - on(event: 'call', cb: (mediaConnection: PeerJs.MediaConnection)=>void): void; - /** - * Emitted when the peer is destroyed and can no longer accept or create any new connections. - * @param event Event name - * @param cb Callback Function - */ - on(event: 'close', cb: ()=>void): void; - /** - * Emitted when the peer is disconnected from the signalling server - * @param event Event name - * @param cb Callback Function - */ - on(event: 'disconnected', cb: ()=>void): void; - /** - * Errors on the peer are almost always fatal and will destroy the peer. - * @param event Event name - * @param cb Callback Function - */ - on(event: 'error', cb: (err: any)=>void): void; - /** - * Remove event listeners.(EventEmitter3) - * @param {String} event The event we want to remove. - * @param {Function} fn The listener that we need to find. - * @param {Boolean} once Only remove once listeners. - */ - off(event: string, fn: Function, once?: boolean): void; - /** - * Close the connection to the server, leaving all existing data and media connections intact. - */ - disconnect(): void; - /** - * Close the connection to the server and terminate all existing connections. - */ - destroy(): void; - /** - * Get a list of available peer IDs - * @param callback - */ - listAllPeers(callback: (peerIds: Array)=>void): void; - - /** - * The brokering ID of this peer - */ - id: string; - /** - * A hash of all connections associated with this peer, keyed by the remote peer's ID. - */ - connections: any; - /** - * false if there is an active connection to the PeerServer. - */ - disconnected: boolean; - /** - * true if this peer and all of its connections can no longer be used. - */ - destroyed: boolean; - } +interface Options { + key: string; + debug?: number; + turn?: boolean; + credential?: Credential; + config?: RTCConfiguration; } -declare var Peer: { - prototype: RTCIceServer; - /** - * A peer can connect to other peers and listen for connections. - * @param id Other peers can connect to this peer using the provided ID. - * If no ID is given, one will be generated by the brokering server. - * @param options for specifying details about PeerServer - */ - new (id: string, options?: PeerJs.PeerJSOption): PeerJs.Peer; +interface Credential { + timestamp?: number; + ttl?: number; + authToken?: string; +} - /** - * A peer can connect to other peers and listen for connections. - * @param options for specifying details about PeerServer - */ - new (options: PeerJs.PeerJSOption): PeerJs.Peer; -}; +interface CallOptions { + metadata?: any; + videoBandWidth?: number; + audioBandwidth?: number; + videoCodec?: string; + audioCodec?: string; + videoReceiveEnabled?: boolean; + audioReceiveEnabled?: boolean; + label?: string; +} + +interface ConnectOptions { + metadata?: any; + serialization?: string; + dcInit?: RTCDataChannelInit; + label?: string; +} + +interface RoomOptions { + mode?: string; + stream?: MediaStream; + videoBandwidth?: number; + audioBandwidth?: number; + videoCodec?: string; + audioCodec?: string; + videoReceiveEnabled?: boolean; + audioReceiveEnabled?: boolean; +} + +interface AnswerOptions { + videoBandwidth?: number; + audioBandwidth?: number; + videoCodec?: string; + audioCodec?: string; +} + +declare class Peer { + constructor(id: string, options: Options); + constructor(options: Options); + + connections: any; + id: string; + open: boolean; + rooms: any; + + call(peerId: string, stream?: MediaStream, options?: CallOptions): MediaConnection | undefined; + connect(peerId: string, options?: ConnectOptions): DataConnection | undefined; + destroy(): undefined; + disconnect(): undefined; + joinRoom(roomName: string, roomOptions?: RoomOptions): SFURoom | MeshRoom | undefined | null; + listAllPeers(cb: (peerIds: Array) => void): void; + updateCredential(newCredential: Credential): undefined; + + on(event: string, cb: (ret: any) => void): void; + on(event: 'open', cb: (id: string) => void): void; + on(event: 'call', cb: (call: MediaConnection) => void): void; + on(event: 'close', cb: () => void): void; + on(event: 'connection', cb: (connection: DataConnection) => void): void; + on(event: 'disconnected', cb: (id: string) => void): void; + on(event: 'error', cb: (err: any) => void): void; +} + +declare class MediaConnection { + metadata: any; + open: boolean; + remoteId: string; + peer: string; + + answer(stream: MediaStream, options?: AnswerOptions): undefined; + close(): void | undefined; + replaceStream(stream: MediaStream): undefined; + + on(event: string, cb: () => void): void; + on(event: 'stream', cb: (stream: MediaStream) => void): void; + on(event: 'close', cb: () => void): void; + on(event: 'removeStream', cb: (reamoteStream: MediaStream) => void): void; +} + +declare class DataConnection { + metadata: any; + open: boolean; + remoteId: string; + peer: string; + + send(data: any): void; + close(): void | undefined; + + on(event: string, cb: () => void): void; + on(event: 'data', cb: (data: any) => void): void; + on(event: 'close', cb: () => void): void; +} + +interface DataObject { + src: string; + data: any; +} + +declare class MeshRoom { + close(): undefined; + getLog(): undefined; + replaceStream(stream: MediaSource): undefined; + send(data: any): undefined; + + on(event: string, cb: () => void): void; + on(event: 'open', cb: () => void): void; + on(event: 'peerJoin', cb: (peerId: string) => void): void; + on(event: 'peerLeave', cb: (peerId: string) => void): void; + on(event: 'log', cb: (logs: Array) => void): void; + once(event: 'log', cb: (logs: Array) => void): void; + on(event: 'stream', cb: (stream: MediaStream) => void): void; + on(event: 'data', cb: (object: DataObject) => void): void; + on(event: 'close', cb: () => void): void; + on(event: 'removeStream', cb: (stream: MediaStream) => void): void; +} + +declare class SFURoom { + close(): undefined; + getLog(): undefined; + replaceStream(stream: MediaSource): undefined; + send(data: any): undefined; + + on(event: string, cb: () => void): void; + on(event: 'open', cb: () => void): void; + on(event: 'peerJoin', cb: (peerId: string) => void): void; + on(event: 'peerLeave', cb: (peerId: string) => void): void; + on(event: 'log', cb: (logs: Array) => void): void; + once(event: 'log', cb: (logs: Array) => void): void; + on(event: 'stream', cb: (stream: MediaStream) => void): void; + on(event: 'data', cb: (object: DataObject) => void): void; + on(event: 'close', cb: () => void): void; + on(event: 'removeStream', cb: (stream: MediaStream) => void): void; +} diff --git a/types/skyway/skyway-tests.ts b/types/skyway/skyway-tests.ts index 2731192f75..46ee924bcb 100644 --- a/types/skyway/skyway-tests.ts +++ b/types/skyway/skyway-tests.ts @@ -1,44 +1,39 @@ -var peerByOption: PeerJs.Peer = new Peer({ +/// + +const peerByOption: Peer = new Peer({ key: 'peerKey', - debug: 3, + debug: 3 }); -peerByOption.listAllPeers(function(items){ - for(var i in items){ - console.log(decodeURI(items[i])); +peerByOption.listAllPeers((items) => { + for (let item in items) { + console.log(decodeURI(items[item])); } }); -var peerById: PeerJs.Peer = new Peer("peerid"); +const peerByIdAndOption: Peer = new Peer('peerid', { + key: 'peerKey', + debug: 3 +}); -var peerByIdAndOption: PeerJs.Peer = new Peer( - "peerId", - { - key: 'peerKey', - debug: 3, - }); - -var id = peerByOption.id; -var connections = peerByOption.connections; -var flag = peerByOption.disconnected; -flag = peerByOption.destroyed; +let id = peerByOption.id; +let connections = peerByOption.connections; peerByOption.disconnect(); peerByOption.destroy(); -var connection = peerById.connect("id", { +let connection = peerByOption.connect("id", { label: 'chat', serialization: 'none', - metadata: {message: 'hi i want to chat with you!'} + metadata: { message: 'hi i want to chat with you!' } }); -var call = peerById.call('callto-id', (window).localStream); +let call = peerByOption.call('callto-id', (window as any).localStream); -var openHandler=()=> console.log("open"); -peerById.on("open", openHandler); -peerById.on("connection", (c)=> console.log("connection")); -peerById.on("call", (media)=> console.log("call")); -peerById.on("close", ()=> console.log("close")); -peerById.on("disconnected", ()=> console.log("disconnected")); -peerById.on("error", (err)=> console.log(err)); -peerById.off("open", openHandler); +let openHandler = () => console.log("open"); +peerByOption.on("open", openHandler); +peerByOption.on("connection", (c) => console.log("connection")); +peerByOption.on("call", (media) => console.log("call")); +peerByOption.on("close", () => console.log("close")); +peerByOption.on("disconnected", () => console.log("disconnected")); +peerByOption.on("error", (err) => console.log(err)); From 0577b97e084594414b2db82616c72e91f04793ea Mon Sep 17 00:00:00 2001 From: izmhr Date: Sun, 25 Nov 2018 21:04:01 +0900 Subject: [PATCH 268/836] checking npm test error --- types/skyway/index.d.ts | 1 - types/skyway/skyway-tests.ts | 2 -- 2 files changed, 3 deletions(-) diff --git a/types/skyway/index.d.ts b/types/skyway/index.d.ts index 8cdbec4a8e..044768a08e 100644 --- a/types/skyway/index.d.ts +++ b/types/skyway/index.d.ts @@ -1,6 +1,5 @@ // Type definitions for SkyWay@1.1.17 // Project: https://github.com/skyway/skyway-js-sdk -// Based on Documentation for skyway-js-doc: https://github.com/skyway/skyway-js-sdk-doc // Definitions by: Toshiya Nakakura // Atsushi Izumihara // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/skyway/skyway-tests.ts b/types/skyway/skyway-tests.ts index 46ee924bcb..702a05e709 100644 --- a/types/skyway/skyway-tests.ts +++ b/types/skyway/skyway-tests.ts @@ -1,5 +1,3 @@ -/// - const peerByOption: Peer = new Peer({ key: 'peerKey', debug: 3 From e8a26cf2519bdf874690b3324751c03a0e4a99d2 Mon Sep 17 00:00:00 2001 From: Al Calzone Date: Sun, 25 Nov 2018 13:16:41 +0100 Subject: [PATCH 269/836] Add definition for removeAllListeners to noble --- types/noble/index.d.ts | 2 ++ types/noble/noble-tests.ts | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/types/noble/index.d.ts b/types/noble/index.d.ts index 61ca1f2113..5b4af235e7 100644 --- a/types/noble/index.d.ts +++ b/types/noble/index.d.ts @@ -30,6 +30,8 @@ export declare function removeListener(event: "scanStop", listener: () => void): export declare function removeListener(event: "discover", listener: (peripheral: Peripheral) => void): events.EventEmitter; export declare function removeListener(event: string, listener: Function): events.EventEmitter; +export declare function removeAllListeners(event?: string): events.EventEmitter; + export declare var state:string; export declare class Peripheral extends events.EventEmitter { diff --git a/types/noble/noble-tests.ts b/types/noble/noble-tests.ts index 0c8dcf6c20..a4441eba6e 100644 --- a/types/noble/noble-tests.ts +++ b/types/noble/noble-tests.ts @@ -35,6 +35,12 @@ noble.removeListener("discover", (peripheral: noble.Peripheral): void => { peripheral.disconnect((): void => {}); }); +noble.removeAllListeners("stateChange"); +noble.removeAllListeners("scanStart"); +noble.removeAllListeners("scanStop"); +noble.removeAllListeners("discover"); +noble.removeAllListeners(); + var peripheral: noble.Peripheral = new noble.Peripheral(); peripheral.uuid = "12ad4e81"; peripheral.advertisement = { From 99f291773163b608b3a339961584f9638c907bbe Mon Sep 17 00:00:00 2001 From: Dominic Griesel Date: Wed, 14 Nov 2018 18:52:43 +0100 Subject: [PATCH 270/836] Add typings for ioBroker adapters --- types/iobroker/index.d.ts | 1387 ++++++++++++++++++++++++++++++ types/iobroker/iobroker-tests.ts | 0 types/iobroker/tsconfig.json | 22 + types/iobroker/tslint.json | 1 + 4 files changed, 1410 insertions(+) create mode 100644 types/iobroker/index.d.ts create mode 100644 types/iobroker/iobroker-tests.ts create mode 100644 types/iobroker/tsconfig.json create mode 100644 types/iobroker/tslint.json diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts new file mode 100644 index 0000000000..fab5a5a107 --- /dev/null +++ b/types/iobroker/index.d.ts @@ -0,0 +1,1387 @@ +/// +import fs = require("fs"); + +// tslint:disable:no-namespace +declare global { + namespace ioBroker { + + enum StateQuality { + good = 0x00, // or undefined or null + bad = 0x01, + general_problem = 0x01, + general_device_problem = 0x41, + general_sensor_problem = 0x81, + device_not_connected = 0x42, + sensor_not_connected = 0x82, + device_reports_error = 0x44, + sensor_reports_error = 0x84, + } + + interface State { + /** The value of the state. */ + val: any; + + /** Direction flag: false for desired value and true for actual value. Default: false. */ + ack: boolean; + + /** Unix timestamp. Default: current time */ + ts: number; + + /** Unix timestamp of the last time the value changed */ + lc: number; + + /** Name of the adapter instance which set the value, e.g. "system.adapter.web.0" */ + from: string; + + /** Optional time in seconds after which the state is reset to null */ + expire?: number; + + /** Optional quality of the state value */ + q?: StateQuality; + + /** Optional comment */ + c?: string; + } + + /** Provides low-level access to the ioBroker states DB */ + interface States { + + /** + * Returns a list of states with the given ids + * @param keys IDs of the states to be retrieved + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getStates(keys: string[], callback: GetStatesCallback2, dontModify?: any): void; + + /** + * Returns the state with the given id + * @param id ID of the state to be retrieved + * @param callback Is called when the operation has finished (successfully or not) + */ + getState(id: string, callback: GetStateCallback): void; + + /** + * Stores a state in the db + * @param id ID of the state to be stored + * @param state The state to be stored in the db + * @param callback Is called when the operation has finished (successfully or not) + */ + setState(id: string, state?: string | number | boolean | State | Partial, callback?: SetStateCallback): void; + + /** + * Updates a state in memory without triggering a save + * @param id ID of the state to be stored + * @param state The state to be updated + * @param callback Is called when the operation has finished (successfully or not) + */ + setRawState(id: string, state: State, callback?: SetStateCallback): void; + + /** + * Deletes a state + * @param id ID of the state to be stored + * @param callback Is called when the operation has finished (successfully or not) + */ + delState(id: string, callback: DeleteStateCallback): void; + + /** + * Retrieves all ids of states matching @link{pattern} + * @param pattern The pattern to match against + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getKeys(pattern: string, callback: GetConfigKeysCallback, dontModify?: any): void; + + /** + * Subscribe to changes of all states matching @link{pattern} + * @param pattern The pattern to match against + * @param callback Is called when the operation has finished (successfully or not) + */ + subscribe(pattern: string, cb: EmptyCallback): void; + /** + * Unsubscribe from changes of all states matching @link{pattern} + * @param pattern The pattern to match against + * @param callback Is called when the operation has finished (successfully or not) + */ + unsubscribe(pattern: string, cb: EmptyCallback): void; + + /** + * Register an adapter instance as subscribable. + * This means that the instance can read information about all subscriptions to its states + * and will be notified of changes. + * @param instance Adapter instance to register, e.g. "admin.0" + * @param cb Is called when the operation has finished (successfully or not) + */ + registerAdapterSubs(instance: string, cb?: (error: null, success: boolean) => void): void; + + /** + * Unregister an adapter instance as subscribable. + * @param instance Adapter instance to unregister, e.g. "admin.0" + * @param cb Is called when the operation has finished (successfully or not) + */ + unregisterAdapterSubs(instance: string, cb?: (error: null, success: boolean) => void): void; + + /** + * EDUCATED GUESS: Notify all clients about changes to an object + * @param type object type + * @param id State/object id + * @param obj The changed object + */ + publishAll(type: string, id: string, obj: Message): void; + + // TODO: Documentation for these functions is missing + pushMessage(id: string, state: Message, callback: SetStateCallback): void; + lenMessage(id: string, callback: GenericCallback): void; + getMessage(id: string, callback: GenericCallback): void; + delMessage(id: string, messageId: number, callback: ErrorCallback): void; + clearAllMessages(callback?: EmptyCallback): void; + subscribeMessage(id: string, cb: EmptyCallback): void; + unsubscribeMessage(id: string, cb: EmptyCallback): void; + + pushLog(id: string, log: Log, callback: SetStateCallback): void; + lenLog(id: string, callback: GenericCallback): void; + getLog(id: string, callback: GenericCallback): void; + delLog(id: string, logId: string, callback: ErrorCallback): void; + clearAllLogs(callback?: EmptyCallback): void; + subscribeLog(id: string, cb: EmptyCallback): void; + unsubscribeLog(id: string, cb: EmptyCallback): void; + + getSession(id: string, callback: GetSessionCallback): void; + setSession(id: string, expire: number, callback?: EmptyCallback): void; + setSession(id: string, expire: number, obj: Session, callback?: EmptyCallback): void; + destroySession(id: string, callback?: EmptyCallback): void; + + /** + * Retrieves a copy of the object with the given ID + * @param id Id of the object to find + * @param callback Is called when the operation has finished (successfully or not) + */ + getConfig(id: string, callback: GetObjectCallback): void; + + /** + * Returns a list of config keys matching + * @param pattern Pattern to match against + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getConfigKeys(pattern: string, callback: GetConfigKeysCallback, dontModify?: any): void; + + /** + * Returns a list of objects with the given ids + * @param keys IDs of the objects to be retrieved + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getConfigs(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; + + /** + * Creates or overwrites a config object in the object db + * @param id ID of the object + * @param obj Object to store + * @param callback Is called when the operation has finished (successfully or not) + */ + setConfig(id: string, obj: ioBroker.Object, callback: SetObjectCallback): void; + + /** + * Deletes a config object in the object db + * @param id ID of the object + * @param callback Is called when the operation has finished (successfully or not) + */ + delConfig(id: string, callback: ErrorCallback): void; + + /** + * Subscribe to config object changes + * @param pattern The pattern to match against + */ + subscribeConfig(pattern: string, callback: EmptyCallback): void; + + /** + * Unsubscribe from config object changes + * @param pattern The pattern to match against + */ + unsubscribeConfig(pattern: string, callback: EmptyCallback): void; + + /** + * Writes a binary state into Redis + * @param id The id of the state + * @param data The data to be written + * @param callback Is called when the operation has finished (successfully or not) + */ + setBinaryState(id: string, data: Buffer, callback: SetStateCallback): void; + + /** + * Reads a binary state from Redis + * @param id The id of the state + * @param callback Is called when the operation has finished (successfully or not) + */ + getBinaryState(id: string, callback: GetBinaryStateCallback): void; + + /** + * Deletes a binary state from Redis + * @param id The id of the state to be deleted + * @param callback Is called when the operation has finished (successfully or not) + */ + delBinaryState(id: string, callback: DeleteStateCallback): void; + + /** Destructor of the class. Call this before shutting down */ + destroy(): void; + + } // end interface States + + type Session = any; // TODO: implement + + type ObjectType = "state" | "channel" | "device"; + type CommonType = "number" | "string" | "boolean" | "array" | "object" | "mixed" | "file"; + + // Maybe this should extend Record, + // but the extra properties aren't defined anywhere, + // so I'd rather force the user to explicitly state + // he knows what he's doing by casting to any + interface ObjectCommon { + /** name of this object */ + name: string; + + // Icon and role aren't defined in SCHEMA.md, + // but they are being used by some adapters + /** Icon for this object */ + icon?: string; + /** role of the object */ + role?: string; + } + + interface StateCommon extends ObjectCommon { + /** Type of this state. See https://github.com/ioBroker/ioBroker/blob/master/doc/SCHEMA.md#state-commonrole for a detailed description */ + type?: CommonType; + /** minimum value */ + min?: number; + /** maximum value */ + max?: number; + /** unit of the value */ + unit?: string; + /** the default value */ + def?: any; + /** description of this state */ + desc?: string; + + /** if this state is readable */ + read: boolean; + /** if this state is writable */ + write: boolean; + /** role of the state (used in user interfaces to indicate which widget to choose) */ + role: string; + + /** + * Dictionary of possible values for this state in the form + *
+			 * {
+			 *     "internal value 1": "displayed value 1",
+			 *     "internal value 2": "displayed value 2",
+			 *     ...
+			 * }
+			 * 
+ * In old ioBroker versions, this could also be a string of the form + * "val1:text1;val2:text2" (now deprecated) + */ + states?: Record | string; + + /** ID of a helper state indicating if the handler of this state is working */ + workingID?: string; + + /** attached history information */ + history?: any; + } + interface ChannelCommon extends ObjectCommon { + /** description of this channel */ + desc?: string; + } + type OtherCommon = ObjectCommon & { + [propName: string]: any; + }; + + interface BaseObject { + /** The ID of this object */ + _id?: string; + native: Record; + enums?: Record; + type: string; // specified in the derived interfaces + common: ObjectCommon; + acl?: ObjectACL; + } + + interface StateObject extends BaseObject { + type: "state"; + common: StateCommon; + acl?: StateACL; + } + interface PartialStateObject extends Partial> { + common?: Partial; + acl?: Partial; + } + + interface ChannelObject extends BaseObject { + type: "channel"; + common: ChannelCommon; + } + interface PartialChannelObject extends Partial> { + common?: Partial; + } + + interface DeviceObject extends BaseObject { + type: "device"; + common: ObjectCommon; // TODO: any definition for device? + } + interface PartialDeviceObject extends Partial> { + common?: Partial; + } + + interface OtherObject extends BaseObject { + type: "adapter" | "config" | "enum" | "group" | "host" | "info" | "instance" | "meta" | "script" | "user"; + common: OtherCommon; + } + interface PartialOtherObject extends Partial> { + common?: Partial; + } + + type Object = StateObject | ChannelObject | DeviceObject | OtherObject; + type PartialObject = PartialStateObject | PartialChannelObject | PartialDeviceObject | PartialOtherObject; + + /** Defines access rights for a single file */ + interface FileACL { + /** Full name of the user who owns this file, e.g. "system.user.admin" */ + owner: string; + /** Full name of the group who owns this file, e.g. "system.group.administrator" */ + ownerGroup: string; + /** Linux-type permissions defining access to this file */ + permissions: number; + } + /** Defines access rights for a single file, applied to a user or group */ + interface EvaluatedFileACL extends FileACL { + /** Whether the user may read the file */ + read: boolean; + /** Whether the user may write the file */ + write: boolean; + } + + /** Defines access rights for a single object */ + interface ObjectACL { + /** Full name of the user who owns this object, e.g. "system.user.admin" */ + owner: string; + /** Full name of the group who owns this object, e.g. "system.group.administrator" */ + ownerGroup: string; + /** Linux-type permissions defining access to this object */ + object: number; + } + /** Defines access rights for a single state object */ + interface StateACL extends ObjectACL { + /** Linux-type permissions defining access to this state */ + state: number; + } + + /** Defines access rights for a single object type */ + interface ObjectOperationPermissions { + /** Whether a user may enumerate objects of this type */ + list: boolean; + /** Whether a user may read objects of this type */ + read: boolean; + /** Whether a user may write objects of this type */ + write: boolean; + /** Whether a user may create objects of this type */ + create: boolean; + /** Whether a user may delete objects of this type */ + "delete": boolean; + } + + /** Defines the rights a user or group has to change objects */ + interface ObjectPermissions { + /** The access rights for files */ + file: ObjectOperationPermissions; + /** The access rights for objects */ + object: ObjectOperationPermissions; + /** The access rights for users/groups */ + users: ObjectOperationPermissions; + /** The access rights for states */ + state?: ObjectOperationPermissions; + } + /** Defined the complete set of access rights a user has */ + interface PermissionSet extends ObjectPermissions { + /** The name of the user this ACL is for */ + user: string; + /** The name of the groups this ACL was merged from */ + groups: string[]; + /** The access rights for certain commands */ + other: { + execute: boolean, + http: boolean, + sendto: boolean, + }; + } + + interface Permission { + /** The type of the permission */ + type: string; + /** Which kind of operation is required */ + operation: string; + } + interface ObjectOrStatePermission extends Permission { + type: "object" | "file" | "users" | "state"; + operation: "list" | "read" | "write" | "create" | "delete"; + } + interface OtherPermission extends Permission { + type: "other"; + operation: "execute" | "http" | "sendto"; + } + interface CommandsPermissions { + // TODO: Are all properties required or is a partial object ok? + getObject: ObjectOrStatePermission; + getObjects: ObjectOrStatePermission; + getObjectView: ObjectOrStatePermission; + setObject: ObjectOrStatePermission; + subscribeObjects: ObjectOrStatePermission; + unsubscribeObjects: ObjectOrStatePermission; + getStates: ObjectOrStatePermission; + getState: ObjectOrStatePermission; + setState: ObjectOrStatePermission; + getStateHistory: ObjectOrStatePermission; + subscribe: ObjectOrStatePermission; + unsubscribe: ObjectOrStatePermission; + getVersion: Permission; + httpGet: OtherPermission; + sendTo: OtherPermission; + sendToHost: OtherPermission; + readFile: ObjectOrStatePermission; + readFile64: ObjectOrStatePermission; + writeFile: ObjectOrStatePermission; + writeFile64: ObjectOrStatePermission; + unlink: ObjectOrStatePermission; + rename: ObjectOrStatePermission; + mkdir: ObjectOrStatePermission; + readDir: ObjectOrStatePermission; + chmodFile: ObjectOrStatePermission; + authEnabled: Permission; + disconnect: Permission; + listPermissions: Permission; + getUserPermissions: ObjectOrStatePermission; + } + + type UserGroup = any; // TODO find out how this looks like + // interface UserGroup { } + + /** Contains information about a user */ + interface User { + /** Which groups this user belongs to */ + groups: UserGroup[]; + /** Access rights of this user */ + acl: ObjectPermissions; + } + + /** Parameters for @link{Objects.getObjectView} */ + interface GetObjectViewParams { + /** First id to include in the return list */ + startkey: string; + /** Last id to include in the return list */ + endkey: string; + } + + /** Parameters for @link{Objects.getObjectList} */ + interface GetObjectListParams extends GetObjectViewParams { + /** Whether docs should be included in the return list */ // TODO: What are docs? + include_docs: boolean; + } + + /** Provides low-level access to the ioBroker objects db */ + interface Objects { + /** + * For a given user, returns the groups he belongs to, and his access rights + * @param user Name of the user. Has to start with "system.user." + * @param callback The callback function to be invoked with the return values + */ + getUserGroup(user: string, callback: GetUserGroupCallback): void; + + /** + * Determines the mime type for a given file extension + * @param ext File extension, including the leading dot, e.g. ".zip" + */ + getMimeType(ext: string): {mimeType: string, isBinary: boolean}; + + /** + * Writes a file. + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param data Contents of the file + * @param options (optional) MIME type of the file (string). Or some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + writeFile(id: string, name: string, data: Buffer | string, callback: ErrorCallback): void; + writeFile(id: string, name: string, data: Buffer | string, options: string | any, callback: ErrorCallback): void; + + /** + * Reads a file. + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + readFile(id: string, name: string, callback: ReadFileCallback): void; + readFile(id: string, name: string, options: any, callback: ReadFileCallback): void; + + /** + * Deletes a file. + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + unlink(id: string, name: string, callback: ErrorCallback): void; + unlink(id: string, name: string, options: any, callback: ErrorCallback): void; + /** + * Deletes a file. + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + delFile(id: string, name: string, callback: ErrorCallback): void; + delFile(id: string, name: string, options: any, callback: ErrorCallback): void; + + /** + * Finds all files and directories starting with + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File or directory name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + readDir(id: string, name: string, callback: ReadDirCallback): void; + readDir(id: string, name: string, options: any, callback: ReadDirCallback): void; + + /** + * Renames a file or directory + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param oldName Old file or directory name + * @param newName Name to rename to + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + rename(id: string, oldName: string, newName: string, callback: ErrorCallback): void; + rename(id: string, oldName: string, newName: string, options: any, callback: ErrorCallback): void; + + /** + * Creates an empty file with the given name + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + touch(id: string, name: string, callback: ErrorCallback): void; + touch(id: string, name: string, options: any, callback: ErrorCallback): void; + + /** + * Deletes all files in the root directory matching + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name Pattern to match against + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + rm(id: string, name: string, callback: RmCallback): void; + rm(id: string, name: string, options: any, callback: RmCallback): void; + + /** + * Creates an empty directory with the given name + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name Directory name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + mkDir(id: string, name: string, callback: ErrorCallback): void; + mkDir(id: string, name: string, options: any, callback: ErrorCallback): void; + + /** + * Takes possession all files in the root directory matching + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name Pattern to match against + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + chownFile(id: string, name: string, callback: ChownFileCallback): void; + chownFile(id: string, name: string, options: any, callback: ChownFileCallback): void; + + /** + * Changes access rights of all files in the root directory matching + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name Pattern to match against + * @param options Mode of the access change as a number or hexadecimal string + * @param callback Is called when the operation has finished (successfully or not) + */ + chmodFile(id: string, name: string, options: {mode: number | string} | Record, callback: ChownFileCallback): void; + + // not documented. enabled = true seems to disable the cache + // enableFileCache(enabled, options, callback) + + /** + * Subscribe to object changes + * @param pattern The pattern to match against + */ + subscribeConfig(pattern: string, callback: EmptyCallback): void; + subscribeConfig(pattern: string, options: any, callback: EmptyCallback): void; + /** + * Subscribe to object changes + * @param pattern The pattern to match against + */ + subscribe(pattern: string, callback: EmptyCallback): void; + subscribe(pattern: string, options: any, callback: EmptyCallback): void; + + /** + * Unsubscribe from object changes + * @param pattern The pattern to match against + */ + unsubscribeConfig(pattern: string, callback: EmptyCallback): void; + unsubscribeConfig(pattern: string, options: any, callback: EmptyCallback): void; + /** + * Unsubscribe from object changes + * @param pattern The pattern to match against + */ + unsubscribe(pattern: string, callback: EmptyCallback): void; + unsubscribe(pattern: string, options: any, callback: EmptyCallback): void; + + /** + * Takes possession of all objects matching + * @param pattern Pattern to match against + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + chownObject(pattern: string, callback: ChownObjectCallback): void; + chownObject(pattern: string, options: any, callback: ChownObjectCallback): void; + + /** + * Changes access rights of all objects matching + * @param pattern Pattern to match against + * @param options Mode of the access change as a number or hexadecimal string + * @param callback Is called when the operation has finished (successfully or not) + */ + chmodObject(pattern: string, callback: ChownObjectCallback): void; + chmodObject(pattern: string, options: any, callback: ChownObjectCallback): void; + + /** + * Retrieves a copy of the object with the given ID + * @param id Id of the object to find + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getObject(id: string, callback: GetObjectCallback): void; + getObject(id: string, options: any, callback: GetObjectCallback): void; + /** + * Retrieves a copy of the object with the given ID + * @param id Id of the object to find + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getConfig(id: string, callback: GetObjectCallback): void; + getConfig(id: string, options: any, callback: GetObjectCallback): void; + + /** + * Returns a list of config keys matching + * @param pattern Pattern to match against + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getConfigKeys(pattern: string, callback: GetConfigKeysCallback, dontModify?: any): void; + getConfigKeys(pattern: string, options: any, callback: GetConfigKeysCallback, dontModify?: any): void; + + /** + * Returns a list of objects with the given ids + * @param keys IDs of the objects to be retrieved + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getObjects(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; + getObjects(keys: string[], options: any, callback: GetObjectsCallback2, dontModify?: any): void; + /** + * Returns a list of objects with the given ids + * @param keys IDs of the objects to be retrieved + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getConfigs(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; + getConfigs(keys: string[], options: any, callback: GetObjectsCallback2, dontModify?: any): void; + + /** + * Creates or overwrites an object in the object db + * @param id ID of the object + * @param obj Object to store + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + setObject(id: string, obj: ioBroker.Object, callback: SetObjectCallback): void; + setObject(id: string, obj: ioBroker.Object, options: any, callback: SetObjectCallback): void; + /** + * Creates or overwrites an object in the object db + * @param id ID of the object + * @param obj Object to store + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + setConfig(id: string, obj: ioBroker.Object, callback: SetObjectCallback): void; + setConfig(id: string, obj: ioBroker.Object, options: any, callback: SetObjectCallback): void; + + /** + * Deletes an object in the object db + * @param id ID of the object + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + delObject(id: string, callback: ErrorCallback): void; + delObject(id: string, options: any, callback: ErrorCallback): void; + /** + * Deletes an object in the object db + * @param id ID of the object + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + delConfig(id: string, callback: ErrorCallback): void; + delConfig(id: string, options: any, callback: ErrorCallback): void; + + /** + * Returns a list of objects with id between params.startkey and params.endkey + * @param params Parameters determining the objects included in the return list. Null to include all objects + * @param options (optional) If the returned list should be sorted. And some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getObjectList(params: GetObjectListParams | null, callback: GetObjectListCallback): void; + getObjectList(params: GetObjectListParams | null, options: { sorted?: boolean } | Record, callback: GetObjectListCallback): void; + + /** + * Query a predefined object view (similar to SQL stored procedures) and return the results + * For a detailed description refer to https://github.com/ioBroker/ioBroker/wiki/Adapter-Development-Documentation#object-fields + * or http://guide.couchdb.org/editions/1/en/views.html + * @param design The namespace of the object view, as defined in io-package.json. Usually the adapter name, e.g. "hm-rpc" + * @param search The name of the object view. + * @param params Parameters to additionally filter out objects from the return list. Null to include all objects + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getObjectView(design: string, search: string, params: GetObjectViewParams | null, callback: GetObjectViewCallback): void; + getObjectView(design: string, search: string, params: GetObjectViewParams | null, options: any, callback: GetObjectViewCallback): void; + + /** + * Extends an object in the object db with new properties + * @param id ID of the object + * @param obj Object to extend the original one with. May be just parts of an object. + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + extendObject(id: string, obj: PartialObject, callback: ExtendObjectCallback): void; + extendObject(id: string, obj: PartialObject, options: any, callback: ExtendObjectCallback): void; + + /** + * Finds an object by ID or name. If multiple objects were found, return the first one + * @param idOrName ID or name of the object + * @param type If != null, only return an object with a common.type equal to this + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + findObject(idOrName: string, type: CommonType | null, callback: FindObjectCallback): void; + findObject(idOrName: string, type: CommonType | null, options: any, callback: FindObjectCallback): void; + + // I'd rather not document a function with the name "destroyDB" + + /** Destructor of the class. Call this before shutting down. */ + destroy(): void; + + } // end interface Objects + + type LogLevel = "silly" | "debug" | "info" | "warn" | "error"; + interface Logger { + /** log message with silly level */ + silly(message: string): void; + /** log message with debug level */ + debug(message: string): void; + /** log message with info level (default output level for all adapters) */ + info(message: string): void; + /** log message with warning severity */ + warn(message: string): void; + /** log message with error severity */ + error(message: string): void; + + /** Verbosity of the log output */ + level: LogLevel; + } + + interface Certificates { + /** private key file */ + key: string | Buffer; + /** public certificate */ + cert: string | Buffer; + /** chained CA certificates */ + ca: (string | Buffer)[]; + } + + /** Callback information for a passed message */ + interface MessageCallbackInfo { + /** The original message payload */ + message: string | object; + /** ID of this callback */ + id: number; + // ??? + ack: boolean; + /** Timestamp of this message */ + time: number; + } + type MessageCallback = (result?: any) => void; + + /** A message being passed between adapter instances */ + interface Message { + /** The command to be executed */ + command: string; + /** The message payload */ + message: string | object; + /** The source of this message */ + from: string; + /** ID of this message */ + _id: number; + /** Callback information. This is set when the source expects a response */ + callback: MessageCallbackInfo; + } + + type Log = any; // TODO: define this https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/states/statesInMemServer.js#L873 + + type EnumList = string | string[]; + + type Enum = any; // TODO: implement this + + interface DirectoryEntry { + file: string; + stats: fs.Stats; + isDir: boolean; + acl: any; // access control list object + modifiedAt: number; + createdAt: number; + } + + interface GetHistoryOptions { + instance?: string; + start?: number; + end?: number; + step?: number; + count?: number; + from?: boolean; + ack?: boolean; + q?: boolean; + addID?: boolean; + limit?: number; + ignoreNull: boolean; + sessionId?: any; + aggregate?: "minmax" | "min" | "max" | "average" | "total" | "count" | "none"; + } + + interface AdapterOptions { + /** The name of the adapter */ + name: string; + + /** path to adapter */ + dirname?: string; + + /** if the global system config should be included in the created object. Default: false */ + systemConfig?: boolean; + + /** provide alternative global configuration for the adapter. Default: null */ + config?: any; + + /** instance of the created adapter. Default: null */ + instance?: number; + + /** If the adapter needs access to the formatDate function to format dates according to the global settings. Default: false */ + useFormatDate?: boolean; + + /** If the adapter collects logs from all adapters (experts only). Default: false */ + logTransporter?: boolean; + + /** Handler for changes of subscribed objects */ + objectChange?: ObjectChangeHandler; + /** Handler for received adapter messages. Can only be used if messagebox in io-package.json is set to true. */ + message?: MessageHandler; + /** Handler for changes of subscribed states */ + stateChange?: StateChangeHandler; + /** Will be called when the adapter is intialized */ + ready?: () => void; + /** Will be called on adapter termination */ + unload?: (callback: EmptyCallback) => void; + + /** if true, stateChange will be called with an id that has no namespace, e.g. "state" instead of "adapter.0.state". Default: false */ + noNamespace?: boolean; + } // end interface AdapterOptions + + // tslint:disable-next-line:no-empty-interface + interface AdapterConfig { + // This is a stub to be augmented in every adapter + } + + interface Adapter { + /** The name of the adapter */ + name: string; + /** The name of the host where the adapter is running */ + host: string; + /** instance number of this adapter instance */ + instance: number; + /** Namespace of adapter objects: "." */ + readonly namespace: string; + /** native part of the adapter settings */ + config: AdapterConfig; + /** common part of the adapter settings */ + common: any; + /** system part of the adapter settings */ + systemConfig?: any; + /** path to the adapter folder */ + adapterDir: string; + /** content of io-package.json */ + ioPack: any; + /** content of package.json */ + pack: any; + /** access to the logging functions */ + log: Logger; + /** adapter version */ + version: any; + states: States; + objects: Objects; + /** if the adapter is connected to the host */ + connected: boolean; + + /* =============================== + Functions defined in adapter.js + =============================== */ + + /** + * Helper function that looks for first free TCP port starting with the given one. + * @param port - The port to start with + * @param callback - gets called when a free port is found + */ + getPort(port: number, callback: (port: number) => void): void; + + /** Stops the adapter. Note: Is not always defined. */ + stop?: () => void; + + // ============================== + // GENERAL + + /** Validates username and password */ + checkPassword(user: string, password: string, callback: (result: boolean) => void): void; + checkPassword(user: string, password: string, options: any, callback: (result: boolean) => void): void; + /** Sets a new password for the given user */ + setPassword(user: string, password: string, options?: any, callback?: (err?: any) => void): void; + /** Checks if a user exists and is in the given group. */ + checkGroup(user: string, group: string, callback: (result: boolean) => void): void; + checkGroup(user: string, group: string, options: any, callback: (result: boolean) => void): void; + /** Determines the users permissions */ + calculatePermissions(user: string, commandsPermissions: CommandsPermissions, callback: (result: PermissionSet) => void): void; + calculatePermissions(user: string, commandsPermissions: CommandsPermissions, options: any, callback: (result: PermissionSet) => void): void; + /** Returns SSL certificates by name (private key, public cert and chained certificate) for creation of HTTPS servers */ + getCertificates(publicName: string, privateName: string, chainedName: string, callback: (err: string | null, certs?: Certificates, useLetsEncryptCert?: boolean) => void): void; + + /** + * Sends a message to a specific instance or all instances of some specific adapter. + * @param instanceName The instance to send this message to. + * If the ID of an instance is given (e.g. "admin.0"), only this instance will receive the message. + * If the name of an adapter is given (e.g. "admin"), all instances of this adapter will receive it. + * @param command (optional) Command name of the target instance. Default: "send" + * @param message The message (e.g. params) to send. + */ + sendTo(instanceName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + sendTo(instanceName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + + /** + * Sends a message to a specific host or all hosts. + */ + sendToHost(hostName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + sendToHost(hostName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + + /** Convert ID to {device: D, channel: C, state: S} */ + idToDCS(id: string): { + device: string; + channel: string; + state: string; + }; + + // ============================== + // own objects + + /** Reads an object from the object db */ + getObject(id: string, callback: GetObjectCallback): void; + getObject(id: string, options: any, callback: GetObjectCallback): void; + /** Creates or overwrites an object in the object db */ + setObject(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; + /** Creates an object in the object db. Existing objects are not overwritten. */ + setObjectNotExists(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; + /** Get all states, channels and devices of this adapter */ + getAdapterObjects(callback: (objects: Record) => void): void; + /** Extend an object and create it if it might not exist */ + extendObject(id: string, objPart: PartialObject, options?: any, callback?: SetObjectCallback): void; + /** + * Deletes an object from the object db + * @param id - The id of the object without namespace + */ + delObject(id: string, options?: any, callback?: ErrorCallback): void; + + // ============================== + // foreign objects + + // tslint:disable:unified-signatures + /** Reads an object (which might not belong to this adapter) from the object db */ + getForeignObject(id: string, callback: GetObjectCallback): void; + getForeignObject(id: string, options: any, callback: GetObjectCallback): void; + /** Get foreign objects by pattern, by specific type and resolve their enums. */ + getForeignObjects(pattern: string, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, options: any, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, options: any, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, options: any, callback: GetObjectsCallback): void; + /** Creates or overwrites an object (which might not belong to this adapter) in the object db */ + setForeignObject(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; + /** Creates an object (which might not belong to this adapter) in the object db. Existing objects are not overwritten. */ + setForeignObjectNotExists(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; + /** Extend an object (which might not belong to this adapter) and create it if it might not exist */ + extendForeignObject(id: string, objPart: PartialObject, options?: any, callback?: SetObjectCallback): void; + // tslint:enable:unified-signatures + /** + * Finds an object by its ID or name + * @param type - common.type of the state + */ + findForeignObject(idOrName: string, type: string, callback: FindObjectCallback): void; + findForeignObject(idOrName: string, type: string, options: any, callback: FindObjectCallback): void; + /** + * Deletes an object (which might not belong to this adapter) from the object db + * @param id - The id of the object including namespace + */ + delForeignObject(id: string, options?: any, callback?: ErrorCallback): void; + + // ============================== + // states + /** Writes a value into the states DB. */ + setState(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateCallback): void; + /** Writes a value into the states DB only if it has changed. */ + setStateChanged(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateChangedCallback): void; + /** Writes a value (which might not belong to this adapter) into the states DB. */ + setForeignState(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateCallback): void; + /** Writes a value (which might not belong to this adapter) into the states DB only if it has changed. */ + setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateChangedCallback): void; + + /** Read a value from the states DB. */ + getState(id: string, callback: GetStateCallback): void; + getState(id: string, options: any, callback: GetStateCallback): void; + /** Read a value (which might not belong to this adapter) from the states DB. */ + getForeignState(id: string, callback: GetStateCallback): void; + getForeignState(id: string, options: any, callback: GetStateCallback): void; + /** Read all states of this adapter which match the given pattern */ + getStates(pattern: string, callback: GetStatesCallback): void; + getStates(pattern: string, options: any, callback: GetStatesCallback): void; + /** Read all states (which might not belong to this adapter) which match the given pattern */ + getForeignStates(pattern: string, callback: GetStatesCallback): void; + getForeignStates(pattern: string, options: any, callback: GetStatesCallback): void; + + /** Deletes a state from the states DB, but not the associated object. Consider using @link{deleteState} instead */ + delState(id: string, options?: any, callback?: ErrorCallback): void; + /** Deletes a state from the states DB, but not the associated object */ + delForeignState(id: string, options?: any, callback?: ErrorCallback): void; + + getHistory(id: string, options: GetHistoryOptions, callback: GetHistoryCallback): void; + + // MISSING: + // pushFifo and similar https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4105 + // logRedirect https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4294 + // requireLog https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4336 + // processLog https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4360 + + /** + * Writes a binary state into Redis + * @param id The id of the state + * @param binary The data to be written + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + setBinaryState(id: string, binary: Buffer, callback: SetStateCallback): void; + setBinaryState(id: string, binary: Buffer, options: any, callback: SetStateCallback): void; + /** + * Reads a binary state from Redis + * @param id The id of the state + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getBinaryState(id: string, callback: GetBinaryStateCallback): void; + getBinaryState(id: string, options: any, callback: GetBinaryStateCallback): void; + + // ============================== + // enums + + /** Returns the enum tree, filtered by the optional enum name */ + getEnum(callback: GetEnumCallback): void; + getEnum(name: string, callback: GetEnumCallback): void; + getEnum(name: string, options: any, callback: GetEnumCallback): void; + getEnums(callback: GetEnumsCallback): void; + getEnums(enumList: EnumList, callback: GetEnumsCallback): void; + getEnums(enumList: EnumList, options: any, callback: GetEnumsCallback): void; + + addChannelToEnum(enumName: string, addTo: string, parentDevice: string, channelName: string, options?: any, callback?: ErrorCallback): void; + deleteChannelFromEnum(enumName: string, parentDevice: string, channelName: string, options?: any, callback?: ErrorCallback): void; + + addStateToEnum(enumName: string, addTo: string, parentDevice: string, parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; + deleteStateFromEnum(enumName: string, parentDevice: string, parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; + + // ============================== + // subscriptions + + /** Subscribe to changes of objects in this instance */ + subscribeObjects(pattern: string, options?: any): void; + /** Subscribe to changes of objects (which might not belong to this adapter) */ + subscribeForeignObjects(pattern: string, options?: any): void; + /** Unsubscribe from changes of objects in this instance */ + unsubscribeObjects(pattern: string, options?: any): void; + /** Unsubscribe from changes of objects (which might not belong to this adapter) */ + unsubscribeForeignObjects(pattern: string, options?: any): void; + + /** Subscribe to changes of states in this instance */ + subscribeStates(pattern: string, options?: any, callback?: ErrorCallback): void; + /** Subscribe to changes of states (which might not belong to this adapter) */ + subscribeForeignStates(pattern: string, options?: any, callback?: ErrorCallback): void; + /** + * Subscribe from changes of states in this instance + * @param pattern - Must match the pattern used to subscribe + */ + unsubscribeStates(pattern: string, options?: any, callback?: ErrorCallback): void; + /** + * Subscribe from changes of states (which might not belong to this adapter) + * @param pattern - Must match the pattern used to subscribe + */ + unsubscribeForeignStates(pattern: string, options?: any, callback?: ErrorCallback): void; + + // ============================== + // devices and channels + + /** creates an object with type device */ + createDevice(deviceName: string, common?: any, native?: any, options?: any, callback?: SetObjectCallback): void; + /** deletes a device, its channels and states */ + deleteDevice(deviceName: string, options?: any, callback?: ErrorCallback): void; + /** gets the devices of this instance */ + + /** creates an object with type channel */ + createChannel(parentDevice: string, channelName: string, roleOrCommon?: string | object, native?: any, options?: any, callback?: SetObjectCallback): void; + /** deletes a channel and its states */ + deleteChannel(channelName: string, options?: any, callback?: ErrorCallback): void; + deleteChannel(parentDevice: string, channelName: string, options?: any, callback?: ErrorCallback): void; + + /** creates a state and the corresponding object */ + createState(parentDevice: string, parentChannel: string, stateName: string, roleOrCommon?: string | object, native?: any, options?: any, callback?: SetObjectCallback): void; + /** deletes a state */ + deleteState(stateName: string, options?: any, callback?: ErrorCallback): void; + deleteState(parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; + deleteState(parentDevice: string, parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; + + /** + * Returns a list of all devices in this adapter instance + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getDevices(callback: GetObjectsCallback3): void; + getDevices(options: any, callback: GetObjectsCallback3): void; + + /** + * Returns a list of all channels in this adapter instance + * @param parentDevice (optional) Name of the parent device to filter the channels by + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getChannels(callback: GetObjectsCallback3): void; + getChannels(parentDevice: string | null, callback: GetObjectsCallback3): void; + getChannels(parentDevice: string | null, options: any, callback: GetObjectsCallback3): void; + /** + * Returns a list of all channels in this adapter instance + * @param parentDevice (optional) Name of the parent device to filter the channels by + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getChannelsOf(callback: GetObjectsCallback3): void; + getChannelsOf(parentDevice: string | null, callback: GetObjectsCallback3): void; + getChannelsOf(parentDevice: string | null, options: any, callback: GetObjectsCallback3): void; + + /** + * Returns a list of all states in this adapter instance + * @param parentDevice (optional) Name of the parent device to filter the channels by + * @param parentChannel (optional) Name of the parent channel to filter the channels by + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getStatesOf(callback: GetObjectsCallback3): void; + getStatesOf(parentDevice: string | null, callback: GetObjectsCallback3): void; + getStatesOf(parentDevice: string | null, parentChannel: string | null, callback: GetObjectsCallback3): void; + getStatesOf(parentDevice: string | null, parentChannel: string | null, options: any, callback: GetObjectsCallback3): void; + + // ============================== + // filesystem + + /** + * reads the content of directory from DB for given adapter and path + * @param adapter - adapter name. If adapter name is null, default will be the name of the current adapter. + * @param path - path to direcory without adapter name. E.g. If you want to read "/vis.0/main/views.json", here must be "/main/views.json" and _adapter must be equal to "vis.0". + */ + readDir(adapterName: string, path: string, callback: ReadDirCallback): void; + readDir(adapterName: string, path: string, options: any, callback: ReadDirCallback): void; + mkDir(adapterName: string, path: string, callback: ErrorCallback): void; + mkDir(adapterName: string, path: string, options: any, callback: ErrorCallback): void; + + readFile(adapterName: string, path: string, callback: ReadFileCallback): void; + readFile(adapterName: string, path: string, options: any, callback: ReadFileCallback): void; + writeFile(adapterName: string, path: string, data: Buffer | string, callback: ErrorCallback): void; + writeFile(adapterName: string, path: string, data: Buffer | string, options: any, callback: ErrorCallback): void; // options see https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/objects/objectsInMemServer.js#L599 + + delFile(adapterName: string, path: string, callback: ErrorCallback): void; + delFile(adapterName: string, path: string, options: any, callback: ErrorCallback): void; + unlink(adapterName: string, path: string, callback: ErrorCallback): void; + unlink(adapterName: string, path: string, options: any, callback: ErrorCallback): void; + + rename(adapterName: string, oldName: string, newName: string, callback: ErrorCallback): void; + rename(adapterName: string, oldName: string, newName: string, options: any, callback: ErrorCallback): void; + + /** + * Changes access rights of all files in the adapter directory + * @param adapter Name of the adapter instance, e.g. "admin.0". Defaults to the namespace of this adapter. + * @param path Pattern to match the file path against + * @param options Mode of the access change as a number or hexadecimal string + * @param callback Is called when the operation has finished (successfully or not) + */ + chmodFile(adapter: string | null, path: string, options: {mode: number | string} | Record, callback: ChownFileCallback): void; + + // ============================== + // formatting + + formatValue(value: number | string, format: any): string; + formatValue(value: number | string, decimals: number, format: any): string; + formatDate(dateObj: string | Date | number, format: string): string; + formatDate(dateObj: string | Date | number, isDuration: boolean | string, format: string): string; + } // end interface Adapter + + type ObjectChangeHandler = (id: string, obj: ioBroker.Object) => void; + type StateChangeHandler = (id: string, obj: State) => void; + type MessageHandler = (obj: Message) => void; + + type EmptyCallback = () => void; + type ErrorCallback = (err?: string) => void; + // TODO: Redefine callbacks as subclass of GenericCallback + type GenericCallback = (err: string | null, result?: T) => void; + + type SetObjectCallback = (err: string | null, obj: { id: string }) => void; + type GetObjectCallback = (err: string | null, obj: ioBroker.Object) => void; + type GetEnumCallback = (err: string | null, enums: Record, requestedEnum: string) => void; + type GetEnumsCallback = ( + err: string | null, + result: { + [groupName: string]: Record, + }, + ) => void; + type GetObjectsCallback = (err: string | null, objects: Record) => void; + + type FindObjectCallback = ( + /** If an error happened, this contains the message */ + err: string | null, + /** If an object was found, this contains the ID */ + id?: string, + /** If an object was found, this contains the common.name */ + name?: string, + ) => void; + + interface GetObjectsItem { + /** The ID of this object */ + id: string; + /** A copy of the object from the DB */ + value: T; + } + // This is a version used by GetDevices/GetChannelsOf/GetStatesOf + type GetObjectsCallback3 = (err: string | null, result?: GetObjectsItem[]) => void; + + type GetStateCallback = (err: string | null, state: State) => void; + type GetStatesCallback = (err: string | null, states: Record) => void; + /** Version of the callback used by States.getStates */ + type GetStatesCallback2 = (err: string | null, states: State[]) => void; + type GetBinaryStateCallback = (err: string | null, state?: Buffer) => void; + type SetStateCallback = (err: string | null, id?: string) => void; + type SetStateChangedCallback = (err: string | null, id: string, notChanged: boolean) => void; + type DeleteStateCallback = (err: string | null, id?: string) => void; + type GetHistoryCallback = (err: string | null, result: (State & { id?: string })[], step: number, sessionId?: string) => void; + + /** Contains the return values of readDir */ + interface ReadDirResult { + /** Name of the file or directory */ + file: string; + /** File system stats */ + stats: fs.Stats; + /** Whether this is a directory or a file */ + isDir: boolean; + /** Access rights */ + acl: EvaluatedFileACL; + /** Date of last modification */ + modifiedAt: number; + /** Date of creation */ + createdAt: number; + } + type ReadDirCallback = (err: string | null, entries?: ReadDirResult[]) => void; + type ReadFileCallback = (err: string | null, file?: Buffer | string, mimeType?: string) => void; + + /** Contains the return values of chownFile */ + interface ChownFileResult { + /** The parent directory of the processed file or directory */ + path: string; + /** Name of the file or directory */ + file: string; + /** File system stats */ + stats: fs.Stats; + /** Whether this is a directory or a file */ + isDir: boolean; + /** Access rights */ + acl: FileACL; + /** Date of last modification */ + modifiedAt: number; + /** Date of creation */ + createdAt: number; + } + type ChownFileCallback = (err: string | null, entries?: ChownFileResult[], id?: string) => void; + + /** Contains the return values of rm */ + interface RmResult { + /** The parent directory of the deleted file or directory */ + path: string; + /** The name of the deleted file or directory */ + file: string; + /** Whether the deleted object was a directory or a file */ + isDir: boolean; + } + type RmCallback = (err: string | null, entries?: RmResult[]) => void; + + type GetUserGroupCallback = (objectsInstance: Objects, user: User, groups: UserGroup[], acl: ObjectPermissions) => void; + + type ChownObjectCallback = (err: string | null, list?: ioBroker.Object[]) => void; + + type GetConfigKeysCallback = (err: string | null, list?: string[]) => void; + // this is a version of the callback used by Objects.getObjects + type GetObjectsCallback2 = (err: string | null, objects?: (ioBroker.Object | { err: string })[]) => void; + + interface GetObjectViewItem { + /** The ID of this object */ + id: string; + /** A copy of the object from the DB or some aggregation result */ + value: ioBroker.Object | any; + } + type GetObjectViewCallback = (err: string | null, result?: { rows: GetObjectViewItem[] }) => void; + + interface GetObjectListItem extends GetObjectViewItem { + /** A copy of the object */ + value: ioBroker.Object; + /** The same as @link{value} */ + doc: ioBroker.Object; + } + type GetObjectListCallback = (err: string | null, result?: { rows: GetObjectListItem[] }) => void; + + type ExtendObjectCallback = (err: string | null, result?: {id: string, value: ioBroker.Object}, id?: string ) => void; + + type GetSessionCallback = (session: Session) => void; + + } // end namespace ioBroker +} // end declare global diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/iobroker/tsconfig.json b/types/iobroker/tsconfig.json new file mode 100644 index 0000000000..3388e650ec --- /dev/null +++ b/types/iobroker/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "iobroker-tests.ts" + ] +} diff --git a/types/iobroker/tslint.json b/types/iobroker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/iobroker/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From ef89cb895e589686e2f6f0efee1fdf7ed73f034b Mon Sep 17 00:00:00 2001 From: "dominic.griesel" Date: Thu, 15 Nov 2018 10:58:26 +0100 Subject: [PATCH 271/836] Fix lint errors --- types/iobroker/index.d.ts | 2769 +++++++++++++++--------------- types/iobroker/iobroker-tests.ts | 5 + types/iobroker/tsconfig.json | 1 + types/iobroker/tslint.json | 9 +- 4 files changed, 1401 insertions(+), 1383 deletions(-) diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index fab5a5a107..baa8424d9b 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -1,1387 +1,1392 @@ +// Ambient type definitions for adapters for ioBroker +// Note: This is not the definition for the package `iobroker`, +// which is just an installer, not a library. +// The definitions are based on ioBroker.js-controller v1.4.2 +// Project: https://github.com/ioBroker/ioBroker +// Definitions by: AlCalzone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + /// -import fs = require("fs"); +import * as fs from "fs"; // tslint:disable:no-namespace declare global { - namespace ioBroker { - - enum StateQuality { - good = 0x00, // or undefined or null - bad = 0x01, - general_problem = 0x01, - general_device_problem = 0x41, - general_sensor_problem = 0x81, - device_not_connected = 0x42, - sensor_not_connected = 0x82, - device_reports_error = 0x44, - sensor_reports_error = 0x84, - } - - interface State { - /** The value of the state. */ - val: any; - - /** Direction flag: false for desired value and true for actual value. Default: false. */ - ack: boolean; - - /** Unix timestamp. Default: current time */ - ts: number; - - /** Unix timestamp of the last time the value changed */ - lc: number; - - /** Name of the adapter instance which set the value, e.g. "system.adapter.web.0" */ - from: string; - - /** Optional time in seconds after which the state is reset to null */ - expire?: number; - - /** Optional quality of the state value */ - q?: StateQuality; - - /** Optional comment */ - c?: string; - } - - /** Provides low-level access to the ioBroker states DB */ - interface States { - - /** - * Returns a list of states with the given ids - * @param keys IDs of the states to be retrieved - * @param callback Is called when the operation has finished (successfully or not) - * @param dontModify unused - */ - getStates(keys: string[], callback: GetStatesCallback2, dontModify?: any): void; - - /** - * Returns the state with the given id - * @param id ID of the state to be retrieved - * @param callback Is called when the operation has finished (successfully or not) - */ - getState(id: string, callback: GetStateCallback): void; - - /** - * Stores a state in the db - * @param id ID of the state to be stored - * @param state The state to be stored in the db - * @param callback Is called when the operation has finished (successfully or not) - */ - setState(id: string, state?: string | number | boolean | State | Partial, callback?: SetStateCallback): void; - - /** - * Updates a state in memory without triggering a save - * @param id ID of the state to be stored - * @param state The state to be updated - * @param callback Is called when the operation has finished (successfully or not) - */ - setRawState(id: string, state: State, callback?: SetStateCallback): void; - - /** - * Deletes a state - * @param id ID of the state to be stored - * @param callback Is called when the operation has finished (successfully or not) - */ - delState(id: string, callback: DeleteStateCallback): void; - - /** - * Retrieves all ids of states matching @link{pattern} - * @param pattern The pattern to match against - * @param callback Is called when the operation has finished (successfully or not) - * @param dontModify unused - */ - getKeys(pattern: string, callback: GetConfigKeysCallback, dontModify?: any): void; - - /** - * Subscribe to changes of all states matching @link{pattern} - * @param pattern The pattern to match against - * @param callback Is called when the operation has finished (successfully or not) - */ - subscribe(pattern: string, cb: EmptyCallback): void; - /** - * Unsubscribe from changes of all states matching @link{pattern} - * @param pattern The pattern to match against - * @param callback Is called when the operation has finished (successfully or not) - */ - unsubscribe(pattern: string, cb: EmptyCallback): void; - - /** - * Register an adapter instance as subscribable. - * This means that the instance can read information about all subscriptions to its states - * and will be notified of changes. - * @param instance Adapter instance to register, e.g. "admin.0" - * @param cb Is called when the operation has finished (successfully or not) - */ - registerAdapterSubs(instance: string, cb?: (error: null, success: boolean) => void): void; - - /** - * Unregister an adapter instance as subscribable. - * @param instance Adapter instance to unregister, e.g. "admin.0" - * @param cb Is called when the operation has finished (successfully or not) - */ - unregisterAdapterSubs(instance: string, cb?: (error: null, success: boolean) => void): void; - - /** - * EDUCATED GUESS: Notify all clients about changes to an object - * @param type object type - * @param id State/object id - * @param obj The changed object - */ - publishAll(type: string, id: string, obj: Message): void; - - // TODO: Documentation for these functions is missing - pushMessage(id: string, state: Message, callback: SetStateCallback): void; - lenMessage(id: string, callback: GenericCallback): void; - getMessage(id: string, callback: GenericCallback): void; - delMessage(id: string, messageId: number, callback: ErrorCallback): void; - clearAllMessages(callback?: EmptyCallback): void; - subscribeMessage(id: string, cb: EmptyCallback): void; - unsubscribeMessage(id: string, cb: EmptyCallback): void; - - pushLog(id: string, log: Log, callback: SetStateCallback): void; - lenLog(id: string, callback: GenericCallback): void; - getLog(id: string, callback: GenericCallback): void; - delLog(id: string, logId: string, callback: ErrorCallback): void; - clearAllLogs(callback?: EmptyCallback): void; - subscribeLog(id: string, cb: EmptyCallback): void; - unsubscribeLog(id: string, cb: EmptyCallback): void; - - getSession(id: string, callback: GetSessionCallback): void; - setSession(id: string, expire: number, callback?: EmptyCallback): void; - setSession(id: string, expire: number, obj: Session, callback?: EmptyCallback): void; - destroySession(id: string, callback?: EmptyCallback): void; - - /** - * Retrieves a copy of the object with the given ID - * @param id Id of the object to find - * @param callback Is called when the operation has finished (successfully or not) - */ - getConfig(id: string, callback: GetObjectCallback): void; - - /** - * Returns a list of config keys matching - * @param pattern Pattern to match against - * @param callback Is called when the operation has finished (successfully or not) - * @param dontModify unused - */ - getConfigKeys(pattern: string, callback: GetConfigKeysCallback, dontModify?: any): void; - - /** - * Returns a list of objects with the given ids - * @param keys IDs of the objects to be retrieved - * @param callback Is called when the operation has finished (successfully or not) - * @param dontModify unused - */ - getConfigs(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; - - /** - * Creates or overwrites a config object in the object db - * @param id ID of the object - * @param obj Object to store - * @param callback Is called when the operation has finished (successfully or not) - */ - setConfig(id: string, obj: ioBroker.Object, callback: SetObjectCallback): void; - - /** - * Deletes a config object in the object db - * @param id ID of the object - * @param callback Is called when the operation has finished (successfully or not) - */ - delConfig(id: string, callback: ErrorCallback): void; - - /** - * Subscribe to config object changes - * @param pattern The pattern to match against - */ - subscribeConfig(pattern: string, callback: EmptyCallback): void; - - /** - * Unsubscribe from config object changes - * @param pattern The pattern to match against - */ - unsubscribeConfig(pattern: string, callback: EmptyCallback): void; - - /** - * Writes a binary state into Redis - * @param id The id of the state - * @param data The data to be written - * @param callback Is called when the operation has finished (successfully or not) - */ - setBinaryState(id: string, data: Buffer, callback: SetStateCallback): void; - - /** - * Reads a binary state from Redis - * @param id The id of the state - * @param callback Is called when the operation has finished (successfully or not) - */ - getBinaryState(id: string, callback: GetBinaryStateCallback): void; - - /** - * Deletes a binary state from Redis - * @param id The id of the state to be deleted - * @param callback Is called when the operation has finished (successfully or not) - */ - delBinaryState(id: string, callback: DeleteStateCallback): void; - - /** Destructor of the class. Call this before shutting down */ - destroy(): void; - - } // end interface States - - type Session = any; // TODO: implement - - type ObjectType = "state" | "channel" | "device"; - type CommonType = "number" | "string" | "boolean" | "array" | "object" | "mixed" | "file"; - - // Maybe this should extend Record, - // but the extra properties aren't defined anywhere, - // so I'd rather force the user to explicitly state - // he knows what he's doing by casting to any - interface ObjectCommon { - /** name of this object */ - name: string; - - // Icon and role aren't defined in SCHEMA.md, - // but they are being used by some adapters - /** Icon for this object */ - icon?: string; - /** role of the object */ - role?: string; - } - - interface StateCommon extends ObjectCommon { - /** Type of this state. See https://github.com/ioBroker/ioBroker/blob/master/doc/SCHEMA.md#state-commonrole for a detailed description */ - type?: CommonType; - /** minimum value */ - min?: number; - /** maximum value */ - max?: number; - /** unit of the value */ - unit?: string; - /** the default value */ - def?: any; - /** description of this state */ - desc?: string; - - /** if this state is readable */ - read: boolean; - /** if this state is writable */ - write: boolean; - /** role of the state (used in user interfaces to indicate which widget to choose) */ - role: string; - - /** - * Dictionary of possible values for this state in the form - *
-			 * {
-			 *     "internal value 1": "displayed value 1",
-			 *     "internal value 2": "displayed value 2",
-			 *     ...
-			 * }
-			 * 
- * In old ioBroker versions, this could also be a string of the form - * "val1:text1;val2:text2" (now deprecated) - */ - states?: Record | string; - - /** ID of a helper state indicating if the handler of this state is working */ - workingID?: string; - - /** attached history information */ - history?: any; - } - interface ChannelCommon extends ObjectCommon { - /** description of this channel */ - desc?: string; - } - type OtherCommon = ObjectCommon & { - [propName: string]: any; - }; - - interface BaseObject { - /** The ID of this object */ - _id?: string; - native: Record; - enums?: Record; - type: string; // specified in the derived interfaces - common: ObjectCommon; - acl?: ObjectACL; - } - - interface StateObject extends BaseObject { - type: "state"; - common: StateCommon; - acl?: StateACL; - } - interface PartialStateObject extends Partial> { - common?: Partial; - acl?: Partial; - } - - interface ChannelObject extends BaseObject { - type: "channel"; - common: ChannelCommon; - } - interface PartialChannelObject extends Partial> { - common?: Partial; - } - - interface DeviceObject extends BaseObject { - type: "device"; - common: ObjectCommon; // TODO: any definition for device? - } - interface PartialDeviceObject extends Partial> { - common?: Partial; - } - - interface OtherObject extends BaseObject { - type: "adapter" | "config" | "enum" | "group" | "host" | "info" | "instance" | "meta" | "script" | "user"; - common: OtherCommon; - } - interface PartialOtherObject extends Partial> { - common?: Partial; - } - - type Object = StateObject | ChannelObject | DeviceObject | OtherObject; - type PartialObject = PartialStateObject | PartialChannelObject | PartialDeviceObject | PartialOtherObject; - - /** Defines access rights for a single file */ - interface FileACL { - /** Full name of the user who owns this file, e.g. "system.user.admin" */ - owner: string; - /** Full name of the group who owns this file, e.g. "system.group.administrator" */ - ownerGroup: string; - /** Linux-type permissions defining access to this file */ - permissions: number; - } - /** Defines access rights for a single file, applied to a user or group */ - interface EvaluatedFileACL extends FileACL { - /** Whether the user may read the file */ - read: boolean; - /** Whether the user may write the file */ - write: boolean; - } - - /** Defines access rights for a single object */ - interface ObjectACL { - /** Full name of the user who owns this object, e.g. "system.user.admin" */ - owner: string; - /** Full name of the group who owns this object, e.g. "system.group.administrator" */ - ownerGroup: string; - /** Linux-type permissions defining access to this object */ - object: number; - } - /** Defines access rights for a single state object */ - interface StateACL extends ObjectACL { - /** Linux-type permissions defining access to this state */ - state: number; - } - - /** Defines access rights for a single object type */ - interface ObjectOperationPermissions { - /** Whether a user may enumerate objects of this type */ - list: boolean; - /** Whether a user may read objects of this type */ - read: boolean; - /** Whether a user may write objects of this type */ - write: boolean; - /** Whether a user may create objects of this type */ - create: boolean; - /** Whether a user may delete objects of this type */ - "delete": boolean; - } - - /** Defines the rights a user or group has to change objects */ - interface ObjectPermissions { - /** The access rights for files */ - file: ObjectOperationPermissions; - /** The access rights for objects */ - object: ObjectOperationPermissions; - /** The access rights for users/groups */ - users: ObjectOperationPermissions; - /** The access rights for states */ - state?: ObjectOperationPermissions; - } - /** Defined the complete set of access rights a user has */ - interface PermissionSet extends ObjectPermissions { - /** The name of the user this ACL is for */ - user: string; - /** The name of the groups this ACL was merged from */ - groups: string[]; - /** The access rights for certain commands */ - other: { - execute: boolean, - http: boolean, - sendto: boolean, - }; - } - - interface Permission { - /** The type of the permission */ - type: string; - /** Which kind of operation is required */ - operation: string; - } - interface ObjectOrStatePermission extends Permission { - type: "object" | "file" | "users" | "state"; - operation: "list" | "read" | "write" | "create" | "delete"; - } - interface OtherPermission extends Permission { - type: "other"; - operation: "execute" | "http" | "sendto"; - } - interface CommandsPermissions { - // TODO: Are all properties required or is a partial object ok? - getObject: ObjectOrStatePermission; - getObjects: ObjectOrStatePermission; - getObjectView: ObjectOrStatePermission; - setObject: ObjectOrStatePermission; - subscribeObjects: ObjectOrStatePermission; - unsubscribeObjects: ObjectOrStatePermission; - getStates: ObjectOrStatePermission; - getState: ObjectOrStatePermission; - setState: ObjectOrStatePermission; - getStateHistory: ObjectOrStatePermission; - subscribe: ObjectOrStatePermission; - unsubscribe: ObjectOrStatePermission; - getVersion: Permission; - httpGet: OtherPermission; - sendTo: OtherPermission; - sendToHost: OtherPermission; - readFile: ObjectOrStatePermission; - readFile64: ObjectOrStatePermission; - writeFile: ObjectOrStatePermission; - writeFile64: ObjectOrStatePermission; - unlink: ObjectOrStatePermission; - rename: ObjectOrStatePermission; - mkdir: ObjectOrStatePermission; - readDir: ObjectOrStatePermission; - chmodFile: ObjectOrStatePermission; - authEnabled: Permission; - disconnect: Permission; - listPermissions: Permission; - getUserPermissions: ObjectOrStatePermission; - } - - type UserGroup = any; // TODO find out how this looks like - // interface UserGroup { } - - /** Contains information about a user */ - interface User { - /** Which groups this user belongs to */ - groups: UserGroup[]; - /** Access rights of this user */ - acl: ObjectPermissions; - } - - /** Parameters for @link{Objects.getObjectView} */ - interface GetObjectViewParams { - /** First id to include in the return list */ - startkey: string; - /** Last id to include in the return list */ - endkey: string; - } - - /** Parameters for @link{Objects.getObjectList} */ - interface GetObjectListParams extends GetObjectViewParams { - /** Whether docs should be included in the return list */ // TODO: What are docs? - include_docs: boolean; - } - - /** Provides low-level access to the ioBroker objects db */ - interface Objects { - /** - * For a given user, returns the groups he belongs to, and his access rights - * @param user Name of the user. Has to start with "system.user." - * @param callback The callback function to be invoked with the return values - */ - getUserGroup(user: string, callback: GetUserGroupCallback): void; - - /** - * Determines the mime type for a given file extension - * @param ext File extension, including the leading dot, e.g. ".zip" - */ - getMimeType(ext: string): {mimeType: string, isBinary: boolean}; - - /** - * Writes a file. - * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" - * @param name File name - * @param data Contents of the file - * @param options (optional) MIME type of the file (string). Or some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - writeFile(id: string, name: string, data: Buffer | string, callback: ErrorCallback): void; - writeFile(id: string, name: string, data: Buffer | string, options: string | any, callback: ErrorCallback): void; - - /** - * Reads a file. - * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" - * @param name File name - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - readFile(id: string, name: string, callback: ReadFileCallback): void; - readFile(id: string, name: string, options: any, callback: ReadFileCallback): void; - - /** - * Deletes a file. - * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" - * @param name File name - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - unlink(id: string, name: string, callback: ErrorCallback): void; - unlink(id: string, name: string, options: any, callback: ErrorCallback): void; - /** - * Deletes a file. - * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" - * @param name File name - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - delFile(id: string, name: string, callback: ErrorCallback): void; - delFile(id: string, name: string, options: any, callback: ErrorCallback): void; - - /** - * Finds all files and directories starting with - * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" - * @param name File or directory name - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - readDir(id: string, name: string, callback: ReadDirCallback): void; - readDir(id: string, name: string, options: any, callback: ReadDirCallback): void; - - /** - * Renames a file or directory - * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" - * @param oldName Old file or directory name - * @param newName Name to rename to - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - rename(id: string, oldName: string, newName: string, callback: ErrorCallback): void; - rename(id: string, oldName: string, newName: string, options: any, callback: ErrorCallback): void; - - /** - * Creates an empty file with the given name - * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" - * @param name File name - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - touch(id: string, name: string, callback: ErrorCallback): void; - touch(id: string, name: string, options: any, callback: ErrorCallback): void; - - /** - * Deletes all files in the root directory matching - * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" - * @param name Pattern to match against - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - rm(id: string, name: string, callback: RmCallback): void; - rm(id: string, name: string, options: any, callback: RmCallback): void; - - /** - * Creates an empty directory with the given name - * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" - * @param name Directory name - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - mkDir(id: string, name: string, callback: ErrorCallback): void; - mkDir(id: string, name: string, options: any, callback: ErrorCallback): void; - - /** - * Takes possession all files in the root directory matching - * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" - * @param name Pattern to match against - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - chownFile(id: string, name: string, callback: ChownFileCallback): void; - chownFile(id: string, name: string, options: any, callback: ChownFileCallback): void; - - /** - * Changes access rights of all files in the root directory matching - * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" - * @param name Pattern to match against - * @param options Mode of the access change as a number or hexadecimal string - * @param callback Is called when the operation has finished (successfully or not) - */ - chmodFile(id: string, name: string, options: {mode: number | string} | Record, callback: ChownFileCallback): void; - - // not documented. enabled = true seems to disable the cache - // enableFileCache(enabled, options, callback) - - /** - * Subscribe to object changes - * @param pattern The pattern to match against - */ - subscribeConfig(pattern: string, callback: EmptyCallback): void; - subscribeConfig(pattern: string, options: any, callback: EmptyCallback): void; - /** - * Subscribe to object changes - * @param pattern The pattern to match against - */ - subscribe(pattern: string, callback: EmptyCallback): void; - subscribe(pattern: string, options: any, callback: EmptyCallback): void; - - /** - * Unsubscribe from object changes - * @param pattern The pattern to match against - */ - unsubscribeConfig(pattern: string, callback: EmptyCallback): void; - unsubscribeConfig(pattern: string, options: any, callback: EmptyCallback): void; - /** - * Unsubscribe from object changes - * @param pattern The pattern to match against - */ - unsubscribe(pattern: string, callback: EmptyCallback): void; - unsubscribe(pattern: string, options: any, callback: EmptyCallback): void; - - /** - * Takes possession of all objects matching - * @param pattern Pattern to match against - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - chownObject(pattern: string, callback: ChownObjectCallback): void; - chownObject(pattern: string, options: any, callback: ChownObjectCallback): void; - - /** - * Changes access rights of all objects matching - * @param pattern Pattern to match against - * @param options Mode of the access change as a number or hexadecimal string - * @param callback Is called when the operation has finished (successfully or not) - */ - chmodObject(pattern: string, callback: ChownObjectCallback): void; - chmodObject(pattern: string, options: any, callback: ChownObjectCallback): void; - - /** - * Retrieves a copy of the object with the given ID - * @param id Id of the object to find - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - getObject(id: string, callback: GetObjectCallback): void; - getObject(id: string, options: any, callback: GetObjectCallback): void; - /** - * Retrieves a copy of the object with the given ID - * @param id Id of the object to find - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - getConfig(id: string, callback: GetObjectCallback): void; - getConfig(id: string, options: any, callback: GetObjectCallback): void; - - /** - * Returns a list of config keys matching - * @param pattern Pattern to match against - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - * @param dontModify unused - */ - getConfigKeys(pattern: string, callback: GetConfigKeysCallback, dontModify?: any): void; - getConfigKeys(pattern: string, options: any, callback: GetConfigKeysCallback, dontModify?: any): void; - - /** - * Returns a list of objects with the given ids - * @param keys IDs of the objects to be retrieved - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - * @param dontModify unused - */ - getObjects(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; - getObjects(keys: string[], options: any, callback: GetObjectsCallback2, dontModify?: any): void; - /** - * Returns a list of objects with the given ids - * @param keys IDs of the objects to be retrieved - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - * @param dontModify unused - */ - getConfigs(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; - getConfigs(keys: string[], options: any, callback: GetObjectsCallback2, dontModify?: any): void; - - /** - * Creates or overwrites an object in the object db - * @param id ID of the object - * @param obj Object to store - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - setObject(id: string, obj: ioBroker.Object, callback: SetObjectCallback): void; - setObject(id: string, obj: ioBroker.Object, options: any, callback: SetObjectCallback): void; - /** - * Creates or overwrites an object in the object db - * @param id ID of the object - * @param obj Object to store - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - setConfig(id: string, obj: ioBroker.Object, callback: SetObjectCallback): void; - setConfig(id: string, obj: ioBroker.Object, options: any, callback: SetObjectCallback): void; - - /** - * Deletes an object in the object db - * @param id ID of the object - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - delObject(id: string, callback: ErrorCallback): void; - delObject(id: string, options: any, callback: ErrorCallback): void; - /** - * Deletes an object in the object db - * @param id ID of the object - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - delConfig(id: string, callback: ErrorCallback): void; - delConfig(id: string, options: any, callback: ErrorCallback): void; - - /** - * Returns a list of objects with id between params.startkey and params.endkey - * @param params Parameters determining the objects included in the return list. Null to include all objects - * @param options (optional) If the returned list should be sorted. And some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - getObjectList(params: GetObjectListParams | null, callback: GetObjectListCallback): void; - getObjectList(params: GetObjectListParams | null, options: { sorted?: boolean } | Record, callback: GetObjectListCallback): void; - - /** - * Query a predefined object view (similar to SQL stored procedures) and return the results - * For a detailed description refer to https://github.com/ioBroker/ioBroker/wiki/Adapter-Development-Documentation#object-fields - * or http://guide.couchdb.org/editions/1/en/views.html - * @param design The namespace of the object view, as defined in io-package.json. Usually the adapter name, e.g. "hm-rpc" - * @param search The name of the object view. - * @param params Parameters to additionally filter out objects from the return list. Null to include all objects - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - getObjectView(design: string, search: string, params: GetObjectViewParams | null, callback: GetObjectViewCallback): void; - getObjectView(design: string, search: string, params: GetObjectViewParams | null, options: any, callback: GetObjectViewCallback): void; - - /** - * Extends an object in the object db with new properties - * @param id ID of the object - * @param obj Object to extend the original one with. May be just parts of an object. - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - extendObject(id: string, obj: PartialObject, callback: ExtendObjectCallback): void; - extendObject(id: string, obj: PartialObject, options: any, callback: ExtendObjectCallback): void; - - /** - * Finds an object by ID or name. If multiple objects were found, return the first one - * @param idOrName ID or name of the object - * @param type If != null, only return an object with a common.type equal to this - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - findObject(idOrName: string, type: CommonType | null, callback: FindObjectCallback): void; - findObject(idOrName: string, type: CommonType | null, options: any, callback: FindObjectCallback): void; - - // I'd rather not document a function with the name "destroyDB" - - /** Destructor of the class. Call this before shutting down. */ - destroy(): void; - - } // end interface Objects - - type LogLevel = "silly" | "debug" | "info" | "warn" | "error"; - interface Logger { - /** log message with silly level */ - silly(message: string): void; - /** log message with debug level */ - debug(message: string): void; - /** log message with info level (default output level for all adapters) */ - info(message: string): void; - /** log message with warning severity */ - warn(message: string): void; - /** log message with error severity */ - error(message: string): void; - - /** Verbosity of the log output */ - level: LogLevel; - } - - interface Certificates { - /** private key file */ - key: string | Buffer; - /** public certificate */ - cert: string | Buffer; - /** chained CA certificates */ - ca: (string | Buffer)[]; - } - - /** Callback information for a passed message */ - interface MessageCallbackInfo { - /** The original message payload */ - message: string | object; - /** ID of this callback */ - id: number; - // ??? - ack: boolean; - /** Timestamp of this message */ - time: number; - } - type MessageCallback = (result?: any) => void; - - /** A message being passed between adapter instances */ - interface Message { - /** The command to be executed */ - command: string; - /** The message payload */ - message: string | object; - /** The source of this message */ - from: string; - /** ID of this message */ - _id: number; - /** Callback information. This is set when the source expects a response */ - callback: MessageCallbackInfo; - } - - type Log = any; // TODO: define this https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/states/statesInMemServer.js#L873 - - type EnumList = string | string[]; - - type Enum = any; // TODO: implement this - - interface DirectoryEntry { - file: string; - stats: fs.Stats; - isDir: boolean; - acl: any; // access control list object - modifiedAt: number; - createdAt: number; - } - - interface GetHistoryOptions { - instance?: string; - start?: number; - end?: number; - step?: number; - count?: number; - from?: boolean; - ack?: boolean; - q?: boolean; - addID?: boolean; - limit?: number; - ignoreNull: boolean; - sessionId?: any; - aggregate?: "minmax" | "min" | "max" | "average" | "total" | "count" | "none"; - } - - interface AdapterOptions { - /** The name of the adapter */ - name: string; - - /** path to adapter */ - dirname?: string; - - /** if the global system config should be included in the created object. Default: false */ - systemConfig?: boolean; - - /** provide alternative global configuration for the adapter. Default: null */ - config?: any; - - /** instance of the created adapter. Default: null */ - instance?: number; - - /** If the adapter needs access to the formatDate function to format dates according to the global settings. Default: false */ - useFormatDate?: boolean; - - /** If the adapter collects logs from all adapters (experts only). Default: false */ - logTransporter?: boolean; - - /** Handler for changes of subscribed objects */ - objectChange?: ObjectChangeHandler; - /** Handler for received adapter messages. Can only be used if messagebox in io-package.json is set to true. */ - message?: MessageHandler; - /** Handler for changes of subscribed states */ - stateChange?: StateChangeHandler; - /** Will be called when the adapter is intialized */ - ready?: () => void; - /** Will be called on adapter termination */ - unload?: (callback: EmptyCallback) => void; - - /** if true, stateChange will be called with an id that has no namespace, e.g. "state" instead of "adapter.0.state". Default: false */ - noNamespace?: boolean; - } // end interface AdapterOptions - - // tslint:disable-next-line:no-empty-interface - interface AdapterConfig { - // This is a stub to be augmented in every adapter - } - - interface Adapter { - /** The name of the adapter */ - name: string; - /** The name of the host where the adapter is running */ - host: string; - /** instance number of this adapter instance */ - instance: number; - /** Namespace of adapter objects: "." */ - readonly namespace: string; - /** native part of the adapter settings */ - config: AdapterConfig; - /** common part of the adapter settings */ - common: any; - /** system part of the adapter settings */ - systemConfig?: any; - /** path to the adapter folder */ - adapterDir: string; - /** content of io-package.json */ - ioPack: any; - /** content of package.json */ - pack: any; - /** access to the logging functions */ - log: Logger; - /** adapter version */ - version: any; - states: States; - objects: Objects; - /** if the adapter is connected to the host */ - connected: boolean; - - /* =============================== - Functions defined in adapter.js - =============================== */ - - /** - * Helper function that looks for first free TCP port starting with the given one. - * @param port - The port to start with - * @param callback - gets called when a free port is found - */ - getPort(port: number, callback: (port: number) => void): void; - - /** Stops the adapter. Note: Is not always defined. */ - stop?: () => void; - - // ============================== - // GENERAL - - /** Validates username and password */ - checkPassword(user: string, password: string, callback: (result: boolean) => void): void; - checkPassword(user: string, password: string, options: any, callback: (result: boolean) => void): void; - /** Sets a new password for the given user */ - setPassword(user: string, password: string, options?: any, callback?: (err?: any) => void): void; - /** Checks if a user exists and is in the given group. */ - checkGroup(user: string, group: string, callback: (result: boolean) => void): void; - checkGroup(user: string, group: string, options: any, callback: (result: boolean) => void): void; - /** Determines the users permissions */ - calculatePermissions(user: string, commandsPermissions: CommandsPermissions, callback: (result: PermissionSet) => void): void; - calculatePermissions(user: string, commandsPermissions: CommandsPermissions, options: any, callback: (result: PermissionSet) => void): void; - /** Returns SSL certificates by name (private key, public cert and chained certificate) for creation of HTTPS servers */ - getCertificates(publicName: string, privateName: string, chainedName: string, callback: (err: string | null, certs?: Certificates, useLetsEncryptCert?: boolean) => void): void; - - /** - * Sends a message to a specific instance or all instances of some specific adapter. - * @param instanceName The instance to send this message to. - * If the ID of an instance is given (e.g. "admin.0"), only this instance will receive the message. - * If the name of an adapter is given (e.g. "admin"), all instances of this adapter will receive it. - * @param command (optional) Command name of the target instance. Default: "send" - * @param message The message (e.g. params) to send. - */ - sendTo(instanceName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; - sendTo(instanceName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; - - /** - * Sends a message to a specific host or all hosts. - */ - sendToHost(hostName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; - sendToHost(hostName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; - - /** Convert ID to {device: D, channel: C, state: S} */ - idToDCS(id: string): { - device: string; - channel: string; - state: string; - }; - - // ============================== - // own objects - - /** Reads an object from the object db */ - getObject(id: string, callback: GetObjectCallback): void; - getObject(id: string, options: any, callback: GetObjectCallback): void; - /** Creates or overwrites an object in the object db */ - setObject(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; - /** Creates an object in the object db. Existing objects are not overwritten. */ - setObjectNotExists(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; - /** Get all states, channels and devices of this adapter */ - getAdapterObjects(callback: (objects: Record) => void): void; - /** Extend an object and create it if it might not exist */ - extendObject(id: string, objPart: PartialObject, options?: any, callback?: SetObjectCallback): void; - /** - * Deletes an object from the object db - * @param id - The id of the object without namespace - */ - delObject(id: string, options?: any, callback?: ErrorCallback): void; - - // ============================== - // foreign objects - - // tslint:disable:unified-signatures - /** Reads an object (which might not belong to this adapter) from the object db */ - getForeignObject(id: string, callback: GetObjectCallback): void; - getForeignObject(id: string, options: any, callback: GetObjectCallback): void; - /** Get foreign objects by pattern, by specific type and resolve their enums. */ - getForeignObjects(pattern: string, callback: GetObjectsCallback): void; - getForeignObjects(pattern: string, options: any, callback: GetObjectsCallback): void; - getForeignObjects(pattern: string, type: ObjectType, callback: GetObjectsCallback): void; - getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, callback: GetObjectsCallback): void; - getForeignObjects(pattern: string, type: ObjectType, options: any, callback: GetObjectsCallback): void; - getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, options: any, callback: GetObjectsCallback): void; - /** Creates or overwrites an object (which might not belong to this adapter) in the object db */ - setForeignObject(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; - /** Creates an object (which might not belong to this adapter) in the object db. Existing objects are not overwritten. */ - setForeignObjectNotExists(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; - /** Extend an object (which might not belong to this adapter) and create it if it might not exist */ - extendForeignObject(id: string, objPart: PartialObject, options?: any, callback?: SetObjectCallback): void; - // tslint:enable:unified-signatures - /** - * Finds an object by its ID or name - * @param type - common.type of the state - */ - findForeignObject(idOrName: string, type: string, callback: FindObjectCallback): void; - findForeignObject(idOrName: string, type: string, options: any, callback: FindObjectCallback): void; - /** - * Deletes an object (which might not belong to this adapter) from the object db - * @param id - The id of the object including namespace - */ - delForeignObject(id: string, options?: any, callback?: ErrorCallback): void; - - // ============================== - // states - /** Writes a value into the states DB. */ - setState(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateCallback): void; - /** Writes a value into the states DB only if it has changed. */ - setStateChanged(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateChangedCallback): void; - /** Writes a value (which might not belong to this adapter) into the states DB. */ - setForeignState(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateCallback): void; - /** Writes a value (which might not belong to this adapter) into the states DB only if it has changed. */ - setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateChangedCallback): void; - - /** Read a value from the states DB. */ - getState(id: string, callback: GetStateCallback): void; - getState(id: string, options: any, callback: GetStateCallback): void; - /** Read a value (which might not belong to this adapter) from the states DB. */ - getForeignState(id: string, callback: GetStateCallback): void; - getForeignState(id: string, options: any, callback: GetStateCallback): void; - /** Read all states of this adapter which match the given pattern */ - getStates(pattern: string, callback: GetStatesCallback): void; - getStates(pattern: string, options: any, callback: GetStatesCallback): void; - /** Read all states (which might not belong to this adapter) which match the given pattern */ - getForeignStates(pattern: string, callback: GetStatesCallback): void; - getForeignStates(pattern: string, options: any, callback: GetStatesCallback): void; - - /** Deletes a state from the states DB, but not the associated object. Consider using @link{deleteState} instead */ - delState(id: string, options?: any, callback?: ErrorCallback): void; - /** Deletes a state from the states DB, but not the associated object */ - delForeignState(id: string, options?: any, callback?: ErrorCallback): void; - - getHistory(id: string, options: GetHistoryOptions, callback: GetHistoryCallback): void; - - // MISSING: - // pushFifo and similar https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4105 - // logRedirect https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4294 - // requireLog https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4336 - // processLog https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4360 - - /** - * Writes a binary state into Redis - * @param id The id of the state - * @param binary The data to be written - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - setBinaryState(id: string, binary: Buffer, callback: SetStateCallback): void; - setBinaryState(id: string, binary: Buffer, options: any, callback: SetStateCallback): void; - /** - * Reads a binary state from Redis - * @param id The id of the state - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - getBinaryState(id: string, callback: GetBinaryStateCallback): void; - getBinaryState(id: string, options: any, callback: GetBinaryStateCallback): void; - - // ============================== - // enums - - /** Returns the enum tree, filtered by the optional enum name */ - getEnum(callback: GetEnumCallback): void; - getEnum(name: string, callback: GetEnumCallback): void; - getEnum(name: string, options: any, callback: GetEnumCallback): void; - getEnums(callback: GetEnumsCallback): void; - getEnums(enumList: EnumList, callback: GetEnumsCallback): void; - getEnums(enumList: EnumList, options: any, callback: GetEnumsCallback): void; - - addChannelToEnum(enumName: string, addTo: string, parentDevice: string, channelName: string, options?: any, callback?: ErrorCallback): void; - deleteChannelFromEnum(enumName: string, parentDevice: string, channelName: string, options?: any, callback?: ErrorCallback): void; - - addStateToEnum(enumName: string, addTo: string, parentDevice: string, parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; - deleteStateFromEnum(enumName: string, parentDevice: string, parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; - - // ============================== - // subscriptions - - /** Subscribe to changes of objects in this instance */ - subscribeObjects(pattern: string, options?: any): void; - /** Subscribe to changes of objects (which might not belong to this adapter) */ - subscribeForeignObjects(pattern: string, options?: any): void; - /** Unsubscribe from changes of objects in this instance */ - unsubscribeObjects(pattern: string, options?: any): void; - /** Unsubscribe from changes of objects (which might not belong to this adapter) */ - unsubscribeForeignObjects(pattern: string, options?: any): void; - - /** Subscribe to changes of states in this instance */ - subscribeStates(pattern: string, options?: any, callback?: ErrorCallback): void; - /** Subscribe to changes of states (which might not belong to this adapter) */ - subscribeForeignStates(pattern: string, options?: any, callback?: ErrorCallback): void; - /** - * Subscribe from changes of states in this instance - * @param pattern - Must match the pattern used to subscribe - */ - unsubscribeStates(pattern: string, options?: any, callback?: ErrorCallback): void; - /** - * Subscribe from changes of states (which might not belong to this adapter) - * @param pattern - Must match the pattern used to subscribe - */ - unsubscribeForeignStates(pattern: string, options?: any, callback?: ErrorCallback): void; - - // ============================== - // devices and channels - - /** creates an object with type device */ - createDevice(deviceName: string, common?: any, native?: any, options?: any, callback?: SetObjectCallback): void; - /** deletes a device, its channels and states */ - deleteDevice(deviceName: string, options?: any, callback?: ErrorCallback): void; - /** gets the devices of this instance */ - - /** creates an object with type channel */ - createChannel(parentDevice: string, channelName: string, roleOrCommon?: string | object, native?: any, options?: any, callback?: SetObjectCallback): void; - /** deletes a channel and its states */ - deleteChannel(channelName: string, options?: any, callback?: ErrorCallback): void; - deleteChannel(parentDevice: string, channelName: string, options?: any, callback?: ErrorCallback): void; - - /** creates a state and the corresponding object */ - createState(parentDevice: string, parentChannel: string, stateName: string, roleOrCommon?: string | object, native?: any, options?: any, callback?: SetObjectCallback): void; - /** deletes a state */ - deleteState(stateName: string, options?: any, callback?: ErrorCallback): void; - deleteState(parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; - deleteState(parentDevice: string, parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; - - /** - * Returns a list of all devices in this adapter instance - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - getDevices(callback: GetObjectsCallback3): void; - getDevices(options: any, callback: GetObjectsCallback3): void; - - /** - * Returns a list of all channels in this adapter instance - * @param parentDevice (optional) Name of the parent device to filter the channels by - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - getChannels(callback: GetObjectsCallback3): void; - getChannels(parentDevice: string | null, callback: GetObjectsCallback3): void; - getChannels(parentDevice: string | null, options: any, callback: GetObjectsCallback3): void; - /** - * Returns a list of all channels in this adapter instance - * @param parentDevice (optional) Name of the parent device to filter the channels by - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - getChannelsOf(callback: GetObjectsCallback3): void; - getChannelsOf(parentDevice: string | null, callback: GetObjectsCallback3): void; - getChannelsOf(parentDevice: string | null, options: any, callback: GetObjectsCallback3): void; - - /** - * Returns a list of all states in this adapter instance - * @param parentDevice (optional) Name of the parent device to filter the channels by - * @param parentChannel (optional) Name of the parent channel to filter the channels by - * @param options (optional) Some internal options. - * @param callback Is called when the operation has finished (successfully or not) - */ - getStatesOf(callback: GetObjectsCallback3): void; - getStatesOf(parentDevice: string | null, callback: GetObjectsCallback3): void; - getStatesOf(parentDevice: string | null, parentChannel: string | null, callback: GetObjectsCallback3): void; - getStatesOf(parentDevice: string | null, parentChannel: string | null, options: any, callback: GetObjectsCallback3): void; - - // ============================== - // filesystem - - /** - * reads the content of directory from DB for given adapter and path - * @param adapter - adapter name. If adapter name is null, default will be the name of the current adapter. - * @param path - path to direcory without adapter name. E.g. If you want to read "/vis.0/main/views.json", here must be "/main/views.json" and _adapter must be equal to "vis.0". - */ - readDir(adapterName: string, path: string, callback: ReadDirCallback): void; - readDir(adapterName: string, path: string, options: any, callback: ReadDirCallback): void; - mkDir(adapterName: string, path: string, callback: ErrorCallback): void; - mkDir(adapterName: string, path: string, options: any, callback: ErrorCallback): void; - - readFile(adapterName: string, path: string, callback: ReadFileCallback): void; - readFile(adapterName: string, path: string, options: any, callback: ReadFileCallback): void; - writeFile(adapterName: string, path: string, data: Buffer | string, callback: ErrorCallback): void; - writeFile(adapterName: string, path: string, data: Buffer | string, options: any, callback: ErrorCallback): void; // options see https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/objects/objectsInMemServer.js#L599 - - delFile(adapterName: string, path: string, callback: ErrorCallback): void; - delFile(adapterName: string, path: string, options: any, callback: ErrorCallback): void; - unlink(adapterName: string, path: string, callback: ErrorCallback): void; - unlink(adapterName: string, path: string, options: any, callback: ErrorCallback): void; - - rename(adapterName: string, oldName: string, newName: string, callback: ErrorCallback): void; - rename(adapterName: string, oldName: string, newName: string, options: any, callback: ErrorCallback): void; - - /** - * Changes access rights of all files in the adapter directory - * @param adapter Name of the adapter instance, e.g. "admin.0". Defaults to the namespace of this adapter. - * @param path Pattern to match the file path against - * @param options Mode of the access change as a number or hexadecimal string - * @param callback Is called when the operation has finished (successfully or not) - */ - chmodFile(adapter: string | null, path: string, options: {mode: number | string} | Record, callback: ChownFileCallback): void; - - // ============================== - // formatting - - formatValue(value: number | string, format: any): string; - formatValue(value: number | string, decimals: number, format: any): string; - formatDate(dateObj: string | Date | number, format: string): string; - formatDate(dateObj: string | Date | number, isDuration: boolean | string, format: string): string; - } // end interface Adapter - - type ObjectChangeHandler = (id: string, obj: ioBroker.Object) => void; - type StateChangeHandler = (id: string, obj: State) => void; - type MessageHandler = (obj: Message) => void; - - type EmptyCallback = () => void; - type ErrorCallback = (err?: string) => void; - // TODO: Redefine callbacks as subclass of GenericCallback - type GenericCallback = (err: string | null, result?: T) => void; - - type SetObjectCallback = (err: string | null, obj: { id: string }) => void; - type GetObjectCallback = (err: string | null, obj: ioBroker.Object) => void; - type GetEnumCallback = (err: string | null, enums: Record, requestedEnum: string) => void; - type GetEnumsCallback = ( - err: string | null, - result: { - [groupName: string]: Record, - }, - ) => void; - type GetObjectsCallback = (err: string | null, objects: Record) => void; - - type FindObjectCallback = ( - /** If an error happened, this contains the message */ - err: string | null, - /** If an object was found, this contains the ID */ - id?: string, - /** If an object was found, this contains the common.name */ - name?: string, - ) => void; - - interface GetObjectsItem { - /** The ID of this object */ - id: string; - /** A copy of the object from the DB */ - value: T; - } - // This is a version used by GetDevices/GetChannelsOf/GetStatesOf - type GetObjectsCallback3 = (err: string | null, result?: GetObjectsItem[]) => void; - - type GetStateCallback = (err: string | null, state: State) => void; - type GetStatesCallback = (err: string | null, states: Record) => void; - /** Version of the callback used by States.getStates */ - type GetStatesCallback2 = (err: string | null, states: State[]) => void; - type GetBinaryStateCallback = (err: string | null, state?: Buffer) => void; - type SetStateCallback = (err: string | null, id?: string) => void; - type SetStateChangedCallback = (err: string | null, id: string, notChanged: boolean) => void; - type DeleteStateCallback = (err: string | null, id?: string) => void; - type GetHistoryCallback = (err: string | null, result: (State & { id?: string })[], step: number, sessionId?: string) => void; - - /** Contains the return values of readDir */ - interface ReadDirResult { - /** Name of the file or directory */ - file: string; - /** File system stats */ - stats: fs.Stats; - /** Whether this is a directory or a file */ - isDir: boolean; - /** Access rights */ - acl: EvaluatedFileACL; - /** Date of last modification */ - modifiedAt: number; - /** Date of creation */ - createdAt: number; - } - type ReadDirCallback = (err: string | null, entries?: ReadDirResult[]) => void; - type ReadFileCallback = (err: string | null, file?: Buffer | string, mimeType?: string) => void; - - /** Contains the return values of chownFile */ - interface ChownFileResult { - /** The parent directory of the processed file or directory */ - path: string; - /** Name of the file or directory */ - file: string; - /** File system stats */ - stats: fs.Stats; - /** Whether this is a directory or a file */ - isDir: boolean; - /** Access rights */ - acl: FileACL; - /** Date of last modification */ - modifiedAt: number; - /** Date of creation */ - createdAt: number; - } - type ChownFileCallback = (err: string | null, entries?: ChownFileResult[], id?: string) => void; - - /** Contains the return values of rm */ - interface RmResult { - /** The parent directory of the deleted file or directory */ - path: string; - /** The name of the deleted file or directory */ - file: string; - /** Whether the deleted object was a directory or a file */ - isDir: boolean; - } - type RmCallback = (err: string | null, entries?: RmResult[]) => void; - - type GetUserGroupCallback = (objectsInstance: Objects, user: User, groups: UserGroup[], acl: ObjectPermissions) => void; - - type ChownObjectCallback = (err: string | null, list?: ioBroker.Object[]) => void; - - type GetConfigKeysCallback = (err: string | null, list?: string[]) => void; - // this is a version of the callback used by Objects.getObjects - type GetObjectsCallback2 = (err: string | null, objects?: (ioBroker.Object | { err: string })[]) => void; - - interface GetObjectViewItem { - /** The ID of this object */ - id: string; - /** A copy of the object from the DB or some aggregation result */ - value: ioBroker.Object | any; - } - type GetObjectViewCallback = (err: string | null, result?: { rows: GetObjectViewItem[] }) => void; - - interface GetObjectListItem extends GetObjectViewItem { - /** A copy of the object */ - value: ioBroker.Object; - /** The same as @link{value} */ - doc: ioBroker.Object; - } - type GetObjectListCallback = (err: string | null, result?: { rows: GetObjectListItem[] }) => void; - - type ExtendObjectCallback = (err: string | null, result?: {id: string, value: ioBroker.Object}, id?: string ) => void; - - type GetSessionCallback = (session: Session) => void; - - } // end namespace ioBroker + namespace ioBroker { + enum StateQuality { + good = 0x00, // or undefined or null + bad = 0x01, + general_problem = 0x01, + general_device_problem = 0x41, + general_sensor_problem = 0x81, + device_not_connected = 0x42, + sensor_not_connected = 0x82, + device_reports_error = 0x44, + sensor_reports_error = 0x84, + } + + interface State { + /** The value of the state. */ + val: any; + + /** Direction flag: false for desired value and true for actual value. Default: false. */ + ack: boolean; + + /** Unix timestamp. Default: current time */ + ts: number; + + /** Unix timestamp of the last time the value changed */ + lc: number; + + /** Name of the adapter instance which set the value, e.g. "system.adapter.web.0" */ + from: string; + + /** Optional time in seconds after which the state is reset to null */ + expire?: number; + + /** Optional quality of the state value */ + q?: StateQuality; + + /** Optional comment */ + c?: string; + } + + /** Provides low-level access to the ioBroker states DB */ + interface States { + /** + * Returns a list of states with the given ids + * @param keys IDs of the states to be retrieved + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getStates(keys: string[], callback: GetStatesCallback2, dontModify?: any): void; + + /** + * Returns the state with the given id + * @param id ID of the state to be retrieved + * @param callback Is called when the operation has finished (successfully or not) + */ + getState(id: string, callback: GetStateCallback): void; + + /** + * Stores a state in the db + * @param id ID of the state to be stored + * @param state The state to be stored in the db + * @param callback Is called when the operation has finished (successfully or not) + */ + setState(id: string, state?: string | number | boolean | State | Partial, callback?: SetStateCallback): void; + + /** + * Updates a state in memory without triggering a save + * @param id ID of the state to be stored + * @param state The state to be updated + * @param callback Is called when the operation has finished (successfully or not) + */ + setRawState(id: string, state: State, callback?: SetStateCallback): void; + + /** + * Deletes a state + * @param id ID of the state to be stored + * @param callback Is called when the operation has finished (successfully or not) + */ + delState(id: string, callback: DeleteStateCallback): void; + + /** + * Retrieves all ids of states matching @link{pattern} + * @param pattern The pattern to match against + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getKeys(pattern: string, callback: GetConfigKeysCallback, dontModify?: any): void; + + /** + * Subscribe to changes of all states matching @link{pattern} + * @param pattern The pattern to match against + * @param callback Is called when the operation has finished (successfully or not) + */ + subscribe(pattern: string, cb: EmptyCallback): void; + /** + * Unsubscribe from changes of all states matching @link{pattern} + * @param pattern The pattern to match against + * @param callback Is called when the operation has finished (successfully or not) + */ + unsubscribe(pattern: string, cb: EmptyCallback): void; + + /** + * Register an adapter instance as subscribable. + * This means that the instance can read information about all subscriptions to its states + * and will be notified of changes. + * @param instance Adapter instance to register, e.g. "admin.0" + * @param cb Is called when the operation has finished (successfully or not) + */ + registerAdapterSubs(instance: string, cb?: (error: null, success: boolean) => void): void; + + /** + * Unregister an adapter instance as subscribable. + * @param instance Adapter instance to unregister, e.g. "admin.0" + * @param cb Is called when the operation has finished (successfully or not) + */ + unregisterAdapterSubs(instance: string, cb?: (error: null, success: boolean) => void): void; + + /** + * EDUCATED GUESS: Notify all clients about changes to an object + * @param type object type + * @param id State/object id + * @param obj The changed object + */ + publishAll(type: string, id: string, obj: Message): void; + + // TODO: Documentation for these functions is missing + pushMessage(id: string, state: Message, callback: SetStateCallback): void; + lenMessage(id: string, callback: GenericCallback): void; + getMessage(id: string, callback: GenericCallback): void; + delMessage(id: string, messageId: number, callback: ErrorCallback): void; + clearAllMessages(callback?: EmptyCallback): void; + subscribeMessage(id: string, cb: EmptyCallback): void; + unsubscribeMessage(id: string, cb: EmptyCallback): void; + + pushLog(id: string, log: Log, callback: SetStateCallback): void; + lenLog(id: string, callback: GenericCallback): void; + getLog(id: string, callback: GenericCallback): void; + delLog(id: string, logId: string, callback: ErrorCallback): void; + clearAllLogs(callback?: EmptyCallback): void; + subscribeLog(id: string, cb: EmptyCallback): void; + unsubscribeLog(id: string, cb: EmptyCallback): void; + + getSession(id: string, callback: GetSessionCallback): void; + setSession(id: string, expire: number, callback?: EmptyCallback): void; + setSession(id: string, expire: number, obj: Session, callback?: EmptyCallback): void; + destroySession(id: string, callback?: EmptyCallback): void; + + /** + * Retrieves a copy of the object with the given ID + * @param id Id of the object to find + * @param callback Is called when the operation has finished (successfully or not) + */ + getConfig(id: string, callback: GetObjectCallback): void; + + /** + * Returns a list of config keys matching + * @param pattern Pattern to match against + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getConfigKeys(pattern: string, callback: GetConfigKeysCallback, dontModify?: any): void; + + /** + * Returns a list of objects with the given ids + * @param keys IDs of the objects to be retrieved + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getConfigs(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; + + /** + * Creates or overwrites a config object in the object db + * @param id ID of the object + * @param obj Object to store + * @param callback Is called when the operation has finished (successfully or not) + */ + setConfig(id: string, obj: ioBroker.Object, callback: SetObjectCallback): void; + + /** + * Deletes a config object in the object db + * @param id ID of the object + * @param callback Is called when the operation has finished (successfully or not) + */ + delConfig(id: string, callback: ErrorCallback): void; + + /** + * Subscribe to config object changes + * @param pattern The pattern to match against + */ + subscribeConfig(pattern: string, callback: EmptyCallback): void; + + /** + * Unsubscribe from config object changes + * @param pattern The pattern to match against + */ + unsubscribeConfig(pattern: string, callback: EmptyCallback): void; + + /** + * Writes a binary state into Redis + * @param id The id of the state + * @param data The data to be written + * @param callback Is called when the operation has finished (successfully or not) + */ + setBinaryState(id: string, data: Buffer, callback: SetStateCallback): void; + + /** + * Reads a binary state from Redis + * @param id The id of the state + * @param callback Is called when the operation has finished (successfully or not) + */ + getBinaryState(id: string, callback: GetBinaryStateCallback): void; + + /** + * Deletes a binary state from Redis + * @param id The id of the state to be deleted + * @param callback Is called when the operation has finished (successfully or not) + */ + delBinaryState(id: string, callback: DeleteStateCallback): void; + + /** Destructor of the class. Call this before shutting down */ + destroy(): void; + } // end interface States + + type Session = any; // TODO: implement + + type ObjectType = "state" | "channel" | "device"; + type CommonType = "number" | "string" | "boolean" | "array" | "object" | "mixed" | "file"; + + // Maybe this should extend Record, + // but the extra properties aren't defined anywhere, + // so I'd rather force the user to explicitly state + // he knows what he's doing by casting to any + interface ObjectCommon { + /** name of this object */ + name: string; + + // Icon and role aren't defined in SCHEMA.md, + // but they are being used by some adapters + /** Icon for this object */ + icon?: string; + /** role of the object */ + role?: string; + } + + interface StateCommon extends ObjectCommon { + /** Type of this state. See https://github.com/ioBroker/ioBroker/blob/master/doc/SCHEMA.md#state-commonrole for a detailed description */ + type?: CommonType; + /** minimum value */ + min?: number; + /** maximum value */ + max?: number; + /** unit of the value */ + unit?: string; + /** the default value */ + def?: any; + /** description of this state */ + desc?: string; + + /** if this state is readable */ + read: boolean; + /** if this state is writable */ + write: boolean; + /** role of the state (used in user interfaces to indicate which widget to choose) */ + role: string; + + /** + * Dictionary of possible values for this state in the form + *
+             * {
+             *     "internal value 1": "displayed value 1",
+             *     "internal value 2": "displayed value 2",
+             *     ...
+             * }
+             * 
+ * In old ioBroker versions, this could also be a string of the form + * "val1:text1;val2:text2" (now deprecated) + */ + states?: Record | string; + + /** ID of a helper state indicating if the handler of this state is working */ + workingID?: string; + + /** attached history information */ + history?: any; + } + interface ChannelCommon extends ObjectCommon { + /** description of this channel */ + desc?: string; + } + type OtherCommon = ObjectCommon & { + [propName: string]: any; + }; + + interface BaseObject { + /** The ID of this object */ + _id?: string; + native: Record; + enums?: Record; + type: string; // specified in the derived interfaces + common: ObjectCommon; + acl?: ObjectACL; + } + + interface StateObject extends BaseObject { + type: "state"; + common: StateCommon; + acl?: StateACL; + } + interface PartialStateObject extends Partial> { + common?: Partial; + acl?: Partial; + } + + interface ChannelObject extends BaseObject { + type: "channel"; + common: ChannelCommon; + } + interface PartialChannelObject extends Partial> { + common?: Partial; + } + + interface DeviceObject extends BaseObject { + type: "device"; + common: ObjectCommon; // TODO: any definition for device? + } + interface PartialDeviceObject extends Partial> { + common?: Partial; + } + + interface OtherObject extends BaseObject { + type: "adapter" | "config" | "enum" | "group" | "host" | "info" | "instance" | "meta" | "script" | "user"; + common: OtherCommon; + } + interface PartialOtherObject extends Partial> { + common?: Partial; + } + + type Object = StateObject | ChannelObject | DeviceObject | OtherObject; + type PartialObject = PartialStateObject | PartialChannelObject | PartialDeviceObject | PartialOtherObject; + + /** Defines access rights for a single file */ + interface FileACL { + /** Full name of the user who owns this file, e.g. "system.user.admin" */ + owner: string; + /** Full name of the group who owns this file, e.g. "system.group.administrator" */ + ownerGroup: string; + /** Linux-type permissions defining access to this file */ + permissions: number; + } + /** Defines access rights for a single file, applied to a user or group */ + interface EvaluatedFileACL extends FileACL { + /** Whether the user may read the file */ + read: boolean; + /** Whether the user may write the file */ + write: boolean; + } + + /** Defines access rights for a single object */ + interface ObjectACL { + /** Full name of the user who owns this object, e.g. "system.user.admin" */ + owner: string; + /** Full name of the group who owns this object, e.g. "system.group.administrator" */ + ownerGroup: string; + /** Linux-type permissions defining access to this object */ + object: number; + } + /** Defines access rights for a single state object */ + interface StateACL extends ObjectACL { + /** Linux-type permissions defining access to this state */ + state: number; + } + + /** Defines access rights for a single object type */ + interface ObjectOperationPermissions { + /** Whether a user may enumerate objects of this type */ + list: boolean; + /** Whether a user may read objects of this type */ + read: boolean; + /** Whether a user may write objects of this type */ + write: boolean; + /** Whether a user may create objects of this type */ + create: boolean; + /** Whether a user may delete objects of this type */ + "delete": boolean; + } + + /** Defines the rights a user or group has to change objects */ + interface ObjectPermissions { + /** The access rights for files */ + file: ObjectOperationPermissions; + /** The access rights for objects */ + object: ObjectOperationPermissions; + /** The access rights for users/groups */ + users: ObjectOperationPermissions; + /** The access rights for states */ + state?: ObjectOperationPermissions; + } + /** Defined the complete set of access rights a user has */ + interface PermissionSet extends ObjectPermissions { + /** The name of the user this ACL is for */ + user: string; + /** The name of the groups this ACL was merged from */ + groups: string[]; + /** The access rights for certain commands */ + other: { + execute: boolean, + http: boolean, + sendto: boolean, + }; + } + + interface Permission { + /** The type of the permission */ + type: string; + /** Which kind of operation is required */ + operation: string; + } + interface ObjectOrStatePermission extends Permission { + type: "object" | "file" | "users" | "state"; + operation: "list" | "read" | "write" | "create" | "delete"; + } + interface OtherPermission extends Permission { + type: "other"; + operation: "execute" | "http" | "sendto"; + } + interface CommandsPermissions { + // TODO: Are all properties required or is a partial object ok? + getObject: ObjectOrStatePermission; + getObjects: ObjectOrStatePermission; + getObjectView: ObjectOrStatePermission; + setObject: ObjectOrStatePermission; + subscribeObjects: ObjectOrStatePermission; + unsubscribeObjects: ObjectOrStatePermission; + getStates: ObjectOrStatePermission; + getState: ObjectOrStatePermission; + setState: ObjectOrStatePermission; + getStateHistory: ObjectOrStatePermission; + subscribe: ObjectOrStatePermission; + unsubscribe: ObjectOrStatePermission; + getVersion: Permission; + httpGet: OtherPermission; + sendTo: OtherPermission; + sendToHost: OtherPermission; + readFile: ObjectOrStatePermission; + readFile64: ObjectOrStatePermission; + writeFile: ObjectOrStatePermission; + writeFile64: ObjectOrStatePermission; + unlink: ObjectOrStatePermission; + rename: ObjectOrStatePermission; + mkdir: ObjectOrStatePermission; + readDir: ObjectOrStatePermission; + chmodFile: ObjectOrStatePermission; + authEnabled: Permission; + disconnect: Permission; + listPermissions: Permission; + getUserPermissions: ObjectOrStatePermission; + } + + type UserGroup = any; // TODO find out how this looks like + // interface UserGroup { } + + /** Contains information about a user */ + interface User { + /** Which groups this user belongs to */ + groups: UserGroup[]; + /** Access rights of this user */ + acl: ObjectPermissions; + } + + /** Parameters for @link{Objects.getObjectView} */ + interface GetObjectViewParams { + /** First id to include in the return list */ + startkey: string; + /** Last id to include in the return list */ + endkey: string; + } + + /** Parameters for @link{Objects.getObjectList} */ + interface GetObjectListParams extends GetObjectViewParams { + /** Whether docs should be included in the return list */ // TODO: What are docs? + include_docs: boolean; + } + + /** Provides low-level access to the ioBroker objects db */ + interface Objects { + /** + * For a given user, returns the groups he belongs to, and his access rights + * @param user Name of the user. Has to start with "system.user." + * @param callback The callback function to be invoked with the return values + */ + getUserGroup(user: string, callback: GetUserGroupCallback): void; + + /** + * Determines the mime type for a given file extension + * @param ext File extension, including the leading dot, e.g. ".zip" + */ + getMimeType(ext: string): { mimeType: string, isBinary: boolean }; + + /** + * Writes a file. + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param data Contents of the file + * @param options (optional) MIME type of the file (string). Or some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + writeFile(id: string, name: string, data: Buffer | string, callback: ErrorCallback): void; + writeFile(id: string, name: string, data: Buffer | string, options: string | {}, callback: ErrorCallback): void; + + /** + * Reads a file. + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + readFile(id: string, name: string, callback: ReadFileCallback): void; + readFile(id: string, name: string, options: any, callback: ReadFileCallback): void; + + /** + * Deletes a file. + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + unlink(id: string, name: string, callback: ErrorCallback): void; + unlink(id: string, name: string, options: any, callback: ErrorCallback): void; + /** + * Deletes a file. + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + delFile(id: string, name: string, callback: ErrorCallback): void; + delFile(id: string, name: string, options: any, callback: ErrorCallback): void; + + /** + * Finds all files and directories starting with + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File or directory name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + readDir(id: string, name: string, callback: ReadDirCallback): void; + readDir(id: string, name: string, options: any, callback: ReadDirCallback): void; + + /** + * Renames a file or directory + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param oldName Old file or directory name + * @param newName Name to rename to + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + rename(id: string, oldName: string, newName: string, callback: ErrorCallback): void; + rename(id: string, oldName: string, newName: string, options: any, callback: ErrorCallback): void; + + /** + * Creates an empty file with the given name + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + touch(id: string, name: string, callback: ErrorCallback): void; + touch(id: string, name: string, options: any, callback: ErrorCallback): void; + + /** + * Deletes all files in the root directory matching + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name Pattern to match against + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + rm(id: string, name: string, callback: RmCallback): void; + rm(id: string, name: string, options: any, callback: RmCallback): void; + + /** + * Creates an empty directory with the given name + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name Directory name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + mkDir(id: string, name: string, callback: ErrorCallback): void; + mkDir(id: string, name: string, options: any, callback: ErrorCallback): void; + + /** + * Takes possession all files in the root directory matching + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name Pattern to match against + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + chownFile(id: string, name: string, callback: ChownFileCallback): void; + chownFile(id: string, name: string, options: any, callback: ChownFileCallback): void; + + /** + * Changes access rights of all files in the root directory matching + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name Pattern to match against + * @param options Mode of the access change as a number or hexadecimal string + * @param callback Is called when the operation has finished (successfully or not) + */ + chmodFile(id: string, name: string, options: { mode: number | string } | Record, callback: ChownFileCallback): void; + + // not documented. enabled = true seems to disable the cache + // enableFileCache(enabled, options, callback) + + /** + * Subscribe to object changes + * @param pattern The pattern to match against + */ + subscribeConfig(pattern: string, callback: EmptyCallback): void; + subscribeConfig(pattern: string, options: any, callback: EmptyCallback): void; + /** + * Subscribe to object changes + * @param pattern The pattern to match against + */ + subscribe(pattern: string, callback: EmptyCallback): void; + subscribe(pattern: string, options: any, callback: EmptyCallback): void; + + /** + * Unsubscribe from object changes + * @param pattern The pattern to match against + */ + unsubscribeConfig(pattern: string, callback: EmptyCallback): void; + unsubscribeConfig(pattern: string, options: any, callback: EmptyCallback): void; + /** + * Unsubscribe from object changes + * @param pattern The pattern to match against + */ + unsubscribe(pattern: string, callback: EmptyCallback): void; + unsubscribe(pattern: string, options: any, callback: EmptyCallback): void; + + /** + * Takes possession of all objects matching + * @param pattern Pattern to match against + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + chownObject(pattern: string, callback: ChownObjectCallback): void; + chownObject(pattern: string, options: any, callback: ChownObjectCallback): void; + + /** + * Changes access rights of all objects matching + * @param pattern Pattern to match against + * @param options Mode of the access change as a number or hexadecimal string + * @param callback Is called when the operation has finished (successfully or not) + */ + chmodObject(pattern: string, callback: ChownObjectCallback): void; + chmodObject(pattern: string, options: any, callback: ChownObjectCallback): void; + + /** + * Retrieves a copy of the object with the given ID + * @param id Id of the object to find + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getObject(id: string, callback: GetObjectCallback): void; + getObject(id: string, options: any, callback: GetObjectCallback): void; + /** + * Retrieves a copy of the object with the given ID + * @param id Id of the object to find + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getConfig(id: string, callback: GetObjectCallback): void; + getConfig(id: string, options: any, callback: GetObjectCallback): void; + + /** + * Returns a list of config keys matching + * @param pattern Pattern to match against + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getConfigKeys(pattern: string, callback: GetConfigKeysCallback, dontModify?: any): void; + getConfigKeys(pattern: string, options: any, callback: GetConfigKeysCallback, dontModify?: any): void; + + /** + * Returns a list of objects with the given ids + * @param keys IDs of the objects to be retrieved + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getObjects(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; + getObjects(keys: string[], options: any, callback: GetObjectsCallback2, dontModify?: any): void; + /** + * Returns a list of objects with the given ids + * @param keys IDs of the objects to be retrieved + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getConfigs(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; + getConfigs(keys: string[], options: any, callback: GetObjectsCallback2, dontModify?: any): void; + + /** + * Creates or overwrites an object in the object db + * @param id ID of the object + * @param obj Object to store + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + setObject(id: string, obj: ioBroker.Object, callback: SetObjectCallback): void; + setObject(id: string, obj: ioBroker.Object, options: any, callback: SetObjectCallback): void; + /** + * Creates or overwrites an object in the object db + * @param id ID of the object + * @param obj Object to store + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + setConfig(id: string, obj: ioBroker.Object, callback: SetObjectCallback): void; + setConfig(id: string, obj: ioBroker.Object, options: any, callback: SetObjectCallback): void; + + /** + * Deletes an object in the object db + * @param id ID of the object + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + delObject(id: string, callback: ErrorCallback): void; + delObject(id: string, options: any, callback: ErrorCallback): void; + /** + * Deletes an object in the object db + * @param id ID of the object + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + delConfig(id: string, callback: ErrorCallback): void; + delConfig(id: string, options: any, callback: ErrorCallback): void; + + /** + * Returns a list of objects with id between params.startkey and params.endkey + * @param params Parameters determining the objects included in the return list. Null to include all objects + * @param options (optional) If the returned list should be sorted. And some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getObjectList(params: GetObjectListParams | null, callback: GetObjectListCallback): void; + getObjectList(params: GetObjectListParams | null, options: { sorted?: boolean } | Record, callback: GetObjectListCallback): void; + + /** + * Query a predefined object view (similar to SQL stored procedures) and return the results + * For a detailed description refer to https://github.com/ioBroker/ioBroker/wiki/Adapter-Development-Documentation#object-fields + * or http://guide.couchdb.org/editions/1/en/views.html + * @param design The namespace of the object view, as defined in io-package.json. Usually the adapter name, e.g. "hm-rpc" + * @param search The name of the object view. + * @param params Parameters to additionally filter out objects from the return list. Null to include all objects + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getObjectView(design: string, search: string, params: GetObjectViewParams | null, callback: GetObjectViewCallback): void; + getObjectView(design: string, search: string, params: GetObjectViewParams | null, options: any, callback: GetObjectViewCallback): void; + + /** + * Extends an object in the object db with new properties + * @param id ID of the object + * @param obj Object to extend the original one with. May be just parts of an object. + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + extendObject(id: string, obj: PartialObject, callback: ExtendObjectCallback): void; + extendObject(id: string, obj: PartialObject, options: any, callback: ExtendObjectCallback): void; + + /** + * Finds an object by ID or name. If multiple objects were found, return the first one + * @param idOrName ID or name of the object + * @param type If != null, only return an object with a common.type equal to this + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + findObject(idOrName: string, type: CommonType | null, callback: FindObjectCallback): void; + findObject(idOrName: string, type: CommonType | null, options: any, callback: FindObjectCallback): void; + + // I'd rather not document a function with the name "destroyDB" + + /** Destructor of the class. Call this before shutting down. */ + destroy(): void; + } // end interface Objects + + type LogLevel = "silly" | "debug" | "info" | "warn" | "error"; + interface Logger { + /** log message with silly level */ + silly(message: string): void; + /** log message with debug level */ + debug(message: string): void; + /** log message with info level (default output level for all adapters) */ + info(message: string): void; + /** log message with warning severity */ + warn(message: string): void; + /** log message with error severity */ + error(message: string): void; + + /** Verbosity of the log output */ + level: LogLevel; + } + + interface Certificates { + /** private key file */ + key: string | Buffer; + /** public certificate */ + cert: string | Buffer; + /** chained CA certificates */ + ca: Array; + } + + /** Callback information for a passed message */ + interface MessageCallbackInfo { + /** The original message payload */ + message: string | object; + /** ID of this callback */ + id: number; + // ??? + ack: boolean; + /** Timestamp of this message */ + time: number; + } + type MessageCallback = (result?: any) => void; + + /** A message being passed between adapter instances */ + interface Message { + /** The command to be executed */ + command: string; + /** The message payload */ + message: string | object; + /** The source of this message */ + from: string; + /** ID of this message */ + _id: number; + /** Callback information. This is set when the source expects a response */ + callback: MessageCallbackInfo; + } + + type Log = any; // TODO: define this https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/states/statesInMemServer.js#L873 + + type EnumList = string | string[]; + + type Enum = any; // TODO: implement this + + interface DirectoryEntry { + file: string; + stats: fs.Stats; + isDir: boolean; + acl: any; // access control list object + modifiedAt: number; + createdAt: number; + } + + interface GetHistoryOptions { + instance?: string; + start?: number; + end?: number; + step?: number; + count?: number; + from?: boolean; + ack?: boolean; + q?: boolean; + addID?: boolean; + limit?: number; + ignoreNull: boolean; + sessionId?: any; + aggregate?: "minmax" | "min" | "max" | "average" | "total" | "count" | "none"; + } + + interface AdapterOptions { + /** The name of the adapter */ + name: string; + + /** path to adapter */ + dirname?: string; + + /** if the global system config should be included in the created object. Default: false */ + systemConfig?: boolean; + + /** provide alternative global configuration for the adapter. Default: null */ + config?: any; + + /** instance of the created adapter. Default: null */ + instance?: number; + + /** If the adapter needs access to the formatDate function to format dates according to the global settings. Default: false */ + useFormatDate?: boolean; + + /** If the adapter collects logs from all adapters (experts only). Default: false */ + logTransporter?: boolean; + + /** Handler for changes of subscribed objects */ + objectChange?: ObjectChangeHandler; + /** Handler for received adapter messages. Can only be used if messagebox in io-package.json is set to true. */ + message?: MessageHandler; + /** Handler for changes of subscribed states */ + stateChange?: StateChangeHandler; + /** Will be called when the adapter is intialized */ + ready?: () => void; + /** Will be called on adapter termination */ + unload?: (callback: EmptyCallback) => void; + + /** if true, stateChange will be called with an id that has no namespace, e.g. "state" instead of "adapter.0.state". Default: false */ + noNamespace?: boolean; + } // end interface AdapterOptions + + // tslint:disable-next-line:no-empty-interface + interface AdapterConfig { + // This is a stub to be augmented in every adapter + } + + interface Adapter { + /** The name of the adapter */ + name: string; + /** The name of the host where the adapter is running */ + host: string; + /** instance number of this adapter instance */ + instance: number; + /** Namespace of adapter objects: "." */ + readonly namespace: string; + /** native part of the adapter settings */ + config: AdapterConfig; + /** common part of the adapter settings */ + common: any; + /** system part of the adapter settings */ + systemConfig?: any; + /** path to the adapter folder */ + adapterDir: string; + /** content of io-package.json */ + ioPack: any; + /** content of package.json */ + pack: any; + /** access to the logging functions */ + log: Logger; + /** adapter version */ + version: any; + states: States; + objects: Objects; + /** if the adapter is connected to the host */ + connected: boolean; + + /* =============================== + Functions defined in adapter.js + =============================== */ + + /** + * Helper function that looks for first free TCP port starting with the given one. + * @param port - The port to start with + * @param callback - gets called when a free port is found + */ + getPort(port: number, callback: (port: number) => void): void; + + /** Stops the adapter. Note: Is not always defined. */ + stop?: () => void; + + // ============================== + // GENERAL + + /** Validates username and password */ + checkPassword(user: string, password: string, callback: (result: boolean) => void): void; + checkPassword(user: string, password: string, options: any, callback: (result: boolean) => void): void; + /** Sets a new password for the given user */ + setPassword(user: string, password: string, options?: any, callback?: (err?: any) => void): void; + /** Checks if a user exists and is in the given group. */ + checkGroup(user: string, group: string, callback: (result: boolean) => void): void; + checkGroup(user: string, group: string, options: any, callback: (result: boolean) => void): void; + /** Determines the users permissions */ + calculatePermissions(user: string, commandsPermissions: CommandsPermissions, callback: (result: PermissionSet) => void): void; + calculatePermissions(user: string, commandsPermissions: CommandsPermissions, options: any, callback: (result: PermissionSet) => void): void; + /** Returns SSL certificates by name (private key, public cert and chained certificate) for creation of HTTPS servers */ + getCertificates(publicName: string, privateName: string, chainedName: string, callback: (err: string | null, certs?: Certificates, useLetsEncryptCert?: boolean) => void): void; + + /** + * Sends a message to a specific instance or all instances of some specific adapter. + * @param instanceName The instance to send this message to. + * If the ID of an instance is given (e.g. "admin.0"), only this instance will receive the message. + * If the name of an adapter is given (e.g. "admin"), all instances of this adapter will receive it. + * @param command (optional) Command name of the target instance. Default: "send" + * @param message The message (e.g. params) to send. + */ + sendTo(instanceName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + sendTo(instanceName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + + /** + * Sends a message to a specific host or all hosts. + */ + sendToHost(hostName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + sendToHost(hostName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + + /** Convert ID to {device: D, channel: C, state: S} */ + idToDCS(id: string): { + device: string; + channel: string; + state: string; + }; + + // ============================== + // own objects + + /** Reads an object from the object db */ + getObject(id: string, callback: GetObjectCallback): void; + getObject(id: string, options: any, callback: GetObjectCallback): void; + /** Creates or overwrites an object in the object db */ + setObject(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; + /** Creates an object in the object db. Existing objects are not overwritten. */ + setObjectNotExists(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; + /** Get all states, channels and devices of this adapter */ + getAdapterObjects(callback: (objects: Record) => void): void; + /** Extend an object and create it if it might not exist */ + extendObject(id: string, objPart: PartialObject, options?: any, callback?: SetObjectCallback): void; + /** + * Deletes an object from the object db + * @param id - The id of the object without namespace + */ + delObject(id: string, options?: any, callback?: ErrorCallback): void; + + // ============================== + // foreign objects + + // tslint:disable:unified-signatures + /** Reads an object (which might not belong to this adapter) from the object db */ + getForeignObject(id: string, callback: GetObjectCallback): void; + getForeignObject(id: string, options: any, callback: GetObjectCallback): void; + /** Get foreign objects by pattern, by specific type and resolve their enums. */ + getForeignObjects(pattern: string, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, options: any, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, options: any, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, options: any, callback: GetObjectsCallback): void; + /** Creates or overwrites an object (which might not belong to this adapter) in the object db */ + setForeignObject(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; + /** Creates an object (which might not belong to this adapter) in the object db. Existing objects are not overwritten. */ + setForeignObjectNotExists(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; + /** Extend an object (which might not belong to this adapter) and create it if it might not exist */ + extendForeignObject(id: string, objPart: PartialObject, options?: any, callback?: SetObjectCallback): void; + // tslint:enable:unified-signatures + /** + * Finds an object by its ID or name + * @param type - common.type of the state + */ + findForeignObject(idOrName: string, type: string, callback: FindObjectCallback): void; + findForeignObject(idOrName: string, type: string, options: any, callback: FindObjectCallback): void; + /** + * Deletes an object (which might not belong to this adapter) from the object db + * @param id - The id of the object including namespace + */ + delForeignObject(id: string, options?: any, callback?: ErrorCallback): void; + + // ============================== + // states + /** Writes a value into the states DB. */ + setState(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateCallback): void; + /** Writes a value into the states DB only if it has changed. */ + setStateChanged(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateChangedCallback): void; + /** Writes a value (which might not belong to this adapter) into the states DB. */ + setForeignState(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateCallback): void; + /** Writes a value (which might not belong to this adapter) into the states DB only if it has changed. */ + setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateChangedCallback): void; + + /** Read a value from the states DB. */ + getState(id: string, callback: GetStateCallback): void; + getState(id: string, options: any, callback: GetStateCallback): void; + /** Read a value (which might not belong to this adapter) from the states DB. */ + getForeignState(id: string, callback: GetStateCallback): void; + getForeignState(id: string, options: any, callback: GetStateCallback): void; + /** Read all states of this adapter which match the given pattern */ + getStates(pattern: string, callback: GetStatesCallback): void; + getStates(pattern: string, options: any, callback: GetStatesCallback): void; + /** Read all states (which might not belong to this adapter) which match the given pattern */ + getForeignStates(pattern: string, callback: GetStatesCallback): void; + getForeignStates(pattern: string, options: any, callback: GetStatesCallback): void; + + /** Deletes a state from the states DB, but not the associated object. Consider using @link{deleteState} instead */ + delState(id: string, options?: any, callback?: ErrorCallback): void; + /** Deletes a state from the states DB, but not the associated object */ + delForeignState(id: string, options?: any, callback?: ErrorCallback): void; + + getHistory(id: string, options: GetHistoryOptions, callback: GetHistoryCallback): void; + + // MISSING: + // pushFifo and similar https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4105 + // logRedirect https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4294 + // requireLog https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4336 + // processLog https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4360 + + /** + * Writes a binary state into Redis + * @param id The id of the state + * @param binary The data to be written + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + setBinaryState(id: string, binary: Buffer, callback: SetStateCallback): void; + setBinaryState(id: string, binary: Buffer, options: any, callback: SetStateCallback): void; + /** + * Reads a binary state from Redis + * @param id The id of the state + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getBinaryState(id: string, callback: GetBinaryStateCallback): void; + getBinaryState(id: string, options: any, callback: GetBinaryStateCallback): void; + + // ============================== + // enums + + /** Returns the enum tree, filtered by the optional enum name */ + getEnum(callback: GetEnumCallback): void; + getEnum(name: string, callback: GetEnumCallback): void; + getEnum(name: string, options: any, callback: GetEnumCallback): void; + getEnums(callback: GetEnumsCallback): void; + getEnums(enumList: EnumList, callback: GetEnumsCallback): void; + getEnums(enumList: EnumList, options: any, callback: GetEnumsCallback): void; + + addChannelToEnum(enumName: string, addTo: string, parentDevice: string, channelName: string, options?: any, callback?: ErrorCallback): void; + deleteChannelFromEnum(enumName: string, parentDevice: string, channelName: string, options?: any, callback?: ErrorCallback): void; + + addStateToEnum(enumName: string, addTo: string, parentDevice: string, parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; + deleteStateFromEnum(enumName: string, parentDevice: string, parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; + + // ============================== + // subscriptions + + /** Subscribe to changes of objects in this instance */ + subscribeObjects(pattern: string, options?: any): void; + /** Subscribe to changes of objects (which might not belong to this adapter) */ + subscribeForeignObjects(pattern: string, options?: any): void; + /** Unsubscribe from changes of objects in this instance */ + unsubscribeObjects(pattern: string, options?: any): void; + /** Unsubscribe from changes of objects (which might not belong to this adapter) */ + unsubscribeForeignObjects(pattern: string, options?: any): void; + + /** Subscribe to changes of states in this instance */ + subscribeStates(pattern: string, options?: any, callback?: ErrorCallback): void; + /** Subscribe to changes of states (which might not belong to this adapter) */ + subscribeForeignStates(pattern: string, options?: any, callback?: ErrorCallback): void; + /** + * Subscribe from changes of states in this instance + * @param pattern - Must match the pattern used to subscribe + */ + unsubscribeStates(pattern: string, options?: any, callback?: ErrorCallback): void; + /** + * Subscribe from changes of states (which might not belong to this adapter) + * @param pattern - Must match the pattern used to subscribe + */ + unsubscribeForeignStates(pattern: string, options?: any, callback?: ErrorCallback): void; + + // ============================== + // devices and channels + + /** creates an object with type device */ + createDevice(deviceName: string, common?: any, native?: any, options?: any, callback?: SetObjectCallback): void; + /** deletes a device, its channels and states */ + deleteDevice(deviceName: string, options?: any, callback?: ErrorCallback): void; + /** gets the devices of this instance */ + + /** creates an object with type channel */ + createChannel(parentDevice: string, channelName: string, roleOrCommon?: string | object, native?: any, options?: any, callback?: SetObjectCallback): void; + /** deletes a channel and its states */ + deleteChannel(channelName: string, options?: any, callback?: ErrorCallback): void; + deleteChannel(parentDevice: string, channelName: string, options?: any, callback?: ErrorCallback): void; + + /** creates a state and the corresponding object */ + createState(parentDevice: string, parentChannel: string, stateName: string, roleOrCommon?: string | object, native?: any, options?: any, callback?: SetObjectCallback): void; + /** deletes a state */ + deleteState(stateName: string, options?: any, callback?: ErrorCallback): void; + deleteState(parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; + deleteState(parentDevice: string, parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; + + /** + * Returns a list of all devices in this adapter instance + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getDevices(callback: GetObjectsCallback3): void; + getDevices(options: any, callback: GetObjectsCallback3): void; + + /** + * Returns a list of all channels in this adapter instance + * @param parentDevice (optional) Name of the parent device to filter the channels by + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getChannels(callback: GetObjectsCallback3): void; + getChannels(parentDevice: string | null, callback: GetObjectsCallback3): void; + getChannels(parentDevice: string | null, options: any, callback: GetObjectsCallback3): void; + /** + * Returns a list of all channels in this adapter instance + * @param parentDevice (optional) Name of the parent device to filter the channels by + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getChannelsOf(callback: GetObjectsCallback3): void; + getChannelsOf(parentDevice: string | null, callback: GetObjectsCallback3): void; + getChannelsOf(parentDevice: string | null, options: any, callback: GetObjectsCallback3): void; + + /** + * Returns a list of all states in this adapter instance + * @param parentDevice (optional) Name of the parent device to filter the channels by + * @param parentChannel (optional) Name of the parent channel to filter the channels by + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getStatesOf(callback: GetObjectsCallback3): void; + getStatesOf(parentDevice: string | null, callback: GetObjectsCallback3): void; + getStatesOf(parentDevice: string | null, parentChannel: string | null, callback: GetObjectsCallback3): void; + getStatesOf(parentDevice: string | null, parentChannel: string | null, options: any, callback: GetObjectsCallback3): void; + + // ============================== + // filesystem + + /** + * reads the content of directory from DB for given adapter and path + * @param adapter - adapter name. If adapter name is null, default will be the name of the current adapter. + * @param path - path to direcory without adapter name. E.g. If you want to read "/vis.0/main/views.json", here must be "/main/views.json" and _adapter must be equal to "vis.0". + */ + readDir(adapterName: string, path: string, callback: ReadDirCallback): void; + readDir(adapterName: string, path: string, options: any, callback: ReadDirCallback): void; + mkDir(adapterName: string, path: string, callback: ErrorCallback): void; + mkDir(adapterName: string, path: string, options: any, callback: ErrorCallback): void; + + readFile(adapterName: string, path: string, callback: ReadFileCallback): void; + readFile(adapterName: string, path: string, options: any, callback: ReadFileCallback): void; + writeFile(adapterName: string, path: string, data: Buffer | string, callback: ErrorCallback): void; + // options see https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/objects/objectsInMemServer.js#L599 + writeFile(adapterName: string, path: string, data: Buffer | string, options: any, callback: ErrorCallback): void; + + delFile(adapterName: string, path: string, callback: ErrorCallback): void; + delFile(adapterName: string, path: string, options: any, callback: ErrorCallback): void; + unlink(adapterName: string, path: string, callback: ErrorCallback): void; + unlink(adapterName: string, path: string, options: any, callback: ErrorCallback): void; + + rename(adapterName: string, oldName: string, newName: string, callback: ErrorCallback): void; + rename(adapterName: string, oldName: string, newName: string, options: any, callback: ErrorCallback): void; + + /** + * Changes access rights of all files in the adapter directory + * @param adapter Name of the adapter instance, e.g. "admin.0". Defaults to the namespace of this adapter. + * @param path Pattern to match the file path against + * @param options Mode of the access change as a number or hexadecimal string + * @param callback Is called when the operation has finished (successfully or not) + */ + chmodFile(adapter: string | null, path: string, options: { mode: number | string } | Record, callback: ChownFileCallback): void; + + // ============================== + // formatting + + formatValue(value: number | string, format: any): string; + formatValue(value: number | string, decimals: number, format: any): string; + formatDate(dateObj: string | Date | number, format: string): string; + formatDate(dateObj: string | Date | number, isDuration: boolean | string, format: string): string; + } // end interface Adapter + + type ObjectChangeHandler = (id: string, obj: ioBroker.Object) => void; + type StateChangeHandler = (id: string, obj: State) => void; + type MessageHandler = (obj: Message) => void; + + type EmptyCallback = () => void; + type ErrorCallback = (err?: string) => void; + // TODO: Redefine callbacks as subclass of GenericCallback + type GenericCallback = (err: string | null, result?: T) => void; + + type SetObjectCallback = (err: string | null, obj: { id: string }) => void; + type GetObjectCallback = (err: string | null, obj: ioBroker.Object) => void; + type GetEnumCallback = (err: string | null, enums: Record, requestedEnum: string) => void; + type GetEnumsCallback = ( + err: string | null, + result: { + [groupName: string]: Record, + }, + ) => void; + type GetObjectsCallback = (err: string | null, objects: Record) => void; + + type FindObjectCallback = ( + /** If an error happened, this contains the message */ + err: string | null, + /** If an object was found, this contains the ID */ + id?: string, + /** If an object was found, this contains the common.name */ + name?: string, + ) => void; + + interface GetObjectsItem { + /** The ID of this object */ + id: string; + /** A copy of the object from the DB */ + value: T; + } + // This is a version used by GetDevices/GetChannelsOf/GetStatesOf + type GetObjectsCallback3 = (err: string | null, result?: Array>) => void; + + type GetStateCallback = (err: string | null, state: State) => void; + type GetStatesCallback = (err: string | null, states: Record) => void; + /** Version of the callback used by States.getStates */ + type GetStatesCallback2 = (err: string | null, states: State[]) => void; + type GetBinaryStateCallback = (err: string | null, state?: Buffer) => void; + type SetStateCallback = (err: string | null, id?: string) => void; + type SetStateChangedCallback = (err: string | null, id: string, notChanged: boolean) => void; + type DeleteStateCallback = (err: string | null, id?: string) => void; + type GetHistoryCallback = (err: string | null, result: Array<(State & { id?: string })>, step: number, sessionId?: string) => void; + + /** Contains the return values of readDir */ + interface ReadDirResult { + /** Name of the file or directory */ + file: string; + /** File system stats */ + stats: fs.Stats; + /** Whether this is a directory or a file */ + isDir: boolean; + /** Access rights */ + acl: EvaluatedFileACL; + /** Date of last modification */ + modifiedAt: number; + /** Date of creation */ + createdAt: number; + } + type ReadDirCallback = (err: string | null, entries?: ReadDirResult[]) => void; + type ReadFileCallback = (err: string | null, file?: Buffer | string, mimeType?: string) => void; + + /** Contains the return values of chownFile */ + interface ChownFileResult { + /** The parent directory of the processed file or directory */ + path: string; + /** Name of the file or directory */ + file: string; + /** File system stats */ + stats: fs.Stats; + /** Whether this is a directory or a file */ + isDir: boolean; + /** Access rights */ + acl: FileACL; + /** Date of last modification */ + modifiedAt: number; + /** Date of creation */ + createdAt: number; + } + type ChownFileCallback = (err: string | null, entries?: ChownFileResult[], id?: string) => void; + + /** Contains the return values of rm */ + interface RmResult { + /** The parent directory of the deleted file or directory */ + path: string; + /** The name of the deleted file or directory */ + file: string; + /** Whether the deleted object was a directory or a file */ + isDir: boolean; + } + type RmCallback = (err: string | null, entries?: RmResult[]) => void; + + type GetUserGroupCallback = (objectsInstance: Objects, user: User, groups: UserGroup[], acl: ObjectPermissions) => void; + + type ChownObjectCallback = (err: string | null, list?: ioBroker.Object[]) => void; + + type GetConfigKeysCallback = (err: string | null, list?: string[]) => void; + // this is a version of the callback used by Objects.getObjects + type GetObjectsCallback2 = (err: string | null, objects?: Array<(ioBroker.Object | { err: string })>) => void; + + interface GetObjectViewItem { + /** The ID of this object */ + id: string; + /** A copy of the object from the DB or some aggregation result */ + value: ioBroker.Object | {}; // TODO: find out how the non-Object return result looks like + } + type GetObjectViewCallback = (err: string | null, result?: { rows: GetObjectViewItem[] }) => void; + + interface GetObjectListItem extends GetObjectViewItem { + /** A copy of the object */ + value: ioBroker.Object; + /** The same as @link{value} */ + doc: ioBroker.Object; + } + type GetObjectListCallback = (err: string | null, result?: { rows: GetObjectListItem[] }) => void; + + type ExtendObjectCallback = (err: string | null, result?: { id: string, value: ioBroker.Object }, id?: string) => void; + + type GetSessionCallback = (session: Session) => void; + } // end namespace ioBroker } // end declare global diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index e69de29bb2..c8b9f0d43e 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -0,0 +1,5 @@ +// Help! what to test here? + +declare const adapter: ioBroker.Adapter; + +adapter.setState("not.a.state", true); diff --git a/types/iobroker/tsconfig.json b/types/iobroker/tsconfig.json index 3388e650ec..5d7e32bdb6 100644 --- a/types/iobroker/tsconfig.json +++ b/types/iobroker/tsconfig.json @@ -7,6 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/iobroker/tslint.json b/types/iobroker/tslint.json index 3db14f85ea..9a4b76fd9c 100644 --- a/types/iobroker/tslint.json +++ b/types/iobroker/tslint.json @@ -1 +1,8 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dtslint.json", + "rules": { + // This package has its own type `Object` which is not equal to the global `Object` type + // To avoid any confusion, it is referenced as `ioBroker.Object` instead of just `Object` + "no-unnecessary-qualifier": false + } +} From 19d8ec03ecc29e6a6159156cb7868876b42593c2 Mon Sep 17 00:00:00 2001 From: "dominic.griesel" Date: Thu, 15 Nov 2018 12:05:20 +0100 Subject: [PATCH 272/836] Try fix tests --- types/iobroker/index.d.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index baa8424d9b..8e6976a991 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -1,12 +1,13 @@ -// Ambient type definitions for adapters for ioBroker -// Note: This is not the definition for the package `iobroker`, -// which is just an installer, not a library. -// The definitions are based on ioBroker.js-controller v1.4.2 +// Type definitions for ioBroker adapters // Project: https://github.com/ioBroker/ioBroker // Definitions by: AlCalzone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 +// Note: This is not the definition for the package `iobroker`, +// which is just an installer, not a library. +// The definitions are based on ioBroker.js-controller v1.4.2 + /// import * as fs from "fs"; From 47bd9f8a70cfa53da16b6dbdb236ac508c0483e1 Mon Sep 17 00:00:00 2001 From: "dominic.griesel" Date: Thu, 15 Nov 2018 12:11:45 +0100 Subject: [PATCH 273/836] Try to fix tests again --- types/iobroker/index.d.ts | 4 ++-- types/iobroker/tslint.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index 8e6976a991..313d7e9718 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ioBroker adapters +// Type definitions for ioBroker 1.4 // Project: https://github.com/ioBroker/ioBroker // Definitions by: AlCalzone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,7 +6,7 @@ // Note: This is not the definition for the package `iobroker`, // which is just an installer, not a library. -// The definitions are based on ioBroker.js-controller v1.4.2 +// The definitions may change with updates to ioBroker.js-controller /// import * as fs from "fs"; diff --git a/types/iobroker/tslint.json b/types/iobroker/tslint.json index 9a4b76fd9c..bdafdd99b4 100644 --- a/types/iobroker/tslint.json +++ b/types/iobroker/tslint.json @@ -1,5 +1,5 @@ { - "extends": "dtslint/dtslint.json", + "extends": "dtslint/dt.json", "rules": { // This package has its own type `Object` which is not equal to the global `Object` type // To avoid any confusion, it is referenced as `ioBroker.Object` instead of just `Object` From adace47dc209c52a74da1641206e7fbcea7023f7 Mon Sep 17 00:00:00 2001 From: Julian Strecker Date: Sun, 25 Nov 2018 13:38:13 +0100 Subject: [PATCH 274/836] [three,physijs] fix tests to fullfill travis needs. --- types/physijs/test/collisions.ts | 4 ++-- types/physijs/test/vehicle.ts | 4 ++-- types/three/test/css3d/css3d_periodictable.ts | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/types/physijs/test/collisions.ts b/types/physijs/test/collisions.ts index 20493189e0..41f09e351d 100644 --- a/types/physijs/test/collisions.ts +++ b/types/physijs/test/collisions.ts @@ -90,7 +90,7 @@ spawnBox = (function() { var box_geometry = new THREE.BoxGeometry( 4, 4, 4 ), handleCollision = function( collided_with ) { - var target = this; + var target = this as any; target.collisions = 0; switch (++target.collisions) { @@ -168,4 +168,4 @@ render = function() { render_stats.update(); }; -window.onload = initScene; \ No newline at end of file +window.onload = initScene; diff --git a/types/physijs/test/vehicle.ts b/types/physijs/test/vehicle.ts index b8643de3b0..37f32279a8 100644 --- a/types/physijs/test/vehicle.ts +++ b/types/physijs/test/vehicle.ts @@ -186,11 +186,11 @@ initScene = function() { ); } - input = { + input = { power: null, direction: null, steering: 0 - }; + } as any; document.addEventListener('keydown', function( ev ) { switch ( ev.keyCode ) { case 37: // left diff --git a/types/three/test/css3d/css3d_periodictable.ts b/types/three/test/css3d/css3d_periodictable.ts index 5c8cb68614..40a29a1ea5 100644 --- a/types/three/test/css3d/css3d_periodictable.ts +++ b/types/three/test/css3d/css3d_periodictable.ts @@ -181,8 +181,8 @@ // var object = new THREE.Object3D(); - object.position.x = (table[i + 3] * 140) - 1330; - object.position.y = - (table[i + 4] * 180) + 990; + object.position.x = ((table[i + 3] as number) * 140) - 1330; + object.position.y = - ((table[i + 4] as number) * 180) + 990; targets.table.push(object); @@ -354,4 +354,4 @@ renderer.render(scene, camera); } -} \ No newline at end of file +} From 3a4659d36dc86a41af8dfeb17a6d87ad890404b8 Mon Sep 17 00:00:00 2001 From: Kamontat Chantrachirathumrong Date: Sun, 25 Nov 2018 14:31:37 +0100 Subject: [PATCH 275/836] Update to version 3.0.2 --- types/tabtab/index.d.ts | 152 +++++++++++++++++++++++++++------------- 1 file changed, 103 insertions(+), 49 deletions(-) diff --git a/types/tabtab/index.d.ts b/types/tabtab/index.d.ts index eba5a58c3a..05291613b2 100644 --- a/types/tabtab/index.d.ts +++ b/types/tabtab/index.d.ts @@ -1,89 +1,143 @@ -// Type definitions for tabtab 0.0.4 +// Type definitions for tabtab 3.0.2 // Project: https://github.com/mklabs/node-tabtab // Definitions by: Vojtěch Habarta +// Kamontat Chantrachirathumrong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - +// TypeScript Version: 2.0 /** - * Main completion method, has support for installation and actual completion. - * @param name Name of the command to complete. - * @param cb Get called when a tab-completion command happens. + * Install option + * + * @param name is a name of the cli command + * @param completer Somethings, you want to complete another program that's where the `completer` option might come handy. */ -export declare function complete(name: string, cb: CallBack): void; +export type InstallOption = { + name: string; + completer: string; +}; /** - * Main completion method, has support for installation and actual completion. - * @param name Name of the command to complete. - * @param completer Name of the command to call on completion. - * @param cb Get called when a tab-completion command happens. + * Uninstall option + * + * @param name is a name of the cli command */ -export declare function complete(name: string, completer: string, cb: CallBack): void; +export type UninstallOption = { + name: string; +}; /** - * Simple helper function to know if the script is run in the context of a completion command. + * This type represent object (Json object) */ -export declare function isComplete(): boolean; +export type Json = { + [key: string]: string; +}; /** - * Helper to return the list of short and long options, parsed from the usual --help output of a command (cake/rake -H, vagrant, commander -h, optimist.help(), ...). + * Tabtab environment data that return from {@link parseEnv} method + * + * @param complete A Boolean indicating whether we act in "plumbing mode" or not + * @param words The Number of words in the completed line + * @param point A Number indicating cursor position + * @param line The String input line + * @param partial The String part of line preceding cursor position + * @param last The last String word of the line + * @param lastPartial The last word String of partial + * @param prev The String word preceding last */ -export declare function parseOut(str: string): { shorts: string[]; longs: string[] }; - -/** - * Same purpose as parseOut, but for parsing tasks from an help command (cake/rake -T, vagrant, etc.). - */ -export declare function parseTasks(str: string, prefix: string, reg?: RegExp | string): string[]; - -/** - * Helper to return completion output and log to standard output. - * @param values Array of values to complete against. - * @param data The data object returned by the complete callback, used mainly to filter results accordingly upon the text that is supplied by the user. - * @param prefix A prefix to add to the completion results, useful for options to add dashes (eg. - or --). - */ -export declare function log(values: string[], data: Data, prefix?: string): void; - -interface CallBack { - (error?: Error, data?: Data, text?: string): any; -} - -/** - * Holds interesting values to drive the output of the completion. - */ -interface Data { - +export type TabtabEnv = { /** - * full command being completed + * A Boolean indicating whether we act in "plumbing mode" or not */ - line: string; + complete: boolean; /** - * number of words + * The Number of words in the completed line */ words: number; /** - * cursor position + * A Number indicating cursor position */ point: number; /** - * tabing in the middle of a word: foo bar baz bar foobarrrrrrr + * The String input line + */ + line: string; + + /** + * The String part of line preceding cursor position */ partial: string; /** - * last word of the line + * The last String word of the line */ last: string; /** - * last partial of the line + * The last word String of partial */ lastPartial: string; - /** - * the previous word + * The String word preceding last */ prev: string; -} +}; + +/** + * this is a item to show when completion enable, + * + * @param name usually is a subcommand name or option name + * @param description this is a optional description of the completion + */ +export type CompleteItem = { + name: string; + description?: string; +}; + +export type CompleteItemOrString = string | CompleteItem; + +/** + * Install and enable completion on user system. + * + * @param option install option + * + */ +export function install(option: InstallOption): Promise; + +/** + * Uninstall and remove all completion on user system + * + * @param option uninstall option + */ +export function uninstall(option: UninstallOption): Promise; + +/** + * Public: Main utility to extract information from command line arguments and + * Environment variables, namely COMP args in "plumbing" mode. + * + * @param env environment (usually will be process.env) + * @returns env is a object of completion environment + * + * @example + * const env = tabtab.parseEnv(process.env); + */ +export function parseEnv(env: Json): TabtabEnv; + +/** + * Helper to normalize String and Objects when logging out. + */ +export function completionItem(item: CompleteItemOrString): CompleteItem; + +/** + * Main logging utility to pass completion items. + * This is simply an helper to log to stdout with each item separated by a new + * line. + * + * Bash needs in addition to filter out the args for the completion to work + * (zsh, fish don't need this). + * + * @param args Strings or Objects with name and description property. + */ +export function log(args: string[] | CompleteItem[] | CompleteItemOrString[]): void; From 8b982e49c565d136473bd3f794837e2374b2136a Mon Sep 17 00:00:00 2001 From: Kamontat Chantrachirathumrong Date: Sun, 25 Nov 2018 14:33:34 +0100 Subject: [PATCH 276/836] Update test define file --- types/tabtab/tabtab-tests.ts | 99 +++++++++++++++++++++++++++--------- 1 file changed, 76 insertions(+), 23 deletions(-) diff --git a/types/tabtab/tabtab-tests.ts b/types/tabtab/tabtab-tests.ts index e0187662ff..7f8e5b4b9c 100644 --- a/types/tabtab/tabtab-tests.ts +++ b/types/tabtab/tabtab-tests.ts @@ -1,30 +1,83 @@ - /// -import tabtab = require('tabtab'); -import child_process = require('child_process'); -import string_decoder = require('string_decoder'); +import { install, log, TabtabEnv, uninstall, parseEnv } from "tabtab"; -if (process.argv.slice(2)[0] === 'completion') { - tabtab.complete('pkgname', function(err, data) { - if (err || !data) return; - if (/^--\w?/.test(data.last)) return tabtab.log(['help', 'version'], data, '--'); - if (/^-\w?/.test(data.last)) return tabtab.log(['n', 'o', 'd', 'e'], data, '-'); - tabtab.log(['list', 'of', 'commands'], data); +const opts = require("minimist")(process.argv.slice(2), { + string: ["foo", "bar"], + boolean: ["help", "version", "loglevel"] +}); - child_process.exec('rake -H', {encoding: null}, function(err, stdout, stderr) { - if (err) return; - var decoder = new string_decoder.StringDecoder('utf8'); - var parsed = tabtab.parseOut(decoder.write(stdout)); - if (/^--\w?/.test(data.last)) return tabtab.log(parsed.longs, data, '--'); - if (/^-\w?/.test(data.last)) return tabtab.log(parsed.shorts, data, '-'); +const args = opts._; + +const completion = (env: TabtabEnv) => { + if (!env.complete) return; + + // Write your completions there + + if (env.prev === "foo") { + return log(["is", "this", "the", "real", "life"]); + } + + if (env.prev === "bar") { + return log(["is", "this", "just", "fantasy"]); + } + + if (env.prev === "--loglevel") { + return log(["error", "warn", "info", "notice", "verbose"]); + } + + return log([ + "--help", + "--version", + "--loglevel", + "foo", + "bar", + "install-completion", + "completion", + "someCommand:someCommand is some kind of command with a description", + { + name: "someOtherCommand:hey", + description: 'You must add a description for items with ":" in them' + }, + "anotherOne" + ]); +}; + +const run = (): Promise => { + const cmd = args[0]; + + // Write your CLI there + + // Here we install for the program `tabtab-test` (this file), with + // completer being the same program. Sometimes, you want to complete + // another program that's where the `completer` option might come handy. + if (cmd === "install-completion") { + return install({ + name: "tabtab-test", + completer: "tabtab-test" }); + } - child_process.exec('cake', {encoding: null}, function(err, stdout, stderr) { - if (err) return; - var decoder = new string_decoder.StringDecoder('utf8'); - var tasks = tabtab.parseTasks(decoder.write(stdout), 'cake'); - tabtab.log(tasks, data); + if (cmd === "uninstall-completion") { + // Here we uninstall for the program `tabtab-test` (this file). + return uninstall({ + name: "tabtab-test" }); - }); -} + } + + // The completion command is added automatically by tabtab when the program + // is completed. + if (cmd === "completion") { + return new Promise(res => { + const env = parseEnv(process.env); + completion(env); + res(); + }); + } + + return new Promise((_, rej) => rej()); +}; + +run().catch(e => { + console.error(e); +}); From 28cec6d7e832384d8e93596e6b723ea179d8d84f Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 25 Nov 2018 15:02:24 +0100 Subject: [PATCH 277/836] Add types for iri --- types/iri/index.d.ts | 89 +++++++++++++++++++++++++++++++++++++++++ types/iri/iri-tests.ts | 43 ++++++++++++++++++++ types/iri/tsconfig.json | 23 +++++++++++ types/iri/tslint.json | 1 + 4 files changed, 156 insertions(+) create mode 100644 types/iri/index.d.ts create mode 100644 types/iri/iri-tests.ts create mode 100644 types/iri/tsconfig.json create mode 100644 types/iri/tslint.json diff --git a/types/iri/index.d.ts b/types/iri/index.d.ts new file mode 100644 index 0000000000..93183bcfad --- /dev/null +++ b/types/iri/index.d.ts @@ -0,0 +1,89 @@ +// Type definitions for iri 1.3 +// Project: https://github.com/awwright/node-iri +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export class IRI { + /** + * The constructor takes a single argument, a URI or IRI string: + */ + constructor(iri: string); + /** + * Returns UTF-16 IRI + */ + toString(): string; + /** + * Returns the IRI without the fragment component. Useful for dereferencing URLs on a network. + */ + defrag(): IRI; + /** + * IRIs with a fragment are not absolute. + */ + isAbsolute(): boolean; + /** + * Resolves the IRI against itself, having the effect of stripping the fragment and checking that the supplied IRI is valid (absolute). + */ + toAbsolute(): IRI; + /** + * Resolves the IRI against itself, having the effect of stripping the fragment and checking that the supplied IRI is valid (absolute). + */ + authority(): string | null; + /** + * Returns the fragment component of the IRI. + */ + fragment(): string | null; + /** + * Returns the hier-part of the IRI, the hierarchial component: Everything between the scheme and query, including leading `//` for the host, if it exists. + */ + hierpart(): string; + /** + * Returns the host component of the URI, either a domain name or string-formatted IP address. Excludes port number and username/password. + */ + host(): string; + /** + * Returns the path component of the hier-part. Does not include the authority/host, query, or fragment. + */ + path(): string; + /** + * Returns the port component of the authority as a string, or `null` if there is no port. + */ + port(): string | null; + /** + * Returns the query component of the IRI including leading "?", or `null` if there is no query component. + */ + query(): string | null; + /** + * Resolve the provided URI/IRI reference against this IRI. + */ + resolveReference(ref: string | IRI): IRI; + /** + * Returns the scheme of the IRI, e.g. "https", "file", or "urn". + */ + scheme(): string | null; + /** + * Returns the username/password component of the IRI. + */ + userinfo(): string | null; + /** + * Returns a URI formatted string with only 7-bit characters. + */ + toURIString(): string; + /** + * Decodes URI-encoded UTF-8 characters and returns a unicode string (Strings in ECMAScript/JavaScript are UTF-16). + */ + toIRIString(): string; + /** + * Returns a new IRI object with URI-encoded UTF-8 characters decoded. + */ + toIRI(): IRI; +} + +/** + * Returns an iri.IRI object with UTF-8 escaped characterd decoded. + */ +export function fromURI(uri: string): IRI; + +/** + * Returns an IRI string decoded from the given URI. + */ +export function toIRIString(uri: string): string; diff --git a/types/iri/iri-tests.ts b/types/iri/iri-tests.ts new file mode 100644 index 0000000000..97a460e02c --- /dev/null +++ b/types/iri/iri-tests.ts @@ -0,0 +1,43 @@ +import { IRI, fromURI, toIRIString } from 'iri'; + +const iri = new IRI('iri'); +// $ExpectType string +iri.toString(); +// $ExpectType IRI +iri.defrag(); +// $ExpectType boolean +iri.isAbsolute(); +// $ExpectType IRI +iri.toAbsolute(); +// $ExpectType string | null +iri.authority(); +// $ExpectType string | null +iri.fragment(); +// $ExpectType string +iri.hierpart(); +// $ExpectType string +iri.host(); +// $ExpectType string +iri.path(); +// $ExpectType string | null +iri.port(); +// $ExpectType string | null +iri.query(); +// $ExpectType IRI +iri.resolveReference('ref'); +iri.resolveReference(iri); +// $ExpectType string | null +iri.scheme(); +// $ExpectType string | null +iri.userinfo(); +// $ExpectType string +iri.toURIString(); +// $ExpectType string +iri.toIRIString(); +// $ExpectType IRI +iri.toIRI(); + +// $ExpectType IRI +fromURI('u'); +// $ExpectType string +toIRIString('u'); diff --git a/types/iri/tsconfig.json b/types/iri/tsconfig.json new file mode 100644 index 0000000000..09b1e0069e --- /dev/null +++ b/types/iri/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", + "iri-tests.ts" + ] +} diff --git a/types/iri/tslint.json b/types/iri/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/iri/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From e80e44b0f032fc4a70d6e4d05354a6e53fb9089b Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 21 Nov 2018 01:06:14 +0100 Subject: [PATCH 278/836] Update types for @xmpp/jid --- types/xmpp__jid/index.d.ts | 84 ++++++++++++++++-------------- types/xmpp__jid/xmpp__jid-tests.ts | 55 ++++++++++--------- 2 files changed, 73 insertions(+), 66 deletions(-) diff --git a/types/xmpp__jid/index.d.ts b/types/xmpp__jid/index.d.ts index f3f5bcc485..51b19051f1 100644 --- a/types/xmpp__jid/index.d.ts +++ b/types/xmpp__jid/index.d.ts @@ -1,55 +1,63 @@ -// Type definitions for @xmpp/jid 0.0 +// Type definitions for @xmpp/jid 0.6 // Project: https://github.com/node-xmpp/node-xmpp/ // Definitions by: PJakcson +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 -export function createJID(local: string, domain: string, resource: string): JID; -export function equal(a: JID, b: JID): boolean; -export function is(a: any): boolean; +export = jid; -/** - * Created by marcneumann on 17.02.17. - */ -export class JID { - local: string; - domain: string; - resource: string; +declare function jid(address: string): jid.JID; +declare function jid(local: string | undefined, domain: string, resource?: string): jid.JID; - constructor(local: string, domain?: string, resource?: string); +declare namespace jid { + function jid(address: string): JID; + function jid(local: string | undefined, domain: string, resource?: string): JID; - parseJID(jid: string): void; + function createJID(local: string | undefined, domain: string, resource?: string): JID; + function equal(a: JID, b: JID): boolean; + function detectEscape(local?: string): boolean; + function escapeLocal(local: string): string; + function unescapeLocal(local: string): string; + function parse(s: string): JID; - toString(unescape?: any): string; + class JID { + local: string; + domain: string; + resource: string; - /** - * Convenience method to distinguish users - */ - bare(): JID; + constructor(local: string | undefined, domain: string, resource?: string); - /** - * Comparison function - */ - equals(other: JID): boolean; + toString(unescape?: boolean): string; - /** - * http://xmpp.org/rfcs/rfc6122.html#addressing-localpart - */ - setLocal(local: string, escape?: any): void; + /** + * Convenience method to distinguish users + */ + bare(): JID; - getLocal(unescape?: any): string; + /** + * Comparison function + */ + equals(other: JID): boolean; - /** - * http://xmpp.org/rfcs/rfc6122.html#addressing-domain - */ - setDomain(value: string): void; + /** + * http://xmpp.org/rfcs/rfc6122.html#addressing-localpart + */ + setLocal(local: string, escape?: boolean): void; - getDomain(): string; + getLocal(unescape?: boolean): string; - /** - * http://xmpp.org/rfcs/rfc6122.html#addressing-resourcepart - */ - setResource(value: string): void; + /** + * http://xmpp.org/rfcs/rfc6122.html#addressing-domain + */ + setDomain(value: string): void; - getResource(): string; + getDomain(): string; + + /** + * http://xmpp.org/rfcs/rfc6122.html#addressing-resourcepart + */ + setResource(value: string): void; + + getResource(): string; + } } diff --git a/types/xmpp__jid/xmpp__jid-tests.ts b/types/xmpp__jid/xmpp__jid-tests.ts index d26ede9a15..4a79d5849f 100644 --- a/types/xmpp__jid/xmpp__jid-tests.ts +++ b/types/xmpp__jid/xmpp__jid-tests.ts @@ -1,40 +1,39 @@ -import { JID } from '@xmpp/jid'; +import jid = require('@xmpp/jid'); -/* - * All return an instance of JID.JID, the new operator is optional. - */ -let addr = new JID('alice@wonderland.net/rabbithole'); // OK -addr = new JID('alice', 'wonderland.net', 'rabbithole'); // BEST; see section on escaping below +let addr: jid.JID; +let str: string; +let bool: boolean; + +addr = jid('alice@wonderland.net/rabbithole'); +addr = jid('alice', 'wonderland.net', 'rabbithole'); -/* - * local - */ addr.local = 'alice'; -addr.local; // alice -// same as +str = addr.local; addr.setLocal('alice'); -addr.getLocal(); // alice +addr.setLocal('alice', true); +str = addr.getLocal(); -/* - * domain - */ addr.domain = 'wonderland.net'; -addr.domain; // wonderland.net -// same as +str = addr.domain; addr.setDomain('wonderland.net'); -addr.getDomain(); // wonderland.net +str = addr.getDomain(); -/* - * resource - */ addr.resource = 'rabbithole'; -addr.resource; // rabbithole -// same as +str = addr.resource; addr.setResource('rabbithole'); -addr.getResource(); // rabbithole +str = addr.getResource(); -addr.toString(); // alice@wonderland.net/rabbithole -addr.bare(); // returns a JID without resource +str = addr.toString(); +str = addr.toString(true); +addr = addr.bare(); -const some_jid = new JID('is', 'a', 'test'); -addr.equals(some_jid); // returns true if the two JIDs are equal, false otherwise +bool = addr.equals(addr); + +bool = jid.equal(addr, addr); + +addr = jid.createJID('my', 'homies'); +bool = jid.equal(addr, addr); +bool = jid.detectEscape('homies'); +str = jid.escapeLocal('homies'); +str = jid.unescapeLocal('homies'); +addr = jid.parse('homies'); From 26b7fc9609d7edea4b1b50f9cc1a9f28f22bc1ef Mon Sep 17 00:00:00 2001 From: Al Calzone Date: Sun, 25 Nov 2018 16:00:57 +0100 Subject: [PATCH 279/836] Update ioBroker typings and tests * Replace any with unknown in many places * Add several overloads * Add tests --- types/iobroker/index.d.ts | 256 ++++++++++++++++++------------- types/iobroker/iobroker-tests.ts | 200 +++++++++++++++++++++++- 2 files changed, 350 insertions(+), 106 deletions(-) diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index 313d7e9718..cee6ce75a6 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 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 3.0 // Note: This is not the definition for the package `iobroker`, // which is just an installer, not a library. @@ -307,7 +307,7 @@ declare global { interface BaseObject { /** The ID of this object */ - _id?: string; + _id: string; native: Record; enums?: Record; type: string; // specified in the derived interfaces @@ -350,6 +350,11 @@ declare global { } type Object = StateObject | ChannelObject | DeviceObject | OtherObject; + // In set[Foreign]Object[NotExists] methods, the ID and acl of the object is optional + interface SettableObject extends Pick> { + _id?: ioBroker.Object["_id"]; + acl?: ioBroker.Object["acl"]; + } type PartialObject = PartialStateObject | PartialChannelObject | PartialDeviceObject | PartialOtherObject; /** Defines access rights for a single file */ @@ -519,7 +524,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ writeFile(id: string, name: string, data: Buffer | string, callback: ErrorCallback): void; - writeFile(id: string, name: string, data: Buffer | string, options: string | {}, callback: ErrorCallback): void; + writeFile(id: string, name: string, data: Buffer | string, options: string | unknown, callback: ErrorCallback): void; /** * Reads a file. @@ -529,7 +534,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ readFile(id: string, name: string, callback: ReadFileCallback): void; - readFile(id: string, name: string, options: any, callback: ReadFileCallback): void; + readFile(id: string, name: string, options: unknown, callback: ReadFileCallback): void; /** * Deletes a file. @@ -539,7 +544,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ unlink(id: string, name: string, callback: ErrorCallback): void; - unlink(id: string, name: string, options: any, callback: ErrorCallback): void; + unlink(id: string, name: string, options: unknown, callback: ErrorCallback): void; /** * Deletes a file. * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" @@ -548,7 +553,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ delFile(id: string, name: string, callback: ErrorCallback): void; - delFile(id: string, name: string, options: any, callback: ErrorCallback): void; + delFile(id: string, name: string, options: unknown, callback: ErrorCallback): void; /** * Finds all files and directories starting with @@ -558,7 +563,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ readDir(id: string, name: string, callback: ReadDirCallback): void; - readDir(id: string, name: string, options: any, callback: ReadDirCallback): void; + readDir(id: string, name: string, options: unknown, callback: ReadDirCallback): void; /** * Renames a file or directory @@ -569,7 +574,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ rename(id: string, oldName: string, newName: string, callback: ErrorCallback): void; - rename(id: string, oldName: string, newName: string, options: any, callback: ErrorCallback): void; + rename(id: string, oldName: string, newName: string, options: unknown, callback: ErrorCallback): void; /** * Creates an empty file with the given name @@ -579,7 +584,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ touch(id: string, name: string, callback: ErrorCallback): void; - touch(id: string, name: string, options: any, callback: ErrorCallback): void; + touch(id: string, name: string, options: unknown, callback: ErrorCallback): void; /** * Deletes all files in the root directory matching @@ -589,7 +594,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ rm(id: string, name: string, callback: RmCallback): void; - rm(id: string, name: string, options: any, callback: RmCallback): void; + rm(id: string, name: string, options: unknown, callback: RmCallback): void; /** * Creates an empty directory with the given name @@ -599,7 +604,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ mkDir(id: string, name: string, callback: ErrorCallback): void; - mkDir(id: string, name: string, options: any, callback: ErrorCallback): void; + mkDir(id: string, name: string, options: unknown, callback: ErrorCallback): void; /** * Takes possession all files in the root directory matching @@ -609,7 +614,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ chownFile(id: string, name: string, callback: ChownFileCallback): void; - chownFile(id: string, name: string, options: any, callback: ChownFileCallback): void; + chownFile(id: string, name: string, options: unknown, callback: ChownFileCallback): void; /** * Changes access rights of all files in the root directory matching @@ -628,26 +633,26 @@ declare global { * @param pattern The pattern to match against */ subscribeConfig(pattern: string, callback: EmptyCallback): void; - subscribeConfig(pattern: string, options: any, callback: EmptyCallback): void; + subscribeConfig(pattern: string, options: unknown, callback: EmptyCallback): void; /** * Subscribe to object changes * @param pattern The pattern to match against */ subscribe(pattern: string, callback: EmptyCallback): void; - subscribe(pattern: string, options: any, callback: EmptyCallback): void; + subscribe(pattern: string, options: unknown, callback: EmptyCallback): void; /** * Unsubscribe from object changes * @param pattern The pattern to match against */ unsubscribeConfig(pattern: string, callback: EmptyCallback): void; - unsubscribeConfig(pattern: string, options: any, callback: EmptyCallback): void; + unsubscribeConfig(pattern: string, options: unknown, callback: EmptyCallback): void; /** * Unsubscribe from object changes * @param pattern The pattern to match against */ unsubscribe(pattern: string, callback: EmptyCallback): void; - unsubscribe(pattern: string, options: any, callback: EmptyCallback): void; + unsubscribe(pattern: string, options: unknown, callback: EmptyCallback): void; /** * Takes possession of all objects matching @@ -656,7 +661,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ chownObject(pattern: string, callback: ChownObjectCallback): void; - chownObject(pattern: string, options: any, callback: ChownObjectCallback): void; + chownObject(pattern: string, options: unknown, callback: ChownObjectCallback): void; /** * Changes access rights of all objects matching @@ -665,7 +670,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ chmodObject(pattern: string, callback: ChownObjectCallback): void; - chmodObject(pattern: string, options: any, callback: ChownObjectCallback): void; + chmodObject(pattern: string, options: unknown, callback: ChownObjectCallback): void; /** * Retrieves a copy of the object with the given ID @@ -674,7 +679,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ getObject(id: string, callback: GetObjectCallback): void; - getObject(id: string, options: any, callback: GetObjectCallback): void; + getObject(id: string, options: unknown, callback: GetObjectCallback): void; /** * Retrieves a copy of the object with the given ID * @param id Id of the object to find @@ -682,7 +687,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ getConfig(id: string, callback: GetObjectCallback): void; - getConfig(id: string, options: any, callback: GetObjectCallback): void; + getConfig(id: string, options: unknown, callback: GetObjectCallback): void; /** * Returns a list of config keys matching @@ -692,7 +697,7 @@ declare global { * @param dontModify unused */ getConfigKeys(pattern: string, callback: GetConfigKeysCallback, dontModify?: any): void; - getConfigKeys(pattern: string, options: any, callback: GetConfigKeysCallback, dontModify?: any): void; + getConfigKeys(pattern: string, options: unknown, callback: GetConfigKeysCallback, dontModify?: any): void; /** * Returns a list of objects with the given ids @@ -702,7 +707,7 @@ declare global { * @param dontModify unused */ getObjects(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; - getObjects(keys: string[], options: any, callback: GetObjectsCallback2, dontModify?: any): void; + getObjects(keys: string[], options: unknown, callback: GetObjectsCallback2, dontModify?: any): void; /** * Returns a list of objects with the given ids * @param keys IDs of the objects to be retrieved @@ -711,7 +716,7 @@ declare global { * @param dontModify unused */ getConfigs(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; - getConfigs(keys: string[], options: any, callback: GetObjectsCallback2, dontModify?: any): void; + getConfigs(keys: string[], options: unknown, callback: GetObjectsCallback2, dontModify?: any): void; /** * Creates or overwrites an object in the object db @@ -720,8 +725,8 @@ declare global { * @param options (optional) Some internal options. * @param callback Is called when the operation has finished (successfully or not) */ - setObject(id: string, obj: ioBroker.Object, callback: SetObjectCallback): void; - setObject(id: string, obj: ioBroker.Object, options: any, callback: SetObjectCallback): void; + setObject(id: string, obj: ioBroker.SettableObject, callback: SetObjectCallback): void; + setObject(id: string, obj: ioBroker.SettableObject, options: unknown, callback: SetObjectCallback): void; /** * Creates or overwrites an object in the object db * @param id ID of the object @@ -729,8 +734,8 @@ declare global { * @param options (optional) Some internal options. * @param callback Is called when the operation has finished (successfully or not) */ - setConfig(id: string, obj: ioBroker.Object, callback: SetObjectCallback): void; - setConfig(id: string, obj: ioBroker.Object, options: any, callback: SetObjectCallback): void; + setConfig(id: string, obj: ioBroker.SettableObject, callback: SetObjectCallback): void; + setConfig(id: string, obj: ioBroker.SettableObject, options: unknown, callback: SetObjectCallback): void; /** * Deletes an object in the object db @@ -739,7 +744,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ delObject(id: string, callback: ErrorCallback): void; - delObject(id: string, options: any, callback: ErrorCallback): void; + delObject(id: string, options: unknown, callback: ErrorCallback): void; /** * Deletes an object in the object db * @param id ID of the object @@ -747,7 +752,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ delConfig(id: string, callback: ErrorCallback): void; - delConfig(id: string, options: any, callback: ErrorCallback): void; + delConfig(id: string, options: unknown, callback: ErrorCallback): void; /** * Returns a list of objects with id between params.startkey and params.endkey @@ -769,7 +774,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ getObjectView(design: string, search: string, params: GetObjectViewParams | null, callback: GetObjectViewCallback): void; - getObjectView(design: string, search: string, params: GetObjectViewParams | null, options: any, callback: GetObjectViewCallback): void; + getObjectView(design: string, search: string, params: GetObjectViewParams | null, options: unknown, callback: GetObjectViewCallback): void; /** * Extends an object in the object db with new properties @@ -779,7 +784,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ extendObject(id: string, obj: PartialObject, callback: ExtendObjectCallback): void; - extendObject(id: string, obj: PartialObject, options: any, callback: ExtendObjectCallback): void; + extendObject(id: string, obj: PartialObject, options: unknown, callback: ExtendObjectCallback): void; /** * Finds an object by ID or name. If multiple objects were found, return the first one @@ -789,7 +794,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ findObject(idOrName: string, type: CommonType | null, callback: FindObjectCallback): void; - findObject(idOrName: string, type: CommonType | null, options: any, callback: FindObjectCallback): void; + findObject(idOrName: string, type: CommonType | null, options: unknown, callback: FindObjectCallback): void; // I'd rather not document a function with the name "destroyDB" @@ -910,9 +915,9 @@ declare global { /** Handler for changes of subscribed states */ stateChange?: StateChangeHandler; /** Will be called when the adapter is intialized */ - ready?: () => void; + ready?: ReadyHandler; /** Will be called on adapter termination */ - unload?: (callback: EmptyCallback) => void; + unload?: UnloadHandler; /** if true, stateChange will be called with an id that has no namespace, e.g. "state" instead of "adapter.0.state". Default: false */ noNamespace?: boolean; @@ -972,15 +977,15 @@ declare global { /** Validates username and password */ checkPassword(user: string, password: string, callback: (result: boolean) => void): void; - checkPassword(user: string, password: string, options: any, callback: (result: boolean) => void): void; + checkPassword(user: string, password: string, options: unknown, callback: (result: boolean) => void): void; /** Sets a new password for the given user */ - setPassword(user: string, password: string, options?: any, callback?: (err?: any) => void): void; + setPassword(user: string, password: string, options?: unknown, callback?: (err?: any) => void): void; /** Checks if a user exists and is in the given group. */ checkGroup(user: string, group: string, callback: (result: boolean) => void): void; - checkGroup(user: string, group: string, options: any, callback: (result: boolean) => void): void; + checkGroup(user: string, group: string, options: unknown, callback: (result: boolean) => void): void; /** Determines the users permissions */ calculatePermissions(user: string, commandsPermissions: CommandsPermissions, callback: (result: PermissionSet) => void): void; - calculatePermissions(user: string, commandsPermissions: CommandsPermissions, options: any, callback: (result: PermissionSet) => void): void; + calculatePermissions(user: string, commandsPermissions: CommandsPermissions, options: unknown, callback: (result: PermissionSet) => void): void; /** Returns SSL certificates by name (private key, public cert and chained certificate) for creation of HTTPS servers */ getCertificates(publicName: string, privateName: string, chainedName: string, callback: (err: string | null, certs?: Certificates, useLetsEncryptCert?: boolean) => void): void; @@ -1013,20 +1018,24 @@ declare global { /** Reads an object from the object db */ getObject(id: string, callback: GetObjectCallback): void; - getObject(id: string, options: any, callback: GetObjectCallback): void; + getObject(id: string, options: unknown, callback: GetObjectCallback): void; /** Creates or overwrites an object in the object db */ - setObject(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; + setObject(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; + setObject(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; /** Creates an object in the object db. Existing objects are not overwritten. */ - setObjectNotExists(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; + setObjectNotExists(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; + setObjectNotExists(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; /** Get all states, channels and devices of this adapter */ getAdapterObjects(callback: (objects: Record) => void): void; /** Extend an object and create it if it might not exist */ - extendObject(id: string, objPart: PartialObject, options?: any, callback?: SetObjectCallback): void; + extendObject(id: string, objPart: PartialObject, callback?: SetObjectCallback): void; + extendObject(id: string, objPart: PartialObject, options: unknown, callback?: SetObjectCallback): void; /** * Deletes an object from the object db * @param id - The id of the object without namespace */ - delObject(id: string, options?: any, callback?: ErrorCallback): void; + delObject(id: string, callback?: ErrorCallback): void; + delObject(id: string, options: unknown, callback?: ErrorCallback): void; // ============================== // foreign objects @@ -1034,61 +1043,83 @@ declare global { // tslint:disable:unified-signatures /** Reads an object (which might not belong to this adapter) from the object db */ getForeignObject(id: string, callback: GetObjectCallback): void; - getForeignObject(id: string, options: any, callback: GetObjectCallback): void; + getForeignObject(id: string, options: unknown, callback: GetObjectCallback): void; /** Get foreign objects by pattern, by specific type and resolve their enums. */ getForeignObjects(pattern: string, callback: GetObjectsCallback): void; - getForeignObjects(pattern: string, options: any, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, options: unknown, callback: GetObjectsCallback): void; getForeignObjects(pattern: string, type: ObjectType, callback: GetObjectsCallback): void; getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, callback: GetObjectsCallback): void; - getForeignObjects(pattern: string, type: ObjectType, options: any, callback: GetObjectsCallback): void; - getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, options: any, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, options: unknown, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, options: unknown, callback: GetObjectsCallback): void; /** Creates or overwrites an object (which might not belong to this adapter) in the object db */ - setForeignObject(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; + setForeignObject(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; + setForeignObject(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; /** Creates an object (which might not belong to this adapter) in the object db. Existing objects are not overwritten. */ - setForeignObjectNotExists(id: string, obj: ioBroker.Object, options?: any, callback?: SetObjectCallback): void; + setForeignObjectNotExists(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; + setForeignObjectNotExists(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; /** Extend an object (which might not belong to this adapter) and create it if it might not exist */ - extendForeignObject(id: string, objPart: PartialObject, options?: any, callback?: SetObjectCallback): void; + extendForeignObject(id: string, objPart: PartialObject, callback?: SetObjectCallback): void; + extendForeignObject(id: string, objPart: PartialObject, options: unknown, callback?: SetObjectCallback): void; // tslint:enable:unified-signatures /** * Finds an object by its ID or name * @param type - common.type of the state */ findForeignObject(idOrName: string, type: string, callback: FindObjectCallback): void; - findForeignObject(idOrName: string, type: string, options: any, callback: FindObjectCallback): void; + findForeignObject(idOrName: string, type: string, options: unknown, callback: FindObjectCallback): void; /** * Deletes an object (which might not belong to this adapter) from the object db * @param id - The id of the object including namespace */ - delForeignObject(id: string, options?: any, callback?: ErrorCallback): void; + delForeignObject(id: string, callback?: ErrorCallback): void; + delForeignObject(id: string, options: unknown, callback?: ErrorCallback): void; // ============================== // states + + // Multiple signatures help understanding what the parameters are about + // tslint:disable:unified-signatures /** Writes a value into the states DB. */ - setState(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateCallback): void; + setState(id: string, state: string | number | boolean | State | Partial, callback?: SetStateCallback): void; + setState(id: string, state: string | number | boolean | State | Partial, ack: boolean, callback?: SetStateCallback): void; + setState(id: string, state: string | number | boolean | State | Partial, options: unknown, callback?: SetStateCallback): void; + setState(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown, callback?: SetStateCallback): void; /** Writes a value into the states DB only if it has changed. */ - setStateChanged(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateChangedCallback): void; + setStateChanged(id: string, state: string | number | boolean | State | Partial, callback?: SetStateChangedCallback): void; + setStateChanged(id: string, state: string | number | boolean | State | Partial, ack: boolean, callback?: SetStateChangedCallback): void; + setStateChanged(id: string, state: string | number | boolean | State | Partial, options: unknown, callback?: SetStateChangedCallback): void; + setStateChanged(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown, callback?: SetStateChangedCallback): void; /** Writes a value (which might not belong to this adapter) into the states DB. */ - setForeignState(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateCallback): void; + setForeignState(id: string, state: string | number | boolean | State | Partial, callback?: SetStateCallback): void; + setForeignState(id: string, state: string | number | boolean | State | Partial, ack: boolean, callback?: SetStateCallback): void; + setForeignState(id: string, state: string | number | boolean | State | Partial, options: unknown, callback?: SetStateCallback): void; + setForeignState(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown, callback?: SetStateCallback): void; /** Writes a value (which might not belong to this adapter) into the states DB only if it has changed. */ - setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, ack?: boolean, options?: any, callback?: SetStateChangedCallback): void; + setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, callback?: SetStateChangedCallback): void; + setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, ack: boolean, callback?: SetStateChangedCallback): void; + setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, options: unknown, callback?: SetStateChangedCallback): void; + setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown, callback?: SetStateChangedCallback): void; + // tslint:enable:unified-signatures /** Read a value from the states DB. */ getState(id: string, callback: GetStateCallback): void; - getState(id: string, options: any, callback: GetStateCallback): void; + getState(id: string, options: unknown, callback: GetStateCallback): void; /** Read a value (which might not belong to this adapter) from the states DB. */ getForeignState(id: string, callback: GetStateCallback): void; - getForeignState(id: string, options: any, callback: GetStateCallback): void; + getForeignState(id: string, options: unknown, callback: GetStateCallback): void; /** Read all states of this adapter which match the given pattern */ getStates(pattern: string, callback: GetStatesCallback): void; - getStates(pattern: string, options: any, callback: GetStatesCallback): void; + getStates(pattern: string, options: unknown, callback: GetStatesCallback): void; /** Read all states (which might not belong to this adapter) which match the given pattern */ getForeignStates(pattern: string, callback: GetStatesCallback): void; - getForeignStates(pattern: string, options: any, callback: GetStatesCallback): void; + getForeignStates(pattern: string, options: unknown, callback: GetStatesCallback): void; /** Deletes a state from the states DB, but not the associated object. Consider using @link{deleteState} instead */ - delState(id: string, options?: any, callback?: ErrorCallback): void; + delState(id: string, callback?: ErrorCallback): void; + delState(id: string, options: unknown, callback?: ErrorCallback): void; /** Deletes a state from the states DB, but not the associated object */ - delForeignState(id: string, options?: any, callback?: ErrorCallback): void; + delForeignState(id: string, callback?: ErrorCallback): void; + delForeignState(id: string, options: unknown, callback?: ErrorCallback): void; getHistory(id: string, options: GetHistoryOptions, callback: GetHistoryCallback): void; @@ -1106,7 +1137,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ setBinaryState(id: string, binary: Buffer, callback: SetStateCallback): void; - setBinaryState(id: string, binary: Buffer, options: any, callback: SetStateCallback): void; + setBinaryState(id: string, binary: Buffer, options: unknown, callback: SetStateCallback): void; /** * Reads a binary state from Redis * @param id The id of the state @@ -1114,7 +1145,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ getBinaryState(id: string, callback: GetBinaryStateCallback): void; - getBinaryState(id: string, options: any, callback: GetBinaryStateCallback): void; + getBinaryState(id: string, options: unknown, callback: GetBinaryStateCallback): void; // ============================== // enums @@ -1122,65 +1153,65 @@ declare global { /** Returns the enum tree, filtered by the optional enum name */ getEnum(callback: GetEnumCallback): void; getEnum(name: string, callback: GetEnumCallback): void; - getEnum(name: string, options: any, callback: GetEnumCallback): void; + getEnum(name: string, options: unknown, callback: GetEnumCallback): void; getEnums(callback: GetEnumsCallback): void; getEnums(enumList: EnumList, callback: GetEnumsCallback): void; - getEnums(enumList: EnumList, options: any, callback: GetEnumsCallback): void; + getEnums(enumList: EnumList, options: unknown, callback: GetEnumsCallback): void; - addChannelToEnum(enumName: string, addTo: string, parentDevice: string, channelName: string, options?: any, callback?: ErrorCallback): void; - deleteChannelFromEnum(enumName: string, parentDevice: string, channelName: string, options?: any, callback?: ErrorCallback): void; + addChannelToEnum(enumName: string, addTo: string, parentDevice: string, channelName: string, options?: unknown, callback?: ErrorCallback): void; + deleteChannelFromEnum(enumName: string, parentDevice: string, channelName: string, options?: unknown, callback?: ErrorCallback): void; - addStateToEnum(enumName: string, addTo: string, parentDevice: string, parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; - deleteStateFromEnum(enumName: string, parentDevice: string, parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; + addStateToEnum(enumName: string, addTo: string, parentDevice: string, parentChannel: string, stateName: string, options?: unknown, callback?: ErrorCallback): void; + deleteStateFromEnum(enumName: string, parentDevice: string, parentChannel: string, stateName: string, options?: unknown, callback?: ErrorCallback): void; // ============================== // subscriptions /** Subscribe to changes of objects in this instance */ - subscribeObjects(pattern: string, options?: any): void; + subscribeObjects(pattern: string, options?: unknown): void; /** Subscribe to changes of objects (which might not belong to this adapter) */ - subscribeForeignObjects(pattern: string, options?: any): void; + subscribeForeignObjects(pattern: string, options?: unknown): void; /** Unsubscribe from changes of objects in this instance */ - unsubscribeObjects(pattern: string, options?: any): void; + unsubscribeObjects(pattern: string, options?: unknown): void; /** Unsubscribe from changes of objects (which might not belong to this adapter) */ - unsubscribeForeignObjects(pattern: string, options?: any): void; + unsubscribeForeignObjects(pattern: string, options?: unknown): void; /** Subscribe to changes of states in this instance */ - subscribeStates(pattern: string, options?: any, callback?: ErrorCallback): void; + subscribeStates(pattern: string, options?: unknown, callback?: ErrorCallback): void; /** Subscribe to changes of states (which might not belong to this adapter) */ - subscribeForeignStates(pattern: string, options?: any, callback?: ErrorCallback): void; + subscribeForeignStates(pattern: string, options?: unknown, callback?: ErrorCallback): void; /** * Subscribe from changes of states in this instance * @param pattern - Must match the pattern used to subscribe */ - unsubscribeStates(pattern: string, options?: any, callback?: ErrorCallback): void; + unsubscribeStates(pattern: string, options?: unknown, callback?: ErrorCallback): void; /** * Subscribe from changes of states (which might not belong to this adapter) * @param pattern - Must match the pattern used to subscribe */ - unsubscribeForeignStates(pattern: string, options?: any, callback?: ErrorCallback): void; + unsubscribeForeignStates(pattern: string, options?: unknown, callback?: ErrorCallback): void; // ============================== // devices and channels /** creates an object with type device */ - createDevice(deviceName: string, common?: any, native?: any, options?: any, callback?: SetObjectCallback): void; + createDevice(deviceName: string, common?: any, native?: any, options?: unknown, callback?: SetObjectCallback): void; /** deletes a device, its channels and states */ - deleteDevice(deviceName: string, options?: any, callback?: ErrorCallback): void; + deleteDevice(deviceName: string, options?: unknown, callback?: ErrorCallback): void; /** gets the devices of this instance */ /** creates an object with type channel */ - createChannel(parentDevice: string, channelName: string, roleOrCommon?: string | object, native?: any, options?: any, callback?: SetObjectCallback): void; + createChannel(parentDevice: string, channelName: string, roleOrCommon?: string | object, native?: any, options?: unknown, callback?: SetObjectCallback): void; /** deletes a channel and its states */ - deleteChannel(channelName: string, options?: any, callback?: ErrorCallback): void; - deleteChannel(parentDevice: string, channelName: string, options?: any, callback?: ErrorCallback): void; + deleteChannel(channelName: string, options?: unknown, callback?: ErrorCallback): void; + deleteChannel(parentDevice: string, channelName: string, options?: unknown, callback?: ErrorCallback): void; /** creates a state and the corresponding object */ - createState(parentDevice: string, parentChannel: string, stateName: string, roleOrCommon?: string | object, native?: any, options?: any, callback?: SetObjectCallback): void; + createState(parentDevice: string, parentChannel: string, stateName: string, roleOrCommon?: string | object, native?: any, options?: unknown, callback?: SetObjectCallback): void; /** deletes a state */ - deleteState(stateName: string, options?: any, callback?: ErrorCallback): void; - deleteState(parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; - deleteState(parentDevice: string, parentChannel: string, stateName: string, options?: any, callback?: ErrorCallback): void; + deleteState(stateName: string, options?: unknown, callback?: ErrorCallback): void; + deleteState(parentChannel: string, stateName: string, options?: unknown, callback?: ErrorCallback): void; + deleteState(parentDevice: string, parentChannel: string, stateName: string, options?: unknown, callback?: ErrorCallback): void; /** * Returns a list of all devices in this adapter instance @@ -1188,7 +1219,7 @@ declare global { * @param callback Is called when the operation has finished (successfully or not) */ getDevices(callback: GetObjectsCallback3): void; - getDevices(options: any, callback: GetObjectsCallback3): void; + getDevices(options: unknown, callback: GetObjectsCallback3): void; /** * Returns a list of all channels in this adapter instance @@ -1198,7 +1229,7 @@ declare global { */ getChannels(callback: GetObjectsCallback3): void; getChannels(parentDevice: string | null, callback: GetObjectsCallback3): void; - getChannels(parentDevice: string | null, options: any, callback: GetObjectsCallback3): void; + getChannels(parentDevice: string | null, options: unknown, callback: GetObjectsCallback3): void; /** * Returns a list of all channels in this adapter instance * @param parentDevice (optional) Name of the parent device to filter the channels by @@ -1207,7 +1238,7 @@ declare global { */ getChannelsOf(callback: GetObjectsCallback3): void; getChannelsOf(parentDevice: string | null, callback: GetObjectsCallback3): void; - getChannelsOf(parentDevice: string | null, options: any, callback: GetObjectsCallback3): void; + getChannelsOf(parentDevice: string | null, options: unknown, callback: GetObjectsCallback3): void; /** * Returns a list of all states in this adapter instance @@ -1219,7 +1250,7 @@ declare global { getStatesOf(callback: GetObjectsCallback3): void; getStatesOf(parentDevice: string | null, callback: GetObjectsCallback3): void; getStatesOf(parentDevice: string | null, parentChannel: string | null, callback: GetObjectsCallback3): void; - getStatesOf(parentDevice: string | null, parentChannel: string | null, options: any, callback: GetObjectsCallback3): void; + getStatesOf(parentDevice: string | null, parentChannel: string | null, options: unknown, callback: GetObjectsCallback3): void; // ============================== // filesystem @@ -1230,23 +1261,23 @@ declare global { * @param path - path to direcory without adapter name. E.g. If you want to read "/vis.0/main/views.json", here must be "/main/views.json" and _adapter must be equal to "vis.0". */ readDir(adapterName: string, path: string, callback: ReadDirCallback): void; - readDir(adapterName: string, path: string, options: any, callback: ReadDirCallback): void; + readDir(adapterName: string, path: string, options: unknown, callback: ReadDirCallback): void; mkDir(adapterName: string, path: string, callback: ErrorCallback): void; - mkDir(adapterName: string, path: string, options: any, callback: ErrorCallback): void; + mkDir(adapterName: string, path: string, options: unknown, callback: ErrorCallback): void; readFile(adapterName: string, path: string, callback: ReadFileCallback): void; - readFile(adapterName: string, path: string, options: any, callback: ReadFileCallback): void; + readFile(adapterName: string, path: string, options: unknown, callback: ReadFileCallback): void; writeFile(adapterName: string, path: string, data: Buffer | string, callback: ErrorCallback): void; // options see https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/objects/objectsInMemServer.js#L599 - writeFile(adapterName: string, path: string, data: Buffer | string, options: any, callback: ErrorCallback): void; + writeFile(adapterName: string, path: string, data: Buffer | string, options: unknown, callback: ErrorCallback): void; delFile(adapterName: string, path: string, callback: ErrorCallback): void; - delFile(adapterName: string, path: string, options: any, callback: ErrorCallback): void; + delFile(adapterName: string, path: string, options: unknown, callback: ErrorCallback): void; unlink(adapterName: string, path: string, callback: ErrorCallback): void; - unlink(adapterName: string, path: string, options: any, callback: ErrorCallback): void; + unlink(adapterName: string, path: string, options: unknown, callback: ErrorCallback): void; rename(adapterName: string, oldName: string, newName: string, callback: ErrorCallback): void; - rename(adapterName: string, oldName: string, newName: string, options: any, callback: ErrorCallback): void; + rename(adapterName: string, oldName: string, newName: string, options: unknown, callback: ErrorCallback): void; /** * Changes access rights of all files in the adapter directory @@ -1264,11 +1295,30 @@ declare global { formatValue(value: number | string, decimals: number, format: any): string; formatDate(dateObj: string | Date | number, format: string): string; formatDate(dateObj: string | Date | number, isDuration: boolean | string, format: string): string; + + // ============================================= + // Events exposed through EventEmitter interface + // ============================================= + on(event: "ready", handler: ReadyHandler): this; + on(event: "unload", handler: UnloadHandler): this; + on(event: "stateChange", handler: StateChangeHandler): this; + on(event: "objectChange", handler: ObjectChangeHandler): this; + on(event: "message", handler: MessageHandler): this; + + removeListener(event: "ready", handler: ReadyHandler): this; + removeListener(event: "unload", handler: UnloadHandler): this; + removeListener(event: "stateChange", handler: StateChangeHandler): this; + removeListener(event: "objectChange", handler: ObjectChangeHandler): this; + removeListener(event: "message", handler: MessageHandler): this; + + removeAllListeners(event?: "ready" | "unload" | "stateChange" | "objectChange" | "message"): this; } // end interface Adapter - type ObjectChangeHandler = (id: string, obj: ioBroker.Object) => void; - type StateChangeHandler = (id: string, obj: State) => void; + type ReadyHandler = () => void; + type ObjectChangeHandler = (id: string, obj: ioBroker.Object | null | undefined) => void; + type StateChangeHandler = (id: string, obj: State | null | undefined) => void; type MessageHandler = (obj: Message) => void; + type UnloadHandler = (callback: EmptyCallback) => void; type EmptyCallback = () => void; type ErrorCallback = (err?: string) => void; @@ -1276,7 +1326,7 @@ declare global { type GenericCallback = (err: string | null, result?: T) => void; type SetObjectCallback = (err: string | null, obj: { id: string }) => void; - type GetObjectCallback = (err: string | null, obj: ioBroker.Object) => void; + type GetObjectCallback = (err: string | null, obj: ioBroker.Object | null | undefined) => void; type GetEnumCallback = (err: string | null, enums: Record, requestedEnum: string) => void; type GetEnumsCallback = ( err: string | null, @@ -1304,7 +1354,7 @@ declare global { // This is a version used by GetDevices/GetChannelsOf/GetStatesOf type GetObjectsCallback3 = (err: string | null, result?: Array>) => void; - type GetStateCallback = (err: string | null, state: State) => void; + type GetStateCallback = (err: string | null, state: State | null | undefined) => void; type GetStatesCallback = (err: string | null, states: Record) => void; /** Version of the callback used by States.getStates */ type GetStatesCallback2 = (err: string | null, states: State[]) => void; @@ -1374,7 +1424,7 @@ declare global { /** The ID of this object */ id: string; /** A copy of the object from the DB or some aggregation result */ - value: ioBroker.Object | {}; // TODO: find out how the non-Object return result looks like + value: ioBroker.Object | unknown; // TODO: find out how the non-Object return result looks like } type GetObjectViewCallback = (err: string | null, result?: { rows: GetObjectViewItem[] }) => void; diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index c8b9f0d43e..997775c76f 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -1,5 +1,199 @@ -// Help! what to test here? +// For now, this "utils" module is necessary, as it is included in every adapter +// Once this PR is merged and @types/iobroker is available, it will become part of +// `iobroker.adapter-core`, which brings typings for it +declare const utils: { + readonly controllerDir: string; + getConfig(): string; -declare const adapter: ioBroker.Adapter; + // tslint:disable:unified-signatures + adapter(adapterName: string): ioBroker.Adapter; + adapter(adapterOptions: ioBroker.AdapterOptions): ioBroker.Adapter; + // tslint:enable:unified-signatures +}; -adapter.setState("not.a.state", true); +declare function assertNever(val: never): never; + +// Let the tests begin +let adapter: ioBroker.Adapter; + +// Test constructors +adapter = utils.adapter("my-adapter-name"); +adapter = utils.adapter({ + name: "my-adapter-name" +}); +adapter = utils.adapter({ + name: "my-adapter-name", + ready: readyHandler, + stateChange: stateChangeHandler, + objectChange: objectChangeHandler, + message: messageHandler, + unload: unloadHandler, +}); + +// Test EventEmitter definitions +adapter + .on("ready", readyHandler) + .on("stateChange", stateChangeHandler) + .on("objectChange", objectChangeHandler) + .on("message", messageHandler) + .on("unload", unloadHandler) + ; +adapter + .removeListener("ready", readyHandler) + .removeListener("stateChange", stateChangeHandler) + .removeListener("objectChange", objectChangeHandler) + .removeListener("message", messageHandler) + .removeListener("unload", unloadHandler) + ; +adapter.removeAllListeners(); + +function readyHandler() { } + +function stateChangeHandler(id: string, state: ioBroker.State | null | undefined) { + // Test State properties + if (state) { + state.ack; + state.c && state.c.toLowerCase(); + state.expire && state.expire.toFixed(); + state.from.toLowerCase(); + state.lc.toFixed(); + state.q && state.q.toFixed(); + state.ts.toFixed(); + state.val; + } +} + +function objectChangeHandler(id: string, object: ioBroker.Object | null | undefined) { + // Test properties of all objects + if (object) { + object._id.toLowerCase(); + object.common.name.toLowerCase(); + object.common.role && object.common.role.toLowerCase(); + object.common.icon && object.common.icon.toLowerCase(); + object.native.toString(); + object.enums && object.enums.toString(); + if (object.acl) { + object.acl.object.toFixed(); + object.acl.owner.toLowerCase(); + object.acl.ownerGroup.toLowerCase(); + } + // Test different object kinds + switch (object.type) { + case "adapter": + case "config": + case "enum": + case "group": + case "host": + case "info": + case "instance": + case "meta": + case "script": + case "user": + // nothing special here, update these tests when we have specialized definitions + break; + + case "state": + if (object.acl) object.acl.state.toFixed(); + object.common.def; + object.common.desc && object.common.desc.toLowerCase(); + object.common.history; + object.common.max && object.common.max.toFixed(); + object.common.min && object.common.min.toFixed(); + object.common.read.valueOf(); + object.common.states && object.common.states.toString(); + object.common.type && object.common.type.toLowerCase(); + object.common.unit && object.common.unit.toLowerCase(); + object.common.workingID && object.common.workingID.toLowerCase(); + object.common.write.valueOf(); + break; + + case "channel": + object.common.desc && object.common.desc.toLowerCase(); + break; + + case "device": + // nothing special here, update these tests when we have specialized definitions + break; + } + } +} + +function messageHandler(msg: ioBroker.Message) { + msg._id.toFixed(); + msg.callback.ack.valueOf(); + msg.callback.id.toFixed(); + msg.callback.message.toString(); + msg.callback.time.toFixed(); + msg.command.toLowerCase(); + msg.from.toLowerCase(); + msg.message.toString(); +} + +function unloadHandler(callback: ioBroker.EmptyCallback) { + adapter.log.info("shutting down"); + callback(); +} + +// Test the most important methods +adapter.setState("state.name", "value"); +adapter.setState("state.name", "value", true); +adapter.setState("state.name", "value", (err, id) => { }); +adapter.setState("state.name", { val: "value", ack: true }); +adapter.setState("state.name", { val: "value", ack: true }, (err, id) => { }); + +adapter.setStateChanged("state.name", "value"); +adapter.setStateChanged("state.name", "value", true); +adapter.setStateChanged("state.name", "value", (err, id) => { }); +adapter.setStateChanged("state.name", { val: "value", ack: true }); +adapter.setStateChanged("state.name", { val: "value", ack: true }, (err, id) => { }); + +adapter.setForeignState("state.name", "value"); +adapter.setForeignState("state.name", "value", true); +adapter.setForeignState("state.name", "value", (err, id) => { }); +adapter.setForeignState("state.name", { val: "value", ack: true }); +adapter.setForeignState("state.name", { val: "value", ack: true }, (err, id) => { }); + +adapter.setForeignStateChanged("state.name", "value"); +adapter.setForeignStateChanged("state.name", "value", true); +adapter.setForeignStateChanged("state.name", "value", (err, id) => { }); +adapter.setForeignStateChanged("state.name", { val: "value", ack: true }); +adapter.setForeignStateChanged("state.name", { val: "value", ack: true }, (err, id) => { }); + +adapter.setObject("obj.id", { type: "state", common: { name: "foo" }, native: {} }); +adapter.setObject("obj.id", { type: "state", common: { name: "foo" }, native: {} }, (err, id) => { }); +adapter.setForeignObject("obj.id", { type: "state", common: { name: "foo" }, native: {} }); +adapter.setForeignObject("obj.id", { type: "state", common: { name: "foo" }, native: {} }, (err, id) => { }); + +adapter.setObjectNotExists("obj.id", { type: "state", common: { name: "foo" }, native: {} }); +adapter.setObjectNotExists("obj.id", { type: "state", common: { name: "foo" }, native: {} }, (err, id) => { }); +adapter.setForeignObjectNotExists("obj.id", { type: "state", common: { name: "foo" }, native: {} }); +adapter.setForeignObjectNotExists("obj.id", { type: "state", common: { name: "foo" }, native: {} }, (err, id) => { }); + +adapter.getObject("obj.id", (err, obj) => { }); +adapter.getForeignObject("obj.id", (err, obj) => { }); + +adapter.subscribeObjects("*"); +adapter.subscribeStates("*"); +adapter.subscribeForeignObjects("*"); +adapter.subscribeForeignStates("*"); +adapter.unsubscribeObjects("*"); +adapter.unsubscribeStates("*"); +adapter.unsubscribeForeignObjects("*"); +adapter.unsubscribeForeignStates("*"); + +adapter.log.info("msg"); +adapter.log.debug("msg"); +adapter.log.warn("msg"); +adapter.log.error("msg"); +adapter.log.silly("msg"); + +switch (adapter.log.level) { + case "debug": + case "error": + case "info": + case "silly": + case "warn": + break; + default: + assertNever(adapter.log.level); +} From e6ad7248578be028804e73688a6348fadca31b77 Mon Sep 17 00:00:00 2001 From: Yaroslav Date: Sun, 25 Nov 2018 18:41:50 +0300 Subject: [PATCH 280/836] tus-js-client: fix fingerprint type --- types/tus-js-client/index.d.ts | 2 +- types/tus-js-client/tus-js-client-tests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/tus-js-client/index.d.ts b/types/tus-js-client/index.d.ts index defb27fea0..4cbb34a818 100644 --- a/types/tus-js-client/index.d.ts +++ b/types/tus-js-client/index.d.ts @@ -6,7 +6,7 @@ export interface UploadOptions { endpoint: string; - fingerprint?: string; + fingerprint?: (file: File, options?: UploadOptions) => string; resume?: boolean; metadata?: { [key: string]: string }; onProgress?: ((bytesSent: number, bytesTotal: number) => void) | null; diff --git a/types/tus-js-client/tus-js-client-tests.ts b/types/tus-js-client/tus-js-client-tests.ts index a13d9da12f..237f1df233 100644 --- a/types/tus-js-client/tus-js-client-tests.ts +++ b/types/tus-js-client/tus-js-client-tests.ts @@ -10,7 +10,7 @@ const file = new File(["foo"], "foo.txt", { const upload = new Tus.Upload(file, { endpoint: "", - fingerprint: "fingerprint", + fingerprint: (file: File) => file.name, resume: true, metadata: { filename: "foo.txt" From 715d23525775a2625e052b50b92e0068e2a40d2b Mon Sep 17 00:00:00 2001 From: Brian Date: Sun, 25 Nov 2018 11:04:43 -0600 Subject: [PATCH 281/836] Added beforeSave and afterSave to hook definitions --- types/sequelize/index.d.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index 88ed87efae..f25aacc3e4 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -2295,8 +2295,8 @@ declare namespace sequelize { * interfaces. * * beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, - * beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestroy and - * afterBulkUpdate. + * beforeDestroy, beforeSave, beforeUpdate, afterCreate, afterDestroy, afterSave, afterUpdate, afterBulkCreate, + * afterBulkDestroy and afterBulkUpdate. */ interface HooksDefineOptions { @@ -2310,6 +2310,8 @@ declare namespace sequelize { afterDelete?: (instance: TInstance, options: Object, fn?: Function) => any; beforeUpdate?: (instance: TInstance, options: Object, fn?: Function) => any; afterUpdate?: (instance: TInstance, options: Object, fn?: Function) => any; + beforeSave?: (instance: TInstance, options: Object, fn?: Function) => any; + afterSave?: (instance: TInstance, options: Object, fn?: Function) => any; beforeBulkCreate?: (instances: TInstance[], options: Object, fn?: Function) => any; afterBulkCreate?: (instances: TInstance[], options: Object, fn?: Function) => any; beforeBulkDestroy?: (options: Object, fn?: Function) => any; @@ -5272,9 +5274,10 @@ declare namespace sequelize { /** * An object of hook function that are called before and after certain lifecycle events. * The possible hooks are: beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, - * beforeBulkUpdate, beforeCreate, beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, - * afterBulkCreate, afterBulkDestory and afterBulkUpdate. See Hooks for more information about hook - * functions and their signatures. Each property can either be a function, or an array of functions. + * beforeBulkUpdate, beforeCreate, beforeDestroy, beforeSave, beforeUpdate, afterCreate, afterDestroy, + * afterSave, afterUpdate, afterBulkCreate, afterBulkDestory and afterBulkUpdate. + * See Hooks for more information about hook functions and their signatures. Each property can either + * be a function, or an array of functions. */ hooks?: HooksDefineOptions; From 839378616bfdf97838212e7f5443d9d4775a21c7 Mon Sep 17 00:00:00 2001 From: Yves Kaufmann Date: Sun, 25 Nov 2018 18:57:36 +0100 Subject: [PATCH 282/836] remove double block comments --- types/mongodb/index.d.ts | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index e516e4d31f..b31a8dd7b9 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -261,11 +261,11 @@ export interface MongoClientOptions extends /** * The name of the application that created this MongoClient instance. */ - appname?: string; + appname?: string; - /** - * Authentifikation credentials - */ + /** + * Authentifikation credentials + */ auth?: { /** * The username for auth @@ -280,7 +280,7 @@ export interface MongoClientOptions extends /** * Determines whether or not to use the new url parser */ - useNewUrlParser?: boolean; + useNewUrlParser?: boolean; /** * Mechanism for authentication: DEFAULT, GSSAPI, PLAIN, MONGODB-X509, 'MONGODB-CR', SCRAM-SHA-1 or SCRAM-SHA-256 @@ -428,12 +428,12 @@ export interface DbCreateOptions extends CommonOptions { * ES6 compatible promise constructor */ promiseLibrary?: Object; - /** https://docs.mongodb.com/manual/reference/read-concern/#read-concern */ + /** + * https://docs.mongodb.com/manual/reference/read-concern/#read-concern + **/ readConcern?: ReadConcern; /** * Sets a cap on how many operations the driver will buffer up before giving up on getting a - */ - /** * working connection, default is -1 which is unlimited. */ bufferMaxEntries?: number; @@ -463,11 +463,8 @@ export interface SocketOptions { connectTimeoutMS?: number; /** * Version of IP stack. Can be 4, 6 or null. default: null. - */ - /** + * * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - */ - /** * refer to http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html */ family?: 4 | 6 | null; @@ -514,9 +511,9 @@ export interface MongosOptions extends SSLOptions, HighAvailabilityOptions { */ acceptableLatencyMS?: number; - /** - * Socket Options - */ + /** + * Socket Options + */ socketOptions?: SocketOptions; } From 43a1c3ef84dbfbe230c5386bb7a5d395d0562774 Mon Sep 17 00:00:00 2001 From: erikma Date: Sun, 25 Nov 2018 12:29:13 -0800 Subject: [PATCH 283/836] Update pigpio types to include changes up to version 1.2.0 --- types/pigpio/index.d.ts | 28 ++++++++++++++++++++++++++-- types/pigpio/pigpio-tests.ts | 9 +++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/types/pigpio/index.d.ts b/types/pigpio/index.d.ts index 79d0ebe0f9..1bc901f084 100644 --- a/types/pigpio/index.d.ts +++ b/types/pigpio/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for pigpio 0.4 +// Type definitions for pigpio 1.2 // Project: https://github.com/fivdi/pigpio -// Definitions by: ManerFan +// Definitions by: ManerFan and erikma // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -424,3 +424,27 @@ export function configureClock(microseconds: number, peripheral: number): void; * @param port an unsigned integer specifying the pigpio socket port number */ export function configureSocketPort(port: number): void; + +/** + * Returns the Raspberry Pi hardware revision as an unsigned integer. Returns 0 + * if the hardware revision can not be determined. + */ +export function hardwareRevision(): number; + +/** + * Gets the current unsigned 32-bit integer value of the number of microseconds + * since system boot. This value wraps around the 32-bit space in just over an hour. + * Use tickDiff() to get the difference between two tick values, to + * ensure the correct JavaScript operations are used to account for the possibility + * of overflow. + */ +export function getTick(): number; + +/** + * Returns the difference in microseconds between the end and start tick counts. + * The tick counts can be retrieved using getTick(), or may be passed + * in a GPIO event callback. + * @param startTick The start of the measured interval. An unsigned integer tick value. + * @param endTick The end of the measured interval. An unsigned integer tick value. + */ +export function tickDiff(startTick: number, endTick: number): number; diff --git a/types/pigpio/pigpio-tests.ts b/types/pigpio/pigpio-tests.ts index 90e7d4485d..f756058b03 100644 --- a/types/pigpio/pigpio-tests.ts +++ b/types/pigpio/pigpio-tests.ts @@ -880,6 +880,15 @@ import * as assert from 'assert'; }, 2000); })(); +(function tickAndTickDiff(): void { + const startTick: number = pigpio.getTick(); + setTimeout(() => { + const endTick: number = pigpio.getTick(); + const diff: number = pigpio.tickDiff(startTick, endTick); + assert.ok(diff > 0, 'expected tick count to increase across a timer call'); + }, 50); +})(); + (function gpio_glitch_filter(): void { const Gpio = pigpio.Gpio; const input = new Gpio(7, { From 3465be17ba8e9ec2628e3bfae2d5b67cdd1955ac Mon Sep 17 00:00:00 2001 From: erikma Date: Sun, 25 Nov 2018 12:35:43 -0800 Subject: [PATCH 284/836] fix lint issue --- types/pigpio/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/pigpio/index.d.ts b/types/pigpio/index.d.ts index 1bc901f084..8eaa6491bb 100644 --- a/types/pigpio/index.d.ts +++ b/types/pigpio/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for pigpio 1.2 // Project: https://github.com/fivdi/pigpio -// Definitions by: ManerFan and erikma +// Definitions by: ManerFan , erikma // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// From 7416fd03c44b5a4d9e9ce6eb5bd4418d754adac0 Mon Sep 17 00:00:00 2001 From: Florian Dreschner Date: Sun, 25 Nov 2018 21:42:31 +0100 Subject: [PATCH 285/836] Add encrypt and decrypt to Pubnub types --- types/pubnub/index.d.ts | 22 +++++++++++++++++++++- types/pubnub/pubnub-tests.ts | 12 ++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 8337acfbe4..1fc38edabf 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for pubnub 4.0 // Project: https://github.com/pubnub/javascript -// Definitions by: bitbankinc , rollymaduk , vitosamson +// Definitions by: bitbankinc , rollymaduk , vitosamson , FlorianDr // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @see https://www.pubnub.com/docs/web-javascript/api-reference-configuration @@ -88,6 +88,18 @@ declare class Pubnub { setState( params: Pubnub.SetStateParameters ): Promise; + + encrypt( + data: string, + customCipherKey?: string, + options?: Pubnub.CryptoParameters, + ): object | string | null; + + decrypt( + data: object, + customCipherKey?: string, + options?: Pubnub.CryptoParameters + ): object | string | null; } declare namespace Pubnub { @@ -296,6 +308,14 @@ declare namespace Pubnub { }; } + // encrypt + interface CryptoParameters { + encryptKey?: boolean; + keyEncoding?: string; + keyLength?: number; + mode?: string; + } + interface Categories { PNNetworkUpCategory: string; PNNetworkDownCategory: string; diff --git a/types/pubnub/pubnub-tests.ts b/types/pubnub/pubnub-tests.ts index 1d8b2bb1ca..50660bd942 100644 --- a/types/pubnub/pubnub-tests.ts +++ b/types/pubnub/pubnub-tests.ts @@ -86,3 +86,15 @@ pubnub.setState({ channels: [] }, (status, res) => { pubnub.setState({ channels: [] }).then(res => { console.log(res.state); }); + +const cryptoOptions = { + encryptKey: true, + keyEncoding: 'utf8', + keyLength: 256, + mode: 'cbc' +}; +const mySecret = { + message: 'Hi!', +}; +pubnub.decrypt(mySecret, undefined, cryptoOptions); +pubnub.encrypt('egrah5rwgrehwqh5eh3hwfwef', undefined, cryptoOptions); From 147d828b80b191986af9e796d635e0cef3fdae14 Mon Sep 17 00:00:00 2001 From: Florian Dreschner Date: Sun, 25 Nov 2018 21:44:14 +0100 Subject: [PATCH 286/836] Add comment for decrypt parameters --- types/pubnub/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 1fc38edabf..0b5f75901c 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -308,7 +308,7 @@ declare namespace Pubnub { }; } - // encrypt + // encrypt & decrypt interface CryptoParameters { encryptKey?: boolean; keyEncoding?: string; From 44ef75a9066b67df3e76d93f12bff05a408e7137 Mon Sep 17 00:00:00 2001 From: Florian Dreschner Date: Sun, 25 Nov 2018 21:58:23 +0100 Subject: [PATCH 287/836] Add version note under header --- types/pubnub/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 0b5f75901c..7e148bc4c4 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: bitbankinc , rollymaduk , vitosamson , FlorianDr // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @see https://www.pubnub.com/docs/web-javascript/api-reference-configuration +// TypeScript Version: 2.2 declare class Pubnub { constructor(config: Pubnub.PubnubConfig); From 620ad409303126f5066dc1dda42ec23ce0bf2f4f Mon Sep 17 00:00:00 2001 From: Karol Samborski Date: Sun, 25 Nov 2018 22:50:42 +0100 Subject: [PATCH 288/836] Type definitions for multiSamlStrategy --- types/passport-saml/index.d.ts | 1 + types/passport-saml/passport-saml-tests.ts | 25 ++++++++++++++++++++++ types/passport-saml/tsconfig.json | 3 ++- 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/types/passport-saml/index.d.ts b/types/passport-saml/index.d.ts index cc2faafe5c..9338b88deb 100644 --- a/types/passport-saml/index.d.ts +++ b/types/passport-saml/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/bergie/passport-saml // Definitions by: Chris Barth // Damian Assennato +// Karol Samborski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/passport-saml/passport-saml-tests.ts b/types/passport-saml/passport-saml-tests.ts index 615c1b7320..b22421fe81 100644 --- a/types/passport-saml/passport-saml-tests.ts +++ b/types/passport-saml/passport-saml-tests.ts @@ -1,6 +1,7 @@ import express = require('express'); import passport = require('passport'); import SamlStrategy = require('passport-saml'); +import MultiSamlStrategy = require('passport-saml/multiSamlStrategy'); import fs = require('fs'); const samlStrategy = new SamlStrategy.Strategy( @@ -33,3 +34,27 @@ passport.use(samlStrategy); passport.authenticate('samlCustomName', {failureRedirect: '/', failureFlash: true}); const metadata = samlStrategy.generateServiceProviderMetadata("decryptionCert"); + +const multiSamlStrategy = new MultiSamlStrategy.MultiSamlStrategy( + { + name: 'samlCustomName', + path: '/login/callback', + entryPoint: 'https://openidp.feide.no/simplesaml/saml2/idp/SSOService.php', + issuer: 'passport-saml', + getSamlOptions(req: express.Request, callback: (err: Error | null, samlOptions: SamlStrategy.SamlConfig) => void) { + callback(null, { + name: 'samlCustomName', + path: '/login/callback2', + entryPoint: 'https://openidp.feide.no/simplesaml/saml2/idp/SSOService.php', + issuer: 'passport-saml', + }); + } + }, + (profile: {}, done: (err: Error | null, user: {}, info?: {}) => void) => { + const user = {}; + done(null, user); + } +); + +passport.use(multiSamlStrategy); +passport.authenticate('samlCustomName', {failureRedirect: '/', failureFlash: true}); diff --git a/types/passport-saml/tsconfig.json b/types/passport-saml/tsconfig.json index 0809dbbaf7..39283fa663 100644 --- a/types/passport-saml/tsconfig.json +++ b/types/passport-saml/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "multiSamlStrategy.d.ts", "passport-saml-tests.ts" ] -} \ No newline at end of file +} From 58db065b6e539e777e8f0b9726fd187297651621 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Alvergnat?= Date: Thu, 22 Nov 2018 22:54:38 +0100 Subject: [PATCH 289/836] Add types for deprecate --- types/deprecate/deprecate-tests.ts | 9 ++++++++ types/deprecate/index.d.ts | 33 ++++++++++++++++++++++++++++++ types/deprecate/tsconfig.json | 23 +++++++++++++++++++++ types/deprecate/tslint.json | 3 +++ 4 files changed, 68 insertions(+) create mode 100644 types/deprecate/deprecate-tests.ts create mode 100644 types/deprecate/index.d.ts create mode 100644 types/deprecate/tsconfig.json create mode 100644 types/deprecate/tslint.json diff --git a/types/deprecate/deprecate-tests.ts b/types/deprecate/deprecate-tests.ts new file mode 100644 index 0000000000..3df2257c40 --- /dev/null +++ b/types/deprecate/deprecate-tests.ts @@ -0,0 +1,9 @@ +import deprecate = require('deprecate'); + +deprecate('someMethod'); +deprecate('someMethod', 'This is deprecated'); +deprecate('someMethod', 'This is deprecated', 'foo', 'bar'); + +deprecate.color = '\x1b[31;1m'; +deprecate.silence = true; +deprecate.stream = process.stderr; diff --git a/types/deprecate/index.d.ts b/types/deprecate/index.d.ts new file mode 100644 index 0000000000..a053721ff5 --- /dev/null +++ b/types/deprecate/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for deprecate 1.1 +// Project: https://github.com/brianc/node-deprecate +// Definitions by: Toilal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +declare namespace deprecate { + /** + * Set to false to not output a color. Defaults to '\x1b[31;1m' which is red. + */ + let color: string; + + /** + * Set to false to do nothing at all when the deprecate method is called. Useful in tests of the library you're deprecating things within. + */ + let silence: boolean; + + /** + * The stream to which output is written. Defaults to process.stderr + */ + let stream: NodeJS.WriteStream; +} + +/** + * Call deprecate within a function you are deprecating. + * + * It will spit out all the messages to the console the first time and only the first time the method is called. + */ +declare function deprecate(methodName: string, ...message: string[]): void; + +export = deprecate; diff --git a/types/deprecate/tsconfig.json b/types/deprecate/tsconfig.json new file mode 100644 index 0000000000..75acd6cda6 --- /dev/null +++ b/types/deprecate/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", + "deprecate-tests.ts" + ] +} diff --git a/types/deprecate/tslint.json b/types/deprecate/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/deprecate/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 6ffa94cda5b88a9cdefeb8a680c591e8e0c27439 Mon Sep 17 00:00:00 2001 From: Larry Gadea Date: Sun, 25 Nov 2018 20:36:20 -0500 Subject: [PATCH 290/836] [puppeteer] fix v1.10.0 definition of waitForTarget hello! i'm using the fancy new waitForTarget and the definition appears to be slightly off. `options` is optional and the return is a `Target` Promise, not `void`. looking at the `BrowserContext` version, it's the same problem due to the new `Timeoutable` changes made in this recent version. i changed the one definition locally and the world did not seem to explode. i'm using Github's nasty PR generator, let me know if you'd prefer i edit this with the template. thanks! --- types/puppeteer/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index bfd14d9c35..cbb31f2fd0 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1715,7 +1715,7 @@ export interface Page extends EventEmitter, FrameBase { } export interface TargetAwaiter { - waitForTarget(predicate: (target: Target) => boolean, options: Timeoutable): Promise; + waitForTarget(predicate: (target: Target) => boolean, options?: Timeoutable): Promise; } /** A Browser is created when Puppeteer connects to a Chromium instance, either through puppeteer.launch or puppeteer.connect. */ From cc95a58bf19a53762240bcdabf1ac18c040a5904 Mon Sep 17 00:00:00 2001 From: Karol Samborski Date: Mon, 26 Nov 2018 07:13:25 +0100 Subject: [PATCH 291/836] Missing file --- types/passport-saml/multiSamlStrategy.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 types/passport-saml/multiSamlStrategy.d.ts diff --git a/types/passport-saml/multiSamlStrategy.d.ts b/types/passport-saml/multiSamlStrategy.d.ts new file mode 100644 index 0000000000..405c7264dc --- /dev/null +++ b/types/passport-saml/multiSamlStrategy.d.ts @@ -0,0 +1,10 @@ +import express = require('express'); +import { Strategy, SamlConfig, VerifyWithRequest, VerifyWithoutRequest } from './index'; + +export interface MultiSamlConfig extends SamlConfig { + getSamlOptions(req: express.Request, callback: (err: Error | null, samlOptions: SamlConfig) => void): void; +} + +export class MultiSamlStrategy extends Strategy { + constructor(config: MultiSamlConfig, verify: VerifyWithRequest | VerifyWithoutRequest); +} From bcd33769d53c79fc0840b4e8900e08d1cf22d878 Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Mon, 26 Nov 2018 15:43:36 +0900 Subject: [PATCH 292/836] Fix abuse of generic type --- types/vfile/index.d.ts | 24 ++++++++++-------------- types/vfile/vfile-tests.ts | 17 +++++++++++++---- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/types/vfile/index.d.ts b/types/vfile/index.d.ts index 2ef3b03f19..792644dacc 100644 --- a/types/vfile/index.d.ts +++ b/types/vfile/index.d.ts @@ -10,26 +10,25 @@ import * as Unist from 'unist'; declare namespace vfile { - type Contents = string | Buffer; + type VFileContents = string | Buffer; interface NodeWithPosition extends Unist.Node { position: Unist.Position; [key: string]: any; } - interface VFileParamsBase { - data?: D; - contents?: Contents; + interface VFileOptions { + contents?: VFileContents; path?: string; basename?: string; stem?: string; extname?: string; dirname?: string; cwd?: string; + data?: any; + [key: string]: any; } - type VFileParams = VFileParamsBase & C; - /** * File-related message describing something at certain position. */ @@ -102,12 +101,11 @@ declare namespace vfile { */ type ToString = (encoding?: BufferEncoding) => string; - interface VFileBase { + interface VFile { /** * @param options If `options` is `string` or `Buffer`, treats it as `{contents: options}`. If `options` is a `VFile`, returns it. All other options are set on the newly created `vfile`. */ - (input?: Contents): VFile; - (input?: VFile | VFileParams): VFile; + (input?: VFileContents | F | VFileOptions): F; message: Message; fail: Fail; info: Info; @@ -119,7 +117,7 @@ declare namespace vfile { * Place to store custom information. * It's OK to store custom data directly on the `vfile`, moving it to `data` gives a little more privacy. */ - data: C['data']; + data: any; /** * List of messages associated with the file. */ @@ -127,7 +125,7 @@ declare namespace vfile { /** * Raw value. */ - contents: Contents; + contents: VFileContents; /** * Path of `vfile`. * Cannot be nullified. @@ -161,8 +159,6 @@ declare namespace vfile { cwd: string; toString: ToString; } - - type VFile = VFileBase & C; } /** @@ -170,6 +166,6 @@ declare namespace vfile { * Path related properties are set in the following order (least specific to most specific): `history`, `path`, `basename`, `stem`, `extname`, `dirname`. * It’s not possible to set either `dirname` or `extname` without setting either `history`, `path`, `basename`, or `stem` as well. */ -declare const vfile: vfile.VFile<{}>; +declare const vfile: vfile.VFile; export = vfile; diff --git a/types/vfile/vfile-tests.ts b/types/vfile/vfile-tests.ts index 0b19246ae8..4d146237b1 100644 --- a/types/vfile/vfile-tests.ts +++ b/types/vfile/vfile-tests.ts @@ -1,4 +1,4 @@ -import vfile = require("vfile"); +import vfile = require('vfile'); import * as Unist from 'unist'; // Instantiation @@ -7,21 +7,30 @@ vfile('string'); vfile(Buffer.from('string')); vfile(vfile()); vfile({ stem: 'readme', extname: '.md' }); -vfile({ custom: 'data' }); try { vfile({ extname: '.md' }); } catch (e) { console.log('Error: set extname without path'); } -const file = vfile<{custom: string, data: {custom: number}}>({ +interface CustomVFile extends vfile.VFile { + custom: string; + data: { + custom: number; + }; +} + +const file = vfile({ path: '~/example.txt', contents: 'Alpha *braavo* charlie.', custom: 'Custom tango', data: { custom: 12345 - }, + } }); +const customIsString: string = file.custom; +const dataCustomIsNumber: number = file.data.custom; +const copiedFile: CustomVFile = vfile(file); file.path; // => '~/example.txt' file.dirname; // => '~' From 66d08e2f06fc28506c6d1a9e7fc86e524d43f0a3 Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Mon, 26 Nov 2018 15:44:03 +0900 Subject: [PATCH 293/836] Include instruction how to extend vfiles --- types/vfile/readme.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 types/vfile/readme.md diff --git a/types/vfile/readme.md b/types/vfile/readme.md new file mode 100644 index 0000000000..349503cef8 --- /dev/null +++ b/types/vfile/readme.md @@ -0,0 +1,32 @@ +## VFile typescript Docs + +Below are some examples of how to use these Definitions.
+Scenarios where the Typescript code is identical to plain Javascript code are omitted. + +### Extending VFile + +```ts +import vfile = require('vfile') + +// 1. Define extended vfile interface +interface CustomVFile extends vfile.VFile { + custom: string; + data: { + custom: number; + }; +} + +// 2. Provide the extended interface to generic type parameter +// So it can be used for return value +const file: CustomVFile = vfile({ + path: '~/example.txt', + contents: 'Alpha *braavo* charlie.', + custom: 'Custom tango', + data: { + custom: 12345 + } +}); + +// vfile recognize extended VFile values. So it will return same type. +const copiedFile: CustomVFile = vfile(file); +``` From f6a42a5032d678cfe4c210e72eb5da78107a2bd7 Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Mon, 26 Nov 2018 15:49:41 +0900 Subject: [PATCH 294/836] Update vfile version --- types/vfile/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/vfile/index.d.ts b/types/vfile/index.d.ts index 792644dacc..ce8f1dce38 100644 --- a/types/vfile/index.d.ts +++ b/types/vfile/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for VFile 2.2 +// Type definitions for VFile 3.0 // Project: https://github.com/vfile/vfile // Definitions by: bizen241 // Junyoung Choi From 3ac5fe40247b925b313457259f42b486130e8a0d Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Mon, 26 Nov 2018 15:51:15 +0900 Subject: [PATCH 295/836] Update vfile-location too because it is using vfile --- types/vfile-location/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/vfile-location/index.d.ts b/types/vfile-location/index.d.ts index e8ad37bc32..b991528c7e 100644 --- a/types/vfile-location/index.d.ts +++ b/types/vfile-location/index.d.ts @@ -1,12 +1,13 @@ // Type definitions for vfile-location 2.0 // Project: https://github.com/vfile/vfile-location // Definitions by: Ika +// Junyoung Choi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 import * as VFile from "vfile"; -declare function vfileLocation(vfile: string | VFile.VFile<{}>): vfileLocation.Location; +declare function vfileLocation(vfile: string | VFile.VFile): vfileLocation.Location; declare namespace vfileLocation { interface Location { From 264964b9a8676d3e81204914927fd81d1e439e6c Mon Sep 17 00:00:00 2001 From: obedm503 Date: Mon, 26 Nov 2018 01:10:58 -0600 Subject: [PATCH 296/836] Add `onError` prop to `IntlProvider` --- types/react-intl/index.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/react-intl/index.d.ts b/types/react-intl/index.d.ts index 17e738bb2a..a4cb8be9b5 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -9,6 +9,7 @@ // Krister Kari // Martin Raedlinger // Kanitkorn Sujautra +// obedm503 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -46,6 +47,7 @@ declare namespace ReactIntl { messages: React.Requireable; defaultLocale: React.Requireable; defaultFormats: React.Requireable; + onError?: (error: string) => void } interface IntlFormat { @@ -78,6 +80,7 @@ declare namespace ReactIntl { defaultLocale: string; defaultFormats: any; now(): number; + onError: (error: string) => void; } interface InjectedIntlProps { From a2f88a9bc1295aa2c58700065536ac055b58308a Mon Sep 17 00:00:00 2001 From: obedm503 Date: Mon, 26 Nov 2018 01:11:36 -0600 Subject: [PATCH 297/836] Add usage of `onError` prop --- types/react-intl/react-intl-tests.tsx | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/types/react-intl/react-intl-tests.tsx b/types/react-intl/react-intl-tests.tsx index b3b23bb38f..74da23a12a 100644 --- a/types/react-intl/react-intl-tests.tsx +++ b/types/react-intl/react-intl-tests.tsx @@ -401,7 +401,15 @@ class TestApp extends React.Component { hello: "Hello, {name}!" }; return ( - + console.error(error)} + > From 879ff2682e6118dcead7d40021087bbaa9b5bd3d Mon Sep 17 00:00:00 2001 From: obedm503 Date: Mon, 26 Nov 2018 01:19:58 -0600 Subject: [PATCH 298/836] Increase minor version --- types/react-intl/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-intl/index.d.ts b/types/react-intl/index.d.ts index a4cb8be9b5..3dc7e9dc59 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -11,7 +11,7 @@ // Kanitkorn Sujautra // obedm503 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 2.9 declare namespace ReactIntl { type DateSource = Date | string | number; From f69a5047986aed0669f04d8172cc5bbba2d6c4a8 Mon Sep 17 00:00:00 2001 From: obedm503 Date: Mon, 26 Nov 2018 01:36:23 -0600 Subject: [PATCH 299/836] cleanup and test --- types/react-intl/index.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/types/react-intl/index.d.ts b/types/react-intl/index.d.ts index 3dc7e9dc59..2c25a55b1f 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -47,7 +47,7 @@ declare namespace ReactIntl { messages: React.Requireable; defaultLocale: React.Requireable; defaultFormats: React.Requireable; - onError?: (error: string) => void + onError: React.Requireable; } interface IntlFormat { @@ -80,7 +80,7 @@ declare namespace ReactIntl { defaultLocale: string; defaultFormats: any; now(): number; - onError: (error: string) => void; + onError(error: string): void; } interface InjectedIntlProps { @@ -200,6 +200,7 @@ declare namespace ReactIntl { defaultFormats?: any; textComponent?: any; initialNow?: any; + onError?: (error: string) => void; } } From 4cfb90807578b054644d81453ca145b90df00c86 Mon Sep 17 00:00:00 2001 From: Alexandre Piel Date: Mon, 26 Nov 2018 09:14:35 +0100 Subject: [PATCH 300/836] make jest ProvidesCallback optinal --- types/jest/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 2b378a6048..d434b5e198 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -251,7 +251,7 @@ declare namespace jest { * @param fn The function for your test * @param timeout The timeout for an async function test */ - (name: string, fn: ProvidesCallback, timeout?: number): void; + (name: string, fn?: ProvidesCallback, timeout?: number): void; /** * Only runs this test in the current file. */ From 59bfd27bf6b5d17c6d9485d8d08b0db3e42add13 Mon Sep 17 00:00:00 2001 From: Jessica Date: Mon, 26 Nov 2018 19:09:42 +0900 Subject: [PATCH 301/836] Add support to the `css` prop from babel-plugin-styled-components --- types/styled-components/index.d.ts | 20 +++++++ types/styled-components/test/index.tsx | 74 +++++++++++++++++++++++--- 2 files changed, 88 insertions(+), 6 deletions(-) diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index a842c94c63..ee64b37772 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -436,4 +436,24 @@ export class StyleSheetManager extends React.Component< StyleSheetManagerProps > {} +export type CSSIntrinsicAttributeType = + | string + | CSSObject + | FlattenSimpleInterpolation + // Sad, but because this is global, there is no way to override it with the ThemedStyledComponentsModule + // Only augmenting DefaultTheme will work for inline css prop + | FlattenInterpolation>>; + export default styled; + +declare module "react" { + interface Attributes { + // NOTE: unlike the plain javascript version, it is not possible to get access + // to the element's own attributes inside function interpolations. + // Only theme will be accessible, and only with the DefaultTheme due to the global + // nature of this declaration. + // If you are writing this inline you already have access to all the attributes anyway, + // no need for the extra indirection. + css?: import(".").CSSIntrinsicAttributeType; // tslint:disable-line whitespace + } +} diff --git a/types/styled-components/test/index.tsx b/types/styled-components/test/index.tsx index e435d90011..c152ffd66e 100644 --- a/types/styled-components/test/index.tsx +++ b/types/styled-components/test/index.tsx @@ -172,7 +172,6 @@ const styledButton = styled.button` const name = "hey"; const ThemedMyButton = withTheme(MyButton); - ; /** @@ -290,7 +289,6 @@ const ObjectStylesBox = styled.div` fontSize: 2 }}; `; - ; /** @@ -322,7 +320,6 @@ const AttrsWithOnlyNewProps = styled.h2.attrs({ as: "h1" })` `; const AttrsInputExtra = styled(AttrsInput).attrs({ autoComplete: "off" })``; - ; /** @@ -419,10 +416,8 @@ const Component = (props: WithThemeProps) => ( ); const ComponentWithTheme = withTheme(Component); - ; // ok ; // ok - {theme => }; /** @@ -610,7 +605,6 @@ const divFnRef = (ref: HTMLDivElement | null) => { const divRef = React.createRef(); const StyledDiv = styled.div``; - ; ; ; // $ExpectError @@ -771,3 +765,71 @@ async function themeAugmentation() { ); } + +// NOTE: this is needed for some tests inside cssProp, +// but actually running this module augmentation will cause +// tests elsewhere to break, and there is no way to contain it. +// Uncomment out as needed to run tests. + +// declare module "styled-components" { +// interface DefaultTheme { +// background: string; +// } +// } + +function cssProp() { + function Custom(props: React.ComponentPropsWithoutRef<"div">) { + return
; + } + + return ( + <> +
+
+
+
+
"blue"}; + `} + /> +
{ + // This requires the DefaultTheme augmentation + // // $ExpectType string + // props.theme.background; + return props.theme.background; + }}; + `} + /> + + + + + "blue"}; + `} + /> + { + // This requires the DefaultTheme augmentation + // // $ExpectType string + // props.theme.background; + return props.theme.background; + }}; + `} + /> + + ); +} From 3fc77b020c5482986330cc606cddc0981052e784 Mon Sep 17 00:00:00 2001 From: Jessica Date: Mon, 26 Nov 2018 19:22:27 +0900 Subject: [PATCH 302/836] Fix the types in rebass__grid --- types/rebass__grid/index.d.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/types/rebass__grid/index.d.ts b/types/rebass__grid/index.d.ts index 079506e631..f49d43a6c6 100644 --- a/types/rebass__grid/index.d.ts +++ b/types/rebass__grid/index.d.ts @@ -10,7 +10,7 @@ export type Omit = Pick; import { ComponentType } from "react"; -import { StyledComponent, Interpolation } from "styled-components"; +import { StyledComponent, CSSIntrinsicAttributeType } from "styled-components"; export type ResponsiveProp = number | string | Array; @@ -34,7 +34,10 @@ export interface CommonProps { px?: ResponsiveProp; py?: ResponsiveProp; theme?: any; - css?: Interpolation; + /** + * NOTE: this is not compatible with the styled-components babel plugin anymore + */ + css?: CSSIntrinsicAttributeType; } export interface BoxProps From d3c9c35fc625641c4c95d54eef25a8c0d84e71a7 Mon Sep 17 00:00:00 2001 From: Mihkel Sokk Date: Mon, 26 Nov 2018 14:26:50 +0200 Subject: [PATCH 303/836] [ejs] renderFile returns Promise without callback, fixes #28934 --- types/ejs/ejs-tests.ts | 3 +++ types/ejs/index.d.ts | 2 ++ 2 files changed, 5 insertions(+) diff --git a/types/ejs/ejs-tests.ts b/types/ejs/ejs-tests.ts index 8a0b2404d7..881a3fe103 100644 --- a/types/ejs/ejs-tests.ts +++ b/types/ejs/ejs-tests.ts @@ -29,6 +29,9 @@ result = ejs.render(template, data, options); result = ejs.renderFile(fileName, SimpleCallback); result = ejs.renderFile(fileName, data, SimpleCallback); result = ejs.renderFile(fileName, data, options, SimpleCallback); +asyncResult = ejs.renderFile(fileName); +asyncResult = ejs.renderFile(fileName, data); +asyncResult = ejs.renderFile(fileName, data, options); ejsFunction = ejs.compile(''); ejsFunction = ejs.compile(read(fileName, "utf8")); diff --git a/types/ejs/index.d.ts b/types/ejs/index.d.ts index 73eb716e23..fc578cffff 100644 --- a/types/ejs/index.d.ts +++ b/types/ejs/index.d.ts @@ -54,6 +54,8 @@ export type RenderFileCallback = (err: Error, str?: string) => T; export function renderFile(path: string, cb: RenderFileCallback): T; export function renderFile(path: string, data: Data, cb: RenderFileCallback): T; export function renderFile(path: string, data: Data, opts: Options, cb: RenderFileCallback): T; +// tslint:disable-next-line no-unnecessary-generics +export function renderFile(path: string, data?: Data, opts?: Options): Promise; /** * Clear intermediate JavaScript cache. Calls {@link Cache#reset}. From a941c86b563f56f65e6038c6f35debe28fba2514 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Ba=C4=8D=C3=ADk?= Date: Mon, 26 Nov 2018 14:57:35 +0100 Subject: [PATCH 304/836] Added RN Image width and height props --- types/react-native/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 2386fc71c2..112abe79a9 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -3629,6 +3629,12 @@ interface ImagePropsAndroid { * Duration of fade in animation. */ fadeDuration?: number; + + /** + * Required sizes if using native image resources on Android + */ + width?: number; + height?: number; } /** From 18d0d101f1c388ce03b6f815337e195fd92fd1d8 Mon Sep 17 00:00:00 2001 From: Kai Dorschner Date: Mon, 26 Nov 2018 15:05:20 +0100 Subject: [PATCH 305/836] Add missing inputIconPosition to type definition. see http://airbnb.io/react-dates/?selectedKind=DRP%20-%20Input%20Props&selectedStory=with%20show%20calendar%20icon%20after%20input&full=0&addons=1&stories=1&panelRight=0&addonPanel=storybook%2Factions%2Factions-panel --- types/react-dates/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react-dates/index.d.ts b/types/react-dates/index.d.ts index 05058b2ca9..9e96538f7d 100644 --- a/types/react-dates/index.d.ts +++ b/types/react-dates/index.d.ts @@ -55,6 +55,7 @@ declare namespace ReactDates { screenReaderInputMessage?: string, showClearDates?: boolean, showDefaultInputIcon?: boolean, + inputIconPosition?: IconPositionShape, customInputIcon?: string | JSX.Element, customArrowIcon?: string | JSX.Element, customCloseIcon?: string | JSX.Element, From 9d01bdd867de647f6469fd6e5e830295e8585c65 Mon Sep 17 00:00:00 2001 From: John Plusje Date: Mon, 26 Nov 2018 15:24:11 +0100 Subject: [PATCH 306/836] Add declarations for stoppable 1.1 --- types/stoppable/index.d.ts | 9 +++++++-- types/stoppable/stoppable-tests.ts | 11 +++++++---- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/types/stoppable/index.d.ts b/types/stoppable/index.d.ts index 395dd828c8..b15444c7ba 100644 --- a/types/stoppable/index.d.ts +++ b/types/stoppable/index.d.ts @@ -1,11 +1,16 @@ -// Type definitions for stoppable 1.0 +// Type definitions for stoppable 1.1 // Project: https://github.com/hunterloftis/stoppable // Definitions by: Eric Byers +// John Plusjé // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// import { Server } from 'http'; -declare function stoppable(server: Server, grace?: number): Server; +interface StoppableServer extends Server { + stop(callback?: (e: Error, gracefully: boolean) => void): void; +} + +declare function stoppable(server: Server, grace?: number): StoppableServer; export = stoppable; diff --git a/types/stoppable/stoppable-tests.ts b/types/stoppable/stoppable-tests.ts index 84cf826bef..89ebf64f6d 100644 --- a/types/stoppable/stoppable-tests.ts +++ b/types/stoppable/stoppable-tests.ts @@ -1,8 +1,11 @@ import * as http from 'http'; import stoppable = require('stoppable'); -const server: http.Server = stoppable(http.createServer()); -server.close(); +const server = stoppable(http.createServer()); +server.stop(); -const server2: http.Server = stoppable(http.createServer(), 10000); -server2.close(); +const server2 = stoppable(http.createServer(), 10000); +server2.stop(); + +const server3 = stoppable(http.createServer()); +server.stop((err, gracefully) => {}); From ce71e7bb557834aa38e36ed35903d80cb35bb4cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Ba=C4=8D=C3=ADk?= Date: Mon, 26 Nov 2018 15:40:11 +0100 Subject: [PATCH 307/836] Removed whitespace --- types/react-native/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 112abe79a9..15423558e4 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -3629,7 +3629,7 @@ interface ImagePropsAndroid { * Duration of fade in animation. */ fadeDuration?: number; - + /** * Required sizes if using native image resources on Android */ From f26696ad1980206be1efc54f1f407b067801a5a7 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Mon, 26 Nov 2018 15:32:07 +0100 Subject: [PATCH 308/836] add typings for open-apifactory --- types/openapi-factory/index.d.ts | 49 +++++++++++++++++++ .../openapi-factory/openapi-factory-tests.ts | 25 ++++++++++ types/openapi-factory/tsconfig.json | 23 +++++++++ types/openapi-factory/tslint.json | 3 ++ 4 files changed, 100 insertions(+) create mode 100644 types/openapi-factory/index.d.ts create mode 100644 types/openapi-factory/openapi-factory-tests.ts create mode 100644 types/openapi-factory/tsconfig.json create mode 100644 types/openapi-factory/tslint.json diff --git a/types/openapi-factory/index.d.ts b/types/openapi-factory/index.d.ts new file mode 100644 index 0000000000..6cb22f7194 --- /dev/null +++ b/types/openapi-factory/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for openapi-factory 4.2 +// Project: https://github.com/wparad/openapi-factory.js +// Definitions by: Daan Boerlage +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare namespace OpenApi { + interface OpenApiOptions { + requestMiddleware?: () => any; + responseMiddleware?: () => any; + errorMiddleware?: () => any; + } +} + +declare class OpenApi { + constructor(options: OpenApi.OpenApiOptions, overrideLogger?: () => void); + + setAuthorizer(authorizerFunc: (req?: any) => any): void; + onEvent(onEventFunc: (req?: any) => any): void; + onSchedule(onScheduleFunc: (req?: any) => any): void; + + head(route: string, p0: (req?: any) => any): void; + head(route: string, p0: object, p1: (req?: any) => any): void; + + get(route: string, p0: (req?: any) => any): void; + get(route: string, p0: object, p1: (req?: any) => any): void; + + post(route: string, p0: (req?: any) => any): void; + post(route: string, p0: object, p1: (req?: any) => any): void; + + put(route: string, p0: (req?: any) => any): void; + put(route: string, p0: object, p1: (req?: any) => any): void; + + patch(route: string, p0: (req?: any) => any): void; + patch(route: string, p0: object, p1: (req?: any) => any): void; + + delete(route: string, p0: (req?: any) => any): void; + delete(route: string, p0: object, p1: (req?: any) => any): void; + + options(route: string, p0: (req?: any) => any): void; + options(route: string, p0: object, p1: (req?: any) => any): void; + + any(route: string, p0: (req?: any) => any): void; + any(route: string, p0: object, p1: (req?: any) => any): void; + + handler(event: object, context: object): Promise; +} + +export = OpenApi; diff --git a/types/openapi-factory/openapi-factory-tests.ts b/types/openapi-factory/openapi-factory-tests.ts new file mode 100644 index 0000000000..13e1e0e7cc --- /dev/null +++ b/types/openapi-factory/openapi-factory-tests.ts @@ -0,0 +1,25 @@ +import * as OpenApiFactory from 'openapi-factory'; + +const api = new OpenApiFactory({}); + +api.setAuthorizer((req: any) => req); +api.onEvent((req: any) => req); +api.onSchedule((req: any) => req); + +api.head('/v1/test', () => 'success'); +api.get('/v1/test', () => 'success'); +api.post('/v1/test', () => 'success'); +api.put('/v1/test', () => 'success'); +api.patch('/v1/test', () => 'success'); +api.delete('/v1/test', () => 'success'); +api.options('/v1/test', () => 'success'); +api.any('/v1/test2', () => 'success'); + +api.head('/v2/test', {test: true}, () => 'success'); +api.get('/v2/test', {test: true}, () => 'success'); +api.post('/v2/test', {test: true}, () => 'success'); +api.put('/v2/test', {test: true}, () => 'success'); +api.patch('/v2/test', {test: true}, () => 'success'); +api.delete('/v2/test', {test: true}, () => 'success'); +api.options('/v2/test', {test: true}, () => 'success'); +api.any('/v2/test2', {test: true}, () => 'success'); diff --git a/types/openapi-factory/tsconfig.json b/types/openapi-factory/tsconfig.json new file mode 100644 index 0000000000..e8528e8e84 --- /dev/null +++ b/types/openapi-factory/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "openapi-factory-tests.ts" + ] +} diff --git a/types/openapi-factory/tslint.json b/types/openapi-factory/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/openapi-factory/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From f675d110aae80c33bdc289624c85052a2a1dc858 Mon Sep 17 00:00:00 2001 From: Florian Dreschner Date: Mon, 26 Nov 2018 16:16:36 +0100 Subject: [PATCH 309/836] Change crypto payload to any --- types/pubnub/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 7e148bc4c4..257ca3cd44 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -94,13 +94,13 @@ declare class Pubnub { data: string, customCipherKey?: string, options?: Pubnub.CryptoParameters, - ): object | string | null; + ): any; decrypt( data: object, customCipherKey?: string, options?: Pubnub.CryptoParameters - ): object | string | null; + ): any; } declare namespace Pubnub { From 5a89441def4da6974049400ae5733aa398400db4 Mon Sep 17 00:00:00 2001 From: juwar Date: Mon, 26 Nov 2018 07:31:17 -0800 Subject: [PATCH 310/836] Updates --- types/highcharts/highcharts-more.d.ts | 5 -- types/highcharts/highstock.d.ts | 8 --- types/highcharts/index.d.ts | 52 +++++++++---------- types/highcharts/modules/boost.d.ts | 5 -- types/highcharts/modules/drilldown.d.ts | 5 -- types/highcharts/modules/exporting.d.ts | 5 -- types/highcharts/modules/map/index.d.ts | 5 -- .../modules/no-data-to-display.d.ts | 5 -- .../highcharts/modules/offline-exporting.d.ts | 5 -- 9 files changed, 26 insertions(+), 69 deletions(-) diff --git a/types/highcharts/highcharts-more.d.ts b/types/highcharts/highcharts-more.d.ts index 630dbb5622..aaa2da832c 100644 --- a/types/highcharts/highcharts-more.d.ts +++ b/types/highcharts/highcharts-more.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highcharts 4.2.6 -// Project: http://www.highcharts.com/ -// Definitions by: Maciej Suchecki -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import * as Highcharts from "highcharts"; declare function HighchartsMore(H: Highcharts.Static): Highcharts.Static; diff --git a/types/highcharts/highstock.d.ts b/types/highcharts/highstock.d.ts index cc92bebe36..1b57d91a7d 100644 --- a/types/highcharts/highstock.d.ts +++ b/types/highcharts/highstock.d.ts @@ -1,11 +1,3 @@ -// Type definitions for Highstock 2.1.6 -// Project: http://www.highcharts.com/ - -// Definitions by: David Deutsch -// Dave Baumann -// Richard Ison -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import * as Highcharts from "highcharts"; declare namespace Highstock { diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 58154954a3..7f0f15591b 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -4647,11 +4647,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize?: number; + maxFontSize: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize?: number; + minFontSize: number | null; /** * A separate color for the negative part of the area. * @since 3.0 @@ -4753,7 +4753,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize?: number; + maxFontSize: number | null; /** * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the * columns from becoming too wide when there is a small number of points in the chart. @@ -4764,7 +4764,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize?: number; + minFontSize: number | null; /** * The minimal height for a column or width for a bar. By default, 0 values are not shown. To visualize a 0 (or * close to zero) point, set the minimal point length to a pixel value like 3. In stacked column charts, @@ -4862,7 +4862,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize?: number; + maxFontSize: number | null; /** * Maximum bubble size. Bubbles will automatically size between the minSize and maxSize to reflect the z value of * each bubble. Can be either pixels (when no unit is given), or a percentage of the smallest one of the plot width @@ -4874,7 +4874,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize?: number; + minFontSize: number | null; /** * Minimum bubble size. Bubbles will automatically size between the minSize and maxSize to reflect the z value of * each bubble. Can be either pixels (when no unit is given), or a percentage of the smallest one of the plot width @@ -5163,11 +5163,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize?: number; + maxFontSize: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize?: number; + minFontSize: number | null; /** * Allow the dial to overshoot the end of the perimeter axis by this many degrees. Say if the gauge axis goes from 0 * to 60, a value of 100, or 1000, will show 5 degrees beyond the end of the axis. Defaults to 0. @@ -5239,7 +5239,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize?: number; + maxFontSize: number | null; /** * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the * columns from becoming too wide when there is a small number of points in the chart. @@ -5250,7 +5250,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize?: number; + minFontSize: number | null; /** * The row size - how many Y axis units each heatmap row should span. * @default 1 @@ -5272,11 +5272,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize?: number; + maxFontSize: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize?: number; + minFontSize: number | null; /** * Whether to apply steps to the line. Possible values are left, center and right. Prior to 2.3.5, only left was * supported. @@ -5350,11 +5350,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize?: number; + maxFontSize: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize?: number; + minFontSize: number | null; /** * The minimum size for a pie in response to auto margins. The pie will try to shrink to make room for data labels * in side the plot area, but only to this size. @@ -5405,11 +5405,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize?: number; + maxFontSize: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize?: number; + minFontSize: number | null; } interface PyramidChart extends SeriesChart { @@ -5488,11 +5488,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize?: number; + maxFontSize: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize?: number; + minFontSize: number | null; } /** @@ -5533,11 +5533,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize?: number; + maxFontSize: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize?: number; + minFontSize: number | null; } /** @@ -5613,7 +5613,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize?: number; + maxFontSize: number | null; /** * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the * columns from becoming too wide when there is a small number of points in the chart. @@ -5624,7 +5624,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize?: number; + minFontSize: number | null; /** * The sort index of the point inside the treemap level. * @since 4.1.10 @@ -5692,11 +5692,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize?: number; + maxFontSize: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize?: number; + minFontSize: number | null; /** * This option decides which algorithm is used for placement, and rotation of a word. The choice of algorith is * therefore a crucial part of the resulting layout of the wordcloud. It is possible for users to add their own @@ -5900,11 +5900,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize?: number; + maxFontSize: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize?: number; + minFontSize: number | null; /** * The name of the series as shown in the legend, tooltip etc. */ diff --git a/types/highcharts/modules/boost.d.ts b/types/highcharts/modules/boost.d.ts index e0a3480f95..2e4da45b13 100644 --- a/types/highcharts/modules/boost.d.ts +++ b/types/highcharts/modules/boost.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highcharts 4.2.6 (boost module) -// Project: http://www.highcharts.com/ -// Definitions by: Daniel Martin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import { Static } from "highcharts"; declare function HighchartsBoost(H: Static): Static; diff --git a/types/highcharts/modules/drilldown.d.ts b/types/highcharts/modules/drilldown.d.ts index adf9bae6f8..46115cb4ad 100644 --- a/types/highcharts/modules/drilldown.d.ts +++ b/types/highcharts/modules/drilldown.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highcharts Drilldown 4.2.7 -// Project: http://www.highcharts.com/ -// Definitions by: Konstantin Rohde -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import { Static } from "highcharts"; declare function HighchartsDrilldown(H: Static): Static; diff --git a/types/highcharts/modules/exporting.d.ts b/types/highcharts/modules/exporting.d.ts index b4b0124a66..18f9615d41 100644 --- a/types/highcharts/modules/exporting.d.ts +++ b/types/highcharts/modules/exporting.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highcharts 4.2.6 (exporting module) -// Project: http://www.highcharts.com/ -// Definitions by: Maciej Suchecki -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import { Static } from "highcharts"; declare function HighchartsExporting(H: Static): Static; diff --git a/types/highcharts/modules/map/index.d.ts b/types/highcharts/modules/map/index.d.ts index ecf553945b..12b2ca0a7e 100644 --- a/types/highcharts/modules/map/index.d.ts +++ b/types/highcharts/modules/map/index.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highmaps 4.2.7 -// Project: http://www.highcharts.com/products/highmaps -// Definitions by: Albert Ozimek -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import * as highcharts from 'highcharts'; import * as geojson from 'geojson'; diff --git a/types/highcharts/modules/no-data-to-display.d.ts b/types/highcharts/modules/no-data-to-display.d.ts index f79ce249d1..bb8d406e03 100644 --- a/types/highcharts/modules/no-data-to-display.d.ts +++ b/types/highcharts/modules/no-data-to-display.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highcharts No Data to Display 4.2.7 -// Project: http://www.highcharts.com/ -// Definitions by: Andrey Zolotin , Rowell Heria -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import { Static } from "highcharts"; declare module "highcharts" { diff --git a/types/highcharts/modules/offline-exporting.d.ts b/types/highcharts/modules/offline-exporting.d.ts index ee38e1c91b..5f536a8588 100644 --- a/types/highcharts/modules/offline-exporting.d.ts +++ b/types/highcharts/modules/offline-exporting.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highcharts 4.2.6 (offline exporting module) -// Project: http://www.highcharts.com/ -// Definitions by: Daniel Martin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import { Static } from "highcharts"; declare function HighchartsOfflineExporting(H: Static): Static; From f3a20e8a3e339390d03f3fbc89e48a49673bfadb Mon Sep 17 00:00:00 2001 From: juwar Date: Mon, 26 Nov 2018 07:59:33 -0800 Subject: [PATCH 311/836] Enable some of the lint rules and fix them. --- types/highcharts/highstock.d.ts | 15 +--- types/highcharts/index.d.ts | 120 +++++++++----------------------- types/highcharts/test/index.ts | 2 +- types/highcharts/tslint.json | 2 - 4 files changed, 37 insertions(+), 102 deletions(-) diff --git a/types/highcharts/highstock.d.ts b/types/highcharts/highstock.d.ts index 1b57d91a7d..70ebfcb5c1 100644 --- a/types/highcharts/highstock.d.ts +++ b/types/highcharts/highstock.d.ts @@ -121,8 +121,7 @@ declare namespace Highstock { } interface Chart { - new (options: Options): ChartObject; - new (options: Options, callback: (chart: ChartObject) => void): ChartObject; + new (options: Options, callback?: (chart: ChartObject) => void): ChartObject; } interface Static extends Highcharts.Static { @@ -134,13 +133,6 @@ declare namespace Highstock { declare global { interface JQuery { highcharts(type: "StockChart"): Highstock.ChartObject; - /** - * Creates a new Highcharts.Chart for the current JQuery selector; usually - * a div selected by $('#container') - * @param options Options for this chart - * @return current selector the current JQuery selector - */ - highcharts(type: "StockChart", options: Highstock.Options): JQuery; /** * Creates a new Highcharts.Chart for the current JQuery selector; usually * a div selected by $('#container') @@ -148,11 +140,10 @@ declare global { * @param callback Callback function used to manipulate the constructed chart instance * @return current selector the current JQuery selector */ - highcharts(type: "StockChart", options: Highstock.Options, callback: (chart: Highstock.ChartObject) => void): JQuery; + highcharts(type: "StockChart", options: Highstock.Options, callback?: (chart: Highstock.ChartObject) => void): JQuery; highcharts(type: string): Highcharts.ChartObject; - highcharts(type: string, options: Highcharts.Options): JQuery; - highcharts(type: string, options: Highcharts.Options, callback: (chart: Highcharts.ChartObject) => void): JQuery; + highcharts(type: string, options: Highcharts.Options, callback?: (chart: Highcharts.ChartObject) => void): JQuery; } } diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 7f0f15591b..5214c4c54c 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -4647,11 +4647,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize: number | null; + maxFontSize?: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize: number | null; + minFontSize?: number | null; /** * A separate color for the negative part of the area. * @since 3.0 @@ -4753,7 +4753,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize: number | null; + maxFontSize?: number | null; /** * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the * columns from becoming too wide when there is a small number of points in the chart. @@ -4764,7 +4764,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize: number | null; + minFontSize?: number | null; /** * The minimal height for a column or width for a bar. By default, 0 values are not shown. To visualize a 0 (or * close to zero) point, set the minimal point length to a pixel value like 3. In stacked column charts, @@ -4862,7 +4862,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize: number | null; + maxFontSize?: number | null; /** * Maximum bubble size. Bubbles will automatically size between the minSize and maxSize to reflect the z value of * each bubble. Can be either pixels (when no unit is given), or a percentage of the smallest one of the plot width @@ -4874,7 +4874,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize: number | null; + minFontSize?: number | null; /** * Minimum bubble size. Bubbles will automatically size between the minSize and maxSize to reflect the z value of * each bubble. Can be either pixels (when no unit is given), or a percentage of the smallest one of the plot width @@ -5163,11 +5163,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize: number | null; + maxFontSize?: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize: number | null; + minFontSize?: number | null; /** * Allow the dial to overshoot the end of the perimeter axis by this many degrees. Say if the gauge axis goes from 0 * to 60, a value of 100, or 1000, will show 5 degrees beyond the end of the axis. Defaults to 0. @@ -5239,7 +5239,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize: number | null; + maxFontSize?: number | null; /** * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the * columns from becoming too wide when there is a small number of points in the chart. @@ -5250,7 +5250,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize: number | null; + minFontSize?: number | null; /** * The row size - how many Y axis units each heatmap row should span. * @default 1 @@ -5272,11 +5272,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize: number | null; + maxFontSize?: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize: number | null; + minFontSize?: number | null; /** * Whether to apply steps to the line. Possible values are left, center and right. Prior to 2.3.5, only left was * supported. @@ -5350,11 +5350,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize: number | null; + maxFontSize?: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize: number | null; + minFontSize?: number | null; /** * The minimum size for a pie in response to auto margins. The pie will try to shrink to make room for data labels * in side the plot area, but only to this size. @@ -5405,11 +5405,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize: number | null; + maxFontSize?: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize: number | null; + minFontSize?: number | null; } interface PyramidChart extends SeriesChart { @@ -5488,11 +5488,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize: number | null; + maxFontSize?: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize: number | null; + minFontSize?: number | null; } /** @@ -5533,11 +5533,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize: number | null; + maxFontSize?: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize: number | null; + minFontSize?: number | null; } /** @@ -5613,7 +5613,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize: number | null; + maxFontSize?: number | null; /** * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the * columns from becoming too wide when there is a small number of points in the chart. @@ -5624,7 +5624,7 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize: number | null; + minFontSize?: number | null; /** * The sort index of the point inside the treemap level. * @since 4.1.10 @@ -5692,11 +5692,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize: number | null; + maxFontSize?: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize: number | null; + minFontSize?: number | null; /** * This option decides which algorithm is used for placement, and rotation of a word. The choice of algorith is * therefore a crucial part of the resulting layout of the wordcloud. It is possible for users to add their own @@ -5900,11 +5900,11 @@ declare namespace Highcharts { /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - maxFontSize: number | null; + maxFontSize?: number | null; /** * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. */ - minFontSize: number | null; + minFontSize?: number | null; /** * The name of the series as shown in the legend, tooltip etc. */ @@ -6729,16 +6729,10 @@ declare namespace Highcharts { /** * Set new categories for the axis. Redraws. * @param categories The new category names. + * @param redraw Whether to redraw the axis or wait for an explicit call to chart.redraw(). * @since 1.2.0 */ - setCategories(categories: string[]): void; - /** - * Set new categories for the axis. - * @param categories The new category names. - * @param redraw Whether to redraw the axis or wait for an explicit call to chart.redraw(). - * @since 1.2.0 - */ - setCategories(categories: string[], redraw: boolean): void; + setCategories(categories: string[], redraw?: boolean): void; /** * Set the minimum and maximum of the axes after render time. If the startOnTick and endOnTick options are true, the * minimum and maximum values are rounded off to the nearest tick. To prevent this, these options can be set to @@ -6848,22 +6842,6 @@ declare namespace Highcharts { * @since 3.0.8 */ drillUp(): void; - /** - * Exporting module required. Submit an SVG version of the chart to a server along with some parameters for - * conversion. - * @since 2.0 - */ - exportChart(): void; - /** - * Exporting module required. Submit an SVG version of the chart to a server along with some parameters for - * conversion. - * @param options Exporting options. Out of the exporting options, the following options can be given as parameters to the exportChart method. - * All options default to the values given in the exporting config options. filename: the filename for the export without extension, - * url: the URL for the server module to do the conversion, width: the width of the PNG or JPEG image generated on the server, - * type: the MIME type of the converted image, sourceWidth: the width of the source (in-page) chart, sourceHeight: the height of the source chart. - * @since 2.0 - */ - exportChart(options: ExportingOptions): void; /** * Exporting module required. Submit an SVG version of the chart to a server along with some parameters for * conversion. @@ -6874,31 +6852,17 @@ declare namespace Highcharts { * @param chartOptions Additional chart options for the exported chart. For example a different background color can be added here. * @since 2.0 */ - exportChart(options: ExportingOptions, chartOptions: Options): void; + exportChart(options?: ExportingOptions, chartOptions?: Options): void; /** * Export the chart to a PNG or SVG without sending it to a server. Requires * modules/exporting.js and modules/offline-exporting.js. - * @since 2.0 - */ - exportChartLocal(): void; - /** - * Export the chart to a PNG or SVG without sending it to a server. Requires - * modules/exporting.js and modules/offline-exporting.js. - * @param options Exporting options. Same as - * the exportChart params. - * @since 2.0 - */ - exportChartLocal(options: ExportingOptions): void; - /** - * Export the chart to a PNG or SVG without sending it to a server. - * Requires modules/exporting.js and modules/offline-exporting.js. * @param options Exporting options. Same as * the exportChart params. * @param chartOptions Additional chart options for the * exported chart. Same as the exportChart params. * @since 2.0 */ - exportChartLocal(options: ExportingOptions, chartOptions: Options): void; + exportChartLocal(options?: ExportingOptions, chartOptions?: Options): void; /** * Get an axis, series or point by its id as given in the configuration options. * @param id The id of the axis, series or point to get. @@ -7042,23 +7006,12 @@ declare namespace Highcharts { /** * This is the constructor for creating a new chart object. * @param options The chart options - */ - new (options: Options): ChartObject; - /** - * This is the constructor for creating a new chart object. - * @param options The chart options * @param callback A function to execute when the chart object is finished loading and rendering. In most cases the chart is built in one thread, * but in Internet Explorer version 8 or less the chart is sometimes initiated before the document is ready, * and in these cases the chart object will not be finished directly after callingnew Highcharts.Chart(). * s a consequence, code that relies on the newly built Chart object should always run in the callback. Defining a chart.event.load handler is equivalent. */ - new (options: Options, callback: (chart: ChartObject) => void): ChartObject; - /** - * This is the constructor for creating a new chart object. - * @param renderTo The id or a reference to a DOM element where the chart should be rendered (since v4.2.0). - * @param options The chart options - */ - new (renderTo: string | HTMLElement, options: Options): ChartObject; + new (options: Options, callback?: (chart: ChartObject) => void): ChartObject; /** * This is the constructor for creating a new chart object. * @param renderTo The id or a reference to a DOM element where the chart should be rendered (since v4.2.0). @@ -7068,7 +7021,7 @@ declare namespace Highcharts { * and in these cases the chart object will not be finished directly after callingnew Highcharts.Chart(). * As a consequence, code that relies on the newly built Chart object should always run in the callback. Defining a chart.event.load handler is equivalent. */ - new (renderTo: string | HTMLElement, options: Options, callback: (chart: ChartObject) => void): ChartObject; + new (renderTo: string | HTMLElement, options: Options, callback?: (chart: ChartObject) => void): ChartObject; } /** @@ -7642,13 +7595,6 @@ declare namespace Highcharts { declare global { interface JQuery { highcharts(): Highcharts.ChartObject; - /** - * Creates a new Highcharts.Chart for the current JQuery selector; usually - * a div selected by $('#container') - * @param options Options for this chart - * @return current {JQuery} selector the current JQuery selector - */ - highcharts(options: Highcharts.Options): JQuery; /** * Creates a new Highcharts.Chart for the current JQuery selector; usually * a div selected by $('#container') @@ -7656,7 +7602,7 @@ declare global { * @param callback Callback function used to manipulate the constructed chart instance * @return current {JQuery} selector the current JQuery selector */ - highcharts(options: Highcharts.Options, callback: (chart: Highcharts.ChartObject) => void): JQuery; + highcharts(options: Highcharts.Options, callback?: (chart: Highcharts.ChartObject) => void): JQuery; } } diff --git a/types/highcharts/test/index.ts b/types/highcharts/test/index.ts index 1eaa5da438..c1fd8b5676 100644 --- a/types/highcharts/test/index.ts +++ b/types/highcharts/test/index.ts @@ -48,7 +48,7 @@ function originalTests() { }] }); - chart1.addSeries({ + chart1.addSeries({ enableMouseTracking: true, data: [1, 2, 3, 4, 5], description: "some description" diff --git a/types/highcharts/tslint.json b/types/highcharts/tslint.json index cfc8218eab..d6b6fde9be 100644 --- a/types/highcharts/tslint.json +++ b/types/highcharts/tslint.json @@ -3,9 +3,7 @@ "rules": { // TODOs "ban-types": false, - "unified-signatures": false, "no-empty-interface": false, - "dt-header": false, "no-declare-current-package": false, "no-object-literal-type-assertion": false, "no-self-import": false, From 84e48532798da9e4488bf047e7595ff8996a7380 Mon Sep 17 00:00:00 2001 From: Alex Lipatov Date: Mon, 26 Nov 2018 11:56:22 -0500 Subject: [PATCH 312/836] Use swagger-parser's namespace as type instead of defining our own. --- types/swagger-express-middleware/index.d.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/types/swagger-express-middleware/index.d.ts b/types/swagger-express-middleware/index.d.ts index 4d83cebfb0..d6b5789e3e 100644 --- a/types/swagger-express-middleware/index.d.ts +++ b/types/swagger-express-middleware/index.d.ts @@ -32,6 +32,9 @@ app.listen(8000, function () { declare module "swagger-express-middleware" { import { Application, Router, RequestHandler, Request, Response } from "express"; + import * as parser from "swagger-parser"; + + type SwaggerParser = typeof parser.SwaggerParser; let s: s.SwaggerMiddlewareConstructor; @@ -363,11 +366,6 @@ declare module "swagger-express-middleware" { externalDocs?: ExternalDocumentationObject } - export interface SwaggerParser { - $refs: any - schema: SwaggerObject - } - type MimeTypes = string[] export interface InfoObject { From 7bba952b5759fceb1b6307c807482380600047b5 Mon Sep 17 00:00:00 2001 From: Daan Boerlage Date: Mon, 26 Nov 2018 18:29:53 +0100 Subject: [PATCH 313/836] [openapi-factory] fix http methods param typings --- types/openapi-factory/index.d.ts | 52 +++++++++++-------- .../openapi-factory/openapi-factory-tests.ts | 36 +++++++------ 2 files changed, 51 insertions(+), 37 deletions(-) diff --git a/types/openapi-factory/index.d.ts b/types/openapi-factory/index.d.ts index 6cb22f7194..e41958e6df 100644 --- a/types/openapi-factory/index.d.ts +++ b/types/openapi-factory/index.d.ts @@ -5,43 +5,53 @@ // TypeScript Version: 2.2 declare namespace OpenApi { - interface OpenApiOptions { + interface ApiOptions { requestMiddleware?: () => any; responseMiddleware?: () => any; errorMiddleware?: () => any; } + + interface HttpMethodOptions { + rawBody?: boolean; + } + + interface HttpResponse { + statusCode?: number; + headers?: object; + body?: (object | string); + } } declare class OpenApi { - constructor(options: OpenApi.OpenApiOptions, overrideLogger?: () => void); + constructor(options: OpenApi.ApiOptions, overrideLogger?: () => void); - setAuthorizer(authorizerFunc: (req?: any) => any): void; - onEvent(onEventFunc: (req?: any) => any): void; - onSchedule(onScheduleFunc: (req?: any) => any): void; + setAuthorizer(authorizerFunc: (req?: any) => Promise): void; + onEvent(onEventFunc: (req?: any) => Promise): void; + onSchedule(onScheduleFunc: (req?: any) => Promise): void; - head(route: string, p0: (req?: any) => any): void; - head(route: string, p0: object, p1: (req?: any) => any): void; + head(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + head(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: any) => any): void; - get(route: string, p0: (req?: any) => any): void; - get(route: string, p0: object, p1: (req?: any) => any): void; + get(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + get(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; - post(route: string, p0: (req?: any) => any): void; - post(route: string, p0: object, p1: (req?: any) => any): void; + post(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + post(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; - put(route: string, p0: (req?: any) => any): void; - put(route: string, p0: object, p1: (req?: any) => any): void; + put(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + put(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; - patch(route: string, p0: (req?: any) => any): void; - patch(route: string, p0: object, p1: (req?: any) => any): void; + patch(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + patch(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; - delete(route: string, p0: (req?: any) => any): void; - delete(route: string, p0: object, p1: (req?: any) => any): void; + delete(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + delete(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; - options(route: string, p0: (req?: any) => any): void; - options(route: string, p0: object, p1: (req?: any) => any): void; + options(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + options(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; - any(route: string, p0: (req?: any) => any): void; - any(route: string, p0: object, p1: (req?: any) => any): void; + any(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + any(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; handler(event: object, context: object): Promise; } diff --git a/types/openapi-factory/openapi-factory-tests.ts b/types/openapi-factory/openapi-factory-tests.ts index 13e1e0e7cc..ad24a5021d 100644 --- a/types/openapi-factory/openapi-factory-tests.ts +++ b/types/openapi-factory/openapi-factory-tests.ts @@ -6,20 +6,24 @@ api.setAuthorizer((req: any) => req); api.onEvent((req: any) => req); api.onSchedule((req: any) => req); -api.head('/v1/test', () => 'success'); -api.get('/v1/test', () => 'success'); -api.post('/v1/test', () => 'success'); -api.put('/v1/test', () => 'success'); -api.patch('/v1/test', () => 'success'); -api.delete('/v1/test', () => 'success'); -api.options('/v1/test', () => 'success'); -api.any('/v1/test2', () => 'success'); +const testReponse = { + statusCode: 200 +}; -api.head('/v2/test', {test: true}, () => 'success'); -api.get('/v2/test', {test: true}, () => 'success'); -api.post('/v2/test', {test: true}, () => 'success'); -api.put('/v2/test', {test: true}, () => 'success'); -api.patch('/v2/test', {test: true}, () => 'success'); -api.delete('/v2/test', {test: true}, () => 'success'); -api.options('/v2/test', {test: true}, () => 'success'); -api.any('/v2/test2', {test: true}, () => 'success'); +api.head('/v1/test', () => testReponse); +api.get('/v1/test', () => testReponse); +api.post('/v1/test', () => testReponse); +api.put('/v1/test', () => testReponse); +api.patch('/v1/test', () => testReponse); +api.delete('/v1/test', () => testReponse); +api.options('/v1/test', () => testReponse); +api.any('/v1/test2', () => testReponse); + +api.head('/v2/test', { rawBody: true }, () => testReponse); +api.get('/v2/test', { rawBody: true }, () => testReponse); +api.post('/v2/test', { rawBody: true }, () => testReponse); +api.put('/v2/test', { rawBody: true }, () => testReponse); +api.patch('/v2/test', { rawBody: true }, () => testReponse); +api.delete('/v2/test', { rawBody: true }, () => testReponse); +api.options('/v2/test', { rawBody: true }, () => testReponse); +api.any('/v2/test2', { rawBody: true }, () => testReponse); From f69313ade8615953ace3f73eeb27bf0480a9166a Mon Sep 17 00:00:00 2001 From: juwar Date: Mon, 26 Nov 2018 10:01:54 -0800 Subject: [PATCH 314/836] Remove no-angle-bracket-type-assertion issues --- types/highcharts/test/highstock.ts | 2 +- types/highcharts/test/index.ts | 240 ++++++++++++++--------------- 2 files changed, 121 insertions(+), 121 deletions(-) diff --git a/types/highcharts/test/highstock.ts b/types/highcharts/test/highstock.ts index f1a464f491..e80e0cb7a3 100644 --- a/types/highcharts/test/highstock.ts +++ b/types/highcharts/test/highstock.ts @@ -66,7 +66,7 @@ $(() => { } }, - series: [ { + series: [{ name: 'USD to EUR', data: someData, lineColor: "blue" diff --git a/types/highcharts/test/index.ts b/types/highcharts/test/index.ts index c1fd8b5676..2bb429ec7a 100644 --- a/types/highcharts/test/index.ts +++ b/types/highcharts/test/index.ts @@ -40,12 +40,12 @@ function originalTests() { renderTo: "container" }, xAxis: {}, - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], description: "foo", type: "line", allowPointSelect: true - }] + } as Highcharts.LineChartSeriesOptions] }); chart1.addSeries({ @@ -61,7 +61,7 @@ function originalTests() { height: 400, spacingRight: 20 }, - xAxis: [ { + xAxis: [{ description: 'x-foo', min: 1, max: 1000, @@ -71,7 +71,7 @@ function originalTests() { gridLineWidth: 1, type: 'logarithmic' }], - yAxis: [ { + yAxis: [{ description: 'y-foo', min: 1, max: 1000, @@ -85,7 +85,7 @@ function originalTests() { legend: { enabled: false }, - series: [ { + series: [{ data: [ [550, 870], [738, 362], [719, 711], [547, 665], [595, 197], [332, 144], [581, 555], [196, 862], [6, 837], [400, 924], [888, 148], [785, 730], @@ -114,12 +114,12 @@ function originalTests() { renderTo: "container" }, xAxis: {}, - series: [ { + series: [{ data: [[1, 1, 2], [2, 2, 3], [3, 2, 3]], description: "foo", type: "columnrange", allowPointSelect: true - }] + } as Highcharts.ColumnRangeChartSeriesOptions] }); const chart4 = new Highcharts.Chart({ @@ -127,12 +127,12 @@ function originalTests() { renderTo: "container" }, xAxis: {}, - series: [ { + series: [{ data: [["01-01-2018", 1, 2], ["02-01-2018", 2, 3], ["03-01-2018", 2, 3]], description: "column range data", type: "columnrange", allowPointSelect: true - }] + } as Highcharts.ColumnRangeChartSeriesOptions] }); const div: HTMLDivElement = null as any; @@ -146,7 +146,7 @@ function originalTests() { }, xAxis: [{ }], - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }] }; @@ -164,47 +164,47 @@ function originalTests() { const renderToIdChart = new Highcharts.Chart("container", { xAxis: {}, - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true - }] + } as Highcharts.LineChartSeriesOptions] }); const renderToElementChart = new Highcharts.Chart(div, { xAxis: {}, - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true - }] + } as Highcharts.LineChartSeriesOptions] }); const createWithFunction = Highcharts.chart({ xAxis: {}, - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true - }] + } as Highcharts.LineChartSeriesOptions] }); const createWithFunctionRenderToId = Highcharts.chart("container", { xAxis: {}, - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true - }] + } as Highcharts.LineChartSeriesOptions] }); const createWithFunctionRenderToElement = Highcharts.chart(div, { xAxis: {}, - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true - }] + } as Highcharts.LineChartSeriesOptions] }); } @@ -245,7 +245,7 @@ function test_ChartOptions() { duration: 500, easing: "linear" }, - backgroundColor: { + backgroundColor: { linearGradient: { x1: 0, y1: 0, @@ -261,7 +261,7 @@ function test_ChartOptions() { colorCount: 42, defaultSeriesType: "deprecated", description: "an arbitrary description", - events: { + events: { addSeries: () => { }, afterPrint: () => { }, beforePrint: () => { }, @@ -281,21 +281,21 @@ function test_ChartOptions() { marginLeft: 10, marginRight: 10, marginTop: 10, - options3d: { + options3d: { alpha: 20, beta: 20, depth: 50, enabled: true, frame: { - back: { + back: { color: "black", size: 2 }, - bottom: { + bottom: { color: "black", size: 2 }, - side: { + side: { color: "black", size: 2 } @@ -309,7 +309,7 @@ function test_ChartOptions() { plotBackgroundImage: "http://image.url/image.jpg", plotBorderColor: "grey", plotBorderWidth: 5, - plotShadow: { + plotShadow: { color: "magenta", offsetX: 10, offsetY: 10, @@ -319,15 +319,15 @@ function test_ChartOptions() { polar: true, reflow: false, renderTo: "elementId", - resetZoomButton: { - position: { + resetZoomButton: { + position: { align: "left", verticalAlign: "top", x: 5, y: 5 }, relativeTo: "chart", - theme: { + theme: { display: "hidden", fill: "black", stroke: "white", @@ -394,7 +394,7 @@ function test_ChartOptions() { }); // animation example - $('#container').highcharts( { + $('#container').highcharts({ chart: { animation: { duration: 1500, @@ -479,7 +479,7 @@ function test_ChartOptions() { chart: { events: { addSeries() { - const label = ( this).renderer.label('A series was added, about to redraw chart', 100, 120) + const label = (this as Highcharts.ChartObject).renderer.label('A series was added, about to redraw chart', 100, 120) .attr({ fill: Highcharts.getOptions().colors[0], padding: 10, @@ -729,21 +729,21 @@ function test_Data() { } }, series: [ - { + { lineWidth: 1 }, - { + { type: 'areaspline', color: '#c4392d', negativeColor: '#5679c4', fillOpacity: 0.5 - } + } as Highcharts.AreaSplineChartSeriesOptions ] }); // limited data example $('#container').highcharts({ - data: { + data: { csv: document.getElementById('csv').innerHTML, startRow: 114, endRow: 134, @@ -753,7 +753,7 @@ function test_Data() { xAxis: { allowDecimals: false }, - series: [ { + series: [{ name: 'Annual mean' }] }); @@ -784,14 +784,14 @@ function test_Drilldown() { type: 'category' }, plotOptions: { - series: { + series: { borderWidth: 0, dataLabels: { enabled: true } - } + } as Highcharts.ColumnChart }, - series: [ { + series: [{ name: '2010', data: [{ name: 'Republican', @@ -806,7 +806,7 @@ function test_Drilldown() { y: 4, drilldown: 'other-2010' }] - }, { + }, { name: '2014', data: [{ name: 'Republican', @@ -823,7 +823,7 @@ function test_Drilldown() { }] }], drilldown: { - series: [ { + series: [{ id: 'republican-2010', data: [ ['East', 4], @@ -831,7 +831,7 @@ function test_Drilldown() { ['North', 1], ['South', 4] ] - }, { + }, { id: 'democrats-2010', data: [ ['East', 6], @@ -839,7 +839,7 @@ function test_Drilldown() { ['North', 2], ['South', 4] ] - }, { + }, { id: 'other-2010', data: [ ['East', 2], @@ -847,7 +847,7 @@ function test_Drilldown() { ['North', 3], ['South', 2] ] - }, { + }, { id: 'republican-2014', data: [ ['East', 2], @@ -855,7 +855,7 @@ function test_Drilldown() { ['North', 1], ['South', 7] ] - }, { + }, { id: 'democrats-2014', data: [ ['East', 4], @@ -863,7 +863,7 @@ function test_Drilldown() { ['North', 5], ['South', 3] ] - }, { + }, { id: 'other-2014', data: [ ['East', 7], @@ -881,14 +881,14 @@ function test_Drilldown() { type: 'column' }, plotOptions: { - series: { + series: { borderWidth: 0, dataLabels: { enabled: true } - } + } as Highcharts.ColumnChart }, - series: [ { + series: [{ name: 'Things', colorByPoint: true, data: [{ @@ -903,7 +903,7 @@ function test_Drilldown() { name: 'Cars', y: 4 }] - }], + } as Highcharts.ColumnChartSeriesOptions], drilldown: { activeAxisLabelStyle: { textDecoration: 'none', @@ -976,7 +976,7 @@ function test_Exporting() { series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }], - exporting: { + exporting: { error: () => { console.log('succesfully asserted exporting.error'); }, @@ -987,7 +987,7 @@ function test_Exporting() { chartOptions: { subtitle: null } - } + } as Highcharts.ExportingOptions }); } @@ -1113,12 +1113,12 @@ function test_AreaOptions() { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, plotOptions: { - series: { + series: { fillColor: { linearGradient: [0, 0, 0, 300], stops: [ [0, Highcharts.getOptions().colors[0]], - [1, ( Highcharts.Color(Highcharts.getOptions().colors[0])).setOpacity(0).get('rgba')] + [1, ((Highcharts.Color(Highcharts.getOptions().colors[0])) as Highcharts.Gradient).setOpacity(0).get('rgba')] ] }, fillOpacity: 0.1, @@ -1129,7 +1129,7 @@ function test_AreaOptions() { threshold: 100, trackByArea: true, stickyTracking: false // to show the difference in tracking - } + } as Highcharts.AreaChartSeriesOptions }, series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] @@ -1146,7 +1146,7 @@ function test_AreaRange() { type: "arearange", zoomType: 'x' }, - series: [ { + series: [{ data: (((arr: number[], len: number) => { for (let i = 0; i < len; i = i + 1) { arr.push(i); @@ -1191,7 +1191,7 @@ function test_AreaRange() { legend: { enabled: false }, - series: [ { + series: [{ name: 'Temperatures', data, dataLabels: { @@ -1199,7 +1199,7 @@ function test_AreaRange() { yHigh: 20, yLow: -20 } - }] + } as Highcharts.AreaRangeChartSeriesOptions] }); }); } @@ -1215,7 +1215,7 @@ function test_Bar() { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, plotOptions: { - series: { + series: { borderColor: '#303030', borderRadius: 5, borderWidth: 2, @@ -1240,7 +1240,7 @@ function test_Bar() { } } } - } + } as Highcharts.BarChartSeriesOptions }, series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] @@ -1274,7 +1274,7 @@ function test_Bar() { // grouping example Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, (color: string) => { - return ( Highcharts.Color(color)) + return (Highcharts.Color(color) as Highcharts.Gradient) .setOpacity(0.5) .get('rgba'); }); @@ -1309,19 +1309,19 @@ function test_Bar() { shadow: false } }, - series: [ { + series: [{ name: 'Tokyo', data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], pointPadding: 0 - }, { + } as Highcharts.BarChartSeriesOptions, { name: 'New York', data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3], pointPadding: 0.1 - }, { + }, { name: 'London', data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2], pointPadding: 0.2 - }, { + }, { name: 'Berlin', data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1], pointPadding: 0.3 @@ -1407,7 +1407,7 @@ function test_Bubble() { maxSize: 50 } }, - series: [ { + series: [{ data: [ [9, 81, 13], [98, 5, 39], @@ -1430,7 +1430,7 @@ function test_Bubble() { zMin: 0, zMax: 100, zThreshold: 0 - }] + } as Highcharts.BubbleChartSeriesOptions] }); // size by absolute value example @@ -1444,7 +1444,7 @@ function test_Bubble() { subtitle: { text: 'Size is computed by absolute value on negative bubbles' }, - series: [ { + series: [{ data: [ [-5, 0, -5], [-4, 0, -4], @@ -1460,7 +1460,7 @@ function test_Bubble() { ], sizeByAbsoluteValues: true, negativeColor: '#FF0000' - }] + } as Highcharts.BubbleChartSeriesOptions] }); } @@ -1479,7 +1479,7 @@ function test_ColumnCrispFalse() { } return arr; }; - const chart = new Highcharts.Chart( { + const chart = new Highcharts.Chart({ title: { text: 'Crisp columns are disabled' }, @@ -1527,7 +1527,7 @@ function test_ErrorBar() { tooltip: { shared: true }, - series: [ { + series: [{ name: 'Temperature', type: 'spline', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6], @@ -1537,7 +1537,7 @@ function test_ErrorBar() { tooltip: { pointFormat: ' {series.name} : {point.y:.1f}°C
' } - }, { + } as Highcharts.SplineChartSeriesOptions, { color: '#FF0000', name: 'Temperature error', type: 'errorbar', @@ -1549,7 +1549,7 @@ function test_ErrorBar() { stemDashStyle: "Solid", stemWidth: 3, whiskerLength: 0 - }] + } as Highcharts.ErrorBarChartSeriesOptions] }); } @@ -1568,7 +1568,7 @@ function test_FindNearestPointBy() { } }, - series: [ { + series: [{ findNearestPointBy: 'x', // Hover at [3.5, 6] to demo x-dimension search // Compare to Series 2 behavior at [5.5, 3] @@ -1584,7 +1584,7 @@ function test_FindNearestPointBy() { [6, 6], [7, 6] ] - }, { + } as Highcharts.IndividualSeriesOptions, { findNearestPointBy: 'xy', // Hover at [1, 4] to demo xy-dimension search. // Useful when having multiple points on the same x-value. @@ -1600,7 +1600,7 @@ function test_FindNearestPointBy() { [6, 3], [7, 3] ] - }] + } as Highcharts.IndividualSeriesOptions] }); } @@ -1618,7 +1618,7 @@ function test_Funnel() { x: -50 }, plotOptions: { - series: { + series: { dataLabels: { enabled: true, format: ' {point.name} ({point.y:,.0f})', @@ -1630,7 +1630,7 @@ function test_Funnel() { reversed: false, height: "10%", width: 100 - } + } as Highcharts.FunnelChartSeriesOptions }, legend: { enabled: false @@ -1701,10 +1701,10 @@ function test_Gauge() { } } }, - series: [ { + series: [{ data: [80], overshoot: 5 - }] + } as Highcharts.GaugeChartSeriesOptions] }); } @@ -1757,14 +1757,14 @@ function test_HeatMap() { ], min: -5 }, - series: [ { + series: [{ borderWidth: 0, colsize: 24 * 36e5, // one day tooltip: { headerFormat: 'Temperature
', pointFormat: '{point.x:%e %b, %Y} {point.y}:00: {point.value} ℃ ' } - }] + } as Highcharts.HeatMapSeriesOptions] }); } @@ -1779,17 +1779,17 @@ function test_Line() { xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, - series: [ { + series: [{ data: [1, 2, 3, 4, null, 6, 7, null, 9], step: 'right', name: 'Right', linecap: 'round' - }, { + } as Highcharts.LineChartSeriesOptions, { data: [5, 6, 7, 8, null, 10, 11, null, 13], step: 'center', name: 'Center', linecap: 'round' - }, { + }, { data: [9, 10, 11, 12, null, 14, 15, null, 17], step: 'left', name: 'Left', @@ -1829,7 +1829,7 @@ function test_Pie() { } } }, - series: [ { + series: [{ name: "Brands", colorByPoint: true, data: [{ @@ -1853,7 +1853,7 @@ function test_Pie() { name: "Proprietary or Undetectable", y: 0.2 }] - }] + } as Highcharts.PieChartSeriesOptions] }); // semi circle @@ -1888,7 +1888,7 @@ function test_Pie() { center: ['50%', '75%'] } }, - series: [ { + series: [{ type: 'pie', name: 'Browser share', innerSize: '50%', @@ -2161,10 +2161,10 @@ function test_Waterfall() { } function test_AccessibilityOptions() { - const accessibilityOptions: Highcharts.AccessibilityOptions = { + const accessibilityOptions: Highcharts.AccessibilityOptions = { describeSingleSeries: true, enabled: true, - keyboardNavigation: { + keyboardNavigation: { enabled: true, skipNullPoints: true }, @@ -2177,7 +2177,7 @@ function test_AccessibilityOptions() { seriesDescriptionFormatter: () => { } }; - const chart = new Highcharts.Chart( { + const chart = new Highcharts.Chart({ accessibility: accessibilityOptions }); } @@ -2435,31 +2435,31 @@ function test_AxisObject() { axis.toPixels(10, true); axis.toValue(10); axis.toValue(10, true); - axis.update( {}); - axis.update( {}, true); + axis.update({}); + axis.update({}, true); } function test_ChartObject() { const chart = $("#container").highcharts(); - chart.addAxis( {}); - chart.addAxis( {}, true); - chart.addAxis( {}, true, false); - chart.addAxis( {}, true, true, false); - chart.addAxis( {}, true, true, { duration: 50 }); - chart.addSeries( {}); - chart.addSeries( {}, false); - chart.addSeries( {}, false, false); - chart.addSeries( {}, false, { duration: 50 }); - chart.addSeriesAsDrilldown( {}, {}); + chart.addAxis({}); + chart.addAxis({}, true); + chart.addAxis({}, true, false); + chart.addAxis({}, true, true, false); + chart.addAxis({}, true, true, { duration: 50 }); + chart.addSeries({}); + chart.addSeries({}, false); + chart.addSeries({}, false, false); + chart.addSeries({}, false, { duration: 50 }); + chart.addSeriesAsDrilldown({}, {}); const container = chart.container; console.log(container.id); chart.destroy(); chart.drillUp(); - chart.exportChart( {}, {}); - chart.exportChartLocal( {}, {}); + chart.exportChart({}, {}); + chart.exportChartLocal({}, {}); const object = chart.get('axisIdOrSeriesIdOrPointId'); const svg1 = chart.getSVG(); - const svg2 = chart.getSVG( {}); + const svg2 = chart.getSVG({}); const selectedPoints = chart.getSelectedPoints(); const selectedSeries = chart.getSelectedSeries(); chart.hideLoading(); @@ -2480,11 +2480,11 @@ function test_ChartObject() { const firstXAxis = chart.xAxis[0]; const firstYAxis = chart.yAxis[0]; const legend = chart.legend; - chart.update( {}); - chart.update( {}, true); - chart.update( {}, true, true); - chart.update( {}, true, true, true); - chart.update( {}, true, true, { + chart.update({}); + chart.update({}, true); + chart.update({}, true, true); + chart.update({}, true, true, true); + chart.update({}, true, true, { duration: 3000, }); } @@ -2564,7 +2564,7 @@ function test_NumericSymbolMagnitude() { } function test_PaneBackground() { - const pane = { + const pane = { backgroundColor: 'blue', borderColor: 'white', borderWidth: 5, @@ -2576,7 +2576,7 @@ function test_PaneBackground() { } function test_PointObject() { - const point = $('#container').highcharts().get('point1'); + const point = $('#container').highcharts().get('point1') as Highcharts.PointObject; const category = point.category; const percentage = point.percentage; point.index; @@ -2608,7 +2608,7 @@ function test_RendererObject() { const renderer = $('#container').highcharts().renderer; renderer.arc(0, 0, 20, 10, 0, Math.PI); renderer.circle(0, 0, 100); - renderer.definition( {}); + renderer.definition({}); renderer.g('groupName'); renderer.image('http://source', 20, 20, 100, 100); renderer.label('Label', 200, 100, 'rect', 0, 0, false, false, 'class'); @@ -2618,15 +2618,15 @@ function test_RendererObject() { } function test_ResponsiveOptions() { - const responsiveOptions: Highcharts.ResponsiveOptions = { + const responsiveOptions: Highcharts.ResponsiveOptions = { rules: [ - { - chartOptions: { + { + chartOptions: { chart: { description: 'just a test' } }, - condition: { + condition: { callback: () => { }, maxHeight: 420, maxWidth: 420, @@ -2643,7 +2643,7 @@ function test_ResponsiveOptions() { } function test_SeriesObject() { - const series = $('#container').highcharts().get('series1'); + const series = $('#container').highcharts().get('series1') as Highcharts.SeriesObject; series.addPoint(0); series.addPoint([0, 0]); series.addPoint({}); From 5b7fc62ce75b058b26c601a0021bb0a89d30d411 Mon Sep 17 00:00:00 2001 From: juwar Date: Mon, 26 Nov 2018 10:12:10 -0800 Subject: [PATCH 315/836] Small fixes from more issues. --- types/highcharts/test/highstock.ts | 2 +- types/highcharts/test/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/highcharts/test/highstock.ts b/types/highcharts/test/highstock.ts index e80e0cb7a3..af9de8d1f9 100644 --- a/types/highcharts/test/highstock.ts +++ b/types/highcharts/test/highstock.ts @@ -70,6 +70,6 @@ $(() => { name: 'USD to EUR', data: someData, lineColor: "blue" - }] + } as Highcharts.AreaRangeChartSeriesOptions] }); }); diff --git a/types/highcharts/test/index.ts b/types/highcharts/test/index.ts index 2bb429ec7a..e5c891b5ef 100644 --- a/types/highcharts/test/index.ts +++ b/types/highcharts/test/index.ts @@ -2450,7 +2450,7 @@ function test_ChartObject() { chart.addSeries({}, false); chart.addSeries({}, false, false); chart.addSeries({}, false, { duration: 50 }); - chart.addSeriesAsDrilldown({}, {}); + chart.addSeriesAsDrilldown({} as Highcharts.PointObject, {}); const container = chart.container; console.log(container.id); chart.destroy(); From 1fef27e8affcb1a8eb34fb7a1f9889d980f65baa Mon Sep 17 00:00:00 2001 From: juwar Date: Mon, 26 Nov 2018 10:20:33 -0800 Subject: [PATCH 316/836] Another one. --- types/highcharts/test/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/highcharts/test/index.ts b/types/highcharts/test/index.ts index e5c891b5ef..1474ee7e9c 100644 --- a/types/highcharts/test/index.ts +++ b/types/highcharts/test/index.ts @@ -2637,7 +2637,7 @@ function test_ResponsiveOptions() { ] }; - const chart = new Highcharts.Chart( { + const chart = new Highcharts.Chart({ responsive: responsiveOptions }); } From d73f3efdcfadea4fb6100686286b53bf92be8275 Mon Sep 17 00:00:00 2001 From: dyniper Date: Tue, 20 Nov 2018 11:56:00 -0800 Subject: [PATCH 317/836] Add new partialBundledLanguages InitOptions --- types/i18next/index.d.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/types/i18next/index.d.ts b/types/i18next/index.d.ts index 84433c26ec..d2e0b4ee6b 100644 --- a/types/i18next/index.d.ts +++ b/types/i18next/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for i18next 11.9 +// Type definitions for i18next 12.1 // Project: http://i18next.com // Definitions by: Michael Ledin // Budi Irawan @@ -160,6 +160,12 @@ declare namespace i18next { */ resources?: Resource; + /** + * Allow initializing with bundled resources while using a backend to load non bundled ones. + * @default false + */ + partialBundledLanguages?: boolean; + /** * language to use (overrides language detection) * @default undefined From e3c335e16e88c7869c90ec2e4b942e3a176f6682 Mon Sep 17 00:00:00 2001 From: John Plusje Date: Mon, 26 Nov 2018 19:48:57 +0100 Subject: [PATCH 318/836] Add call to server.close() in order to show that http.Server is properly extended. Added a StoppableServer type for typing the created server instance. --- types/stoppable/index.d.ts | 8 +++++--- types/stoppable/stoppable-tests.ts | 7 ++++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/types/stoppable/index.d.ts b/types/stoppable/index.d.ts index b15444c7ba..1b30c5a995 100644 --- a/types/stoppable/index.d.ts +++ b/types/stoppable/index.d.ts @@ -7,10 +7,12 @@ /// import { Server } from 'http'; -interface StoppableServer extends Server { - stop(callback?: (e: Error, gracefully: boolean) => void): void; +declare namespace stoppable { + interface StoppableServer extends Server { + stop(callback?: (e: Error, gracefully: boolean) => void): void; + } } -declare function stoppable(server: Server, grace?: number): StoppableServer; +declare function stoppable(server: Server, grace?: number): stoppable.StoppableServer; export = stoppable; diff --git a/types/stoppable/stoppable-tests.ts b/types/stoppable/stoppable-tests.ts index 89ebf64f6d..930a2340bd 100644 --- a/types/stoppable/stoppable-tests.ts +++ b/types/stoppable/stoppable-tests.ts @@ -1,11 +1,12 @@ import * as http from 'http'; import stoppable = require('stoppable'); -const server = stoppable(http.createServer()); +const server: stoppable.StoppableServer = stoppable(http.createServer()); server.stop(); -const server2 = stoppable(http.createServer(), 10000); +const server2: stoppable.StoppableServer = stoppable(http.createServer(), 10000); server2.stop(); -const server3 = stoppable(http.createServer()); +const server3: stoppable.StoppableServer = stoppable(http.createServer()); server.stop((err, gracefully) => {}); +server.close(); From 35483b43559b94114dca755f130e6ccb48f18d3b Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 26 Nov 2018 20:30:14 +0100 Subject: [PATCH 319/836] Impove types for bitwise-xor --- types/bitwise-xor/bitwise-xor-tests.ts | 12 ++-- types/bitwise-xor/index.d.ts | 7 +-- types/bitwise-xor/tsconfig.json | 4 +- types/bitwise-xor/tslint.json | 78 +------------------------- 4 files changed, 11 insertions(+), 90 deletions(-) diff --git a/types/bitwise-xor/bitwise-xor-tests.ts b/types/bitwise-xor/bitwise-xor-tests.ts index b19768f11f..13ddab8b66 100644 --- a/types/bitwise-xor/bitwise-xor-tests.ts +++ b/types/bitwise-xor/bitwise-xor-tests.ts @@ -1,10 +1,8 @@ +'use strict'; +import xor = require('bitwise-xor'); -"use strict"; +let b: Buffer; -import xor = require("bitwise-xor"); - -var b: Buffer; - -b = xor("a", "b"); -b = xor(new Buffer("a"), new Buffer("b")); +b = xor('a', 'b'); +b = xor(new Buffer('a'), new Buffer('b')); diff --git a/types/bitwise-xor/index.d.ts b/types/bitwise-xor/index.d.ts index 9960023c97..3147c5b675 100644 --- a/types/bitwise-xor/index.d.ts +++ b/types/bitwise-xor/index.d.ts @@ -1,15 +1,14 @@ -// Type definitions for bitwise-xor 0.0.0 +// Type definitions for bitwise-xor 0.0 // Project: https://github.com/czzarr/node-bitwise-xor // Definitions by: Rogier Schouten +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// - /** * Bitwise XOR between two Buffers or Strings, returns a Buffer */ -declare function xor(b1: Buffer, b2: Buffer): Buffer; -declare function xor(s1: string, s2: string): Buffer; +declare function xor(a: Buffer | string, b: Buffer | string): Buffer; export = xor; diff --git a/types/bitwise-xor/tsconfig.json b/types/bitwise-xor/tsconfig.json index a6b66cda37..f02f5ef72b 100644 --- a/types/bitwise-xor/tsconfig.json +++ b/types/bitwise-xor/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "bitwise-xor-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/bitwise-xor/tslint.json b/types/bitwise-xor/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/bitwise-xor/tslint.json +++ b/types/bitwise-xor/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" } From c830fd6999d65e1c02f3be796233fb380f396826 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 26 Nov 2018 21:00:12 +0100 Subject: [PATCH 320/836] Add types for create-hash --- types/create-hash/create-hash-tests.ts | 9 +++++++++ types/create-hash/index.d.ts | 26 ++++++++++++++++++++++++++ types/create-hash/tsconfig.json | 23 +++++++++++++++++++++++ types/create-hash/tslint.json | 1 + 4 files changed, 59 insertions(+) create mode 100644 types/create-hash/create-hash-tests.ts create mode 100644 types/create-hash/index.d.ts create mode 100644 types/create-hash/tsconfig.json create mode 100644 types/create-hash/tslint.json diff --git a/types/create-hash/create-hash-tests.ts b/types/create-hash/create-hash-tests.ts new file mode 100644 index 0000000000..d039a5a704 --- /dev/null +++ b/types/create-hash/create-hash-tests.ts @@ -0,0 +1,9 @@ +import createHash = require('create-hash'); + +const hash = createHash('sha224'); + +hash.update('synchronous write'); +hash.digest(); +hash.write('write to it as a stream'); +hash.end(); +hash.read(); diff --git a/types/create-hash/index.d.ts b/types/create-hash/index.d.ts new file mode 100644 index 0000000000..712be2520f --- /dev/null +++ b/types/create-hash/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for create-hash 1.2 +// Project: https://github.com/crypto-browserify/createHash +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import { Hash } from 'crypto'; + +export = createHash; + +declare function createHash(algo: createHash.Algorithm): Hash; + +declare namespace createHash { + type Algorithm = + | 'md5' + | 'rmd160' + | 'ripemd160' + | 'sha' + | 'sha1' + | 'sha224' + | 'sha256' + | 'sha384' + | 'sha512'; +} diff --git a/types/create-hash/tsconfig.json b/types/create-hash/tsconfig.json new file mode 100644 index 0000000000..83e50b425c --- /dev/null +++ b/types/create-hash/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", + "create-hash-tests.ts" + ] +} diff --git a/types/create-hash/tslint.json b/types/create-hash/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/create-hash/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From b41337dd487ca3a99359e93a9067073643870d99 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 26 Nov 2018 21:15:37 +0100 Subject: [PATCH 321/836] Add types for create-hmac --- types/create-hmac/create-hmac-tests.ts | 9 +++++++++ types/create-hmac/index.d.ts | 26 ++++++++++++++++++++++++++ types/create-hmac/tsconfig.json | 23 +++++++++++++++++++++++ types/create-hmac/tslint.json | 1 + 4 files changed, 59 insertions(+) create mode 100644 types/create-hmac/create-hmac-tests.ts create mode 100644 types/create-hmac/index.d.ts create mode 100644 types/create-hmac/tsconfig.json create mode 100644 types/create-hmac/tslint.json diff --git a/types/create-hmac/create-hmac-tests.ts b/types/create-hmac/create-hmac-tests.ts new file mode 100644 index 0000000000..f233a0390a --- /dev/null +++ b/types/create-hmac/create-hmac-tests.ts @@ -0,0 +1,9 @@ +import createHmac = require('create-hmac'); + +const hmac = createHmac('sha224', Buffer.from('secret key')); + +hmac.update('synchronous write'); +hmac.digest(); +hmac.write('write to it as a stream'); +hmac.end(); +hmac.read(); diff --git a/types/create-hmac/index.d.ts b/types/create-hmac/index.d.ts new file mode 100644 index 0000000000..3d6bcfeafa --- /dev/null +++ b/types/create-hmac/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for create-hmac 1.1 +// Project: https://github.com/crypto-browserify/createHmac +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import { Hmac } from 'crypto'; + +export = createHmac; + +declare function createHmac(algo: createHmac.Algorithm, key: string | Buffer): Hmac; + +declare namespace createHmac { + type Algorithm = + | 'rmd160' + | 'ripemd160' + | 'md5' + | 'sha' + | 'sha1' + | 'sha224' + | 'sha256' + | 'sha384' + | 'sha512'; +} diff --git a/types/create-hmac/tsconfig.json b/types/create-hmac/tsconfig.json new file mode 100644 index 0000000000..badd99da29 --- /dev/null +++ b/types/create-hmac/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", + "create-hmac-tests.ts" + ] +} diff --git a/types/create-hmac/tslint.json b/types/create-hmac/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/create-hmac/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From afe5664ded8cec5ccf443e2dd682298f5b53c5b7 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 26 Nov 2018 21:41:06 +0100 Subject: [PATCH 322/836] Add types for sha.js --- types/sha.js/index.d.ts | 26 ++++++++++++++++++++++++++ types/sha.js/sha.js-tests.ts | 15 +++++++++++++++ types/sha.js/tsconfig.json | 23 +++++++++++++++++++++++ types/sha.js/tslint.json | 1 + 4 files changed, 65 insertions(+) create mode 100644 types/sha.js/index.d.ts create mode 100644 types/sha.js/sha.js-tests.ts create mode 100644 types/sha.js/tsconfig.json create mode 100644 types/sha.js/tslint.json diff --git a/types/sha.js/index.d.ts b/types/sha.js/index.d.ts new file mode 100644 index 0000000000..d5dc4ba752 --- /dev/null +++ b/types/sha.js/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for sha.js 2.4 +// Project: https://github.com/crypto-browserify/sha.js +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Hash } from 'crypto'; + +export = SHA; + +declare function SHA(algorithm: string): Hash; + +declare namespace SHA { + type Algorithm = 'sha' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512'; + interface HashStatic { + new (): Hash; + } + + const sha: HashStatic; + const sha1: HashStatic; + const sha224: HashStatic; + const sha256: HashStatic; + const sha384: HashStatic; + const sha512: HashStatic; +} diff --git a/types/sha.js/sha.js-tests.ts b/types/sha.js/sha.js-tests.ts new file mode 100644 index 0000000000..fd3cde2e47 --- /dev/null +++ b/types/sha.js/sha.js-tests.ts @@ -0,0 +1,15 @@ +import shajs = require('sha.js'); + +shajs('sha256') + .update('42') + .digest('hex'); +new shajs.sha().update('42').digest('hex'); +new shajs.sha1().update('42').digest('hex'); +new shajs.sha224().update('42').digest('hex'); +new shajs.sha256().update('42').digest('hex'); +new shajs.sha384().update('42').digest('hex'); +new shajs.sha512().update('42').digest('hex'); + +const sha256stream = shajs('sha256'); +sha256stream.end('42'); +(sha256stream.read() as Buffer).toString('hex'); diff --git a/types/sha.js/tsconfig.json b/types/sha.js/tsconfig.json new file mode 100644 index 0000000000..9f10462f5a --- /dev/null +++ b/types/sha.js/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", + "sha.js-tests.ts" + ] +} diff --git a/types/sha.js/tslint.json b/types/sha.js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sha.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 9ed2a742a2989285e8ca98bbc3b3c418df508c72 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 26 Nov 2018 22:03:57 +0100 Subject: [PATCH 323/836] Add types for ripemd160 --- types/ripemd160/index.d.ts | 16 ++++++++++++++++ types/ripemd160/ripemd160-tests.ts | 7 +++++++ types/ripemd160/tsconfig.json | 23 +++++++++++++++++++++++ types/ripemd160/tslint.json | 1 + 4 files changed, 47 insertions(+) create mode 100644 types/ripemd160/index.d.ts create mode 100644 types/ripemd160/ripemd160-tests.ts create mode 100644 types/ripemd160/tsconfig.json create mode 100644 types/ripemd160/tslint.json diff --git a/types/ripemd160/index.d.ts b/types/ripemd160/index.d.ts new file mode 100644 index 0000000000..27de423a18 --- /dev/null +++ b/types/ripemd160/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for ripemd160 2.0 +// Project: https://github.com/crypto-browserify/ripemd160#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Hash } from 'crypto'; + +export = RIPEMD160; + +declare const RIPEMD160: RIPEMD160Static; + +interface RIPEMD160Static { + new (): Hash; +} diff --git a/types/ripemd160/ripemd160-tests.ts b/types/ripemd160/ripemd160-tests.ts new file mode 100644 index 0000000000..3a78efbac3 --- /dev/null +++ b/types/ripemd160/ripemd160-tests.ts @@ -0,0 +1,7 @@ +import RIPEMD160 = require('ripemd160'); + +new RIPEMD160().update('42').digest('hex'); + +const ripemd160stream = new RIPEMD160(); +ripemd160stream.end('42'); +(ripemd160stream.read() as Buffer).toString('hex'); diff --git a/types/ripemd160/tsconfig.json b/types/ripemd160/tsconfig.json new file mode 100644 index 0000000000..07abc9bd05 --- /dev/null +++ b/types/ripemd160/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", + "ripemd160-tests.ts" + ] +} diff --git a/types/ripemd160/tslint.json b/types/ripemd160/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ripemd160/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From dac19ea9e5d43d976abce50f6302cd7df32ddbb7 Mon Sep 17 00:00:00 2001 From: Cameron Martin Date: Mon, 26 Nov 2018 21:40:06 +0000 Subject: [PATCH 324/836] [@babel/core]: Fixed typo in method name. Renamed one overload of `transformFromAstSync` to `transformFromAstAsync`. See https://github.com/babel/babel/blob/61f2aed5b0d3ef869dca2f8e2673e46079df7d09/packages/babel-core/src/transform-ast.js#L75 and https://github.com/babel/babel/blob/61f2aed5b0d3ef869dca2f8e2673e46079df7d09/packages/babel-core/src/index.js#L29 --- types/babel__core/babel__core-tests.ts | 4 ++++ types/babel__core/index.d.ts | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/types/babel__core/babel__core-tests.ts b/types/babel__core/babel__core-tests.ts index a873c3392f..623d4121fe 100644 --- a/types/babel__core/babel__core-tests.ts +++ b/types/babel__core/babel__core-tests.ts @@ -29,3 +29,7 @@ babel.transformFromAst(parsedAst!, sourceCode, options, (err, result) => { const transformFromAstSyncResult = babel.transformFromAstSync(parsedAst!, sourceCode, options); const { code, map, ast } = transformFromAstSyncResult!; + +babel.transformFromAstAsync(parsedAst!, sourceCode, options).then(transformFromAstAsyncResult => { + const { code, map, ast } = transformFromAstAsyncResult!; +}); diff --git a/types/babel__core/index.d.ts b/types/babel__core/index.d.ts index 85a89392af..ad061fba80 100644 --- a/types/babel__core/index.d.ts +++ b/types/babel__core/index.d.ts @@ -349,7 +349,7 @@ export function transformFromAstSync(ast: Node, code?: string, opts?: TransformO /** * Given an AST, transform it. */ -export function transformFromAstSync(ast: Node, code?: string, opts?: TransformOptions): Promise; +export function transformFromAstAsync(ast: Node, code?: string, opts?: TransformOptions): Promise; // A babel plugin is a simple function which must return an object matching // the following interface. Babel will throw if it finds unknown properties. From 9fa2b6599f6309a7e33e5b5ab1387537ed68d9df Mon Sep 17 00:00:00 2001 From: Boris Sergeyev Date: Mon, 26 Nov 2018 22:18:35 +0100 Subject: [PATCH 325/836] [react-redux] extended ThunkActionCreator testsuite to check all overloads --- types/react-redux/react-redux-tests.tsx | 59 ++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 5 deletions(-) diff --git a/types/react-redux/react-redux-tests.tsx b/types/react-redux/react-redux-tests.tsx index f47683047e..554ace09ff 100644 --- a/types/react-redux/react-redux-tests.tsx +++ b/types/react-redux/react-redux-tests.tsx @@ -120,12 +120,61 @@ function MapDispatchWithThunkActionCreators() { } class TestComponent extends React.Component {} - const Test = connect( - null, - ({ simpleAction, thunkAction }), - )(TestComponent); + const mapStateToProps = ({ foo }: { foo: string }) => ({ foo }); + const mapDispatchToProps = { simpleAction, thunkAction }; - const verify = ; + const Test1 = connect(null, mapDispatchToProps)(TestComponent); + const Test2 = connect(mapStateToProps, mapDispatchToProps)(TestComponent); + const Test3 = connect( + null, mapDispatchToProps, null, { storeKey: 'somekey' } + )(TestComponent); + const Test4 = connect( + mapStateToProps, mapDispatchToProps, null, { storeKey: 'somekey' } + )(TestComponent); + const verify =
+ ; + + ; + +
; +} + +function MapManualDispatchThatLooksLikeThunk() { + interface OwnProps { + foo: string; + } + interface TestComponentProps extends OwnProps { + remove: (item: string) => () => object; + } + class TestComponent extends React.Component { + render() { + return
; + } + } + + const mapStateToProps = ({ foo }: { foo: string }) => ({ foo }); + function mapDispatchToProps(dispatch: Dispatch) { + return { + remove(item: string) { + return () => dispatch({ type: 'REMOVE_ITEM', item }); + } + }; + } + + const Test1 = connect(null, mapDispatchToProps)(TestComponent); + const Test2 = connect(mapStateToProps, mapDispatchToProps)(TestComponent); + const Test3 = connect( + null, mapDispatchToProps, null, { storeKey: 'somekey' } + )(TestComponent); + const Test4 = connect( + mapStateToProps, mapDispatchToProps, null, { storeKey: 'somekey' } + )(TestComponent); + const verify =
+ ; + + ; + +
; } function MapStateAndDispatchObject() { From 8cbf6d938de2e838a4f3cc9695576958ed55f4c3 Mon Sep 17 00:00:00 2001 From: Boris Sergeyev Date: Mon, 26 Nov 2018 22:19:18 +0100 Subject: [PATCH 326/836] [react-redux] fixed type definitions to pass extended tests --- types/react-redux/index.d.ts | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index bf65d89fd5..dc8a9af912 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -160,7 +160,12 @@ export interface Connect { ( mapStateToProps: null | undefined, - mapDispatchToProps: MapDispatchToPropsParam + mapDispatchToProps: MapDispatchToPropsNonObject + ): InferableComponentEnhancerWithProps; + + ( + mapStateToProps: null | undefined, + mapDispatchToProps: TDispatchProps, ): InferableComponentEnhancerWithProps< WithThunkActionCreators, TOwnProps @@ -168,7 +173,12 @@ export interface Connect { ( mapStateToProps: MapStateToPropsParam, - mapDispatchToProps: MapDispatchToPropsParam + mapDispatchToProps: MapDispatchToPropsNonObject + ): InferableComponentEnhancerWithProps; + + ( + mapStateToProps: MapStateToPropsParam, + mapDispatchToProps: TDispatchProps, ): InferableComponentEnhancerWithProps< TStateProps & WithThunkActionCreators, TOwnProps @@ -208,7 +218,14 @@ export interface Connect { ( mapStateToProps: null | undefined, - mapDispatchToProps: MapDispatchToPropsParam, + mapDispatchToProps: MapDispatchToPropsNonObject, + mergeProps: null | undefined, + options: Options<{}, TStateProps, TOwnProps> + ): InferableComponentEnhancerWithProps; + + ( + mapStateToProps: null | undefined, + mapDispatchToProps: TDispatchProps, mergeProps: null | undefined, options: Options<{}, TStateProps, TOwnProps> ): InferableComponentEnhancerWithProps< @@ -218,7 +235,14 @@ export interface Connect { ( mapStateToProps: MapStateToPropsParam, - mapDispatchToProps: MapDispatchToPropsParam, + mapDispatchToProps: MapDispatchToPropsNonObject, + mergeProps: null | undefined, + options: Options + ): InferableComponentEnhancerWithProps; + + ( + mapStateToProps: MapStateToPropsParam, + mapDispatchToProps: TDispatchProps, mergeProps: null | undefined, options: Options ): InferableComponentEnhancerWithProps< @@ -248,10 +272,12 @@ export type MapDispatchToProps = MapDispatchToPropsFunction | TDispatchProps; export type MapDispatchToPropsFactory = - (dispatch: Dispatch, ownProps: TOwnProps) => MapDispatchToProps; + (dispatch: Dispatch, ownProps: TOwnProps) => MapDispatchToPropsFunction; export type MapDispatchToPropsParam = MapDispatchToPropsFactory | MapDispatchToProps; +export type MapDispatchToPropsNonObject = MapDispatchToPropsFactory | MapDispatchToPropsFunction; + export type MergeProps = (stateProps: TStateProps, dispatchProps: TDispatchProps, ownProps: TOwnProps) => TMergedProps; From 009260118e5ebe5a5afe3ebf749998d69e0e5ea7 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 25 Nov 2018 23:53:43 +0100 Subject: [PATCH 327/836] Add types for saslmechanisms --- types/saslmechanisms/index.d.ts | 31 ++++++++++++++++++++ types/saslmechanisms/saslmechanisms-tests.ts | 22 ++++++++++++++ types/saslmechanisms/tsconfig.json | 23 +++++++++++++++ types/saslmechanisms/tslint.json | 1 + 4 files changed, 77 insertions(+) create mode 100644 types/saslmechanisms/index.d.ts create mode 100644 types/saslmechanisms/saslmechanisms-tests.ts create mode 100644 types/saslmechanisms/tsconfig.json create mode 100644 types/saslmechanisms/tslint.json diff --git a/types/saslmechanisms/index.d.ts b/types/saslmechanisms/index.d.ts new file mode 100644 index 0000000000..62f71e8a25 --- /dev/null +++ b/types/saslmechanisms/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for saslmechanisms 0.1 +// Project: https://github.com/jaredhanson/js-sasl +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Factory; + +declare class Factory { + static Factory: typeof Factory; + + use(name: string, mechanism: Factory.MechanismStatic): this; + use(mechanism: Factory.MechanismStatic): this; + create(mechanisms: string[]): Factory.Mechanism | null; +} + +declare namespace Factory { + interface MechanismStatic { + new (): Mechanism; + prototype: { + [key: string]: any; + name: string; + }; + } + interface Mechanism { + name: string; + + response(cred: { [key: string]: any }): string; + + challenge(chal: string): void; + } +} diff --git a/types/saslmechanisms/saslmechanisms-tests.ts b/types/saslmechanisms/saslmechanisms-tests.ts new file mode 100644 index 0000000000..d7e6fe7620 --- /dev/null +++ b/types/saslmechanisms/saslmechanisms-tests.ts @@ -0,0 +1,22 @@ +import Fct = require('saslmechanisms'); +import { Factory, MechanismStatic, Mechanism } from 'saslmechanisms'; + +const Mech: MechanismStatic = null as any; + +const factory = new Fct(); +new Factory(); +new Factory.Factory(); + +// $ExpectType Factory +factory.use(Mech); +factory.use('Mech', Mech); + +const mech: Mechanism | null = factory.create(['Mech']); +if (mech) { + // $ExpectType string + mech.name; + // $ExpectType string + mech.response({ foo: 'bar' }); + // $ExpectType void + mech.challenge('challenge'); +} diff --git a/types/saslmechanisms/tsconfig.json b/types/saslmechanisms/tsconfig.json new file mode 100644 index 0000000000..64beedfc0f --- /dev/null +++ b/types/saslmechanisms/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", + "saslmechanisms-tests.ts" + ] +} diff --git a/types/saslmechanisms/tslint.json b/types/saslmechanisms/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/saslmechanisms/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 9f4587cc6731cf6e733de34f6a09c71415a373f8 Mon Sep 17 00:00:00 2001 From: Cameron Martin Date: Mon, 26 Nov 2018 23:52:05 +0000 Subject: [PATCH 328/836] [@babel/traverse]: Added types to argument of Scope#push. Copied from the flow types (https://github.com/babel/babel/blob/61f2aed5b0d3ef869dca2f8e2673e46079df7d09/packages/babel-traverse/src/scope/index.js#L778) with one exception - kind was made optional, since this is assigned a default value (https://github.com/babel/babel/blob/61f2aed5b0d3ef869dca2f8e2673e46079df7d09/packages/babel-traverse/src/scope/index.js#L801) and is most likely a mistake in the flow types. --- types/babel__traverse/index.d.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/types/babel__traverse/index.d.ts b/types/babel__traverse/index.d.ts index 465a60464f..4825dc5303 100644 --- a/types/babel__traverse/index.d.ts +++ b/types/babel__traverse/index.d.ts @@ -90,7 +90,13 @@ export class Scope { removeData(key: string): void; - push(opts: any): void; + push(opts: { + id: object, + init?: object, + unique?: boolean, + _blockHoist?: number, + kind?: "var" | "let", + }): void; getProgramParent(): Scope; From aa086a84c1eb3b2499f77d0d075f91a672f11573 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Santiago=20Aguilar=20Hern=C3=A1ndez?= Date: Mon, 26 Nov 2018 19:16:28 -0500 Subject: [PATCH 329/836] * Applied better practices --- types/better-sqlite3/better-sqlite3-tests.ts | 22 +++-- types/better-sqlite3/index.d.ts | 86 +++++++++++++++++++- types/better-sqlite3/tsconfig.json | 1 - types/better-sqlite3/types.d.ts | 80 ------------------ 4 files changed, 99 insertions(+), 90 deletions(-) delete mode 100644 types/better-sqlite3/types.d.ts diff --git a/types/better-sqlite3/better-sqlite3-tests.ts b/types/better-sqlite3/better-sqlite3-tests.ts index 5d8b95ecf7..7272d88f7e 100644 --- a/types/better-sqlite3/better-sqlite3-tests.ts +++ b/types/better-sqlite3/better-sqlite3-tests.ts @@ -1,27 +1,33 @@ import Database = require('better-sqlite3'); -import { RunResult } from 'better-sqlite3/types'; const integer = Database.Integer(1); const err = new Database.SqliteError('ok', 'ok'); -const result: RunResult = { changes: 1, lastInsertRowid: 1 }; +const result: Database.RunResult = { changes: 1, lastInsertRowid: 1 }; +const options: Database.Options = { fileMustExist: true, memory: true, readonly: true }; +const registrationOptions: Database.RegistrationOptions = { + deterministic: true, + name: '', + safeIntegers: true, + varargs: true +}; let db = Database('.'); -db = new Database('.', {memory: true}); +db = new Database('.', { memory: true }); db.exec('CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL);'); db.exec('INSERT INTO test(name) VALUES("name");'); db.pragma('data_version', true); db.checkpoint(); db.checkpoint('main'); -db.register(() => {}); -db.register({name: 'noop', deterministic: true, varargs: true}, () => {}); +db.register(() => { }); +db.register({ name: 'noop', deterministic: true, varargs: true }, () => { }); db.defaultSafeIntegers(); db.defaultSafeIntegers(true); const stmt = db.prepare('SELECT * FROM test WHERE name == ?;'); stmt.get(['name']); -stmt.all({name: 'name'}); -stmt.each('name', (row: {name: string}) => {}); -stmt.each((row: {name: string}) => {}); +stmt.all({ name: 'name' }); +stmt.each('name', (row: { name: string }) => { }); +stmt.each((row: { name: string }) => { }); stmt.pluck(); stmt.pluck(true); stmt.bind('name'); diff --git a/types/better-sqlite3/index.d.ts b/types/better-sqlite3/index.d.ts index d120209765..5a4859e21f 100644 --- a/types/better-sqlite3/index.d.ts +++ b/types/better-sqlite3/index.d.ts @@ -5,7 +5,91 @@ // Santiago Aguilar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import { DatabaseConstructor } from "./types"; +import Integer = require("integer"); + +declare class Statement { + database: Database; + source: string; + returnsData: boolean; + constructor(db: Database, sources: string[]); + + run(...params: any[]): Database.RunResult; + get(...params: any[]): any; + all(...params: any[]): any[]; + each(params: any, cb: (row: any) => void): void; + each(cb: (row: any) => void): void; + each(...params: any[]): void; + pluck(toggleState?: boolean): this; + bind(...params: any[]): this; + safeIntegers(toggleState?: boolean): this; +} + +declare class Transaction { + database: Database; + source: string; + constructor(db: Database, sources: string[]); + + run(...params: any[]): Database.RunResult; + bind(...params: any[]): this; + safeIntegers(toggleState?: boolean): this; +} + +interface Database { + memory: boolean; + readonly: boolean; + name: string; + open: boolean; + inTransaction: boolean; + + prepare(source: string): Statement; + transaction(sources: string[]): Transaction; + exec(source: string): this; + pragma(source: string, simplify?: boolean): any; + checkpoint(databaseName?: string): this; + register(cb: (...params: any[]) => any): this; + register( + options: Database.RegistrationOptions, + cb: (...params: any[]) => any + ): this; + close(): this; + defaultSafeIntegers(toggleState?: boolean): this; +} + +declare class SqliteError implements Error { + name: string; + message: string; + code: string; + constructor(message: string, code: string); +} + +interface DatabaseConstructor { + new (filename: string, options?: Database.Options): Database; + (filename: string, options?: Database.Options): Database; + prototype: Database; + + Integer: typeof Integer; + SqliteError: typeof SqliteError; +} + +declare namespace Database { + interface RunResult { + changes: number; + lastInsertRowid: Integer.IntLike; + } + + interface Options { + memory?: boolean; + readonly?: boolean; + fileMustExist?: boolean; + } + + interface RegistrationOptions { + name?: string; + varargs?: boolean; + deterministic?: boolean; + safeIntegers?: boolean; + } +} declare const Database: DatabaseConstructor; export = Database; diff --git a/types/better-sqlite3/tsconfig.json b/types/better-sqlite3/tsconfig.json index 891afa0aad..30a480355b 100644 --- a/types/better-sqlite3/tsconfig.json +++ b/types/better-sqlite3/tsconfig.json @@ -18,7 +18,6 @@ }, "files": [ "index.d.ts", - "types.d.ts", "better-sqlite3-tests.ts" ] } \ No newline at end of file diff --git a/types/better-sqlite3/types.d.ts b/types/better-sqlite3/types.d.ts deleted file mode 100644 index 61f376b0bf..0000000000 --- a/types/better-sqlite3/types.d.ts +++ /dev/null @@ -1,80 +0,0 @@ -import Integer = require("integer"); - -export interface RunResult { - changes: number; - lastInsertRowid: Integer.IntLike; -} - -export class Statement { - database: Database; - source: string; - returnsData: boolean; - constructor(db: Database, sources: string[]); - - run(...params: any[]): RunResult; - get(...params: any[]): any; - all(...params: any[]): any[]; - each(params: any, cb: (row: any) => void): void; - each(cb: (row: any) => void): void; - each(...params: any[]): void; - pluck(toggleState?: boolean): this; - bind(...params: any[]): this; - safeIntegers(toggleState?: boolean): this; -} - -export class Transaction { - database: Database; - source: string; - constructor(db: Database, sources: string[]); - - run(...params: any[]): RunResult; - bind(...params: any[]): this; - safeIntegers(toggleState?: boolean): this; -} - -export interface DatabaseOptions { - memory?: boolean; - readonly?: boolean; - fileMustExist?: boolean; -} - -export interface RegistrationOptions { - name?: string; - varargs?: boolean; - deterministic?: boolean; - safeIntegers?: boolean; -} - -export interface Database { - memory: boolean; - readonly: boolean; - name: string; - open: boolean; - inTransaction: boolean; - - prepare(source: string): Statement; - transaction(sources: string[]): Transaction; - exec(source: string): this; - pragma(source: string, simplify?: boolean): any; - checkpoint(databaseName?: string): this; - register(cb: (...params: any[]) => any): this; - register(options: RegistrationOptions, cb: (...params: any[]) => any): this; - close(): this; - defaultSafeIntegers(toggleState?: boolean): this; -} - -export class SqliteError implements Error { - name: string; - message: string; - code: string; - constructor(message: string, code: string); -} - -export interface DatabaseConstructor { - new (filename: string, options?: DatabaseOptions): Database; - (filename: string, options?: DatabaseOptions): Database; - prototype: Database; - - Integer: typeof Integer; - SqliteError: typeof SqliteError; -} From 838a295269bc8f0674c902db18d87b95e3cc406e Mon Sep 17 00:00:00 2001 From: ksaryan Date: Mon, 26 Nov 2018 16:20:05 -0800 Subject: [PATCH 330/836] Add ios_backgroundColor prop to Switch --- types/react-native/index.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 2386fc71c2..9e68e283a9 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -8177,6 +8177,13 @@ export interface SwitchProps extends SwitchPropsIOS { * Default value is false. */ value?: boolean; + + /** + * On iOS, custom color for the background. + * Can be seen when the switch value is false or when the switch is disabled. + */ + ios_backgroundColor?: string; + style?: StyleProp; } From 389b8185f9630eb48b27b95c40f5c39b8c15137a Mon Sep 17 00:00:00 2001 From: obedm503 Date: Mon, 26 Nov 2018 20:31:12 -0600 Subject: [PATCH 331/836] Revert typescript version change --- types/react-intl/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-intl/index.d.ts b/types/react-intl/index.d.ts index 2c25a55b1f..aaba74820b 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -11,7 +11,7 @@ // Kanitkorn Sujautra // obedm503 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.9 +// TypeScript Version: 2.8 declare namespace ReactIntl { type DateSource = Date | string | number; From 5934128c87ea053d8443a14b5fa1b692f1db2730 Mon Sep 17 00:00:00 2001 From: obedm503 Date: Mon, 26 Nov 2018 20:39:22 -0600 Subject: [PATCH 332/836] fix trailing whitespace --- types/react-intl/react-intl-tests.tsx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/types/react-intl/react-intl-tests.tsx b/types/react-intl/react-intl-tests.tsx index 74da23a12a..63af762e61 100644 --- a/types/react-intl/react-intl-tests.tsx +++ b/types/react-intl/react-intl-tests.tsx @@ -401,13 +401,13 @@ class TestApp extends React.Component { hello: "Hello, {name}!" }; return ( - console.error(error)} > From 82d92693da98494f58dcbaf62b514fa14051fad5 Mon Sep 17 00:00:00 2001 From: quas94 Date: Tue, 27 Nov 2018 16:27:11 +1100 Subject: [PATCH 333/836] Update typedefs --- .../dropbox-chooser/dropbox-chooser-tests.ts | 6 +++--- types/dropbox-chooser/index.d.ts | 19 ++++++++++--------- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/types/dropbox-chooser/dropbox-chooser-tests.ts b/types/dropbox-chooser/dropbox-chooser-tests.ts index f0930733f8..e998bad7bf 100644 --- a/types/dropbox-chooser/dropbox-chooser-tests.ts +++ b/types/dropbox-chooser/dropbox-chooser-tests.ts @@ -1,7 +1,7 @@ // Tests for Dropbox Chooser DefinitelyTyped TS definitions -const options: DropboxChooserOptions = { - success: (files: ReadonlyArray) => { +const options: Dropbox.ChooserOptions = { + success: (files: ReadonlyArray) => { console.log('Success, selected files were:', files); }, }; @@ -9,7 +9,7 @@ const options: DropboxChooserOptions = { const Dropbox = window.Dropbox!; Dropbox.choose(options); -const sampleFile: DropboxChooserFile = { +const sampleFile: Dropbox.ChooserFile = { id: 'SAMPLE_ID', name: 'HelloBox.jpg', link: 'http://localhost/1.png', diff --git a/types/dropbox-chooser/index.d.ts b/types/dropbox-chooser/index.d.ts index 8c9db6f72d..c9a9db4d70 100644 --- a/types/dropbox-chooser/index.d.ts +++ b/types/dropbox-chooser/index.d.ts @@ -4,13 +4,14 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Dropbox { - interface DropboxChooser { + + interface Chooser { choose(options: ChooserOptions): void; } interface ChooserOptions { - // alled when a user selects an item in the Chooser - success(files: ReadonlyArray): void; + // called when a user selects an item in the Chooser + success(files: ReadonlyArray): void; // called when the user closes the dialog without selecting a file cancel?(): void; @@ -31,7 +32,7 @@ declare namespace Dropbox { sizeLimit?: number; } - interface File { + interface ChooserFile { // Unique ID for the file, compatible with Dropbox API v2. id: string; @@ -55,12 +56,12 @@ declare namespace Dropbox { // whether or not the file is actually a directory isDir: boolean; } -} -type DropboxChooser = Dropbox.DropboxChooser; -type DropboxChooserOptions = Dropbox.ChooserOptions; -type DropboxChooserFile = Dropbox.File; + // Refer to "Handling the response" section of: https://www.dropbox.com/developers/chooser + type ChooserFileBoundingBox = 75 | 256 | 800 | 1280 | 2048; + type ChooserFileMode = 'fit' | 'crop' | 'fit_one_and_overflow'; +} interface Window { - Dropbox?: DropboxChooser; + Dropbox?: Dropbox.Chooser; } From 2df4d594006f2a9070e2359ac791768c14430623 Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Tue, 27 Nov 2018 14:40:20 +0900 Subject: [PATCH 334/836] Set data unknown --- types/vfile/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/vfile/index.d.ts b/types/vfile/index.d.ts index ce8f1dce38..7329e8e9ec 100644 --- a/types/vfile/index.d.ts +++ b/types/vfile/index.d.ts @@ -117,7 +117,7 @@ declare namespace vfile { * Place to store custom information. * It's OK to store custom data directly on the `vfile`, moving it to `data` gives a little more privacy. */ - data: any; + data: unknown; /** * List of messages associated with the file. */ From 1da614b33511ba1968a40a86df80dede10895967 Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Tue, 27 Nov 2018 14:40:34 +0900 Subject: [PATCH 335/836] Clean up type tests --- types/vfile/vfile-tests.ts | 116 ++++++++++++++++++++++--------------- 1 file changed, 68 insertions(+), 48 deletions(-) diff --git a/types/vfile/vfile-tests.ts b/types/vfile/vfile-tests.ts index 4d146237b1..5c14c8502b 100644 --- a/types/vfile/vfile-tests.ts +++ b/types/vfile/vfile-tests.ts @@ -2,56 +2,38 @@ import vfile = require('vfile'); import * as Unist from 'unist'; // Instantiation -vfile(); +const file: vfile.VFile = vfile(); vfile('string'); vfile(Buffer.from('string')); vfile(vfile()); vfile({ stem: 'readme', extname: '.md' }); -try { - vfile({ extname: '.md' }); -} catch (e) { - console.log('Error: set extname without path'); -} -interface CustomVFile extends vfile.VFile { - custom: string; - data: { - custom: number; - }; -} - -const file = vfile({ - path: '~/example.txt', - contents: 'Alpha *braavo* charlie.', - custom: 'Custom tango', - data: { - custom: 12345 - } -}); -const customIsString: string = file.custom; -const dataCustomIsNumber: number = file.data.custom; -const copiedFile: CustomVFile = vfile(file); - -file.path; // => '~/example.txt' -file.dirname; // => '~' +vfile({ path: 1234 }); // $ExpectError +file.path = '~/test.txt'; +file.dirname = '~'; file.extname = '.md'; +file.basename = 'test.text'; +file.history = ['~/test.txt']; // => ['~/example.txt', '~/example.md', '~/index.text'] +file.messages = [{ + file: '~/test.txt', + ruleId: '', + reason: '', + line: 1, + column: 1, + location: { + start: { + line: 1, + column: 1, + }, + end: { + line: 1, + column: 1, + } + }, + source: '' +}]; -file.basename; // => 'example.md' - -file.basename = 'index.text'; - -file.history; // => ['~/example.txt', '~/example.md', '~/index.text'] - -file.message('`braavo` is misspelt; did you mean `bravo`?', {line: 1, column: 8}); - -console.log(file.messages); - -// Typings of the custom data can be resolved from the parameters above -const custom: string = file.custom; // 'Custom tango' -const dataCustom: number = file.data.custom; // 12345 - -// message method accept any Stringifiable Position(e.g. point, position, node with position) const startPoint: Unist.Point = { line: 1, column: 1, @@ -63,18 +45,56 @@ const position: Unist.Position = { column: 2, }, }; -// Accept Point + file.message('test', startPoint); -// Accept Position file.message('test', position); -// Accept Node with extra value file.message('test', { type: 'ramdom node', position, extraValue: 'extra tango', }); -// But, it must reject any malformed position + file.message('test', { start: 'invalid point' }); // $ExpectError -// Typings of original properties must be kept -const fileWithWrongParams = vfile({ path: 1234 }); // $ExpectError +// Using `data` prop +interface CustomData { + message: string; +} +function isCustomData(data: any): data is CustomData { + return data != null && typeof data.message === 'string'; +} +function doSomethingWithCustomData(data: CustomData) { +} +const customData: CustomData = { + message: 'tango' +}; +const fileWithData = vfile({ + data: customData +}); + +if (isCustomData(fileWithData.data)) { + doSomethingWithCustomData(fileWithData.data); +} +doSomethingWithCustomData(fileWithData.data); // $ExpectError + +// Extending vfile +interface CustomVFile extends vfile.VFile { + custom: string; + data: { + custom: number; + }; +} + +const customVFile = vfile({ + path: '~/example.txt', + contents: 'Alpha *braavo* charlie.', + custom: 'Custom tango', + data: { + custom: 12345 + } +}); + +customVFile.custom = 'test'; +customVFile.data.custom = 1234; + +const copiedFile: CustomVFile = vfile(customVFile); From dcf5a0dbd497d343a92b6084440c7ffb12cc220f Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Tue, 27 Nov 2018 14:47:42 +0900 Subject: [PATCH 336/836] Add decription for `data` prop --- types/vfile/readme.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/types/vfile/readme.md b/types/vfile/readme.md index 349503cef8..21525242cb 100644 --- a/types/vfile/readme.md +++ b/types/vfile/readme.md @@ -3,6 +3,34 @@ Below are some examples of how to use these Definitions.
Scenarios where the Typescript code is identical to plain Javascript code are omitted. +### Using `data` property + +Because `data` property type is set `unknown`, you have to make your own type guard. + +```ts +interface CustomData { + message: string; +} +// This is the type guard +function isCustomData(data: any): data is CustomData { + return data != null && typeof data.message === 'string'; +} +function doSomethingWithCustomData(data: CustomData) { +} +const customData: CustomData = { + message: 'tango' +}; +const fileWithData = vfile({ + data: customData +}); + +if (isCustomData(fileWithData.data)) { + doSomethingWithCustomData(fileWithData.data); +} +// The below code will throw a compiler error +doSomethingWithCustomData(fileWithData.data); // $ExpectError +``` + ### Extending VFile ```ts From dcc3948836f0a3683aeb8cb9b6395742760757a8 Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Tue, 27 Nov 2018 14:49:51 +0900 Subject: [PATCH 337/836] Upgrade typescript version because it is using `unknown` --- types/vfile/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/vfile/index.d.ts b/types/vfile/index.d.ts index 7329e8e9ec..df729e0a49 100644 --- a/types/vfile/index.d.ts +++ b/types/vfile/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: bizen241 // Junyoung Choi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 3.0 /// From e0b6335bbc3545f111bf199e52f4364569b806f1 Mon Sep 17 00:00:00 2001 From: quas94 Date: Tue, 27 Nov 2018 16:55:24 +1100 Subject: [PATCH 338/836] Remove newline --- types/dropbox-chooser/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/dropbox-chooser/index.d.ts b/types/dropbox-chooser/index.d.ts index c9a9db4d70..c5fd8a6cd6 100644 --- a/types/dropbox-chooser/index.d.ts +++ b/types/dropbox-chooser/index.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Dropbox { - interface Chooser { choose(options: ChooserOptions): void; } From 84bc355df06ea07679ab0634483c08f76ac4bb7c Mon Sep 17 00:00:00 2001 From: Boris Sergeyev Date: Tue, 27 Nov 2018 07:18:16 +0100 Subject: [PATCH 339/836] [react-redux] improved naming of higher-order-type that handles thunks --- types/react-redux/index.d.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index dc8a9af912..bcbcced0bd 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -112,19 +112,19 @@ export type InferableComponentEnhancerWithProps = export type InferableComponentEnhancer = InferableComponentEnhancerWithProps; -export type WrappedThunkActionCreator any> = +export type InferThunkActionCreatorType any> = TActionCreator extends (...args: infer TParams) => (...args: any[]) => infer TReturn ? (...args: TParams) => TReturn : TActionCreator; export type HandleThunkActionCreator = TActionCreator extends (...args: any[]) => any - ? WrappedThunkActionCreator + ? InferThunkActionCreatorType : TActionCreator; // redux-thunk middleware returns thunk's return value from dispatch call // https://github.com/reduxjs/redux-thunk#composition -export type WithThunkActionCreators = +export type ResolveThunks = TDispatchProps extends { [key: string]: any } ? { [C in keyof TDispatchProps]: HandleThunkActionCreator @@ -167,7 +167,7 @@ export interface Connect { mapStateToProps: null | undefined, mapDispatchToProps: TDispatchProps, ): InferableComponentEnhancerWithProps< - WithThunkActionCreators, + ResolveThunks, TOwnProps >; @@ -180,7 +180,7 @@ export interface Connect { mapStateToProps: MapStateToPropsParam, mapDispatchToProps: TDispatchProps, ): InferableComponentEnhancerWithProps< - TStateProps & WithThunkActionCreators, + TStateProps & ResolveThunks, TOwnProps >; @@ -229,7 +229,7 @@ export interface Connect { mergeProps: null | undefined, options: Options<{}, TStateProps, TOwnProps> ): InferableComponentEnhancerWithProps< - WithThunkActionCreators, + ResolveThunks, TOwnProps >; @@ -246,7 +246,7 @@ export interface Connect { mergeProps: null | undefined, options: Options ): InferableComponentEnhancerWithProps< - TStateProps & WithThunkActionCreators, + TStateProps & ResolveThunks, TOwnProps >; // tslint:enable:no-unnecessary-generics From ebb397fb9eab1217421bd2f80d301a157ec15bb2 Mon Sep 17 00:00:00 2001 From: Cameron Martin Date: Tue, 27 Nov 2018 09:12:09 +0000 Subject: [PATCH 340/836] Implemented suggested changes. --- types/babel__traverse/babel__traverse-tests.ts | 3 ++- types/babel__traverse/index.d.ts | 7 +++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/types/babel__traverse/babel__traverse-tests.ts b/types/babel__traverse/babel__traverse-tests.ts index 5b4fbbef5f..2f5b5ca74d 100644 --- a/types/babel__traverse/babel__traverse-tests.ts +++ b/types/babel__traverse/babel__traverse-tests.ts @@ -89,7 +89,8 @@ const v1: Visitor = { const id = path.scope.generateUidIdentifierBasedOnNode(path.node.id!); path.remove(); - path.scope.parent.push({ id, init: path.node }); + path.scope.parent.push({ id }); + path.scope.parent.push({ id, init: t.stringLiteral('foo'), kind: "const" }); path.scope.rename("n", "x"); path.scope.rename("n"); diff --git a/types/babel__traverse/index.d.ts b/types/babel__traverse/index.d.ts index 4825dc5303..93c768a913 100644 --- a/types/babel__traverse/index.d.ts +++ b/types/babel__traverse/index.d.ts @@ -91,11 +91,10 @@ export class Scope { removeData(key: string): void; push(opts: { - id: object, - init?: object, + id: t.LVal, + init?: t.Expression, unique?: boolean, - _blockHoist?: number, - kind?: "var" | "let", + kind?: "var" | "let" | "const", }): void; getProgramParent(): Scope; From 9b183dbac86e46d7ffd08bcb6c5ee6385c3cc081 Mon Sep 17 00:00:00 2001 From: Cameron Martin Date: Tue, 27 Nov 2018 09:13:03 +0000 Subject: [PATCH 341/836] Introduced $ExpectError. See https://github.com/Microsoft/dtslint#write-tests --- types/babel__traverse/babel__traverse-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/babel__traverse/babel__traverse-tests.ts b/types/babel__traverse/babel__traverse-tests.ts index 2f5b5ca74d..1a1bf712d7 100644 --- a/types/babel__traverse/babel__traverse-tests.ts +++ b/types/babel__traverse/babel__traverse-tests.ts @@ -105,7 +105,7 @@ const BindingKindTest: Visitor = { kind === 'const'; kind === 'let'; kind === 'var'; - // The following should fail when uncommented - // kind === 'anythingElse'; + // $ExpectError + kind === 'anythingElse'; }, }; From 0d5716d5f08c94062e7ac396587ed956f168ea6d Mon Sep 17 00:00:00 2001 From: Stefano Bourscheid Date: Tue, 27 Nov 2018 11:33:48 +0100 Subject: [PATCH 342/836] Remove 2.x support from react-native-video --- types/react-native-video/index.d.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/types/react-native-video/index.d.ts b/types/react-native-video/index.d.ts index 726169caca..63d0ff6c89 100644 --- a/types/react-native-video/index.d.ts +++ b/types/react-native-video/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native-video 2.0 and 3.1 +// Type definitions for react-native-video 3.1 // Project: https://github.com/react-native-community/react-native-video // Definitions by: HuHuanming // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -95,8 +95,6 @@ export interface VideoProperties extends ViewProps { onPlaybackRateChange?(): void; onAudioFocusChanged?(): void; onAudioBecomingNoisy?(): void; - - /* 3.0 onwards */ selectedTextTrack?: { type: 'system' | 'disabled' | 'title' | 'language' | 'index'; value?: string | number; From 97c9978a5636017e3df50a6dba07d6184d2eae63 Mon Sep 17 00:00:00 2001 From: Christian Chown Date: Tue, 27 Nov 2018 12:05:37 +0000 Subject: [PATCH 343/836] Correct onSelect signature for unenhanced calendars --- types/react-infinite-calendar/index.d.ts | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/types/react-infinite-calendar/index.d.ts b/types/react-infinite-calendar/index.d.ts index 3f0c827ed9..8d17e6dd4e 100644 --- a/types/react-infinite-calendar/index.d.ts +++ b/types/react-infinite-calendar/index.d.ts @@ -8,6 +8,21 @@ import * as React from 'react'; export type DateType = Date | string | number; +export enum EVENT_TYPE { + START = 1, + HOVER, + END +} + +export interface RangedSelection { + eventType: EVENT_TYPE; + start: Date; + end: Date; +} + +type RangedSelectFunction = (rangedDate: RangedSelection) => void; +type DateSelectFunction = (date: string) => void; + export interface ReactInfiniteCalendarProps { selected?: DateType | false | { start: DateType; end: DateType }; width?: number | 'auto' | '100%'; @@ -57,7 +72,7 @@ export interface ReactInfiniteCalendarProps { weekdayColor?: string; }; className?: string; - onSelect?: (date: string | { eventType: EVENT_TYPE; start: Date; end: Date }) => void; + onSelect?: DateSelectFunction | RangedSelectFunction; onScroll?: (scrollTop: number) => void; onScrollEnd?: (scrollTop: number) => void; rowHeight?: number; @@ -75,10 +90,4 @@ export function withMultipleDates(component: CalendarClass): CalendarClass; export function withKeyboardSupport(component: CalendarClass): CalendarClass; export function defaultMultipleDateInterpolation(component: CalendarClass): CalendarClass; -export enum EVENT_TYPE { - START = 1, - HOVER, - END -} - export default class ReactInfiniteCalendar extends React.Component {} From aa7352876a9c634bcae92726746bd92ea0c02005 Mon Sep 17 00:00:00 2001 From: Christian Chown Date: Tue, 27 Nov 2018 12:13:54 +0000 Subject: [PATCH 344/836] Export onSelect function types --- types/react-infinite-calendar/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-infinite-calendar/index.d.ts b/types/react-infinite-calendar/index.d.ts index 8d17e6dd4e..10a246c5ae 100644 --- a/types/react-infinite-calendar/index.d.ts +++ b/types/react-infinite-calendar/index.d.ts @@ -20,8 +20,8 @@ export interface RangedSelection { end: Date; } -type RangedSelectFunction = (rangedDate: RangedSelection) => void; -type DateSelectFunction = (date: string) => void; +export type RangedSelectFunction = (rangedDate: RangedSelection) => void; +export type DateSelectFunction = (date: string) => void; export interface ReactInfiniteCalendarProps { selected?: DateType | false | { start: DateType; end: DateType }; From 7e23c69081ef5211b821463eb9c223e891c7a456 Mon Sep 17 00:00:00 2001 From: Nokky Goren <30292793+ApeNox@users.noreply.github.com> Date: Tue, 27 Nov 2018 16:31:11 +0200 Subject: [PATCH 345/836] Update definitions to accommodate API changes InputProps are now optional. The Component now receives props via direct application. --- types/react-places-autocomplete/index.d.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index 62e3d93a1d..26046fc06f 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -15,9 +15,7 @@ export interface formattedSuggestionType { } export interface PropTypes { - inputProps: { - value: string; - onChange: (value: string) => void; + inputProps?: { type?: string; name?: string; placeholder?: string; @@ -49,6 +47,9 @@ export interface PropTypes { radius?: number | string; types?: string[]; }; + value: string; + onChange?: (value: string) => void; + onBlur?: (event: React.FocusEvent) => void; debounce?: number; highlightFirstSuggestion?: boolean; From b91830f72f5a229b7376fcfa238ef38c077b2122 Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Tue, 27 Nov 2018 23:35:27 +0900 Subject: [PATCH 346/836] Fix typescript version of vfile-location --- types/vfile-location/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/vfile-location/index.d.ts b/types/vfile-location/index.d.ts index b991528c7e..fbea17630e 100644 --- a/types/vfile-location/index.d.ts +++ b/types/vfile-location/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Ika // Junyoung Choi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 3.0 import * as VFile from "vfile"; From f5e979aa4e03525afab03c4bff3c339762b57314 Mon Sep 17 00:00:00 2001 From: Nokky Goren <30292793+ApeNox@users.noreply.github.com> Date: Tue, 27 Nov 2018 16:53:21 +0200 Subject: [PATCH 347/836] fix optional inputs --- types/react-places-autocomplete/index.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index 26046fc06f..f95164a89d 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -19,7 +19,6 @@ export interface PropTypes { type?: string; name?: string; placeholder?: string; - onBlur?: (event: React.FocusEvent) => void; disabled?: boolean; }; onError?: (status: string, clearSuggestion: () => void) => void; @@ -47,7 +46,7 @@ export interface PropTypes { radius?: number | string; types?: string[]; }; - value: string; + value?: string; onChange?: (value: string) => void; onBlur?: (event: React.FocusEvent) => void; From f4f4074e189ffb8b461566c4430bd3d4620daa17 Mon Sep 17 00:00:00 2001 From: Nokky Goren <30292793+ApeNox@users.noreply.github.com> Date: Tue, 27 Nov 2018 16:55:07 +0200 Subject: [PATCH 348/836] Update types version --- types/react-places-autocomplete/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index f95164a89d..19d53c863d 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-places-autocomplete 6.1 +// Type definitions for react-places-autocomplete 7 // Project: https://github.com/kenny-hibino/react-places-autocomplete/ // Definitions by: Guilherme Hübner // Andrew Makarov From 0a3010fe25eaded32b64e515df877479ca13cb53 Mon Sep 17 00:00:00 2001 From: Nokky Goren <30292793+ApeNox@users.noreply.github.com> Date: Tue, 27 Nov 2018 16:57:11 +0200 Subject: [PATCH 349/836] Update Tests --- .../react-places-autocomplete-tests.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx index 41e6ff37b4..a7a7816d99 100644 --- a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx +++ b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx @@ -45,7 +45,7 @@ class Test extends React.Component { return (
- + ); } From 4731065fe25d5aa1e192166802321482db70dd21 Mon Sep 17 00:00:00 2001 From: Nokky Goren <30292793+ApeNox@users.noreply.github.com> Date: Tue, 27 Nov 2018 17:02:42 +0200 Subject: [PATCH 350/836] Update index.d.ts --- types/react-places-autocomplete/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index 19d53c863d..6a6a85c19e 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-places-autocomplete 7 +// Type definitions for react-places-autocomplete 7.2 // Project: https://github.com/kenny-hibino/react-places-autocomplete/ // Definitions by: Guilherme Hübner // Andrew Makarov From 83a419ec7bd69ba15089a669a0aab466189d2b42 Mon Sep 17 00:00:00 2001 From: Chris O'Toole Date: Tue, 27 Nov 2018 10:38:11 -0500 Subject: [PATCH 351/836] Don't update main package version number --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 2bd57a4c7c..09fe064d48 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "private": true, "name": "definitely-typed", - "version": "0.0.4", + "version": "0.0.3", "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped", "repository": { "type": "git", From c7f49bd2d0d3e9f5cd066b6e340db5f404a0d212 Mon Sep 17 00:00:00 2001 From: dasimple Date: Tue, 27 Nov 2018 18:47:12 +0200 Subject: [PATCH 352/836] First typings for gdal package --- types/gdal/gdal-tests.ts | 78 ++++ types/gdal/index.d.ts | 764 +++++++++++++++++++++++++++++++++++++++ types/gdal/tsconfig.json | 22 ++ types/gdal/tslint.json | 1 + 4 files changed, 865 insertions(+) create mode 100644 types/gdal/gdal-tests.ts create mode 100644 types/gdal/index.d.ts create mode 100644 types/gdal/tsconfig.json create mode 100644 types/gdal/tslint.json diff --git a/types/gdal/gdal-tests.ts b/types/gdal/gdal-tests.ts new file mode 100644 index 0000000000..d30c83d571 --- /dev/null +++ b/types/gdal/gdal-tests.ts @@ -0,0 +1,78 @@ +import * as gdal from 'gdal'; + +// gdal.checksumImage(srcRasterBand, 0, 0, 512, 512); + +gdal.config.get('GDAL_DATA'); +gdal.config.set('GDAL_DATA', 'C:\\warmerda\\bld\\data'); + +/*gdal.contourGenerate({ + src: srcRasterBand, + dst: dstRasterBand +});*/ + +gdal.decToDMS(60, 'lat'); +gdal.decToDMS(60, 'lat', 2); + +/*gdal.fillNodata({ + +});*/ + +let creationOptionsArray: string[]; +creationOptionsArray = ['VRT_CREATION_OPTION=...']; +let creationOptionsObject: object; +creationOptionsObject = { + VRT_CREATION_OPTION: '...' +}; +gdal.open('C:\\datasets\\ogr.shp'); +gdal.open('C:\\datasets\\ogr.shp', 'r'); +gdal.open('C:\\datasets\\ogr.shp', 'r', 'ESRI Shapefile'); +gdal.open('C:\\datasets\\ogr.shp', 'r', ['ESRI Shapefile']); +gdal.open('C:\\datasets\\ogr.shp', 'r+'); +gdal.open('C:\\datasets\\ogr.shp', 'r+', 'ESRI Shapefile'); +gdal.open('C:\\datasets\\ogr.shp', 'r+', ['ESRI Shapefile']); +gdal.open('C:\\datasets\\raster.vrt', 'w', 'VRT'); +gdal.open('C:\\datasets\\raster.vrt', 'w', 'VRT', 512, 512, 3, 1, creationOptionsArray); +gdal.open('C:\\datasets\\raster.vrt', 'w', 'VRT', 512, 512, 3, 1, creationOptionsObject); +gdal.open('C:\\datasets\\raster.vrt', 'w', ['VRT']); +gdal.open('C:\\datasets\\raster.vrt', 'w', ['VRT'], 512, 512, 3, 1, creationOptionsArray); +gdal.open('C:\\datasets\\raster.vrt', 'w', ['VRT'], 512, 512, 3, 1, creationOptionsObject); + +/*let polygonizeOptions: gdal.PolygonizeOptions; +polygonizeOptions = { + src: srcRasterBand, + dst: dstRasterBand, + connectedness: 1, + mask: maskRasterBand, + pixValField: 1, + useFloats: true +}; +gdal.polygonize(polygonizeOptions); +gdal.polygonize({ + src: srcRasterBand, + dst: dstRasterBand, + pixValField: 1 +});*/ + +gdal.quiet(); + +/*let reprojectImageOptions: gdal.ReprojectImageOptions; +reprojectImageOptions = { + src: srcRasterBand, + dst: dstRasterBand, + s_srs: sourceSRS, + t_srs: targetSRS +}; +gdal.reprojectImage(reprojectImageOptions); +gdal.reprojectImage({ + +}); + +gdal.sieveFilter({ + +}); + +gdal.suggestedWarpOutput({ + +});*/ + +gdal.verbose(); diff --git a/types/gdal/index.d.ts b/types/gdal/index.d.ts new file mode 100644 index 0000000000..50280cff3d --- /dev/null +++ b/types/gdal/index.d.ts @@ -0,0 +1,764 @@ +// Type definitions for gdal 0.9 +// Project: https://github.com/naturalatlas/node-gdal#readme +// Definitions by: Andrei Digori +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +export as namespace gdal; + +/* Internal interfaces */ + +export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; +export type Resampling = 'NEAREST' | 'GAUSS' | 'CUBIC' | 'AVERAGE' | 'MODE' | 'AVERAGE_MAGPHASE' | 'NONE'; + +export interface XY +{ + x: number; + y: number; +} + +export interface XYZ extends XY +{ + z: number; +} + +export interface EnvelopeBounds +{ + minX: number, + maxX: number, + minY: number, + maxY: number +} + +export interface Envelope3DBounds extends EnvelopeBounds +{ + minZ: number, + maxZ: number +} + +export interface RasterBandStatistics +{ + min: number; + max: number; + mean: number; + std_dev: number; +} + +export interface RasterBandPixelsWriteOptions +{ + buffer_width?: number; + buffer_height?: number; + pixel_space?: number; + line_space?: number; +} + +export interface RasterBandPixelsReadOptions +{ + buffer_width?: number; + buffer_height?: number; + pixel_space?: number; + line_space?: number; + data_type?: string; +} + +export interface ContourGenerateOptions +{ + src: RasterBand; + dst: Layer; + offset?: number; + interval?: number; + fixedLevels?: number[]; + nodata?: number; + idField?: number; + elevField?: number; +} + +export interface FillNoDataOptions +{ + src: RasterBand; + mask?: RasterBand; + searchDist: number; + smoothingIterations?: number; +} + +export interface PolygonizeOptions +{ + src: RasterBand; + dst: Layer; + mask?: RasterBand; + pixValField: number; + connectedness?: number; + useFloats?: boolean; +} + +export interface ReprojectImageOptions +{ + src: Dataset; + dst: Dataset; + s_srs: SpatialReference; + t_srs: SpatialReference; + resampling?: string; + cutline?: Geometry; + srcBands?: number[]; + dstBands?: number[]; + srcAlphaBand?: number; + dstAlphaBand?: number; + srcNodata?: number; + dstNodata?: number; + memoryLimit?: number; + maxError?: number; + multi?: boolean; + options?: string[] | object; +} + +export interface SieveFilterOptions +{ + src: RasterBand; + dst: RasterBand; + mask?: RasterBand; + threshold: number; + connectedness?: number; +} + +export interface SuggestedWarpOutputOptions +{ + src: Dataset; + s_srs: SpatialReference; + t_srs: SpatialReference; + maxError?: number; +} + +/* From API: https://naturalatlas.github.io/node-gdal/ */ + +/* Constants */ + +// CPL Error Codes +export const CPLE_AppDefined: number; +export const CPLE_AssertionFailed: number; +export const CPLE_FileIO: number; +export const CPLE_IllegalArg: number; +export const CPLE_None: number; +export const CPLE_NotSupported: number; +export const CPLE_NoWriteAccess: number; +export const CPLE_ObjectNull: number; +export const CPLE_OpenFailed: number; +export const CPLE_OutOfMemory: number; +export const CPLE_UserInterrupt: number; + +// CPL Error Levels +export const CE_Debug: number; +export const CE_Failure: number; +export const CE_Fatal: number; +export const CE_None: number; +export const CE_Warning: number; + +// DCAP +export const DCAP_CREATE: string; +export const DCAP_CREATECOPY: string; +export const DCAP_VIRTUALIO: string; + +// DMD +export const DMD_CREATIONDATATYPES: string; +export const DMD_CREATIONOPTIONLIST: string; +export const DMD_EXTENSION: string; +export const DMD_HELPTOPIC: string; +export const DMD_LONGNAME: string; +export const DMD_MIMETYPE: string; + +// GCI +export const GCI_AlphaBand: string; +export const GCI_BlackBand: string; +export const GCI_BlueBand: string; +export const GCI_CyanBand: string; +export const GCI_GrayIndex: string; +export const GCI_GreenBand: string; +export const GCI_HueBand: string; +export const GCI_LightnessBand: string; +export const GCI_MagentaBand: string; +export const GCI_PaletteIndex: string; +export const GCI_RedBand: string; +export const GCI_SaturationBand: string; +export const GCI_Undefined: string; +export const GCI_YCbCr_CbBand: string; +export const GCI_YCbCr_CrBand: string; +export const GCI_YCbCr_YBand: string; +export const GCI_YellowBand: string; + +// GDT +export const GDT_Byte: string; +export const GDT_CFloat32: string; +export const GDT_CFloat64: string; +export const GDT_CInt16: string; +export const GDT_CInt32: string; +export const GDT_Float32: string; +export const GDT_Float64: string; +export const GDT_Int16: string; +export const GDT_Int32: string; +export const GDT_UInt16: string; +export const GDT_UInt32: string; +export const GDT_Unknown: string; + +// GRA +export const GRA_Average: string; +export const GRA_Bilinear: string; +export const GRA_Cubic: string; +export const GRA_CubicSpline: string; +export const GRA_Lanczos: string; +export const GRA_Mode: string; +export const GRA_NearestNeighbor: string; + +// ODsC +export const ODrCCreateDataSource: string; +export const ODrCDeleteDataSource: string; +export const ODsCCreateGeomFieldAfterCreateLayer: string; +export const ODsCCreateLayer: string; +export const ODsCDeleteLayer: string; + +// OFT +export const OFTBinary: string; +export const OFTDate: string; +export const OFTDateTime: string; +export const OFTInteger: string; +export const OFTIntegerList: string; +export const OFTReal: string; +export const OFTRealList: string; +export const OFTString: string; +export const OFTStringList: string; +export const OFTTime: string; +export const OFTWideString: string; +export const OFTWideStringList: string; + +// OJ +export const OJLeft: string; +export const OJRight: string; +export const OJUndefined: string; + +// OLC +export const OLCAlterFieldDefn: string; +export const OLCCreateField: string; +export const OLCCreateGeomField: string; +export const OLCDeleteFeature: string; +export const OLCDeleteField: string; +export const OLCFastFeatureCount: string; +export const OLCFastGetExtent: string; +export const OLCFastSetNextByIndex: string; +export const OLCFastSpatialFilter: string; +export const OLCIgnoreFields: string; +export const OLCRandomRead: string; +export const OLCRandomWrite: string; +export const OLCReorderFields: string; +export const OLCSequentialWrite: string; +export const OLCStringsAsUTF8: string; +export const OLCTransactions: string; + +// wkbByteOrder +export const wkbNDR: string; +export const wkbXDR: string; + +// wkbGeometryType +export const wkb25DBit: number; +export const wkbGeometryCollection: number; +export const wkbGeometryCollection25D: number; +export const wkbLinearRing: string; +export const wkbLinearRing25D: number; +export const wkbLineString: number; +export const wkbLineString25D: number; +export const wkbMultiLineString: number; +export const wkbMultiLineString25D: number; +export const wkbMultiPoint: number; +export const wkbMultiPoint25D: number; +export const wkbMultiPolygon: number; +export const wkbMultiPolygon25D: number; +export const wkbNone: number; +export const wkbPoint: number; +export const wkbPoint25D: number; +export const wkbPolygon: number; +export const wkbPolygon25D: number; +export const wkbUnknown: number; + +// wkbVariant +export const wkbVariantIso: string; +export const wkbVariantOgc: string; +export const wkbVariantOldOgc: string; + +/* Classes and interfaces */ + +export class CoordinateTransformation +{ + constructor(source: SpatialReference, target: SpatialReference | Dataset); + transformPoint(x: number, y: number, z?: number): XYZ; +} + +export interface Dataset +{ + buildOverviews(resampling: Resampling, overviews: number[], bands?: number[]): void; + close(): void; + executeSQL(statement: string, spatial_filter?: Geometry, dialect?: string): Layer; + flush(): void; + getFileList(): string[]; + getGCPProjection(): string; + getGCPs(): object[]; + getMetadata(domain?: string): object; + setGCPs(gcps: object[], projection: string): void; + testCapability(capability: string): boolean; + + readonly bands: DatasetBands; + readonly description: string; + readonly driver: Driver; + geoTransform: number[]; + readonly layers: DatasetLayers; + readonly rasterSize: XY; + srs: SpatialReference; +} + +export interface DatasetBands +{ + count(): number; + create(dataType: number): RasterBand; + forEach(callback: (band: RasterBand, i: number) => void): void; + get(id: number): RasterBand; + map(callback: (band: RasterBand, i: number) => T): T[]; + + readonly ds: Dataset; +} + +export interface DatasetLayers +{ + copy(src_lyr_name: string, dst_lyr_name: string, options?: object | string[]): Layer; + count(): number; + create(name: string, srs: SpatialReference, geomType: number | Function, creation_options: string[] | object): Layer; + forEach(callback: (layer: Layer, i: number) => void): void; + get(key: string | number): Layer; + map(callback: (layer: Layer, i: number) => T): T[]; + remove(index: number): void; + + readonly ds: Dataset; +} + +export interface Driver +{ + copyFiles(name_old: string, name_new: string): void; + create(filename: string, x_size?: number, y_size?: number, band_count?: number, data_type?: number, creation_options?: string[] | object): Dataset; + createCopy(filename: string, src: Dataset, strict?: boolean, options?: string[] | object): Dataset; + deleteDataset(filename: string): void; + getMetadata(domain?: string): object; + open(path: string, mode?: 'r' | 'r+'): Dataset; + rename(new_name: string, old_name: string): void; + + readonly description: string; +} + +export class Envelope +{ + constructor(bounds: EnvelopeBounds); + contains(envelope: Envelope): boolean; + intersect(envelope: Envelope): void; + intersects(envelope: Envelope): boolean; + isEmpty(): boolean; + merge(envelope: Envelope): void; + toPolygon(): Polygon; +} + +export class Envelope3D extends Envelope +{ + constructor(bounds: Envelope3DBounds); +} + +export class Feature +{ + constructor(definition: Layer | FeatureDefn); + clone(): Feature; + destroy(): void; + equals(feature: Feature): boolean; + getFieldDefn(index: number): FieldDefn; + getGeometry(): Geometry; + setFrom(feature: Feature, index_map?: number[], forgiving?: boolean): void; + setGeometry(geometry: Geometry): void; + + readonly defn: FeatureDefn; + fid: number; + readonly fields: FeatureFields; +} + +export class FeatureDefn +{ + constructor(); + clone(): FeatureDefn; + + readonly fields: FeatureDefnFields; + geomIgnored: boolean; + geomType: number; + readonly name: string; + styleIgnored: boolean; +} + +export interface FeatureDefnFields +{ + add(field: FieldDefn | FieldDefn[]): void; + count(): number; + forEach(callback: (field: FieldDefn, i: number) => void): void; + get(key: string | number): FieldDefn; + getNames(): string[]; + indexOf(name: string): number; + map(callback: (field: FieldDefn, i: number) => T): T[]; + remove(key: string | number): void; + reorder(map: number[]): void; + + readonly featureDefn: FeatureDefn; +} + +export interface FeatureFields +{ + count(): number; + forEach(callback: (value: any, key: string) => void): void; + get(key: string | number): any; + getNames(): string[]; + indexOf(name: string): number; + map(callback: (value: any, key: string) => T): T[]; + reset(values: object, value: any): void; + set(key: string | number, value: any): void; + toArray(): any[]; + toJSON(): string; + toObject(): object; + + readonly feature: Feature; +} + +export class FieldDefn +{ + constructor(name: string, type: string); + + ignored: boolean; + justification: string; + name: string; + precision: number; + type: string; + width: number; +} + +export interface GDALDrivers +{ + count(): number; + forEach(callback: (driver: Driver, i: number) => void): void; + get(index: number | string): Driver; + getNames(): string[]; + map(callback: (driver: Driver, i: number) => T): T[]; +} + +export abstract class Geometry +{ + static create(type: number): Geometry; + static fromWKB(wkb: number, srs?: SpatialReference): Geometry; + static fromWKT(wkt: string, srs?: SpatialReference): Geometry; + static getConstructor(type: number): Function; + static getName(type: number): string; + + boundary(): Geometry; + buffer(distance: number, segments: number): Geometry; + centroid(): Point; + clone(): Geometry; + closeRings(): void; + contains(geometry: Geometry): boolean; + convexHull(): Geometry; + crosses(geometry: Geometry): boolean; + difference(geometry: Geometry): Geometry; + disjoint(geometry: Geometry): boolean; + distance(geometry: Geometry): number; + empty(): void; + equals(geometry: Geometry): boolean; + getEnvelope(): Envelope; + getEnvelope3D(): Envelope3D; + intersection(geometry: Geometry): Geometry; + intersects(geometry: Geometry): boolean; + isEmpty(): boolean; + isRing(): boolean; + isSimple(): boolean; + isValid(): boolean; + overlaps(geometry: Geometry): boolean; + segmentize(segment_length: number): number; + simplify(tolerance: number): Geometry; + simplifyPreserveTopology(tolerance: number): Geometry; + swapXY(): void; + symDifference(geometry: Geometry): Geometry; + toGML(): Geometry; + toJSON(): Geometry; + toKML(): Geometry; + toObject(): object; + touches(geometry: Geometry): boolean; + toWKB(byte_order?: string, variant?: string): Geometry; + toWKT(): Geometry; + transform(transformation: CoordinateTransformation): void; + transformTo(srs: SpatialReference): void; + union(geometry: Geometry): Geometry; + within(geometry: Geometry): boolean; + + readonly coordinateDimension: number; + readonly dimension: number; + readonly name: string; + srs: SpatialReference; + readonly wkbSize: number; + readonly wkbType: number; +} + +export class GeometryCollection extends Geometry +{ + getArea(): number; + getLength(): number; + + children: GeometryCollectionChildren; +} + +export interface GeometryCollectionChildren +{ + add(geometry: Geometry | Geometry[]): void; + count(): number; + forEach(callback: (geometry: Geometry, i: number) => void): void; + get(index: number): Geometry; + map(callback: (geometry: Geometry, i: number) => T): T[]; + remove(index: number): void; + toArray(): Geometry[]; + + readonly layer: Layer; +} + +export interface Layer +{ + flush(): void; + getExtent(force?: boolean): Envelope; + getSpatialFilter(): Geometry; + setAttributeFilter(filter: string): void; + setSpatialFilter(filter: Geometry): void; + setSpatialFilter(minX: number, maxX: number, minY: number, maxY: number): void; + testCapability(capability: string): boolean; + + readonly ds: Dataset; + readonly features: LayerFeatures; + readonly fidColumn: string; + readonly fields: LayerFields; + readonly geomColumn: string; + readonly geomType: number; + readonly name: string; + readonly srs: SpatialReference; +} + +export interface LayerFeatures +{ + add(feature: Feature): void; + count(force?: boolean): number; + first(): Feature; + forEach(callback: (feature: Feature, i: number) => void): void; + get(id: number): Feature; + map(callback: (feature: Feature, i: number) => T): T[]; + next(): Feature; + remove(id: number): void; + set(id: number, feature: Feature): void; + + readonly layer: Layer; +} + +export interface LayerFields +{ + add(def: FieldDefn | FieldDefn[], approx?: boolean): void; + count(): number; + forEach(callback: (field: FieldDefn, i: number) => void): void; + fromJSON(object: object, approx_ok?: boolean): LayerFields; + get(field: string | number): FieldDefn; + getNames(): string[]; + indexOf(field: string): number; + map(callback: (field: FieldDefn, i: number) => T): T[]; + remove(field: string | number): void; + reorder(map: number[]): void; + + readonly layer: Layer; +} + +export class LinearRing extends LineString +{ + getArea(): number; +} + +export class LineString extends Geometry +{ + addSubLineString(line: LineString, start?: number, end?: number): void; + getLength(): number; + value(distance: number): Point; + + readonly points: LineStringPoints; +} + +export interface LineStringPoints +{ + add(point: Point | Point[]): void; + count(): number; + forEach(callback: (point: Point, i: number) => void): void; + get(index: number): Point; + map(callback: (point: Point, i: number) => T): T[]; + remove(index: number): void; + resize(count: number): void; + reverse(): void; + set(index: number, point: Point): void; + toArray(): Point[]; +} + +export class MultiLineString extends GeometryCollection +{ + polygonize(): Polygon; +} + +export class MultiPoint extends GeometryCollection +{ + +} + +export class MultiPolygon extends GeometryCollection +{ + getArea(): number; + unionCascaded(): Geometry; +} + +export class Point extends Geometry +{ + constructor(x: number, y: number, z?: number); + + x: number; + y: number; + z: number; +} + +export class Polygon extends Geometry +{ + getArea(): number; + + rings: PolygonRings; +} + +export interface PolygonRings +{ + add(ring: LinearRing | LinearRing[]): void; + count(): number; + forEach(callback: (ring: LinearRing, i: number) => void): void; + get(index: number): LinearRing; + map(callback: (ring: LinearRing, i: number) => T): T[]; + remove(index: number): void; + toArray(): LinearRing[]; + + readonly layer: Layer; +} + +export interface RasterBand +{ + computeStatistics(allow_approximation: boolean): RasterBandStatistics; + createMaskBand(flags: number): void; + fill(real_value: number, imaginary_value?: number): void; + flush(): void; + getMaskBand(): RasterBand; + getMaskFlags(): number; + getMetadata(domain?: string): object; + getStatistics(allow_approximation: boolean, force: boolean): RasterBandStatistics; + setStatistics(min: number, max: number, mean: number, std_dev: number): void; + + readonly blockSize: XY; + categoryNames: string[]; + colorInterpretation: string; + readonly dataType: string; + readonly description: string; + readonly ds: Dataset; + readonly hasArbitraryOverviews: boolean; + readonly id: number; + readonly maximum: number; + readonly minimum: number; + noDataValue: number; + offset: number; + readonly overviews: RasterBandOverviews; + readonly pixels: RasterBandPixels; + readonly readOnly: boolean; + scale: number; + readonly size: XY; + unitType: string; +} + +export interface RasterBandOverviews +{ + count(): number; + forEach(callback: (overviewBand: RasterBand, i: number) => void): void; + get(index: number): RasterBand; + getBySampleCount(samples: number): RasterBand; + map(callback: (overviewBand: RasterBand, i: number) => T): T[]; +} + +export interface RasterBandPixels +{ + get(x: number, y: number): number; + read(x: number, y: number, width: number, height: number, data?: TypedArray, options?: RasterBandPixelsReadOptions): TypedArray; + readBlock(x: number, y: number, data?: TypedArray): TypedArray; + set(x: number, y: number, value: number): void; + write(x: number, y: number, width: number, height: number, data: TypedArray, options?: RasterBandPixelsWriteOptions): void; + writeBlock(x: number, y: number, data: TypedArray): void; +} + +export class SpatialReference +{ + constructor(wkt?: string); + autoIdentifyEPSG(): void; + clone(): SpatialReference; + cloneGeogCS(): SpatialReference; + EPSGTreatsAsLatLong(): boolean; + EPSGTreatsAsNorthingEasting(): boolean; + getAngularUnits(): { value: any, unit: any }; + getAttrValue(node_name: string, attr_index?: number): string; + getAuthorityCode(target_key: string): string; + getAuthorityName(target_key: string): string; + getLinearUnits(): { value: any, unit: any }; + isCompound(): boolean; + isGeocentric(): boolean; + isGeographic(): boolean; + isLocal(): boolean; + isProjected(): boolean; + isSame(srs: SpatialReference): boolean; + isSameGeogCS(srs: SpatialReference): boolean; + isSameVertCS(srs: SpatialReference): boolean; + isVertical(): boolean; + morphFromESRI(): void; + morphToESRI(): void; + setWellKnownGeogCS(name: string): void; + toPrettyWKT(simplify?: boolean): string; + toProj4(): string; + toWKT(): string; + toXML(): string; + validate(): string; + + static fromCRSURL(input: string): SpatialReference; + static fromEPSG(input: string): SpatialReference; + static fromEPSGA(input: number): SpatialReference; + static fromESRI(input: string[]): SpatialReference; + static fromMICoordSys(input: string): SpatialReference; + static fromProj4(input: string): SpatialReference; + static fromURL(url: string): SpatialReference; + static fromURN(input: string): SpatialReference; + static fromUserInput(input: string): SpatialReference; + static fromWKT(wkt: string): SpatialReference; + static fromWMSAUTO(input: string): SpatialReference; + static fromXML(input: string): SpatialReference; +} + +export namespace config +{ + function get(key: string): string; + function set(key: string, value: string): void; +} + +export const drivers: GDALDrivers; +export const lastError: { number: any, message: any, type: any }; +export const version: string; + +export function checksumImage(src: RasterBand, x?: number, y?: number, w?: number, h?: number): number; +export function contourGenerate(options: ContourGenerateOptions): void; +export function decToDMS(angle: number, axis: 'lat' | 'long', precision?: number): string; +export function fillNodata(options: FillNoDataOptions): void; +export function open(path: string, mode?: 'r' | 'r+' | 'w', drivers?: string | string[], x_size?: number, y_size?: number, band_count?: number, data_type?: number, creation_options?: string[] | object): Dataset; +export function polygonize(options: PolygonizeOptions): void; +export function quiet(): void; +export function reprojectImage(options: ReprojectImageOptions): void; +export function sieveFilter(options: SieveFilterOptions): void; +export function suggestedWarpOutput(options: SuggestedWarpOutputOptions): { rasterSize: any, geoTransform: any }; +export function verbose(): void; \ No newline at end of file diff --git a/types/gdal/tsconfig.json b/types/gdal/tsconfig.json new file mode 100644 index 0000000000..a7bd1cf386 --- /dev/null +++ b/types/gdal/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gdal-tests.ts" + ] +} diff --git a/types/gdal/tslint.json b/types/gdal/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gdal/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 37d0e8c735d8573f238b51461fb3489190274def Mon Sep 17 00:00:00 2001 From: Nicolas Biehler Date: Fri, 23 Nov 2018 15:35:35 +0100 Subject: [PATCH 353/836] fix: extend elasticsearch alias params As shown in elasticsearch documentation (https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html#filtered), an alias can have a routing value and a filter specified. --- types/elasticsearch/elasticsearch-tests.ts | 43 ++++++++++++++++------ types/elasticsearch/index.d.ts | 2 - 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/types/elasticsearch/elasticsearch-tests.ts b/types/elasticsearch/elasticsearch-tests.ts index ee57f847fa..0d12a931ed 100644 --- a/types/elasticsearch/elasticsearch-tests.ts +++ b/types/elasticsearch/elasticsearch-tests.ts @@ -209,7 +209,7 @@ client.get({ id: '1', routing: '1' }, (error, response) => { - const routing = response._routing; + const routing = response._routing; }); client.mget({ @@ -338,22 +338,43 @@ client.indices.updateAliases({ // ... }); -client.reindex({ - body: { - source: { - index: "twitter" - }, - dest: { - index: "new_twitter" +client.indices.updateAliases({ + body: { + actions: [ + { + add: { + index: 'logstash-2018.11', alias: 'logstash-filtered', filter: { + query: { + exists: { field: 'id' } + } + }, + routing: 'id' } } + ] + } +}).then((response) => { + // ... +}, (error) => { + // ... +}); + +client.reindex({ + body: { + source: { + index: "twitter" + }, + dest: { + index: "new_twitter" + } + } }) -.then(response => { + .then(response => { const { took, timed_out } = response; // ... -}); + }); // Errors function testErrors() { - throw new elasticsearch.errors.AuthenticationException(); + throw new elasticsearch.errors.AuthenticationException(); } diff --git a/types/elasticsearch/index.d.ts b/types/elasticsearch/index.d.ts index 62202dbc90..401627d2c1 100644 --- a/types/elasticsearch/index.d.ts +++ b/types/elasticsearch/index.d.ts @@ -1407,8 +1407,6 @@ export interface IndicesUpdateAliasesParamsAction { index?: string; indices?: string[]; alias: string; - routing?: string; - filter?: object; }; remove_index?: { index: string; From cf4ed80a0837167bd53fdb9d23321fac19468efc Mon Sep 17 00:00:00 2001 From: NN Date: Tue, 27 Nov 2018 17:58:48 +0200 Subject: [PATCH 354/836] Fix #30848 configHash can be a string in HardSourceWebpackPlugin --- types/hard-source-webpack-plugin/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/hard-source-webpack-plugin/index.d.ts b/types/hard-source-webpack-plugin/index.d.ts index 3e02ee1d8a..4a83b58034 100644 --- a/types/hard-source-webpack-plugin/index.d.ts +++ b/types/hard-source-webpack-plugin/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for hard-source-webpack-plugin 0.9 +// Type definitions for hard-source-webpack-plugin 1.0 // Project: https://github.com/mzgoddard/hard-source-webpack-plugin#readme // Definitions by: woitechen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -15,7 +15,7 @@ declare namespace hard_source_webpack_plugin { } interface Options { cacheDirectory?: string; - configHash?: (webpackConfig?: webpack.Configuration) => string; + configHash?: string | ((webpackConfig?: webpack.Configuration) => string); environmentHash?: { root: string; directories: string[]; From a104ee185677834365ba69b74bd14cd14723d5e7 Mon Sep 17 00:00:00 2001 From: andreidigori <45198612+andreidigori@users.noreply.github.com> Date: Tue, 27 Nov 2018 19:05:34 +0200 Subject: [PATCH 355/836] Update tsconfig.json Set "strictFunctionTypes": false, --- types/gdal/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/types/gdal/tsconfig.json b/types/gdal/tsconfig.json index a7bd1cf386..3a5bfaf917 100644 --- a/types/gdal/tsconfig.json +++ b/types/gdal/tsconfig.json @@ -7,6 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": false, "baseUrl": "../", "typeRoots": [ "../" From 08b098667ad9ab2e6ff405662be41b947af7e04f Mon Sep 17 00:00:00 2001 From: andreidigori <45198612+andreidigori@users.noreply.github.com> Date: Tue, 27 Nov 2018 19:20:57 +0200 Subject: [PATCH 356/836] Update index.d.ts TsLint check --- types/gdal/index.d.ts | 138 ++++++++++++++---------------------------- 1 file changed, 46 insertions(+), 92 deletions(-) diff --git a/types/gdal/index.d.ts b/types/gdal/index.d.ts index 50280cff3d..41a89ff72f 100644 --- a/types/gdal/index.d.ts +++ b/types/gdal/index.d.ts @@ -11,49 +11,42 @@ export as namespace gdal; export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; export type Resampling = 'NEAREST' | 'GAUSS' | 'CUBIC' | 'AVERAGE' | 'MODE' | 'AVERAGE_MAGPHASE' | 'NONE'; -export interface XY -{ +export interface XY { x: number; y: number; } -export interface XYZ extends XY -{ +export interface XYZ extends XY { z: number; } -export interface EnvelopeBounds -{ +export interface EnvelopeBounds { minX: number, maxX: number, minY: number, maxY: number } -export interface Envelope3DBounds extends EnvelopeBounds -{ +export interface Envelope3DBounds extends EnvelopeBounds { minZ: number, maxZ: number } -export interface RasterBandStatistics -{ +export interface RasterBandStatistics { min: number; max: number; mean: number; std_dev: number; } -export interface RasterBandPixelsWriteOptions -{ +export interface RasterBandPixelsWriteOptions { buffer_width?: number; buffer_height?: number; pixel_space?: number; line_space?: number; } -export interface RasterBandPixelsReadOptions -{ +export interface RasterBandPixelsReadOptions { buffer_width?: number; buffer_height?: number; pixel_space?: number; @@ -61,8 +54,7 @@ export interface RasterBandPixelsReadOptions data_type?: string; } -export interface ContourGenerateOptions -{ +export interface ContourGenerateOptions { src: RasterBand; dst: Layer; offset?: number; @@ -73,16 +65,14 @@ export interface ContourGenerateOptions elevField?: number; } -export interface FillNoDataOptions -{ +export interface FillNoDataOptions { src: RasterBand; mask?: RasterBand; searchDist: number; smoothingIterations?: number; } -export interface PolygonizeOptions -{ +export interface PolygonizeOptions { src: RasterBand; dst: Layer; mask?: RasterBand; @@ -91,8 +81,7 @@ export interface PolygonizeOptions useFloats?: boolean; } -export interface ReprojectImageOptions -{ +export interface ReprojectImageOptions { src: Dataset; dst: Dataset; s_srs: SpatialReference; @@ -111,8 +100,7 @@ export interface ReprojectImageOptions options?: string[] | object; } -export interface SieveFilterOptions -{ +export interface SieveFilterOptions { src: RasterBand; dst: RasterBand; mask?: RasterBand; @@ -120,8 +108,7 @@ export interface SieveFilterOptions connectedness?: number; } -export interface SuggestedWarpOutputOptions -{ +export interface SuggestedWarpOutputOptions { src: Dataset; s_srs: SpatialReference; t_srs: SpatialReference; @@ -283,14 +270,12 @@ export const wkbVariantOldOgc: string; /* Classes and interfaces */ -export class CoordinateTransformation -{ +export class CoordinateTransformation { constructor(source: SpatialReference, target: SpatialReference | Dataset); transformPoint(x: number, y: number, z?: number): XYZ; } -export interface Dataset -{ +export interface Dataset { buildOverviews(resampling: Resampling, overviews: number[], bands?: number[]): void; close(): void; executeSQL(statement: string, spatial_filter?: Geometry, dialect?: string): Layer; @@ -311,8 +296,7 @@ export interface Dataset srs: SpatialReference; } -export interface DatasetBands -{ +export interface DatasetBands { count(): number; create(dataType: number): RasterBand; forEach(callback: (band: RasterBand, i: number) => void): void; @@ -322,8 +306,7 @@ export interface DatasetBands readonly ds: Dataset; } -export interface DatasetLayers -{ +export interface DatasetLayers { copy(src_lyr_name: string, dst_lyr_name: string, options?: object | string[]): Layer; count(): number; create(name: string, srs: SpatialReference, geomType: number | Function, creation_options: string[] | object): Layer; @@ -335,8 +318,7 @@ export interface DatasetLayers readonly ds: Dataset; } -export interface Driver -{ +export interface Driver { copyFiles(name_old: string, name_new: string): void; create(filename: string, x_size?: number, y_size?: number, band_count?: number, data_type?: number, creation_options?: string[] | object): Dataset; createCopy(filename: string, src: Dataset, strict?: boolean, options?: string[] | object): Dataset; @@ -348,8 +330,7 @@ export interface Driver readonly description: string; } -export class Envelope -{ +export class Envelope { constructor(bounds: EnvelopeBounds); contains(envelope: Envelope): boolean; intersect(envelope: Envelope): void; @@ -359,13 +340,11 @@ export class Envelope toPolygon(): Polygon; } -export class Envelope3D extends Envelope -{ +export class Envelope3D extends Envelope { constructor(bounds: Envelope3DBounds); } -export class Feature -{ +export class Feature { constructor(definition: Layer | FeatureDefn); clone(): Feature; destroy(): void; @@ -380,8 +359,7 @@ export class Feature readonly fields: FeatureFields; } -export class FeatureDefn -{ +export class FeatureDefn { constructor(); clone(): FeatureDefn; @@ -392,8 +370,7 @@ export class FeatureDefn styleIgnored: boolean; } -export interface FeatureDefnFields -{ +export interface FeatureDefnFields { add(field: FieldDefn | FieldDefn[]): void; count(): number; forEach(callback: (field: FieldDefn, i: number) => void): void; @@ -407,8 +384,7 @@ export interface FeatureDefnFields readonly featureDefn: FeatureDefn; } -export interface FeatureFields -{ +export interface FeatureFields { count(): number; forEach(callback: (value: any, key: string) => void): void; get(key: string | number): any; @@ -424,8 +400,7 @@ export interface FeatureFields readonly feature: Feature; } -export class FieldDefn -{ +export class FieldDefn { constructor(name: string, type: string); ignored: boolean; @@ -436,8 +411,7 @@ export class FieldDefn width: number; } -export interface GDALDrivers -{ +export interface GDALDrivers { count(): number; forEach(callback: (driver: Driver, i: number) => void): void; get(index: number | string): Driver; @@ -445,8 +419,7 @@ export interface GDALDrivers map(callback: (driver: Driver, i: number) => T): T[]; } -export abstract class Geometry -{ +export abstract class Geometry { static create(type: number): Geometry; static fromWKB(wkb: number, srs?: SpatialReference): Geometry; static fromWKT(wkt: string, srs?: SpatialReference): Geometry; @@ -500,16 +473,14 @@ export abstract class Geometry readonly wkbType: number; } -export class GeometryCollection extends Geometry -{ +export class GeometryCollection extends Geometry { getArea(): number; getLength(): number; children: GeometryCollectionChildren; } -export interface GeometryCollectionChildren -{ +export interface GeometryCollectionChildren { add(geometry: Geometry | Geometry[]): void; count(): number; forEach(callback: (geometry: Geometry, i: number) => void): void; @@ -521,8 +492,7 @@ export interface GeometryCollectionChildren readonly layer: Layer; } -export interface Layer -{ +export interface Layer { flush(): void; getExtent(force?: boolean): Envelope; getSpatialFilter(): Geometry; @@ -541,8 +511,7 @@ export interface Layer readonly srs: SpatialReference; } -export interface LayerFeatures -{ +export interface LayerFeatures { add(feature: Feature): void; count(force?: boolean): number; first(): Feature; @@ -556,8 +525,7 @@ export interface LayerFeatures readonly layer: Layer; } -export interface LayerFields -{ +export interface LayerFields { add(def: FieldDefn | FieldDefn[], approx?: boolean): void; count(): number; forEach(callback: (field: FieldDefn, i: number) => void): void; @@ -572,13 +540,11 @@ export interface LayerFields readonly layer: Layer; } -export class LinearRing extends LineString -{ +export class LinearRing extends LineString { getArea(): number; } -export class LineString extends Geometry -{ +export class LineString extends Geometry { addSubLineString(line: LineString, start?: number, end?: number): void; getLength(): number; value(distance: number): Point; @@ -586,8 +552,7 @@ export class LineString extends Geometry readonly points: LineStringPoints; } -export interface LineStringPoints -{ +export interface LineStringPoints { add(point: Point | Point[]): void; count(): number; forEach(callback: (point: Point, i: number) => void): void; @@ -600,24 +565,20 @@ export interface LineStringPoints toArray(): Point[]; } -export class MultiLineString extends GeometryCollection -{ +export class MultiLineString extends GeometryCollection { polygonize(): Polygon; } -export class MultiPoint extends GeometryCollection -{ +export class MultiPoint extends GeometryCollection { } -export class MultiPolygon extends GeometryCollection -{ +export class MultiPolygon extends GeometryCollection { getArea(): number; unionCascaded(): Geometry; } -export class Point extends Geometry -{ +export class Point extends Geometry { constructor(x: number, y: number, z?: number); x: number; @@ -625,15 +586,13 @@ export class Point extends Geometry z: number; } -export class Polygon extends Geometry -{ +export class Polygon extends Geometry { getArea(): number; rings: PolygonRings; } -export interface PolygonRings -{ +export interface PolygonRings { add(ring: LinearRing | LinearRing[]): void; count(): number; forEach(callback: (ring: LinearRing, i: number) => void): void; @@ -645,8 +604,7 @@ export interface PolygonRings readonly layer: Layer; } -export interface RasterBand -{ +export interface RasterBand { computeStatistics(allow_approximation: boolean): RasterBandStatistics; createMaskBand(flags: number): void; fill(real_value: number, imaginary_value?: number): void; @@ -677,8 +635,7 @@ export interface RasterBand unitType: string; } -export interface RasterBandOverviews -{ +export interface RasterBandOverviews { count(): number; forEach(callback: (overviewBand: RasterBand, i: number) => void): void; get(index: number): RasterBand; @@ -686,8 +643,7 @@ export interface RasterBandOverviews map(callback: (overviewBand: RasterBand, i: number) => T): T[]; } -export interface RasterBandPixels -{ +export interface RasterBandPixels { get(x: number, y: number): number; read(x: number, y: number, width: number, height: number, data?: TypedArray, options?: RasterBandPixelsReadOptions): TypedArray; readBlock(x: number, y: number, data?: TypedArray): TypedArray; @@ -696,8 +652,7 @@ export interface RasterBandPixels writeBlock(x: number, y: number, data: TypedArray): void; } -export class SpatialReference -{ +export class SpatialReference { constructor(wkt?: string); autoIdentifyEPSG(): void; clone(): SpatialReference; @@ -741,8 +696,7 @@ export class SpatialReference static fromXML(input: string): SpatialReference; } -export namespace config -{ +export namespace config { function get(key: string): string; function set(key: string, value: string): void; } From 6260aa95216a27a4a5816b1f45bff85c22e6eaea Mon Sep 17 00:00:00 2001 From: Josh Dover Date: Tue, 27 Nov 2018 11:26:43 -0600 Subject: [PATCH 357/836] Order overloaded functions consistently --- types/elasticsearch/index.d.ts | 58 +++++++++++++++++----------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/types/elasticsearch/index.d.ts b/types/elasticsearch/index.d.ts index 0d16cc6a4b..8b8bf07d96 100644 --- a/types/elasticsearch/index.d.ts +++ b/types/elasticsearch/index.d.ts @@ -23,76 +23,76 @@ export class Client { nodes: Nodes; snapshot: Snapshot; tasks: Tasks; - bulk(params: BulkIndexDocumentsParams): Promise; bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; + bulk(params: BulkIndexDocumentsParams): Promise; clearScroll(params: ClearScrollParams, callback: (error: any, response: any) => void): void; clearScroll(params: ClearScrollParams): Promise; count(params: CountParams, callback: (error: any, response: CountResponse) => void): void; count(params: CountParams): Promise; - create(params: CreateDocumentParams): Promise; create(params: CreateDocumentParams, callback: (err: any, response: CreateDocumentResponse, status: any) => void): void; - delete(params: DeleteDocumentParams): Promise; + create(params: CreateDocumentParams): Promise; delete(params: DeleteDocumentParams, callback: (error: any, response: DeleteDocumentResponse) => void): void; - deleteByQuery(params: DeleteDocumentByQueryParams): Promise; + delete(params: DeleteDocumentParams): Promise; deleteByQuery(params: DeleteDocumentByQueryParams, callback: (error: any, response: DeleteDocumentByQueryResponse) => void): void; - deleteScript(params: DeleteScriptParams): Promise; + deleteByQuery(params: DeleteDocumentByQueryParams): Promise; deleteScript(params: DeleteScriptParams, callback: (error: any, response: any) => void): void; - deleteTemplate(params: DeleteTemplateParams): Promise; + deleteScript(params: DeleteScriptParams): Promise; deleteTemplate(params: DeleteTemplateParams, callback: (error: any, response: any) => void): void; - exists(params: ExistsParams): Promise; + deleteTemplate(params: DeleteTemplateParams): Promise; exists(params: ExistsParams, callback: (error: any, response: boolean, status?: any) => void): void; - explain(params: ExplainParams): Promise; + exists(params: ExistsParams): Promise; explain(params: ExplainParams, callback: (error: any, response: ExplainResponse) => void): void; - fieldStats(params: FieldStatsParams): Promise; + explain(params: ExplainParams): Promise; fieldStats(params: FieldStatsParams, callback: (error: any, response: FieldStatsResponse) => void): void; + fieldStats(params: FieldStatsParams): Promise; get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; get(params: GetParams): Promise>; - getScript(params: GetScriptParams): Promise; getScript(params: GetScriptParams, callback: (error: any, response: any) => void): void; - getSource(params: GetSourceParams): Promise; + getScript(params: GetScriptParams): Promise; getSource(params: GetSourceParams, callback: (error: any, response: any) => void): void; - getTemplate(params: GetTemplateParams): Promise; + getSource(params: GetSourceParams): Promise; getTemplate(params: GetTemplateParams, callback: (error: any, response: any) => void): void; - index(params: IndexDocumentParams): Promise; + getTemplate(params: GetTemplateParams): Promise; index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; - info(params: InfoParams): Promise; + index(params: IndexDocumentParams): Promise; info(params: InfoParams, callback: (error: any, response: any) => void): void; + info(params: InfoParams): Promise; mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; mget(params: MGetParams): Promise>; msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; msearch(params: MSearchParams): Promise>; msearchTemplate(params: MSearchTemplateParams, callback: (error: any, response: MSearchResponse) => void): void; msearchTemplate(params: MSearchTemplateParams): Promise>; - mtermvectors(params: MTermVectorsParams): Promise; mtermvectors(params: MTermVectorsParams, callback: (error: any, response: any) => void): void; - ping(params: PingParams): Promise; + mtermvectors(params: MTermVectorsParams): Promise; ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; - putScript(params: PutScriptParams): Promise; + ping(params: PingParams): Promise; putScript(params: PutScriptParams, callback: (err: any, response: any, status: any) => void): void; - putTemplate(params: PutTemplateParams): Promise; + putScript(params: PutScriptParams): Promise; putTemplate(params: PutTemplateParams, callback: (err: any, response: any, status: any) => void): void; - reindex(params: ReindexParams): Promise; + putTemplate(params: PutTemplateParams): Promise; reindex(params: ReindexParams, callback: (error: any, response: ReindexResponse) => void): void; - reindexRethrottle(params: ReindexRethrottleParams): Promise; + reindex(params: ReindexParams): Promise; reindexRethrottle(params: ReindexRethrottleParams, callback: (error: any, response: any) => void): void; - renderSearchTemplate(params: RenderSearchTemplateParams): Promise; + reindexRethrottle(params: ReindexRethrottleParams): Promise; renderSearchTemplate(params: RenderSearchTemplateParams, callback: (error: any, response: any) => void): void; - scroll(params: ScrollParams): Promise>; + renderSearchTemplate(params: RenderSearchTemplateParams): Promise; scroll(params: ScrollParams, callback: (error: any, response: SearchResponse) => void): void; - search(params: SearchParams): Promise>; + scroll(params: ScrollParams): Promise>; search(params: SearchParams, callback: (error: any, response: SearchResponse) => void): void; - searchShards(params: SearchShardsParams): Promise; + search(params: SearchParams): Promise>; searchShards(params: SearchShardsParams, callback: (error: any, response: SearchShardsResponse) => void): void; - searchTemplate(params: SearchTemplateParams): Promise; + searchShards(params: SearchShardsParams): Promise; searchTemplate(params: SearchTemplateParams, callback: (error: any, response: any) => void): void; - suggest(params: SuggestParams): Promise; + searchTemplate(params: SearchTemplateParams): Promise; suggest(params: SuggestParams, callback: (error: any, response: any) => void): void; - termvectors(params: TermvectorsParams): Promise; + suggest(params: SuggestParams): Promise; termvectors(params: TermvectorsParams, callback: (error: any, response: any) => void): void; - update(params: UpdateDocumentParams): Promise; + termvectors(params: TermvectorsParams): Promise; update(params: UpdateDocumentParams, callback: (error: any, response: any) => void): void; - updateByQuery(params: UpdateDocumentByQueryParams): Promise; + update(params: UpdateDocumentParams): Promise; updateByQuery(params: UpdateDocumentByQueryParams, callback: (error: any, response: UpdateDocumentByQueryResponse) => void): void; + updateByQuery(params: UpdateDocumentByQueryParams): Promise; close(): void; } From 2de6fbab6151900dba10d85f9a6268ac13a88d1b Mon Sep 17 00:00:00 2001 From: huan086 Date: Tue, 27 Nov 2018 14:37:15 +0800 Subject: [PATCH 358/836] [radix64] Add Typescript definitions. --- types/radix64/index.d.ts | 23 +++++++++++++++++++++++ types/radix64/radix64-tests.ts | 11 +++++++++++ types/radix64/tsconfig.json | 23 +++++++++++++++++++++++ types/radix64/tslint.json | 1 + 4 files changed, 58 insertions(+) create mode 100644 types/radix64/index.d.ts create mode 100644 types/radix64/radix64-tests.ts create mode 100644 types/radix64/tsconfig.json create mode 100644 types/radix64/tslint.json diff --git a/types/radix64/index.d.ts b/types/radix64/index.d.ts new file mode 100644 index 0000000000..f376184fce --- /dev/null +++ b/types/radix64/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for radix64 1.1 +// Project: https://github.com/maxired/radix64 +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type MethodsString = 'base64' | 'base64URL' | 'base64URLNaturalSort' | 'base64URLASCIISort'; + +interface MethodsEnum { + BASE64: MethodsString; + BASE64URL: MethodsString; + BASE64NATURAL: MethodsString; + BASE64ASCII: MethodsString; + DEFAULT: MethodsString; +} + +interface Radix { + radix64: (number: number, method?: MethodsString) => string; + ascii64: (number: number, pad?: number) => string; + methods: MethodsEnum; +} + +declare const radix: Radix; +export = radix; diff --git a/types/radix64/radix64-tests.ts b/types/radix64/radix64-tests.ts new file mode 100644 index 0000000000..a77554c238 --- /dev/null +++ b/types/radix64/radix64-tests.ts @@ -0,0 +1,11 @@ +import radix64 = require("radix64"); + +const num: string = radix64.radix64(42); + +const numAndEnum: string = radix64.radix64(1337, radix64.methods.BASE64NATURAL); + +const numAndString: string = radix64.radix64(1337, 'base64URL'); + +const asciiNum: string = radix64.ascii64(42); + +const asciiNumAndPad: string = radix64.ascii64(42, 25); diff --git a/types/radix64/tsconfig.json b/types/radix64/tsconfig.json new file mode 100644 index 0000000000..362ad6d26e --- /dev/null +++ b/types/radix64/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", + "radix64-tests.ts" + ] +} diff --git a/types/radix64/tslint.json b/types/radix64/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/radix64/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From e6924a21bba6f7f30810c69d3796bce5ce6a9129 Mon Sep 17 00:00:00 2001 From: Christian Chown Date: Tue, 27 Nov 2018 17:29:18 +0000 Subject: [PATCH 359/836] DateSelectFunction takes a Date, not a string --- types/react-infinite-calendar/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-infinite-calendar/index.d.ts b/types/react-infinite-calendar/index.d.ts index 10a246c5ae..ac09df7bf4 100644 --- a/types/react-infinite-calendar/index.d.ts +++ b/types/react-infinite-calendar/index.d.ts @@ -21,7 +21,7 @@ export interface RangedSelection { } export type RangedSelectFunction = (rangedDate: RangedSelection) => void; -export type DateSelectFunction = (date: string) => void; +export type DateSelectFunction = (date: Date) => void; export interface ReactInfiniteCalendarProps { selected?: DateType | false | { start: DateType; end: DateType }; From acd8209e0673bf6e558e8342706c7b5809b9e7c5 Mon Sep 17 00:00:00 2001 From: andreidigori <45198612+andreidigori@users.noreply.github.com> Date: Tue, 27 Nov 2018 19:29:25 +0200 Subject: [PATCH 360/836] Update index.d.ts Linting --- types/gdal/index.d.ts | 31 +++++++++++-------------------- 1 file changed, 11 insertions(+), 20 deletions(-) diff --git a/types/gdal/index.d.ts b/types/gdal/index.d.ts index 41a89ff72f..6aca0120de 100644 --- a/types/gdal/index.d.ts +++ b/types/gdal/index.d.ts @@ -21,15 +21,15 @@ export interface XYZ extends XY { } export interface EnvelopeBounds { - minX: number, - maxX: number, - minY: number, - maxY: number + minX: number; + maxX: number; + minY: number; + maxY: number; } export interface Envelope3DBounds extends EnvelopeBounds { - minZ: number, - maxZ: number + minZ: number; + maxZ: number; } export interface RasterBandStatistics { @@ -309,7 +309,7 @@ export interface DatasetBands { export interface DatasetLayers { copy(src_lyr_name: string, dst_lyr_name: string, options?: object | string[]): Layer; count(): number; - create(name: string, srs: SpatialReference, geomType: number | Function, creation_options: string[] | object): Layer; + create(name: string, srs: SpatialReference, geomType: number | Geometry, creation_options: string[] | object): Layer; forEach(callback: (layer: Layer, i: number) => void): void; get(key: string | number): Layer; map(callback: (layer: Layer, i: number) => T): T[]; @@ -423,7 +423,7 @@ export abstract class Geometry { static create(type: number): Geometry; static fromWKB(wkb: number, srs?: SpatialReference): Geometry; static fromWKT(wkt: string, srs?: SpatialReference): Geometry; - static getConstructor(type: number): Function; + static getConstructor(type: number): Geometry; static getName(type: number): string; boundary(): Geometry; @@ -488,7 +488,6 @@ export interface GeometryCollectionChildren { map(callback: (geometry: Geometry, i: number) => T): T[]; remove(index: number): void; toArray(): Geometry[]; - readonly layer: Layer; } @@ -500,7 +499,6 @@ export interface Layer { setSpatialFilter(filter: Geometry): void; setSpatialFilter(minX: number, maxX: number, minY: number, maxY: number): void; testCapability(capability: string): boolean; - readonly ds: Dataset; readonly features: LayerFeatures; readonly fidColumn: string; @@ -521,7 +519,6 @@ export interface LayerFeatures { next(): Feature; remove(id: number): void; set(id: number, feature: Feature): void; - readonly layer: Layer; } @@ -536,7 +533,6 @@ export interface LayerFields { map(callback: (field: FieldDefn, i: number) => T): T[]; remove(field: string | number): void; reorder(map: number[]): void; - readonly layer: Layer; } @@ -548,7 +544,6 @@ export class LineString extends Geometry { addSubLineString(line: LineString, start?: number, end?: number): void; getLength(): number; value(distance: number): Point; - readonly points: LineStringPoints; } @@ -580,7 +575,6 @@ export class MultiPolygon extends GeometryCollection { export class Point extends Geometry { constructor(x: number, y: number, z?: number); - x: number; y: number; z: number; @@ -588,7 +582,6 @@ export class Point extends Geometry { export class Polygon extends Geometry { getArea(): number; - rings: PolygonRings; } @@ -600,7 +593,6 @@ export interface PolygonRings { map(callback: (ring: LinearRing, i: number) => T): T[]; remove(index: number): void; toArray(): LinearRing[]; - readonly layer: Layer; } @@ -614,7 +606,6 @@ export interface RasterBand { getMetadata(domain?: string): object; getStatistics(allow_approximation: boolean, force: boolean): RasterBandStatistics; setStatistics(min: number, max: number, mean: number, std_dev: number): void; - readonly blockSize: XY; categoryNames: string[]; colorInterpretation: string; @@ -681,7 +672,6 @@ export class SpatialReference { toWKT(): string; toXML(): string; validate(): string; - static fromCRSURL(input: string): SpatialReference; static fromEPSG(input: string): SpatialReference; static fromEPSGA(input: number): SpatialReference; @@ -709,10 +699,11 @@ export function checksumImage(src: RasterBand, x?: number, y?: number, w?: numbe export function contourGenerate(options: ContourGenerateOptions): void; export function decToDMS(angle: number, axis: 'lat' | 'long', precision?: number): string; export function fillNodata(options: FillNoDataOptions): void; -export function open(path: string, mode?: 'r' | 'r+' | 'w', drivers?: string | string[], x_size?: number, y_size?: number, band_count?: number, data_type?: number, creation_options?: string[] | object): Dataset; +export function open(path: string, mode?: 'r' | 'r+' | 'w', drivers?: string | string[]): Dataset; +export function open(path: string, mode?: 'w', drivers?: string | string[], x_size?: number, y_size?: number, band_count?: number, data_type?: number, creation_options?: string[] | object): Dataset; export function polygonize(options: PolygonizeOptions): void; export function quiet(): void; export function reprojectImage(options: ReprojectImageOptions): void; export function sieveFilter(options: SieveFilterOptions): void; export function suggestedWarpOutput(options: SuggestedWarpOutputOptions): { rasterSize: any, geoTransform: any }; -export function verbose(): void; \ No newline at end of file +export function verbose(): void; From d076418dc2fb9748a78bb49a4a585b577703d158 Mon Sep 17 00:00:00 2001 From: andreidigori <45198612+andreidigori@users.noreply.github.com> Date: Tue, 27 Nov 2018 19:33:23 +0200 Subject: [PATCH 361/836] Update index.d.ts Linting --- types/gdal/index.d.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/types/gdal/index.d.ts b/types/gdal/index.d.ts index 6aca0120de..d6c76ba226 100644 --- a/types/gdal/index.d.ts +++ b/types/gdal/index.d.ts @@ -564,9 +564,7 @@ export class MultiLineString extends GeometryCollection { polygonize(): Polygon; } -export class MultiPoint extends GeometryCollection { - -} +export class MultiPoint extends GeometryCollection {} export class MultiPolygon extends GeometryCollection { getArea(): number; From 289c533aadb4ee5d6a7ef2a740c4d38cd7b6cc59 Mon Sep 17 00:00:00 2001 From: Cameron Martin Date: Tue, 27 Nov 2018 17:27:21 +0000 Subject: [PATCH 362/836] [@babel/traverse]: Fixed type of path when using enter & exit visitor. --- types/babel__traverse/babel__traverse-tests.ts | 8 ++++++-- types/babel__traverse/index.d.ts | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/types/babel__traverse/babel__traverse-tests.ts b/types/babel__traverse/babel__traverse-tests.ts index 5b4fbbef5f..974831dbca 100644 --- a/types/babel__traverse/babel__traverse-tests.ts +++ b/types/babel__traverse/babel__traverse-tests.ts @@ -4,10 +4,14 @@ import * as t from "@babel/types"; // Examples from: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md const MyVisitor: Visitor = { Identifier: { - enter() { + enter(path) { + // $ExpectType NodePath + path; console.log("Entered!"); }, - exit() { + exit(path) { + // $ExpectType NodePath + path; console.log("Exited!"); } } diff --git a/types/babel__traverse/index.d.ts b/types/babel__traverse/index.d.ts index 465a60464f..740f5f4429 100644 --- a/types/babel__traverse/index.d.ts +++ b/types/babel__traverse/index.d.ts @@ -142,7 +142,7 @@ export type Visitor = VisitNodeObject & { [P in Node["type"]]?: VisitNode>; }; -export type VisitNode = VisitNodeFunction | VisitNodeObject; +export type VisitNode = VisitNodeFunction | VisitNodeObject

; export type VisitNodeFunction = (this: T, path: NodePath

, state: any) => void; From 2bd511da769254c4dc31a651b7ff05c1e3dd571f Mon Sep 17 00:00:00 2001 From: timhwang21 Date: Tue, 27 Nov 2018 12:47:24 -0500 Subject: [PATCH 363/836] [node-forge] add types for missing modules; fix incorrect types Add typedefs for: * `jsbn` (bare minimum); API isn't public so should be fine * `random` Improve typedefs for: * `pki` public and private keys * Add types for `pki.rsa` keys Add stubs for: (I didn't fix as these types aren't currently relevant to my work) * `pss` * `pki.ed25519` Also fixed some incorrect types, e.g. `createBuffer` was mistyped. Added test case for RSA signing. Also fixed some incorrect tests, and commented out ones that seemed entirely broken. The two removed lines don't trigger type errors on master, but if you actually run the file they will error: `ts-node types/node-forge/node-forge-tests.ts` --- types/node-forge/index.d.ts | 132 ++++++++++++++++++--------- types/node-forge/node-forge-tests.ts | 20 +++- 2 files changed, 104 insertions(+), 48 deletions(-) diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index d362eb1c27..40badbbcf4 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for node-forge 0.7.6 +// Type definitions for node-forge 0.7.7 // Project: https://github.com/digitalbazaar/forge // Definitions by: Seth Westphal // Kay Schecker @@ -7,6 +7,7 @@ // Beeno Tung // Joe Flateau // Nikita Koryabkin +// timhwang21 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -20,6 +21,15 @@ declare module "node-forge" { type Utf8 = string; type OID = string; + namespace jsbn { + class BigInteger { + data: number[]; + t: number; + s: number; + toString(): string; + } + } + namespace pem { interface EncodeOptions { @@ -40,28 +50,18 @@ declare module "node-forge" { } namespace pki { - type PEM = string; - type Key = any; + type PublicKey = rsa.PublicKey | ed25519.Key; + type PrivateKey = rsa.PrivateKey | ed25519.Key; interface KeyPair { publicKey: PublicKey; privateKey: PrivateKey; } - interface PublicKey { - encrypt(data: string, scheme?: string, schemeOptions?: number): Bytes - verify(digest: string, signature: string, scheme?: string): boolean - } - - interface PrivateKey { - decrypt(data: string, scheme?: string, schemeOptions?: number): string - sign(md: string, scheme?: string): Bytes - } - function pemToDer(pem: PEM): util.ByteStringBuffer; function privateKeyToPem(key: PrivateKey, maxline?: number): PEM; - function privateKeyInfoToPem(key: PrivateKey, maxline?: number): PEM; + function privateKeyInfoToPem(key: Bytes, maxline?: number): PEM; function publicKeyToPem(key: PublicKey, maxline?: number): PEM; function publicKeyFromPem(pem: PEM): PublicKey; function privateKeyFromPem(pem: PEM): PrivateKey; @@ -73,7 +73,38 @@ declare module "node-forge" { } var oids: oids; + namespace ed25519 { + type Key = ArrayBuffer; + } + namespace rsa { + type EncryptionScheme = 'RSAES-PKCS1-V1_5' | 'RSA-OAEP' | 'RAW' | 'NONE' | null; + type SignatureScheme = 'RSASSA-PKCS1-V1_5' | pss.PSS | 'NONE' | null; + + interface PublicKey { + n: jsbn.BigInteger; + e: jsbn.BigInteger; + encrypt(data: Bytes, scheme?: EncryptionScheme, schemeOptions?: any): Bytes; + verify(digest: Bytes, signature: Bytes, scheme?: SignatureScheme): boolean; + } + + interface PrivateKey { + n: jsbn.BigInteger; + e: jsbn.BigInteger; + d: jsbn.BigInteger; + p: jsbn.BigInteger; + q: jsbn.BigInteger; + dP: jsbn.BigInteger; + dQ: jsbn.BigInteger; + qInv: jsbn.BigInteger; + decrypt(data: Bytes, scheme?: EncryptionScheme, schemeOptions?: any): Bytes; + sign(md: md.MessageDigest, scheme?: SignatureScheme): Bytes; + } + + interface KeyPair { + publicKey: PublicKey; + privateKey: PrivateKey; + } interface GenerateKeyPairOptions { bits?: number; @@ -84,9 +115,9 @@ declare module "node-forge" { prng?: any; algorithm?: string; } - + function setPublicKey(n: any, e: any): any; - + function generateKeyPair(bits?: number, e?: number, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; function generateKeyPair(options?: GenerateKeyPairOptions, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; } @@ -160,8 +191,8 @@ declare module "node-forge" { hash: any; }; extensions: any[]; - privateKey: Key; - publicKey: Key; + privateKey: PrivateKey; + publicKey: PublicKey; md: any; /** * Sets the subject of this certificate. @@ -200,7 +231,7 @@ declare module "node-forge" { * @param key the private key to sign with. * @param md the message digest object to use (defaults to forge.md.sha1). */ - sign(key: pki.Key, md: md.MessageDigest): void; + sign(key: pki.PrivateKey, md?: md.MessageDigest): void; /** * Attempts verify the signature on the passed certificate using this * certificate's public key. @@ -215,19 +246,30 @@ declare module "node-forge" { function certificateFromAsn1(obj: asn1.Asn1, computeHash?: boolean): Certificate; - function decryptRsaPrivateKey(pem: PEM, passphrase?: string): Key; + function decryptRsaPrivateKey(pem: PEM, passphrase?: string): PrivateKey; function createCertificate(): Certificate; - + function certificationRequestToPem(cert: Certificate, maxline?: number): PEM; - + function certificationRequestFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate; - + function createCertificationRequest(): Certificate; - - function publicKeyToAsn1(publicKey: Key): any; - - function publicKeyToRSAPublicKey(publicKey: Key): any; + + function publicKeyToAsn1(publicKey: PublicKey): any; + + function publicKeyToRSAPublicKey(publicKey: PublicKey): any; + } + + namespace random { + function getBytes(count: number, callback?: (bytes: Bytes) => any): Bytes; + function getBytesSync(count: number): Bytes; + type CB = (_: any, seed: string) => void; + interface Random { + seedFileSync: (needed: number) => string; + seedFile: (needed: number, cb: CB) => void; + } + function createInstance(): Random; } namespace ssh { @@ -249,22 +291,22 @@ declare module "node-forge" { /** * @description Encodes a private RSA key as an OpenSSH file */ - function privateKeyToOpenSSH(privateKey: pki.Key, passphrase?: string): string; + function privateKeyToOpenSSH(privateKey: pki.PrivateKey, passphrase?: string): string; /** * @description Encodes (and optionally encrypts) a private RSA key as a Putty PPK file */ - function privateKeyToPutty(privateKey: pki.Key, passphrase?: string, comment?: string): string; + function privateKeyToPutty(privateKey: pki.PrivateKey, passphrase?: string, comment?: string): string; /** * @description Encodes a public RSA key as an OpenSSH file */ - function publicKeyToOpenSSH(publicKey: pki.Key, comment?: string): string | pki.PEM; + function publicKeyToOpenSSH(publicKey: pki.PublicKey, comment?: string): string | pki.PEM; /** * @description Gets the SSH fingerprint for the given public key */ - function getPublicKeyFingerprint(publicKey: pki.Key, options?: FingerprintOptions): util.ByteStringBuffer | Hex | string; + function getPublicKeyFingerprint(publicKey: pki.PublicKey, options?: FingerprintOptions): util.ByteStringBuffer | Hex | string; } namespace asn1 { @@ -377,7 +419,7 @@ declare module "node-forge" { function decodeUtf8(encoded: Utf8): string; function createBuffer(): ByteBuffer; - function createBuffer(input: string, encode: string): ByteBuffer; + function createBuffer(input: Bytes | ArrayBuffer | ArrayBufferView | ByteStringBuffer, encode: string): ByteBuffer; namespace binary { namespace raw { @@ -418,7 +460,7 @@ declare module "node-forge" { interface Bag { type: string; attributes: any; - key?: pki.Key; + key?: pki.PrivateKey; cert?: pki.Certificate; asn1: asn1.Asn1 } @@ -441,12 +483,12 @@ declare module "node-forge" { function pkcs12FromAsn1(obj: any, strict?: boolean, password?: string): Pkcs12Pfx; function pkcs12FromAsn1(obj: any, password?: string): Pkcs12Pfx; } - + namespace pkcs7 { interface PkcsSignedData { content?: string | util.ByteBuffer; contentInfo?: { value: any[] }; - + addCertificate(certificate: pki.Certificate): void; addSigner(options: { key: string; @@ -459,14 +501,16 @@ declare module "node-forge" { }): void; toAsn1(): asn1.Asn1; } - + function createSignedData(): PkcsSignedData; } namespace md { + type Encoding = "raw" | "utf8" + interface MessageDigest { - update(msg: string, encoding?: string): MessageDigest; + update(msg: string, encoding?: Encoding): MessageDigest; digest(): util.ByteStringBuffer; } @@ -477,7 +521,7 @@ declare module "node-forge" { namespace sha256 { function create(): MessageDigest; } - + namespace sha512 { function create(): MessageDigest; } @@ -513,18 +557,16 @@ declare module "node-forge" { tag: util.ByteStringBuffer; } } - + namespace pss { - function create(any: any): any; + type PSS = any; + + function create(any: any): PSS; } - + namespace mgf { namespace mgf1 { function create(any: any): any; } } - - namespace random { - function getBytesSync(length: number): Bytes; - } } diff --git a/types/node-forge/node-forge-tests.ts b/types/node-forge/node-forge-tests.ts index abc863f7ff..a8d352ad1a 100644 --- a/types/node-forge/node-forge-tests.ts +++ b/types/node-forge/node-forge-tests.ts @@ -8,9 +8,7 @@ let x: string = forge.ssh.privateKeyToOpenSSH(key); let pemKey: forge.pki.PEM = publicKeyPem; let publicKeyRsa = forge.pki.publicKeyFromPem(pemKey); let privateKeyRsa = forge.pki.privateKeyFromPem(privateKeyPem); -let privateKeyRsa2 = forge.pki.privateKeyInfoToPem(privateKeyRsa); let byteBufferString = forge.pki.pemToDer(privateKeyPem); -let certPem = forge.pki.certificateFromPem(pemKey); let cert = forge.pki.createCertificate(); { @@ -118,6 +116,7 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin } { + let key = forge.random.getBytesSync(24) let payload = { asd: 'asd' }; let cipher = forge.cipher.createCipher('3DES-ECB', forge.util.createBuffer(key, 'raw')); cipher.start(); @@ -133,7 +132,7 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin let decrypted = decipher.output as forge.util.ByteStringBuffer; let content = JSON.parse(forge.util.encodeUtf8(decrypted.getBytes())); - if (content.asd == payload.asd) throw Error('forge.cipher.createCipher failed'); + if (content.asd !== payload.asd) throw Error('forge.cipher.createCipher failed'); } { @@ -189,3 +188,18 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin // self-sign certificate cert.sign(keypair.privateKey, forge.md.sha256.create()); } + +{ + let md: forge.md.MessageDigest; + let hex: string; + let signature: forge.Bytes + + md = forge.md.sha256.create(); + md = md.update('Test'); + hex = md.digest().toHex(); + + signature = keypair.privateKey.sign(md) + if (!keypair.publicKey.verify(md.digest().bytes(), signature)) { + throw Error("rsa signature verification fail"); + } +} From f757203084ed5793a80255c032740738d0a82c86 Mon Sep 17 00:00:00 2001 From: Jake Boone Date: Tue, 27 Nov 2018 11:44:14 -0700 Subject: [PATCH 364/836] [react-datepicker] v2.0.0 --- types/react-datepicker/index.d.ts | 69 ++++++++++++++++++----------- types/react-datepicker/package.json | 1 - 2 files changed, 44 insertions(+), 26 deletions(-) diff --git a/types/react-datepicker/index.d.ts b/types/react-datepicker/index.d.ts index 23e542d322..6368e273e3 100644 --- a/types/react-datepicker/index.d.ts +++ b/types/react-datepicker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-datepicker 1.1 +// Type definitions for react-datepicker 2.0 // Project: https://github.com/Hacker0x01/react-datepicker // Definitions by: Rajab Shakirov , // Andrey Balokha , @@ -7,11 +7,11 @@ // Roy Xue // Koala Human // Sean Kelley +// Jake Boone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from "react"; -import * as moment from "moment"; import * as Popper from "popper.js"; export interface ReactDatePickerProps { @@ -20,59 +20,65 @@ export interface ReactDatePickerProps { autoComplete?: string; autoFocus?: boolean; calendarClassName?: string; + calendarContainer?(props: { children: React.ReactNode[] }): React.ReactNode; children?: React.ReactNode; className?: string; customInput?: React.ReactNode; customInputRef?: string; dateFormat?: string | string[]; dateFormatCalendar?: string; - dayClassName?(date: moment.Moment): string | null; + dayClassName?(date: Date): string | null; disabled?: boolean; disabledKeyboardNavigation?: boolean; dropdownMode?: 'scroll' | 'select'; - endDate?: moment.Moment; - excludeDates?: moment.Moment[]; - excludeTimes?: moment.Moment[]; - filterDate?(date: moment.Moment): boolean; + endDate?: Date; + excludeDates?: Date[]; + excludeTimes?: Date[]; + filterDate?(date: Date): boolean; fixedHeight?: boolean; forceShowMonthNavigation?: boolean; - formatWeekNumber?(date: moment.Moment): string | number; - highlightDates?: moment.Moment[]; + formatWeekNumber?(date: Date): string | number; + highlightDates?: Date[]; id?: string; - includeDates?: moment.Moment[]; - includeTimes?: moment.Moment[]; + includeDates?: Date[]; + includeTimes?: Date[]; + injectTimes?: Date[]; inline?: boolean; isClearable?: boolean; locale?: string; - maxDate?: moment.Moment; - maxTime?: moment.Moment; - minDate?: moment.Moment; - minTime?: moment.Moment; + maxDate?: Date; + maxTime?: Date; + minDate?: Date; + minTime?: Date; monthsShown?: number; name?: string; onBlur?(event: React.FocusEvent): void; - onChange(date: moment.Moment | null, event: React.SyntheticEvent | undefined): void; + onChange(date: Date | null, event: React.SyntheticEvent | undefined): void; onChangeRaw?(event: React.FocusEvent): void; onClickOutside?(event: React.MouseEvent): void; onFocus?(event: React.FocusEvent): void; onKeyDown?(event: React.KeyboardEvent): void; - onMonthChange?(date: moment.Moment): void; - onSelect?(date: moment.Moment, event: React.SyntheticEvent | undefined): void; - onWeekSelect?(firstDayOfWeek: moment.Moment, weekNumber: string | number, event: React.SyntheticEvent | undefined): void; - onYearChange?(date: moment.Moment): void; - openToDate?: moment.Moment; + onMonthChange?(date: Date): void; + onSelect?(date: Date, event: React.SyntheticEvent | undefined): void; + onWeekSelect?(firstDayOfWeek: Date, weekNumber: string | number, event: React.SyntheticEvent | undefined): void; + onInputClick?(): void; + onYearChange?(date: Date): void; + onInputError?(err: {code: number; msg: string}): void; + open?: boolean; + openToDate?: Date; peekNextMonth?: boolean; placeholderText?: string; popperClassName?: string; popperContainer?(props: { children: React.ReactNode[] }): React.ReactNode; popperModifiers?: Popper.Modifiers; popperPlacement?: string; + popperProps?: {}; preventOpenOnFocus?: boolean; readOnly?: boolean; required?: boolean; scrollableMonthYearDropdown?: boolean; scrollableYearDropdown?: boolean; - selected?: moment.Moment | null; + selected?: Date | null; selectsEnd?: boolean; selectsStart?: boolean; shouldCloseOnSelect?: boolean; @@ -83,21 +89,34 @@ export interface ReactDatePickerProps { showTimeSelectOnly?: boolean; showWeekNumbers?: boolean; showYearDropdown?: boolean; - startDate?: moment.Moment; + startDate?: Date; startOpen?: boolean; tabIndex?: number; timeCaption?: string; timeFormat?: string; timeIntervals?: number; title?: string; - todayButton?: string; + todayButton?: React.ReactNode; useShortMonthInDropdown?: boolean; useWeekdaysShort?: boolean; - utcOffset?: number; value?: string; weekLabel?: string; withPortal?: boolean; yearDropdownItemNumber?: number; + formatWeekDay?(date: Date): string; + clearButtonTitle?: string; + previousMonthButtonLabel?: string; + nextMonthButtonLabel?: string; + renderCustomHeader?(params: { + date: Date; + changeYear(year: number): void; + changeMonth(month: number): void; + decreaseMonth(): void; + increaseMonth(): void; + prevMonthButtonDisabled: boolean; + nextMonthButtonDisabled: boolean; + }): React.ReactNode; + renderDayContents?(dayOfMonth: number): React.ReactNode; } declare const ReactDatePicker: React.ClassicComponentClass; export default ReactDatePicker; diff --git a/types/react-datepicker/package.json b/types/react-datepicker/package.json index fc763e4d4b..245f69cd2c 100644 --- a/types/react-datepicker/package.json +++ b/types/react-datepicker/package.json @@ -1,7 +1,6 @@ { "private": true, "dependencies": { - "moment": ">=2.14.0", "popper.js": "^1.14.1" } } From 075dc4a1ce3f16807dfe3e4aa13893a814958fde Mon Sep 17 00:00:00 2001 From: Dominik Moritz Date: Tue, 27 Nov 2018 10:48:49 -0800 Subject: [PATCH 365/836] Delete Vega typings since Vega comes with its own types. --- types/vega/index.d.ts | 562 ----------- types/vega/tsconfig.json | 24 - types/vega/tslint.json | 79 -- types/vega/vega-tests.ts | 2035 -------------------------------------- 4 files changed, 2700 deletions(-) delete mode 100644 types/vega/index.d.ts delete mode 100644 types/vega/tsconfig.json delete mode 100644 types/vega/tslint.json delete mode 100644 types/vega/vega-tests.ts diff --git a/types/vega/index.d.ts b/types/vega/index.d.ts deleted file mode 100644 index da7b0fee32..0000000000 --- a/types/vega/index.d.ts +++ /dev/null @@ -1,562 +0,0 @@ -// Type definitions for Vega -// Project: http://trifacta.github.io/vega/ -// Definitions by: Tom Crockett -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace vg { - - export type ChartViewConstructor = { - (args: {renderer: 'svg'} & ViewArgs): SvgView; - (args: {renderer: 'canvas'} & ViewArgs): CanvasView; - (args: ViewArgs): View; - }; - - export interface Parse { - spec(url: string, callback: (chart: ChartViewConstructor) => void): void; - spec(spec: Spec, callback: (chart: ChartViewConstructor) => void): void; - data(dataSet: Data[], callback: () => void): void; - // TODO all the other stuff - } - - export interface ViewArgs { - // TODO docs - el?: any; - data?: any; - hover?: boolean; - renderer?: string; - } - - export interface View { - // TODO docs - width(): number; - width(w: number): this; - - height(): number; - height(h: number): this; - - padding(): Padding; - padding(p: Padding): this; - - viewport(): number[]; - viewport(v: number[]): this; - - renderer(r: string): this; - - data(): Runtime.DataSets; - data(d: any/*TODO*/): this; - - initialize(selector: string): this; - initialize(node: Element): this; - - render(r?: any[]): this; - - update(options?: UpdateOptions): this; - - model(): Vega.Model; - - defs(): Defs; - defs(defs: Defs): this; - } - - export interface SvgView extends View { - svg(): string; - } - - export interface CanvasView extends View { - canvas(): any; // Returns a node-canvas instance - } - - export interface Padding { - // TODO docs - top: number; - right: number; - bottom: number; - left: number; - } - - export interface UpdateOptions { - // TODO docs - props?: string; - items?: any; - duration?: number; - ease?: string; - } - - export interface Bounds { - x1: number; - y1: number; - x2: number; - y2: number; - clear(): Bounds; - set(x1: number, y1: number, x2: number, y2: number): Bounds; - add(x: number, y: number): Bounds; - expand(d: number): Bounds; - round(): Bounds; - translate(dx: number, dy: number): Bounds; - rotate(angle: number, x: number, y: number): Bounds; - union(b: Bounds): Bounds; - encloses(b: Bounds): boolean; - intersects(b: Bounds): boolean; - contains(x: number, y: number): boolean; - width(): number; - height(): number; - } - - export interface Model { - defs(): Defs; - defs(defs: Defs): Model; - - data(): Runtime.DataSets; - data(data: Runtime.DataSets): Model; - - ingest(name: string, tx: any/*TODO*/, input: any/*TODO*/): void; - - dependencies(name: string, tx: any/*TODO*/): void; - - width(w: number): Model; - - height(h: number): Model; - - scene(): Node; - scene(node: Node): Model; - - build(): Model; - - encode(trans?: any/*TODO*/, request?: string, item?: any): Model; - - reset(): Model; - } - - export namespace Runtime { - export interface DataSets { - [name: string]: Datum[]; - } - - export interface Datum { - [key: string]: any - } - - export interface Marks { - type: string; - width: number; - height: number; - scales: Scale[]; - axes: Axis[]; - legends: Legend[]; - marks: Mark[]; - } - - export interface PropertySets { - enter?: Properties; - exit?: Properties; - update?: Properties; - hover?: Properties; - } - - export interface Properties { - (item: Node, group: Node, trans: any/*TODO*/): void; - } - } - - export interface Node { - def: Vega.Mark; - marktype: string; - interactive: boolean; - items: Node[]; - bounds: Bounds; - - // mark item members - hasPropertySet(name: string): boolean; - cousin(offset: number, index: number): Node; - sibling(offset: number): Node; - remove(): Node; - touch(): void; - - // group members - scales?: {[name: string]: any}; - axisItems?: Node[]; - } - - export interface Defs { - width: number; - height: number; - viewport?: number[]; - padding: any; - marks: Runtime.Marks; - data: Data[]; - } - - export interface Spec { - /** - * A unique name for the visualization specification. - */ - name?: string; - /** - * The total width, in pixels, of the data rectangle. Default is 500 if - * undefined. - */ - width?: number; - /** - * The total height, in pixels, of the data rectangle. Default is 500 if - * undefined. - */ - height?: number; - /** - * The width and height of the on-screen viewport, in pixels. If necessary, - * clipping and scrolling will be applied. - */ - viewport?: number[]; - /** - * [Number | Object | String] - * The internal padding, in pixels, from the edge of the visualization - * canvas to the data rectangle. If an object is provided, it must include - * {top, left, right, bottom} properties. Two string values are also - * acceptable: "auto" (the default) and "strict". Auto-padding computes the - * padding dynamically based on the contents of the visualization. All - * marks, including axes and legends, are used to compute the necessary - * padding. "Strict" auto-padding attempts to adjust the padding such that - * the overall width and height of the visualization is unchanged. This mode - * can cause the visualization's width and height parameters to be adjusted - * such that the total size, including padding, remains constant. Note that - * in some cases strict padding is not possible; for example, if the axis - * labels are much larger than the data rectangle. - */ - padding?: number | string | { - top: number; left: number; right: number; bottom: number - }; // string is "auto" or "strict" - /** - * Definitions of data to visualize. - */ - data: Data[]; - /** - * Scale transform definitions. - */ - scales?: Scale[]; - /** - * Axis definitions. - */ - axes?: Axis[]; - /** - * Legend definitions. - */ - legends?: Legend[]; - /** - * Graphical mark definitions. - */ - marks: (Mark | GroupMark)[]; - } - - export interface Data { - /** - * A unique name for the data set. - */ - name: string; - /** - * An object that specifies the format for the data file, if loaded from a - * URL. - */ - format?: Data.Format; - /** - * The actual data set to use. The values property allows data to be inlined - * directly within the specification itself. - */ - values?: any; - /** - * The name of another data set to use as the source for this data set. The - * source property is particularly useful in combination with a transform - * pipeline to derive new data. - */ - source?: string; - /** - * A URL from which to load the data set. Use the format property to ensure - * the loaded data is correctly parsed. If the format property is not specified, - * the data is assumed to be in a row-oriented JSON format. - */ - url?: string; - /** - * An array of transforms to perform on the data. Transform operators will be - * run on the default data, as provided by late-binding or as specified by the - * source, values, or url properties. - */ - transform?: Data.Transform[]; - } - - export namespace Data { - export interface FormatBase { - /** - * The currently supported format types are json (JavaScript Object - * Notation), csv (comma-separated values), tsv (tab-separated values), - * topojson, and treejson. - */ - type: string; - // TODO: fields for specific formats - } - - /** - * The JSON property containing the desired data. - * This parameter can be used when the loaded JSON file may have surrounding structure or meta-data. - * For example "property": "values.features" is equivalent to retrieving json.values.features from the - * loaded JSON object. - */ - export interface JsonFormat extends FormatBase { - type: string; // "json" - property?: string; - } - - export interface CsvOrTsvFormat extends FormatBase { - type: string; // "csv" | "tsv" - parse?: { - [propertyName: string]: string; // "number" | "boolean" | "date" - } - } - - export interface TopoJsonFormat extends FormatBase { - type: string; // "topojson" - feature?: string; - mesh?: string; - } - - export interface TreeJson extends FormatBase { - type: string; // "treejson" - children?: string; - parse?: { - [propertyName: string]: string; // "number" | "boolean" | "date" - } - } - - export type Format = JsonFormat | CsvOrTsvFormat | TopoJsonFormat | TreeJson; - - export interface Transform { - // TODO - } - } - - export interface Scale { - // TODO docs - - // -- Common scale properties - name?: string; - type?: string; - domain?: any; - domainMin?: any; - domainMax?: any; - range?: any; - rangeMin?: any; - rangeMax?: any; - reverse?: boolean; - round?: boolean; - - // -- Ordinal scale properties - points?: boolean; - padding?: number; - sort?: boolean; - - // -- Time/Quantitative scale properties - clamp?: boolean; - /** boolean for quantitative scales, string for time scales */ - nice?: boolean | string; - - // -- Quantitative scale properties - exponent?: number; - zero?: boolean; - } - - export interface Axis { - // TODO docs - type: string; - scale: string; - orient?: string; - title?: string; - titleOffset?: number; - format?: string; - ticks?: number; - values?: any[]; - subdivide?: number; - tickPadding?: number; - tickSize?: number; - tickSizeMajor?: number; - tickSizeMinor?: number; - tickSizeEnd?: number; - offset?: any; - layer?: string; - grid?: boolean; - properties?: Axis.Properties - } - - export namespace Axis { - export interface Properties { - ticks?: PropertySet; - minorTicks?: PropertySet; - grid?: PropertySet; - labels?: PropertySet; - title?: PropertySet; - axis?: PropertySet; - } - } - - export interface Legend { - // TODO - } - - export interface Mark { - // TODO docs - // Stuff from Spec.Mark - type: string; // "rect" | "symbol" | "path" | "arc" | "area" | "line" | "rule" | "image" | "text" | "group" - name?: string; - description?: string; - from?: Mark.From; - key?: string; - delay?: ValueRefs; - /** - * "linear-in" | "linear-out" | "linear-in-out" | "linear-out-in" | "quad-in" | "quad-out" | "quad-in-out" | - * "quad-out-in" | "cubic-in" | "cubic-out" | "cubic-in-out" | "cubic-out-in" | "sin-in" | "sin-out" | "sin-in-out" | - * "sin-out-in" | "exp-in" | "exp-out" | "exp-in-out" | "exp-out-in" | "circle-in" | "circle-out" | "circle-in-out" | - * "circle-out-in" | "bounce-in" | "bounce-out" | "bounce-in-out" | "bounce-out-in" - */ - ease?: string; - - interactive?: boolean; - - // Runtime PropertySets - properties?: PropertySets; - } - - export module Mark { - export interface From { - // TODO docs - data?: string; - mark?: string; - transform?: Data.Transform[]; - } - } - - export interface GroupMark extends Mark { - type: string; // "group" - /** - * Scale transform definitions. - */ - scales?: Scale[]; - /** - * Axis definitions. - */ - axes?: Axis[]; - /** - * Legend definitions. - */ - legends?: Legend[]; - /** - * Groups differ from other mark types in their ability to contain children marks. - * Marks defined within a group mark can inherit data from their parent group. - * For inheritance to work each data element for a group must contain data elements of its own. - * This arrangement of nested data is typically achieved by facetting the data, such that each group-level data element includes its own array of sub-elements - */ - marks?: (Mark | GroupMark)[]; - } - - export interface PropertySets { - // TODO docs - enter?: PropertySet; - exit?: PropertySet; - update?: PropertySet; - hover?: PropertySet; - } - - export interface PropertySet { - // TODO docs - - // -- Shared visual properties - x?: ValueRefs; - x2?: ValueRefs; - width?: ValueRefs; - y?: ValueRefs; - y2?: ValueRefs; - height?: ValueRefs; - opacity?: ValueRefs; - fill?: ValueRefs; - fillOpacity?: ValueRefs; - stroke?: ValueRefs; - strokeWidth?: ValueRefs; - strokeOpacity?: ValueRefs; - strokeDash?: ValueRefs; - strokeDashOffset?: ValueRefs; - - // -- symbol - size?: ValueRefs; - shape?: ValueRefs; - - // -- path - path?: ValueRefs; - - // -- arc - innerRadius?: ValueRefs; - outerRadius?: ValueRefs; - startAngle?: ValueRefs; - endAngle?: ValueRefs; - - // -- area / line - interpolate?: ValueRefs; - tension?: ValueRefs; - - // -- image / text - align?: ValueRefs; - baseline?: ValueRefs; - - // -- image - url?: ValueRefs; - - // -- text - text?: ValueRefs; - dx?: ValueRefs; - dy?: ValueRefs; - angle?: ValueRefs; - font?: ValueRefs; - fontSize?: ValueRefs; - fontWeight?: ValueRefs; - fontStyle?: ValueRefs; - } - - export interface ValueRef { - // TODO docs - value?: any; - field?: any; - group?: any; - scale?: any; - mult?: number; - offset?: number; - band?: boolean; - test?: string; - } - - export type ValueRefs = ValueRef | ValueRef[]; - - export var parse: Parse; - export namespace scene { - export function item(mark: Node): Node; - } - - export class Bounds implements Bounds { - x1: number; - y1: number; - x2: number; - y2: number; - clear(): Bounds; - set(x1: number, y1: number, x2: number, y2: number): Bounds; - add(x: number, y: number): Bounds; - expand(d: number): Bounds; - round(): Bounds; - translate(dx: number, dy: number): Bounds; - rotate(angle: number, x: number, y: number): Bounds; - union(b: Bounds): Bounds; - encloses(b: Bounds): boolean; - intersects(b: Bounds): boolean; - contains(x: number, y: number): boolean; - width(): number; - height(): number; - } - - // TODO: classes for View, Model, etc. -} - -export = vg; -export as namespace vg; -export as namespace Vega; diff --git a/types/vega/tsconfig.json b/types/vega/tsconfig.json deleted file mode 100644 index f49e5e811b..0000000000 --- a/types/vega/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "vega-tests.ts" - ] -} \ No newline at end of file diff --git a/types/vega/tslint.json b/types/vega/tslint.json deleted file mode 100644 index a41bf5d19a..0000000000 --- a/types/vega/tslint.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} diff --git a/types/vega/vega-tests.ts b/types/vega/vega-tests.ts deleted file mode 100644 index 5baeaee024..0000000000 --- a/types/vega/vega-tests.ts +++ /dev/null @@ -1,2035 +0,0 @@ - - -// examples from http://trifacta.github.io/vega/editor/ -var specs: Vega.Spec[]; - -specs[0] = { - "name": "arc", - "width": 400, - "height": 400, - "data": [ - { - "name": "table", - "values": [12, 23, 47, 6, 52, 19], - "transform": [ - { "type": "pie", "value": "data" } - ] - } - ], - "scales": [ - { - "name": "r", - "type": "sqrt", - "domain": { "data": "table", "field": "data" }, - "range": [20, 100] - } - ], - "marks": [ - { - "type": "arc", - "from": { "data": "table" }, - "properties": { - "enter": { - "x": { "group": "width", "mult": 0.5 }, - "y": { "group": "height", "mult": 0.5 }, - "startAngle": { "field": "startAngle" }, - "endAngle": { "field": "endAngle" }, - "innerRadius": { "value": 20 }, - "outerRadius": { "scale": "r" }, - "stroke": { "value": "#fff" } - }, - "update": { - "fill": { "value": "#ccc" } - }, - "hover": { - "fill": { "value": "pink" } - } - } - } - ] -} - -specs[1] = { - "width": 500, - "height": 200, - "padding": { "top": 10, "left": 30, "bottom": 30, "right": 10 }, - "data": [ - { - "name": "table", - "values": [ - { "x": 1, "y": 28 }, { "x": 2, "y": 55 }, - { "x": 3, "y": 43 }, { "x": 4, "y": 91 }, - { "x": 5, "y": 81 }, { "x": 6, "y": 53 }, - { "x": 7, "y": 19 }, { "x": 8, "y": 87 }, - { "x": 9, "y": 52 }, { "x": 10, "y": 48 }, - { "x": 11, "y": 24 }, { "x": 12, "y": 49 }, - { "x": 13, "y": 87 }, { "x": 14, "y": 66 }, - { "x": 15, "y": 17 }, { "x": 16, "y": 27 }, - { "x": 17, "y": 68 }, { "x": 18, "y": 16 }, - { "x": 19, "y": 49 }, { "x": 20, "y": 15 } - ] - } - ], - "scales": [ - { - "name": "x", - "type": "linear", - "range": "width", - "zero": false, - "domain": { "data": "table", "field": "data.x" } - }, - { - "name": "y", - "type": "linear", - "range": "height", - "nice": true, - "domain": { "data": "table", "field": "data.y" } - } - ], - "axes": [ - { "type": "x", "scale": "x", "ticks": 20 }, - { "type": "y", "scale": "y" } - ], - "marks": [ - { - "type": "area", - "from": { "data": "table" }, - "properties": { - "enter": { - "interpolate": { "value": "monotone" }, - "x": { "scale": "x", "field": "data.x" }, - "y": { "scale": "y", "field": "data.y" }, - "y2": { "scale": "y", "value": 0 }, - "fill": { "value": "steelblue" } - }, - "update": { - "fillOpacity": { "value": 1 } - }, - "hover": { - "fillOpacity": { "value": 0.5 } - } - } - } - ] -} - -specs[2] = { - "width": 200, - "height": 720, - "data": [ - { - "name": "barley", - "url": "data/barley.json" - }, - { - "name": "variety", - "source": "barley", - "transform": [ - { "type": "facet", "keys": ["data.variety"] }, - { "type": "stats", "value": "data.yield", "median": true }, - { "type": "sort", "by": "-median" } - ] - }, - { - "name": "site", - "source": "barley", - "transform": [ - { "type": "facet", "keys": ["data.site"] }, - { "type": "stats", "value": "data.yield", "median": true }, - { "type": "sort", "by": "-median" } - ] - } - ], - "scales": [ - { - "name": "g", - "type": "ordinal", - "range": "height", - "padding": 0.15, - "domain": { "data": "site", "field": "key" } - }, - { - "name": "x", - "type": "linear", - "nice": true, - "range": "width", - "domain": { "data": "barley", "field": "data.yield" } - }, - { - "name": "c", - "type": "ordinal", - "range": "category10" - } - ], - "axes": [ - { "type": "x", "scale": "x", "offset": -12 } - ], - "marks": [ - { - "type": "text", - "from": { "data": "site" }, - "properties": { - "enter": { - "x": { "group": "width", "mult": 0.5 }, - "y": { "scale": "g", "field": "key", "offset": -2 }, - "fontWeight": { "value": "bold" }, - "text": { "field": "key" }, - "align": { "value": "center" }, - "baseline": { "value": "bottom" }, - "fill": { "value": "#000" } - } - } - }, - { - "type": "group", - "from": { "data": "site" }, - "scales": [ - { - "name": "y", - "type": "ordinal", - "range": "height", - "points": true, - "padding": 1.2, - "domain": { "data": "variety", "field": "key" } - } - ], - "axes": [ - { - "type": "y", - "scale": "y", - "tickSize": 0, - "properties": { "axis": { "stroke": { "value": "transparent" } } } - } - ], - "properties": { - "enter": { - "x": { "value": 0.5 }, - "y": { "scale": "g", "field": "key" }, - "height": { "scale": "g", "band": true }, - "width": { "group": "width" }, - "stroke": { "value": "#ccc" } - } - }, - "marks": [ - { - "type": "symbol", - "properties": { - "enter": { - "x": { "scale": "x", "field": "data.yield" }, - "y": { "scale": "y", "field": "data.variety" }, - "size": { "value": 50 }, - "stroke": { "scale": "c", "field": "data.year" }, - "strokeWidth": { "value": 2 } - } - } - } - ] - } - ] -} - -specs[3] = { - "width": 960, - "height": 500, - "data": [ - { - "name": "unemp", - "url": "data/unemployment.tsv", - "format": { "type": "tsv", "parse": { "rate": "number" } } - }, - { - "name": "counties", - "url": "data/us-10m.json", - "format": { "type": "topojson", "feature": "counties" }, - "transform": [ - { "type": "geopath", "value": "data", "projection": "albersUsa" }, - { - "type": "zip", - "key": "data.id", - "with": "unemp", - "withKey": "data.id", - "as": "value", - "default": null - }, - { "type": "filter", "test": "d.path!=null && d.value!=null" } - ] - } - ], - "scales": [ - { - "name": "color", - "type": "quantize", - "domain": [0, 0.15], - "range": ["#f7fbff", "#deebf7", "#c6dbef", "#9ecae1", "#6baed6", - "#4292c6", "#2171b5", "#08519c", "#08306b"] - } - ], - "marks": [ - { - "type": "path", - "from": { "data": "counties" }, - "properties": { - "enter": { "path": { "field": "path" } }, - "update": { "fill": { "scale": "color", "field": "value.data.rate" } }, - "hover": { "fill": { "value": "red" } } - } - } - ] -} - -specs[4] = { - "width": 300, - "height": 240, - "data": [ - { - "name": "table", - "url": "data/groups.json" - } - ], - "scales": [ - { - "name": "cat", - "type": "ordinal", - "range": "height", - "padding": 0.2, - "domain": { "data": "table", "field": "data.category" } - }, - { - "name": "val", - "range": "width", - "round": true, - "nice": true, - "domain": { "data": "table", "field": "data.value" } - }, - { - "name": "color", - "type": "ordinal", - "range": "category20" - } - ], - "axes": [ - { "type": "y", "scale": "cat", "tickSize": 0, "tickPadding": 8 }, - { "type": "x", "scale": "val" } - ], - "marks": [ - { - "type": "group", - "from": { - "data": "table", - "transform": [{ "type": "facet", "keys": ["data.category"] }] - }, - "properties": { - "enter": { - "y": { "scale": "cat", "field": "key" }, - "height": { "scale": "cat", "band": true } - } - }, - "scales": [ - { - "name": "pos", - "type": "ordinal", - "range": "height", - "domain": { "field": "data.position" } - } - ], - "marks": [ - { - "type": "rect", - "properties": { - "enter": { - "y": { "scale": "pos", "field": "data.position" }, - "height": { "scale": "pos", "band": true }, - "x": { "scale": "val", "field": "data.value" }, - "x2": { "scale": "val", "value": 0 }, - "fill": { "scale": "color", "field": "data.position" } - } - } - }, - { - "type": "text", - "properties": { - "enter": { - "y": { "scale": "pos", "field": "data.position" }, - "dy": { "scale": "pos", "band": true, "mult": 0.5 }, - "x": { "scale": "val", "field": "data.value", "offset": -4 }, - "fill": { "value": "white" }, - "align": { "value": "right" }, - "baseline": { "value": "middle" }, - "text": { "field": "data.value" } - } - } - } - ] - } - ] -} - -specs[5] = { - "width": 400, - "height": 100, - "padding": { "top": 30, "left": 30, "bottom": 30, "right": 10 }, - "data": [ - { - "name": "stats", - "values": [ - { "label": "Category A", "mean": 1, "lo": 0, "hi": 2 }, - { "label": "Category B", "mean": 2, "lo": 1.5, "hi": 2.5 }, - { "label": "Category C", "mean": 3, "lo": 1.7, "hi": 4.3 }, - { "label": "Category D", "mean": 4, "lo": 3, "hi": 5 }, - { "label": "Category E", "mean": 5, "lo": 4.1, "hi": 5.9 } - ] - } - ], - "scales": [ - { - "name": "y", - "type": "ordinal", - "range": "height", - "domain": { "data": "stats", "field": "index" } - }, - { - "name": "x", - "range": [100, 400], - "nice": true, - "zero": true, - "domain": { "data": "stats", "field": "data.hi" } - } - ], - "axes": [ - { "type": "x", "scale": "x", "ticks": 6 } - ], - "marks": [ - { - "type": "text", - "from": { "data": "stats" }, - "properties": { - "enter": { - "x": { "value": 0 }, - "y": { "scale": "y", "field": "index" }, - "baseline": { "value": "middle" }, - "fill": { "value": "#000" }, - "text": { "field": "data.label" }, - "font": { "value": "Helvetica Neue" }, - "fontSize": { "value": 13 } - } - } - }, - { - "type": "rect", - "from": { "data": "stats" }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "data.lo" }, - "x2": { "scale": "x", "field": "data.hi" }, - "y": { "scale": "y", "field": "index", "offset": -1 }, - "height": { "value": 1 }, - "fill": { "value": "#888" } - } - } - }, - { - "type": "symbol", - "from": { "data": "stats" }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "data.mean" }, - "y": { "scale": "y", "field": "index" }, - "size": { "value": 40 }, - "fill": { "value": "#000" } - } - } - } - ] -} - -specs[6] = { - "name": "force", - "width": 500, - "height": 500, - "padding": { "top": 0, "bottom": 0, "left": 0, "right": 0 }, - "data": [ - { - "name": "edges", - "url": "data/miserables.json", - "format": { "type": "json", "property": "links" }, - "transform": [ - { "type": "copy", "from": "data", "fields": ["source", "target"] } - ] - }, - { - "name": "nodes", - "url": "data/miserables.json", - "format": { "type": "json", "property": "nodes" }, - "transform": [ - { - "type": "force", - "links": "edges", - "linkDistance": 70, - "charge": -100, - "iterations": 1000 - } - ] - } - ], - "marks": [ - { - "type": "path", - "from": { - "data": "edges", - "transform": [ - { "type": "link", "shape": "line" } - ] - }, - "properties": { - "update": { - "path": { "field": "path" }, - "stroke": { "value": "#ccc" }, - "strokeWidth": { "value": 0.5 } - } - } - }, - { - "type": "symbol", - "from": { "data": "nodes" }, - "properties": { - "enter": { - "fillOpacity": { "value": 0.3 }, - "stroke": { "value": "steelblue" } - }, - "update": { - "x": { "field": "x" }, - "y": { "field": "y" }, - "fill": { "value": "steelblue" } - }, - "hover": { - "fill": { "value": "#f00" } - } - } - } - ] -}; - -specs[7] = { - "name": "image", - "width": 200, - "height": 200, - "padding": { "left": 30, "top": 10, "bottom": 30, "right": 10 }, - "data": [ - { - "name": "data", - "values": [ - { "x": 0.5, "y": 0.5, "img": "data/ffox.png" }, - { "x": 1.5, "y": 1.5, "img": "data/gimp.png" }, - { "x": 2.5, "y": 2.5, "img": "data/7zip.png" } - ] - } - ], - "scales": [ - { "name": "x", "domain": [0, 3], "range": "width" }, - { "name": "y", "domain": [0, 3], "range": "height" } - ], - "axes": [ - { "type": "x", "scale": "x" }, - { "type": "y", "scale": "y" } - ], - "marks": [ - { - "type": "image", - "from": { "data": "data" }, - "properties": { - "enter": { - "url": { "field": "data.img" }, - "width": { "value": 50 }, - "height": { "value": 50 }, - "x": { "scale": "x", "field": "data.x" }, - "y": { "scale": "y", "field": "data.y" }, - "align": { "value": "center" }, - "baseline": { "value": "middle" } - }, - "update": { - "opacity": { "value": 1.0 } - }, - "hover": { - "opacity": { "value": 0.5 } - } - } - } - ] -} - -specs[8] = { - "width": 800, - "height": 500, - "padding": { "left": 15, "right": 65, "top": 10, "bottom": 20 }, - "data": [ - { - "name": "jobs", - "url": "data/jobs.json" - }, - { - "name": "series", - "source": "jobs", - "transform": [ - { "type": "facet", "keys": ["data.job", "data.sex"] }, - { "type": "stats", "value": "data.perc" }, - { "type": "stack", "point": "data.year", "height": "data.perc", "order": "reverse" } - ] - }, - { - "name": "stats", - "source": "jobs", - "transform": [ - { "type": "facet", "keys": ["data.year"] }, - { "type": "stats", "value": "data.perc" } - ] - } - ], - "scales": [ - { - "name": "x", - "type": "linear", - "range": "width", - "zero": false, "round": true, - "domain": { "data": "jobs", "field": "data.year" } - }, - { - "name": "y", - "type": "linear", - "range": "height", "round": true, - "domain": { "data": "stats", "field": "sum" } - }, - { - "name": "color", - "type": "ordinal", - "domain": ["men", "women"], - "range": ["#33f", "#f33"] - }, - { - "name": "alpha", - "type": "linear", - "domain": { "data": "series", "field": "sum" }, - "range": [0.4, 0.8] - }, - { - "name": "font", - "type": "sqrt", - "range": [0, 24], "round": true, - "domain": { "data": "stats", "field": "sum" } - }, - { - "name": "align", - "type": "quantize", - "range": ["left", "center", "right"], "zero": false, - "domain": [1730, 2130] - }, - { - "name": "offset", - "type": "quantize", - "range": [6, 0, -6], "zero": false, - "domain": [1730, 2130] - } - ], - "axes": [ - { "type": "x", "scale": "x", "format": "d", "ticks": 15, "tickSizeEnd": 0 }, - { - "type": "y", "scale": "y", "format": "n", "orient": "right", - "grid": true, "layer": "back", "tickSize": 12, - "properties": { - "axis": { "stroke": { "value": "transparent" } }, - "grid": { "stroke": { "value": "#ccc" } }, - "ticks": { "stroke": { "value": "#ccc" } } - } - } - ], - "marks": [ - { - "type": "group", - "from": { "data": "series" }, - "marks": [ - { - "type": "area", - "properties": { - "update": { - "x": { "scale": "x", "field": "data.year" }, - "y": { "scale": "y", "field": "y" }, - "y2": { "scale": "y", "field": "y2" }, - "fill": { "scale": "color", "field": "data.sex" }, - "fillOpacity": { "scale": "alpha", "group": "sum" } - }, - "hover": { - "fillOpacity": { "value": 0.2 } - } - } - } - ] - }, - { - "type": "group", - "from": { "data": "series" }, - "marks": [ - { - "type": "text", - "from": { - "transform": [ - { "type": "slice", "by": "max", "field": "data.perc" } - ] - }, - "interactive": false, - "properties": { - "update": { - "x": { "scale": "x", "field": "data.year" }, - "dx": { "scale": "offset", "field": "data.year" }, - "y": { "scale": "y", "field": "cy" }, - "fill": { "value": "#000" }, - "fillOpacity": { "scale": "font", "field": "data.perc", "mult": 0.15 }, - "fontSize": { "scale": "font", "field": "data.perc", "offset": 5 }, - "text": { "field": "data.job" }, - "align": { "scale": "align", "field": "data.year" }, - "baseline": { "value": "middle" } - } - } - } - ] - } - ] -}; - -specs[9] = { - "name": "lifelines", - "width": 400, - "height": 100, - "data": [ - { - "name": "people", - "values": [ - { - "label": "Washington", "born": -7506057600000, "died": -5366196000000, - "enter": -5701424400000, "leave": -5453884800000 - }, - { - "label": "Adams", "born": -7389766800000, "died": -4528285200000, - "enter": -5453884800000, "leave": -5327740800000 - }, - { - "label": "Jefferson", "born": -7154586000000, "died": -4528285200000, - "enter": -5327740800000, "leave": -5075280000000 - }, - { - "label": "Madison", "born": -6904544400000, "died": -4213184400000, - "enter": -5075280000000, "leave": -4822819200000 - }, - { - "label": "Monroe", "born": -6679904400000, "died": -4370518800000, - "enter": -4822819200000, "leave": -4570358400000 - } - ] - }, - { - "name": "events", - "format": { "type": "json", "parse": { "when": "date" } }, - "values": [ - { "name": "Decl. of Independence", "when": "July 4, 1776" }, - { "name": "U.S. Constitution", "when": "3/4/1789" }, - { "name": "Louisiana Purchase", "when": "April 30, 1803" }, - { "name": "Monroe Doctrine", "when": "Dec 2, 1823" } - ] - } - - ], - "scales": [ - { - "name": "y", - "type": "ordinal", - "range": "height", - "domain": { "data": "people", "field": "data.label" } - }, - { - "name": "x", - "type": "time", - "range": "width", - "round": true, - "nice": "year", - "domain": { "data": "people", "field": ["data.born", "data.died"] } - } - ], - "axes": [ - { "type": "x", "scale": "x" } - ], - "marks": [ - { - "type": "text", - "from": { "data": "events" }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "data.when" }, - "y": { "value": -10 }, - "angle": { "value": -25 }, - "fill": { "value": "#000" }, - "text": { "field": "data.name" }, - "font": { "value": "Helvetica Neue" }, - "fontSize": { "value": 10 } - } - } - }, - { - "type": "rect", - "from": { "data": "events" }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "data.when" }, - "y": { "value": -8 }, - "width": { "value": 1 }, - "height": { "group": "height", "offset": 8 }, - "fill": { "value": "#888" } - } - } - }, - { - "type": "text", - "from": { "data": "people" }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "data.born" }, - "y": { "scale": "y", "field": "data.label", "offset": -3 }, - "fill": { "value": "#000" }, - "text": { "field": "data.label" }, - "font": { "value": "Helvetica Neue" }, - "fontSize": { "value": 10 } - } - } - }, - { - "type": "rect", - "from": { "data": "people" }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "data.born" }, - "x2": { "scale": "x", "field": "data.died" }, - "y": { "scale": "y", "field": "data.label" }, - "height": { "value": 2 }, - "fill": { "value": "#557" } - } - } - }, - { - "type": "rect", - "from": { "data": "people" }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "data.enter" }, - "x2": { "scale": "x", "field": "data.leave" }, - "y": { "scale": "y", "field": "data.label", "offset": -1 }, - "height": { "value": 4 }, - "fill": { "value": "#e44" } - } - } - } - ] -} - -specs[10] = { - "width": 1920, - "height": 1000, - "viewport": [960, 500], - "data": [ - { - "name": "world", - "url": "data/world-110m.json", - "format": { "type": "topojson", "feature": "countries" } - } - ], - "marks": [ - { - "type": "path", - "from": { - "data": "world", - "transform": [{ - "type": "geopath", - "value": "data", - "projection": "winkel3", - "scale": 300, - "translate": [960, 500] - }] - }, - "properties": { - "enter": { - "stroke": { "value": "#fff" }, - "path": { "field": "path" } - }, - "update": { "fill": { "value": "#ccc" } }, - "hover": { "fill": { "value": "pink" } } - } - } - ] -} - -specs[11] = { - "width": 760, - "height": 260, - "data": [ - { - "name": "temp", - "url": "data/napoleon.json", - "format": { "type": "json", "property": "temp" }, - "transform": [ - { "type": "formula", "field": "lat", "expr": "55" }, - { - "type": "geo", - "lat": "lat", - "lon": "data.lon", - "center": [32.52, 53.3], - "scale": 3000 - } - ] - }, - { - "name": "army", - "url": "data/napoleon.json", - "format": { "type": "json", "property": "army" }, - "transform": [ - { - "type": "geo", - "lat": "data.lat", - "lon": "data.lon", - "center": [32.52, 53.3], - "scale": 3000 - } - ] - }, - { - "name": "cities", - "url": "data/napoleon.json", - "format": { "type": "json", "property": "cities" }, - "transform": [ - { - "type": "geo", - "lat": "data.lat", - "lon": "data.lon", - "center": [32.52, 53.3], - "scale": 3000 - } - ] - } - ], - "scales": [ - { - "name": "color", - "type": "ordinal", - "domain": { "data": "army", "field": "data.dir" }, - "range": ["brown", "black"] - }, - { - "name": "lw", - "type": "linear", "zero": false, - "domain": { "data": "army", "field": "data.size" }, - "range": [1, 50] - } - ], - "marks": [ - { - "type": "group", - "properties": { - "enter": { - "x": { "value": 0 }, - "y": { "value": 200 }, - "width": { "group": "width" }, - "height": { "value": 60 } - } - }, - "scales": [ - { - "name": "y", - "type": "linear", "zero": false, "round": true, - "domain": { "data": "temp", "field": "data.temp" }, - "range": "height" - } - ], - "axes": [ - { - "type": "y", "scale": "y", "ticks": 4, "orient": "right", - "grid": true, "layer": "back" - } - ], - "marks": [ - { - "type": "rule", - "from": { "data": "temp" }, - "properties": { - "enter": { - "x": { "field": "x" }, - "y1": 0, - "y2": { "scale": "y", "field": "data.temp" }, - "stroke": { "value": "#ccc" } - } - } - }, - { - "type": "line", - "from": { "data": "temp" }, - "properties": { - "enter": { - "x": { "field": "x" }, - "y": { "scale": "y", "field": "data.temp" }, - "stroke": { "value": "#000" }, - "strokeWidth": { "value": 2 } - } - } - }, - { - "type": "text", - "from": { "data": "temp" }, - "properties": { - "enter": { - "x": { "field": "x", "offset": -2 }, - "y": { "scale": "y", "field": "data.temp", "offset": 6 }, - "fill": { "value": "#000" }, - "text": { "field": "data.date" }, - "font": { "value": "Georgia" }, - "fontSize": { "value": 10 }, - "align": { "value": "center" }, - "baseline": { "value": "top" } - } - } - } - ] - }, - { - "type": "group", - "from": { - "data": "army", - "transform": [ - { "type": "facet", "keys": ["data.group", "data.dir"] } - ] - }, - "marks": [ - { - "type": "group", - "from": { - "transform": [ - { "type": "window", "size": 2, "step": 1 } - ] - }, - "marks": [ - { - "type": "line", - "properties": { - "enter": { - "x": { "field": "x" }, - "y": { "field": "y" }, - "stroke": { "scale": "color", "field": "data.dir" }, - "strokeWidth": { "scale": "lw", "field": "data.size" }, - "strokeCap": { "value": "round" } - } - } - } - ] - } - ] - }, - { - "type": "symbol", - "from": { "data": "cities" }, - "properties": { - "enter": { - "x": { "field": "x" }, - "y": { "field": "y" }, - "size": { "value": 25 }, - "fill": { "value": "brown" }, - "stroke": { "value": "#000" } - } - } - }, - { - "type": "text", - "from": { "data": "cities" }, - "properties": { - "enter": { - "x": { "field": "x", "offset": 1 }, - "y": { "field": "y", "offset": -4 }, - "fill": { "value": "#fff" }, - "fillOpacity": { "value": 0.8 }, - "text": { "field": "data.city" }, - "align": { "value": "center" }, - "baseline": { "value": "bottom" }, - "font": { "value": "Georgia" }, - "fontSize": { "value": 9 }, - "fontStyle": { "value": "italic" } - } - } - }, - { - "type": "text", - "from": { "data": "cities" }, - "properties": { - "enter": { - "x": { "field": "x" }, - "y": { "field": "y", "offset": -5 }, - "fill": { "value": "#000" }, - "text": { "field": "data.city" }, - "align": { "value": "center" }, - "baseline": { "value": "bottom" }, - "font": { "value": "Georgia" }, - "fontSize": { "value": 9 }, - "fontStyle": { "value": "italic" } - } - } - } - ] -} - -specs[12] = { - "width": 700, - "height": 400, - "data": [ - { - "name": "cars", - "url": "data/cars.json" - }, - { - "name": "fields", - "values": ["cyl", "dsp", "lbs", "hp", "acc", "mpg", "year"] - } - ], - "scales": [ - { - "name": "ord", - "type": "ordinal", - "range": "width", "points": true, - "domain": { "data": "fields", "field": "data" } - }, - { - "name": "cyl", - "range": "height", "zero": false, "nice": true, - "domain": { "data": "cars", "field": "data.cyl" } - }, - { - "name": "dsp", - "range": "height", "zero": false, "nice": true, - "domain": { "data": "cars", "field": "data.dsp" } - }, - { - "name": "lbs", - "range": "height", "zero": false, "nice": true, - "domain": { "data": "cars", "field": "data.lbs" } - }, - { - "name": "hp", - "range": "height", "zero": false, "nice": true, - "domain": { "data": "cars", "field": "data.hp" } - }, - { - "name": "acc", - "range": "height", "zero": false, "nice": true, - "domain": { "data": "cars", "field": "data.acc" } - }, - { - "name": "mpg", - "range": "height", "zero": false, "nice": true, - "domain": { "data": "cars", "field": "data.mpg" } - }, - { - "name": "year", - "range": "height", "zero": false, "nice": true, - "domain": { "data": "cars", "field": "data.year" } - } - ], - "axes": [ - { "type": "y", "scale": "cyl", "offset": { "scale": "ord", "value": "cyl" } }, - { "type": "y", "scale": "dsp", "offset": { "scale": "ord", "value": "dsp" } }, - { "type": "y", "scale": "lbs", "offset": { "scale": "ord", "value": "lbs" } }, - { "type": "y", "scale": "hp", "offset": { "scale": "ord", "value": "hp" } }, - { "type": "y", "scale": "acc", "offset": { "scale": "ord", "value": "acc" } }, - { "type": "y", "scale": "mpg", "offset": { "scale": "ord", "value": "mpg" } }, - { "type": "y", "scale": "year", "offset": { "scale": "ord", "value": "year" } } - ], - "marks": [ - { - "type": "group", - "from": { "data": "cars" }, - "marks": [ - { - "type": "line", - "from": { "data": "fields" }, - "properties": { - "enter": { - "x": { "scale": "ord", "field": "data" }, - "y": { "scale": { "field": "data" }, "group": "data", "field": "data" }, - "stroke": { "value": "steelblue" }, - "strokeWidth": { "value": 1 }, - "strokeOpacity": { "value": 0.3 } - } - } - } - ] - }, - { - "type": "text", - "from": { "data": "fields" }, - "properties": { - "enter": { - "x": { "scale": "ord", "field": "data", "offset": -8 }, - "y": { "group": "height", "offset": 6 }, - "fontWeight": { "value": "bold" }, - "fill": { "value": "black" }, - "text": { "field": "data" }, - "align": { "value": "right" }, - "baseline": { "value": "top" } - } - } - } - ] -} - -specs[13] = { - "width": 700, - "height": 400, - "padding": { "top": 0, "left": 0, "bottom": 20, "right": 0 }, - "data": [ - { - "name": "pop2000", - "url": "data/population.json", - "transform": [ - { "type": "filter", "test": "d.data.year == 2000" } - ] - } - ], - "scales": [ - { - "name": "g", - "domain": [0, 1], - "range": [340, 10] - }, - { - "name": "y", - "type": "ordinal", - "range": "height", - "reverse": true, - "domain": { "data": "pop2000", "field": "data.age" } - }, - { - "name": "c", - "type": "ordinal", - "domain": [1, 2], - "range": ["#1f77b4", "#e377c2"] - } - ], - "marks": [ - { - "type": "text", - "interactive": false, - "from": { - "data": "pop2000", - "transform": [{ "type": "unique", "field": "data.age", "as": "age" }] - }, - "properties": { - "enter": { - "x": { "value": 325 }, - "y": { "scale": "y", "field": "age", "offset": 11 }, - "text": { "field": "age" }, - "baseline": { "value": "middle" }, - "align": { "value": "center" }, - "fill": { "value": "#000" } - } - } - }, - { - "type": "group", - "from": { - "data": "pop2000", - "transform": [ - { "type": "facet", "keys": ["data.sex"] } - ] - }, - "properties": { - "update": { - "x": { "scale": "g", "field": "index" }, - "y": { "value": 0 }, - "width": { "value": 300 }, - "height": { "group": "height" } - } - }, - "scales": [ - { - "name": "x", - "type": "linear", - "range": "width", - "reverse": true, - "nice": true, - "domain": { "data": "pop2000", "field": "data.people" } - } - ], - "axes": [ - { "type": "x", "scale": "x", "format": "s" } - ], - "marks": [ - { - "type": "rect", - "properties": { - "enter": { - "x": { "scale": "x", "field": "data.people" }, - "x2": { "scale": "x", "value": 0 }, - "y": { "scale": "y", "field": "data.age" }, - "height": { "scale": "y", "band": true, "offset": -1 }, - "fillOpacity": { "value": 0.6 }, - "fill": { "scale": "c", "field": "data.sex" } - } - } - } - ] - } - ] -} - -specs[14] = { - "width": 200, - "height": 200, - "data": [ - { - "name": "iris", - "url": "data/iris.json" - } - ], - "scales": [ - { - "name": "x", - "nice": true, - "range": "width", - "domain": { "data": "iris", "field": "data.sepalWidth" } - }, - { - "name": "y", - "nice": true, - "range": "height", - "domain": { "data": "iris", "field": "data.petalLength" } - }, - { - "name": "c", - "type": "ordinal", - "domain": { "data": "iris", "field": "data.species" }, - "range": ["#800", "#080", "#008"] - } - ], - "axes": [ - { "type": "x", "scale": "x", "offset": 5, "ticks": 5, "title": "Sepal Width" }, - { "type": "y", "scale": "y", "offset": 5, "ticks": 5, "title": "Petal Length" } - ], - "legends": [ - { - "fill": "c", - "title": "Species", - "offset": 0, - "properties": { - "symbols": { - "fillOpacity": { "value": 0.5 }, - "stroke": { "value": "transparent" } - } - } - } - ], - "marks": [ - { - "type": "symbol", - "from": { "data": "iris" }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "data.sepalWidth" }, - "y": { "scale": "y", "field": "data.petalLength" }, - "fill": { "scale": "c", "field": "data.species" }, - "fillOpacity": { "value": 0.5 } - }, - "update": { - "size": { "value": 100 }, - "stroke": { "value": "transparent" } - }, - "hover": { - "size": { "value": 300 }, - "stroke": { "value": "white" } - } - } - } - ] -} - -specs[15] = { - "width": 600, - "height": 600, - "data": [ - { - "name": "iris", - "url": "data/iris.json" - }, - { - "name": "fields", - "values": ["petalLength", "petalWidth", "sepalWidth", "sepalLength"] - } - ], - "scales": [ - { - "name": "gx", - "type": "ordinal", - "range": "width", - "round": true, - "domain": { "data": "fields", "field": "data" } - }, - { - "name": "gy", - "type": "ordinal", - "range": "height", - "round": true, - "domain": { "data": "fields", "field": "data" } - }, - { - "name": "c", - "type": "ordinal", - "domain": { "data": "iris", "field": "data.species" }, - "range": ["#800", "#080", "#008"] - } - ], - "legends": [ - { - "fill": "c", - "title": "Species", - "offset": 10, - "properties": { - "symbols": { - "fillOpacity": { "value": 0.5 }, - "stroke": { "value": "transparent" } - } - } - } - ], - "marks": [ - { - "type": "group", - "from": { - "data": "fields", - "transform": [{ "type": "cross" }] - }, - "properties": { - "enter": { - "x": { "scale": "gx", "field": "a.data" }, - "y": { "scale": "gy", "field": "b.data" }, - "width": { "scale": "gx", "band": true, "offset": -35 }, - "height": { "scale": "gy", "band": true, "offset": -35 }, - "stroke": { "value": "#ddd" } - } - }, - "scales": [ - { - "name": "x", - "range": "width", - "zero": false, - "round": true, - "domain": { "data": "iris", "field": { "group": "a.data" } } - }, - { - "name": "y", - "range": "height", - "zero": false, - "round": true, - "domain": { "data": "iris", "field": { "group": "b.data" } } - } - ], - "axes": [ - { "type": "x", "scale": "x", "ticks": 5 }, - { "type": "y", "scale": "y", "ticks": 5 } - ], - "marks": [ - { - "type": "symbol", - "from": { "data": "iris" }, - "properties": { - "enter": { - "x": { "scale": "x", "field": { "group": "a.data" } }, - "y": { "scale": "y", "field": { "group": "b.data" } }, - "fill": { "scale": "c", "field": "data.spec[0]ies" }, - "fillOpacity": { "value": 0.5 } - }, - "update": { - "size": { "value": 36 }, - "stroke": { "value": "transparent" } - }, - "hover": { - "size": { "value": 100 }, - "stroke": { "value": "white" } - } - } - } - ] - } - ] -} - -specs[16] = { - "width": 500, - "height": 200, - "padding": { "top": 10, "left": 30, "bottom": 30, "right": 10 }, - "data": [ - { - "name": "table", - "values": [ - { "x": 0, "y": 28, "c": 0 }, { "x": 0, "y": 55, "c": 1 }, - { "x": 1, "y": 43, "c": 0 }, { "x": 1, "y": 91, "c": 1 }, - { "x": 2, "y": 81, "c": 0 }, { "x": 2, "y": 53, "c": 1 }, - { "x": 3, "y": 19, "c": 0 }, { "x": 3, "y": 87, "c": 1 }, - { "x": 4, "y": 52, "c": 0 }, { "x": 4, "y": 48, "c": 1 }, - { "x": 5, "y": 24, "c": 0 }, { "x": 5, "y": 49, "c": 1 }, - { "x": 6, "y": 87, "c": 0 }, { "x": 6, "y": 66, "c": 1 }, - { "x": 7, "y": 17, "c": 0 }, { "x": 7, "y": 27, "c": 1 }, - { "x": 8, "y": 68, "c": 0 }, { "x": 8, "y": 16, "c": 1 }, - { "x": 9, "y": 49, "c": 0 }, { "x": 9, "y": 15, "c": 1 } - ] - }, - { - "name": "stats", - "source": "table", - "transform": [ - { "type": "facet", "keys": ["data.x"] }, - { "type": "stats", "value": "data.y" } - ] - } - ], - "scales": [ - { - "name": "x", - "type": "linear", - "range": "width", - "zero": false, - "domain": { "data": "table", "field": "data.x" } - }, - { - "name": "y", - "type": "linear", - "range": "height", - "nice": true, - "domain": { "data": "stats", "field": "sum" } - }, - { - "name": "color", - "type": "ordinal", - "range": "category10" - } - ], - "axes": [ - { "type": "x", "scale": "x" }, - { "type": "y", "scale": "y" } - ], - "marks": [ - { - "type": "group", - "from": { - "data": "table", - "transform": [ - { "type": "facet", "keys": ["data.c"] }, - { "type": "stack", "point": "data.x", "height": "data.y" } - ] - }, - "marks": [ - { - "type": "area", - "properties": { - "enter": { - "interpolate": { "value": "monotone" }, - "x": { "scale": "x", "field": "data.x" }, - "y": { "scale": "y", "field": "y" }, - "y2": { "scale": "y", "field": "y2" }, - "fill": { "scale": "color", "field": "data.c" } - }, - "update": { - "fillOpacity": { "value": 1 } - }, - "hover": { - "fillOpacity": { "value": 0.5 } - } - } - } - ] - } - ] -} - -specs[17] = { - "width": 500, - "height": 200, - "padding": { "top": 10, "left": 30, "bottom": 30, "right": 10 }, - "data": [ - { - "name": "table", - "values": [ - { "x": 0, "y": 28, "c": 0 }, { "x": 0, "y": 55, "c": 1 }, - { "x": 1, "y": 43, "c": 0 }, { "x": 1, "y": 91, "c": 1 }, - { "x": 2, "y": 81, "c": 0 }, { "x": 2, "y": 53, "c": 1 }, - { "x": 3, "y": 19, "c": 0 }, { "x": 3, "y": 87, "c": 1 }, - { "x": 4, "y": 52, "c": 0 }, { "x": 4, "y": 48, "c": 1 }, - { "x": 5, "y": 24, "c": 0 }, { "x": 5, "y": 49, "c": 1 }, - { "x": 6, "y": 87, "c": 0 }, { "x": 6, "y": 66, "c": 1 }, - { "x": 7, "y": 17, "c": 0 }, { "x": 7, "y": 27, "c": 1 }, - { "x": 8, "y": 68, "c": 0 }, { "x": 8, "y": 16, "c": 1 }, - { "x": 9, "y": 49, "c": 0 }, { "x": 9, "y": 15, "c": 1 } - ] - }, - { - "name": "stats", - "source": "table", - "transform": [ - { "type": "facet", "keys": ["data.x"] }, - { "type": "stats", "value": "data.y" } - ] - } - ], - "scales": [ - { - "name": "x", - "type": "ordinal", - "range": "width", - "domain": { "data": "table", "field": "data.x" } - }, - { - "name": "y", - "type": "linear", - "range": "height", - "nice": true, - "domain": { "data": "stats", "field": "sum" } - }, - { - "name": "color", - "type": "ordinal", - "range": "category10" - } - ], - "axes": [ - { "type": "x", "scale": "x" }, - { "type": "y", "scale": "y" } - ], - "marks": [ - { - "type": "group", - "from": { - "data": "table", - "transform": [ - { "type": "facet", "keys": ["data.c"] }, - { "type": "stack", "point": "data.x", "height": "data.y" } - ] - }, - "marks": [ - { - "type": "rect", - "properties": { - "enter": { - "x": { "scale": "x", "field": "data.x" }, - "width": { "scale": "x", "band": true, "offset": -1 }, - "y": { "scale": "y", "field": "y" }, - "y2": { "scale": "y", "field": "y2" }, - "fill": { "scale": "color", "field": "data.c" } - }, - "update": { - "fillOpacity": { "value": 1 } - }, - "hover": { - "fillOpacity": { "value": 0.5 } - } - } - } - ] - } - ] -} - -specs[18] = { - "width": 500, - "height": 200, - "data": [ - { - "name": "stocks", - "url": "data/stocks.csv", - "format": { "type": "csv", "parse": { "price": "number", "date": "date" } } - } - ], - "scales": [ - { - "name": "x", - "type": "time", - "range": "width", - "domain": { "data": "stocks", "field": "data.date" } - }, - { - "name": "y", - "type": "linear", - "range": "height", - "nice": true, - "domain": { "data": "stocks", "field": "data.price" } - }, - { - "name": "color", "type": "ordinal", "range": "category10" - } - ], - "axes": [ - { "type": "x", "scale": "x", "tickSizeEnd": 0 }, - { "type": "y", "scale": "y" } - ], - "marks": [ - { - "type": "group", - "from": { - "data": "stocks", - "transform": [{ "type": "facet", "keys": ["data.symbol"] }] - }, - "marks": [ - { - "type": "line", - "properties": { - "enter": { - "x": { "scale": "x", "field": "data.date" }, - "y": { "scale": "y", "field": "data.price" }, - "stroke": { "scale": "color", "field": "data.symbol" }, - "strokeWidth": { "value": 2 } - } - } - }, - { - "type": "text", - "from": { - "transform": [{ "type": "filter", "test": "index==data.length-1" }] - }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "data.date", "offset": 2 }, - "y": { "scale": "y", "field": "data.price" }, - "fill": { "scale": "color", "field": "data.symbol" }, - "text": { "field": "data.symbol" }, - "baseline": { "value": "middle" } - } - } - } - ] - } - ] -} - -specs[19] = { - "name": "treemap", - "width": 960, - "height": 500, - "padding": 2.5, - "data": [ - { - "name": "tree", - "url": "data/flare.json", - "format": { "type": "treejson" }, - "transform": [ - { "type": "treemap", "value": "data.size" } - ] - } - ], - "scales": [ - { - "name": "color", - "type": "ordinal", - "range": [ - "#3182bd", "#6baed6", "#9ecae1", "#c6dbef", "#e6550d", - "#fd8d3c", "#fdae6b", "#fdd0a2", "#31a354", "#74c476", - "#a1d99b", "#c7e9c0", "#756bb1", "#9e9ac8", "#bcbddc", - "#dadaeb", "#636363", "#969696", "#bdbdbd", "#d9d9d9" - ] - }, - { - "name": "size", - "type": "ordinal", - "domain": [0, 1, 2, 3], - "range": [256, 28, 20, 14] - }, - { - "name": "opacity", - "type": "ordinal", - "domain": [0, 1, 2, 3], - "range": [0.15, 0.5, 0.8, 1.0] - } - ], - "marks": [ - { - "type": "rect", - "from": { - "data": "tree", - "transform": [{ "type": "filter", "test": "d.values" }] - }, - "interactive": false, - "properties": { - "enter": { - "x": { "field": "x" }, - "y": { "field": "y" }, - "width": { "field": "width" }, - "height": { "field": "height" }, - "fill": { "scale": "color", "field": "data.name" } - } - } - }, - { - "type": "rect", - "from": { - "data": "tree", - "transform": [{ "type": "filter", "test": "!d.values" }] - }, - "properties": { - "enter": { - "x": { "field": "x" }, - "y": { "field": "y" }, - "width": { "field": "width" }, - "height": { "field": "height" }, - "stroke": { "value": "#fff" } - }, - "update": { - "fill": { "value": "rgba(0,0,0,0)" } - }, - "hover": { - "fill": { "value": "red" } - } - } - }, - { - "type": "text", - "from": { - "data": "tree", - "transform": [{ "type": "filter", "test": "d.values" }] - }, - "interactive": false, - "properties": { - "enter": { - "x": { "field": "x" }, - "y": { "field": "y" }, - "dx": { "field": "width", "mult": 0.5 }, - "dy": { "field": "height", "mult": 0.5 }, - "font": { "value": "Helvetica Neue" }, - "fontSize": { "scale": "size", "field": "depth" }, - "align": { "value": "center" }, - "baseline": { "value": "middle" }, - "fill": { "value": "#000" }, - "fillOpacity": { "scale": "opacity", "field": "depth" }, - "text": { "field": "data.name" } - } - } - } - ] -} - -specs[20] = { - "width": 250, - "height": 200, - "data": [ - { - "name": "weather", - "url": "data/weather.json" - } - ], - "scales": [ - { - "name": "x", - "type": "ordinal", - "range": "width", - "padding": 0.1, "round": true, - "domain": { "data": "weather", "field": "index" } - }, - { - "name": "y", - "range": "height", - "nice": true, "zero": false, "round": true, - "domain": { - "data": "weather", - "field": ["data.record.low", "data.record.high"] - } - } - ], - "axes": [ - { - "type": "y", "scale": "y", "ticks": 3, "tickSize": 0, - "orient": "right", "grid": true, - "properties": { - "grid": { "stroke": { "value": "white" }, "strokeWidth": { "value": 2 } }, - "axis": { "stroke": { "value": "transparent" } } - } - } - ], - "marks": [ - { - "type": "text", - "from": { "data": "weather" }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "index" }, - "dx": { "scale": "x", "band": true, "mult": 0.5 }, - "y": { "value": 0 }, - "fill": { "value": "#000" }, - "text": { "field": "data.day" }, - "align": { "value": "center" }, - "baseline": { "value": "bottom" } - } - } - }, - { - "type": "rect", - "from": { "data": "weather" }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "index" }, - "width": { "scale": "x", "band": true, "offset": -1 }, - "y": { "scale": "y", "field": "data.record.low" }, - "y2": { "scale": "y", "field": "data.record.high" }, - "fill": { "value": "#ccc" } - } - } - }, - { - "type": "rect", - "from": { "data": "weather" }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "index" }, - "width": { "scale": "x", "band": true, "offset": -1 }, - "y": { "scale": "y", "field": "data.normal.low" }, - "y2": { "scale": "y", "field": "data.normal.high" }, - "fill": { "value": "#999" } - } - } - }, - { - "type": "rect", - "from": { - "data": "weather", - "transform": [{ "type": "filter", "test": "d.data.actual" }] - }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "index", "offset": 4 }, - "width": { "scale": "x", "band": true, "offset": -8 }, - "y": { "scale": "y", "field": "data.actual.low" }, - "y2": { "scale": "y", "field": "data.actual.high" }, - "fill": { "value": "#000" } - } - } - }, - { - "type": "rect", - "from": { - "data": "weather", - "transform": [{ "type": "filter", "test": "d.data.forecast" }] - }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "index", "offset": 9 }, - "width": { "scale": "x", "band": true, "offset": -18 }, - "y": { "scale": "y", "field": "data.forecast.low.low" }, - "y2": { "scale": "y", "field": "data.forecast.high.high" }, - "fill": { "value": "#000" } - } - } - }, - { - "type": "rect", - "from": { - "data": "weather", - "transform": [{ "type": "filter", "test": "d.data.forecast" }] - }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "index", "offset": 4 }, - "width": { "scale": "x", "band": true, "offset": -8 }, - "y": { "scale": "y", "field": "data.forecast.low.low" }, - "y2": { "scale": "y", "field": "data.forecast.low.high" }, - "fill": { "value": "#000" } - } - } - }, - { - "type": "rect", - "from": { - "data": "weather", - "transform": [{ "type": "filter", "test": "d.data.forecast" }] - }, - "properties": { - "enter": { - "x": { "scale": "x", "field": "index", "offset": 4 }, - "width": { "scale": "x", "band": true, "offset": -8 }, - "y": { "scale": "y", "field": "data.forecast.high.low" }, - "y2": { "scale": "y", "field": "data.forecast.high.high" }, - "fill": { "value": "#000" } - } - } - } - ] -} - -const hoverFill21: Vega.ValueRefs = [{ - "test": "datum.value < 30", - "value": "#f00" -}, { - "value": "#f55" -}]; - -specs[21] = { - "name": "wordcloud", - "width": 400, - "height": 400, - "padding": { "top": 0, "bottom": 0, "left": 0, "right": 0 }, - "data": [ - { - "name": "table", - "values": [ - { "text": "poem", "value": 80 }, - { "text": "peom", "value": 44 }, - { "text": "moep", "value": 40 }, - { "text": "meop", "value": 36 }, - { "text": "emop", "value": 32 }, - { "text": "epom", "value": 28 }, - { "text": "opem", "value": 24 }, - { "text": "omep", "value": 20 }, - { "text": "mope", "value": 56 }, - { "text": "mepo", "value": 12 }, - { "text": "pemo", "value": 10 }, - { "text": "pome", "value": 10 } - ], - "transform": [ - { - "type": "wordcloud", - "text": "data.text", - "font": "Helvetica Neue", - "fontSize": "data.value", - "rotate": { "random": [-60, -30, 0, 30, 60] } - } - ] - } - ], - "marks": [ - { - "type": "text", - "from": { "data": "table" }, - "properties": { - "enter": { - "x": { "field": "x" }, - "y": { "field": "y" }, - "angle": { "field": "angle" }, - "align": { "value": "center" }, - "baseline": { "value": "alphabetic" }, - "font": { "field": "font" }, - "fontSize": { "field": "fontSize" }, - "text": { "field": "data.text" } - }, - "update": { - "fill": [{ - "test": "datum.value < 30", - "value": "steelblue" - }, { - "value": "blue" - }] - }, - "hover": { - "fill": hoverFill21 - } - } - } - ] -} - -specs.forEach(spec => { - vg.parse.spec(spec, chart => { - chart({el:"#vis"}).update(); - }); -}); From c3f0ee0d5d9765ac9fe65da8c75e477a71e398ca Mon Sep 17 00:00:00 2001 From: Jake Boone Date: Tue, 27 Nov 2018 11:55:08 -0700 Subject: [PATCH 366/836] [react-datepicker] fix v2 tests --- types/react-datepicker/react-datepicker-tests.tsx | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/types/react-datepicker/react-datepicker-tests.tsx b/types/react-datepicker/react-datepicker-tests.tsx index 1414672684..4a3fd93cac 100644 --- a/types/react-datepicker/react-datepicker-tests.tsx +++ b/types/react-datepicker/react-datepicker-tests.tsx @@ -1,17 +1,16 @@ import * as React from 'react'; -import * as moment from 'moment'; import DatePicker from 'react-datepicker'; {}} - onYearChange={(date: moment.Moment) => {}} + selected={new Date()} + onChange={(date: Date | null) => {}} + onYearChange={(date: Date) => {}} popperModifiers={{ flip: { enabled: false } }} - includeTimes={[moment()]} + includeTimes={[new Date()]} >

From 994038d60cacf827c189629a44abf00b3e07ace2 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Thu, 15 Nov 2018 15:21:20 -0800 Subject: [PATCH 367/836] Remove node dependencies from react --- types/react-dom/server/index.d.ts | 8 +++++++- types/react/test/index.ts | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/types/react-dom/server/index.d.ts b/types/react-dom/server/index.d.ts index 53bbca7250..ef42606717 100644 --- a/types/react-dom/server/index.d.ts +++ b/types/react-dom/server/index.d.ts @@ -1,4 +1,10 @@ -/// +// forward declarations +declare global { + namespace NodeJS { + // tslint:disable-next-line:no-empty-interface + interface ReadableStream {} + } +} import { ReactElement } from 'react'; diff --git a/types/react/test/index.ts b/types/react/test/index.ts index 97d61118b9..0b747edd66 100644 --- a/types/react/test/index.ts +++ b/types/react/test/index.ts @@ -14,6 +14,23 @@ import update = require("react-addons-update"); import createReactClass = require("create-react-class"); import * as DOM from "react-dom-factories"; +// forward declarations (avoids an unnecessary dependency on NodeJS) +declare global { + interface Console { + log(message?: any, ...optionalParams: any[]): void; + } + var console: Console; + + function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; + function clearInterval(intervalId: NodeJS.Timeout): void; + + namespace NodeJS { + // tslint:disable-next-line:no-empty-interface + interface Timer {} + interface Timeout extends Timer {} + } +} + interface Props extends React.Attributes { hello: string; world?: string | null; From f961f35307f3c2e2d085dde65fc46484efd2150d Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Fri, 16 Nov 2018 12:48:36 -0800 Subject: [PATCH 368/836] Remove node dependencies from react --- types/react/test/index.ts | 46 ++++++++++++----------------------- types/react/v15/test/index.ts | 29 ++++++++++++---------- 2 files changed, 32 insertions(+), 43 deletions(-) diff --git a/types/react/test/index.ts b/types/react/test/index.ts index 0b747edd66..672de32b37 100644 --- a/types/react/test/index.ts +++ b/types/react/test/index.ts @@ -14,23 +14,6 @@ import update = require("react-addons-update"); import createReactClass = require("create-react-class"); import * as DOM from "react-dom-factories"; -// forward declarations (avoids an unnecessary dependency on NodeJS) -declare global { - interface Console { - log(message?: any, ...optionalParams: any[]): void; - } - var console: Console; - - function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; - function clearInterval(intervalId: NodeJS.Timeout): void; - - namespace NodeJS { - // tslint:disable-next-line:no-empty-interface - interface Timer {} - interface Timeout extends Timer {} - } -} - interface Props extends React.Attributes { hello: string; world?: string | null; @@ -103,7 +86,7 @@ declare const container: Element; render() { return null; } componentDidMount() { // $ExpectError -> this will be true in next BC release where state is gonna be `null | Readonly` - console.log(this.state.inputValue); + this.state.inputValue; } mutateState() { // $ExpectError @@ -184,7 +167,7 @@ class ModernComponent extends React.Component value: this.state.inputValue ? this.state.inputValue : undefined }), DOM.input({ - onChange: event => console.log(event.target) + onChange: event => event.target })); } @@ -518,17 +501,20 @@ class Timer extends React.Component<{}, TimerState> { state = { secondsElapsed: 0 }; - private _interval: NodeJS.Timer; + // NOTE: creates unnecessary dependency on 'node'. leaving for reference purposes + // private _interval: NodeJS.Timer; tick() { this.setState((prevState, props) => ({ secondsElapsed: prevState.secondsElapsed + 1 })); } componentDidMount() { - this._interval = setInterval(() => this.tick(), 1000); + // NOTE: creates unnecessary dependency on 'node'. leaving for reference purposes + // this._interval = setInterval(() => this.tick(), 1000); } componentWillUnmount() { - clearInterval(this._interval); + // NOTE: creates unnecessary dependency on 'node'. leaving for reference purposes + // clearInterval(this._interval); } render() { return DOM.div( @@ -615,14 +601,14 @@ Perf.printExclusive(); Perf.printWasted(); Perf.printOperations(); -console.log(Perf.getExclusive()); -console.log(Perf.getInclusive()); -console.log(Perf.getWasted()); -console.log(Perf.getOperations()); -console.log(Perf.getExclusive(measurements)); -console.log(Perf.getInclusive(measurements)); -console.log(Perf.getWasted(measurements)); -console.log(Perf.getOperations(measurements)); +Perf.getExclusive(); +Perf.getInclusive(); +Perf.getWasted(); +Perf.getOperations(); +Perf.getExclusive(measurements); +Perf.getInclusive(measurements); +Perf.getWasted(measurements); +Perf.getOperations(measurements); // Renamed to printOperations(). Please use it instead. Perf.printDOM(measurements); diff --git a/types/react/v15/test/index.ts b/types/react/v15/test/index.ts index 30dd3bd75d..42ca5999a8 100644 --- a/types/react/v15/test/index.ts +++ b/types/react/v15/test/index.ts @@ -120,7 +120,7 @@ class ModernComponent extends React.Component value: this.state.inputValue }), React.DOM.input({ - onChange: event => console.log(event.target) + onChange: event => event.target })); } @@ -342,7 +342,7 @@ const htmlAttr: React.HTMLProps = { event.stopPropagation(); }, onAnimationStart: event => { - console.log(event.currentTarget.className); + event.currentTarget.className; }, dangerouslySetInnerHTML: { __html: "STRONG" @@ -505,17 +505,20 @@ class Timer extends React.Component<{}, TimerState> { state = { secondsElapsed: 0 }; - private _interval: NodeJS.Timer; + // NOTE: creates unnecessary dependency on 'node'. leaving for reference purposes + // private _interval: NodeJS.Timer; tick() { this.setState((prevState, props) => ({ secondsElapsed: prevState.secondsElapsed + 1 })); } componentDidMount() { - this._interval = setInterval(() => this.tick(), 1000); + // NOTE: creates unnecessary dependency on 'node'. leaving for reference purposes + // this._interval = setInterval(() => this.tick(), 1000); } componentWillUnmount() { - clearInterval(this._interval); + // NOTE: creates unnecessary dependency on 'node'. leaving for reference purposes + // clearInterval(this._interval); } render() { return React.DOM.div( @@ -602,14 +605,14 @@ Perf.printExclusive(); Perf.printWasted(); Perf.printOperations(); -console.log(Perf.getExclusive()); -console.log(Perf.getInclusive()); -console.log(Perf.getWasted()); -console.log(Perf.getOperations()); -console.log(Perf.getExclusive(measurements)); -console.log(Perf.getInclusive(measurements)); -console.log(Perf.getWasted(measurements)); -console.log(Perf.getOperations(measurements)); +Perf.getExclusive(); +Perf.getInclusive(); +Perf.getWasted(); +Perf.getOperations(); +Perf.getExclusive(measurements); +Perf.getInclusive(measurements); +Perf.getWasted(measurements); +Perf.getOperations(measurements); // Renamed to printOperations(). Please use it instead. Perf.printDOM(measurements); From 48eba801e2af7ea945f8f4cd06d247b2890889ac Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Fri, 16 Nov 2018 14:17:11 -0800 Subject: [PATCH 369/836] Fix lint errors due to new lint rules --- types/meteor/test/globals/meteor-tests.ts | 16 ++++++++-------- types/meteor/test/meteor-tests.ts | 16 ++++++++-------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/types/meteor/test/globals/meteor-tests.ts b/types/meteor/test/globals/meteor-tests.ts index 782701086f..e3a3e750bb 100644 --- a/types/meteor/test/globals/meteor-tests.ts +++ b/types/meteor/test/globals/meteor-tests.ts @@ -371,19 +371,19 @@ Comments.find({ viewNumber: { $gt: 100 } }); Comments.find({ viewNumber: { $not: { $lt: 100, $gt: 1000 } } }); Comments.find({ tags: { $in: [ "tag-1", "tag-2", "tag-3" ] } }); Comments.find({ $or: [ { text: "hello" }, { text: "world" } ] }); -Comments.find({ $or: [ - { text: "hello" }, - { text: "world", viewNumber: { $gt: 0 } } +Comments.find({ $or: [ + { text: "hello" }, + { text: "world", viewNumber: { $gt: 0 } } ], authorId: "test-author-id" }); -Comments.find({ $and: [ - { $or: [{ authorId: "author-id-1" }, { authorId: "author-id-2" }] }, +Comments.find({ $and: [ + { $or: [{ authorId: "author-id-1" }, { authorId: "author-id-2" }] }, { $or: [{ tags: "tag-1" }, { tags: "tag-2" }] } ]}); Comments.find({ $query: {inlineLinks: { $exists: true, $type: "array" } } }); -Comments.find({ inlineLinks: { $elemMatch: { - objectType: InlineObjectType.Image, - objectUrl: { $regex: "https://(www\.?)youtube\.com" } +Comments.find({ inlineLinks: { $elemMatch: { + objectType: InlineObjectType.Image, + objectUrl: { $regex: "https://(www\.?)youtube\.com" } } } }); Comments.find({ "inlineLinks.objectType": InlineObjectType.Person }); Comments.find({ tags: "tag-1" }); diff --git a/types/meteor/test/meteor-tests.ts b/types/meteor/test/meteor-tests.ts index b45284df52..63f83ef79d 100644 --- a/types/meteor/test/meteor-tests.ts +++ b/types/meteor/test/meteor-tests.ts @@ -383,19 +383,19 @@ Comments.find({ viewNumber: { $gt: 100 } }); Comments.find({ viewNumber: { $not: { $lt: 100, $gt: 1000 } } }); Comments.find({ tags: { $in: [ "tag-1", "tag-2", "tag-3" ] } }); Comments.find({ $or: [ { text: "hello" }, { text: "world" } ] }); -Comments.find({ $or: [ - { text: "hello" }, - { text: "world", viewNumber: { $gt: 0 } } +Comments.find({ $or: [ + { text: "hello" }, + { text: "world", viewNumber: { $gt: 0 } } ], authorId: "test-author-id" }); -Comments.find({ $and: [ - { $or: [{ authorId: "author-id-1" }, { authorId: "author-id-2" }] }, +Comments.find({ $and: [ + { $or: [{ authorId: "author-id-1" }, { authorId: "author-id-2" }] }, { $or: [{ tags: "tag-1" }, { tags: "tag-2" }] } ]}); Comments.find({ $query: { inlineLinks: { $exists: true, $type: "array" } } }); -Comments.find({ inlineLinks: { $elemMatch: { - objectType: InlineObjectType.Image, - objectUrl: { $regex: "https://(www\.?)youtube\.com" } +Comments.find({ inlineLinks: { $elemMatch: { + objectType: InlineObjectType.Image, + objectUrl: { $regex: "https://(www\.?)youtube\.com" } } } }); Comments.find({ "inlineLinks.objectType": InlineObjectType.Person }); Comments.find({ tags: "tag-1" }); From f8a87d07b3253029c217f25002f3ff4e8f05a1a8 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Tue, 27 Nov 2018 11:24:21 -0800 Subject: [PATCH 370/836] Address PR feedback --- types/react/test/index.ts | 37 ++++++++++++++++++++--------------- types/react/v15/test/index.ts | 37 ++++++++++++++++++++--------------- 2 files changed, 42 insertions(+), 32 deletions(-) diff --git a/types/react/test/index.ts b/types/react/test/index.ts index 672de32b37..8a4a2bd89b 100644 --- a/types/react/test/index.ts +++ b/types/react/test/index.ts @@ -14,6 +14,14 @@ import update = require("react-addons-update"); import createReactClass = require("create-react-class"); import * as DOM from "react-dom-factories"; +// NOTE: forward declarations for tests +declare function setInterval(...args: any[]): any; +declare function clearInterval(...args: any[]): any; +declare var console: Console; +interface Console { + log(...args: any[]): void; +} + interface Props extends React.Attributes { hello: string; world?: string | null; @@ -86,7 +94,7 @@ declare const container: Element; render() { return null; } componentDidMount() { // $ExpectError -> this will be true in next BC release where state is gonna be `null | Readonly` - this.state.inputValue; + console.log(this.state.inputValue); } mutateState() { // $ExpectError @@ -167,7 +175,7 @@ class ModernComponent extends React.Component value: this.state.inputValue ? this.state.inputValue : undefined }), DOM.input({ - onChange: event => event.target + onChange: event => console.log(event.target) })); } @@ -501,20 +509,17 @@ class Timer extends React.Component<{}, TimerState> { state = { secondsElapsed: 0 }; - // NOTE: creates unnecessary dependency on 'node'. leaving for reference purposes - // private _interval: NodeJS.Timer; + private _interval: number; tick() { this.setState((prevState, props) => ({ secondsElapsed: prevState.secondsElapsed + 1 })); } componentDidMount() { - // NOTE: creates unnecessary dependency on 'node'. leaving for reference purposes - // this._interval = setInterval(() => this.tick(), 1000); + this._interval = setInterval(() => this.tick(), 1000); } componentWillUnmount() { - // NOTE: creates unnecessary dependency on 'node'. leaving for reference purposes - // clearInterval(this._interval); + clearInterval(this._interval); } render() { return DOM.div( @@ -601,14 +606,14 @@ Perf.printExclusive(); Perf.printWasted(); Perf.printOperations(); -Perf.getExclusive(); -Perf.getInclusive(); -Perf.getWasted(); -Perf.getOperations(); -Perf.getExclusive(measurements); -Perf.getInclusive(measurements); -Perf.getWasted(measurements); -Perf.getOperations(measurements); +console.log(Perf.getExclusive()); +console.log(Perf.getInclusive()); +console.log(Perf.getWasted()); +console.log(Perf.getOperations()); +console.log(Perf.getExclusive(measurements)); +console.log(Perf.getInclusive(measurements)); +console.log(Perf.getWasted(measurements)); +console.log(Perf.getOperations(measurements)); // Renamed to printOperations(). Please use it instead. Perf.printDOM(measurements); diff --git a/types/react/v15/test/index.ts b/types/react/v15/test/index.ts index 42ca5999a8..79d05ac8d0 100644 --- a/types/react/v15/test/index.ts +++ b/types/react/v15/test/index.ts @@ -11,6 +11,14 @@ import * as TestUtils from "react-addons-test-utils"; import TransitionGroup = require("react-addons-transition-group"); import update = require("react-addons-update"); +// NOTE: forward declarations for tests +declare function setInterval(...args: any[]): any; +declare function clearInterval(...args: any[]): any; +declare var console: Console; +interface Console { + log(...args: any[]): void; +} + interface Props extends React.Attributes { hello: string; world?: string; @@ -120,7 +128,7 @@ class ModernComponent extends React.Component value: this.state.inputValue }), React.DOM.input({ - onChange: event => event.target + onChange: event => console.log(event.target) })); } @@ -342,7 +350,7 @@ const htmlAttr: React.HTMLProps = { event.stopPropagation(); }, onAnimationStart: event => { - event.currentTarget.className; + console.log(event.currentTarget.className); }, dangerouslySetInnerHTML: { __html: "STRONG" @@ -505,20 +513,17 @@ class Timer extends React.Component<{}, TimerState> { state = { secondsElapsed: 0 }; - // NOTE: creates unnecessary dependency on 'node'. leaving for reference purposes - // private _interval: NodeJS.Timer; + private _interval: number; tick() { this.setState((prevState, props) => ({ secondsElapsed: prevState.secondsElapsed + 1 })); } componentDidMount() { - // NOTE: creates unnecessary dependency on 'node'. leaving for reference purposes - // this._interval = setInterval(() => this.tick(), 1000); + this._interval = setInterval(() => this.tick(), 1000); } componentWillUnmount() { - // NOTE: creates unnecessary dependency on 'node'. leaving for reference purposes - // clearInterval(this._interval); + clearInterval(this._interval); } render() { return React.DOM.div( @@ -605,14 +610,14 @@ Perf.printExclusive(); Perf.printWasted(); Perf.printOperations(); -Perf.getExclusive(); -Perf.getInclusive(); -Perf.getWasted(); -Perf.getOperations(); -Perf.getExclusive(measurements); -Perf.getInclusive(measurements); -Perf.getWasted(measurements); -Perf.getOperations(measurements); +console.log(Perf.getExclusive()); +console.log(Perf.getInclusive()); +console.log(Perf.getWasted()); +console.log(Perf.getOperations()); +console.log(Perf.getExclusive(measurements)); +console.log(Perf.getInclusive(measurements)); +console.log(Perf.getWasted(measurements)); +console.log(Perf.getOperations(measurements)); // Renamed to printOperations(). Please use it instead. Perf.printDOM(measurements); From 0226045de5e8db79594af54dbab3f5b77b972d3c Mon Sep 17 00:00:00 2001 From: Cameron Martin Date: Tue, 27 Nov 2018 20:42:30 +0000 Subject: [PATCH 371/836] Implemented all changes outlined in the comments in pull request #30862. --- .../babel__traverse/babel__traverse-tests.ts | 37 +++++++++++++++++++ types/babel__traverse/index.d.ts | 14 +++---- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/types/babel__traverse/babel__traverse-tests.ts b/types/babel__traverse/babel__traverse-tests.ts index 974831dbca..772b392b63 100644 --- a/types/babel__traverse/babel__traverse-tests.ts +++ b/types/babel__traverse/babel__traverse-tests.ts @@ -112,3 +112,40 @@ const BindingKindTest: Visitor = { // kind === 'anythingElse'; }, }; + +interface SomeVisitorState { someState: string; } + +const VisitorStateTest: Visitor = { + enter(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + exit(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + Identifier(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + FunctionDeclaration: { + enter(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + exit(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + } + } +}; diff --git a/types/babel__traverse/index.d.ts b/types/babel__traverse/index.d.ts index 740f5f4429..a0a3730057 100644 --- a/types/babel__traverse/index.d.ts +++ b/types/babel__traverse/index.d.ts @@ -138,17 +138,17 @@ export class Binding { constantViolations: NodePath[]; } -export type Visitor = VisitNodeObject & { - [P in Node["type"]]?: VisitNode>; +export type Visitor = VisitNodeObject & { + [Type in Node["type"]]?: VisitNode>; }; -export type VisitNode = VisitNodeFunction | VisitNodeObject

; +export type VisitNode = VisitNodeFunction | VisitNodeObject; -export type VisitNodeFunction = (this: T, path: NodePath

, state: any) => void; +export type VisitNodeFunction = (this: S, path: NodePath

, state: S) => void; -export interface VisitNodeObject { - enter?(path: NodePath, state: any): void; - exit?(path: NodePath, state: any): void; +export interface VisitNodeObject { + enter?: VisitNodeFunction; + exit?: VisitNodeFunction; } export class NodePath { From 6edec833a26d69eb5982014628fbd7cec28d1188 Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 27 Nov 2018 22:41:31 +0100 Subject: [PATCH 372/836] Add new Expo type definitions from official docs --- types/expo/expo-tests.tsx | 3 ++- types/expo/index.d.ts | 10 +++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 5bb6b5abc4..75dee784de 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -145,7 +145,8 @@ Audio.setAudioModeAsync({ playsInSilentModeIOS: true, interruptionModeIOS: 2, interruptionModeAndroid: 1, - allowsRecordingIOS: true + allowsRecordingIOS: true, + playThroughEarpieceAndroid: false }); Audio.setIsEnabledAsync(true); diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index b406b4e8ec..ad94eb38ed 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -12,6 +12,7 @@ // Nathan Phillip Brink // Martin Olsson // Levan Basharuli +// Pavel Ihm // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -405,6 +406,9 @@ 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; @@ -566,7 +570,7 @@ export interface PlaybackStatusToSet { volume?: number; } -export type PlaybackSource = RequireSource | { uri: string } | Asset; +export type PlaybackSource = RequireSource | { uri: string, headers?: { [string]: string }, overrideFileExtensionAndroid?: string } | Asset; export class PlaybackObject { /** @@ -2355,7 +2359,7 @@ export namespace Calendar { /** Name for the account that owns this calendar */ ownerAccount?: string; // Android - /** Time zone for the calendar */ + /** Time zone for the calendar */ timeZone?: string; // Android /** Alarm methods that this calendar supports */ @@ -2398,7 +2402,7 @@ export namespace Calendar { /** Visible name of the event */ title?: string; - /** Location field of the event */ + /** Location field of the event */ location?: string; /** Date when the event record was created */ From 675bc38625d0e0767639d7423ffcada9f3d67574 Mon Sep 17 00:00:00 2001 From: Pavel Date: Tue, 27 Nov 2018 23:03:24 +0100 Subject: [PATCH 373/836] Fix build errors --- types/expo/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index ad94eb38ed..9e48e391d8 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -407,7 +407,7 @@ 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).*/ + /** Boolean selecting if audio should go to earpiece (only on Android). */ playThroughEarpieceAndroid: boolean; } @@ -570,7 +570,7 @@ export interface PlaybackStatusToSet { volume?: number; } -export type PlaybackSource = RequireSource | { uri: string, headers?: { [string]: string }, overrideFileExtensionAndroid?: string } | Asset; +export type PlaybackSource = RequireSource | { uri: string, headers?: { [header: string]: string }, overrideFileExtensionAndroid?: string } | Asset; export class PlaybackObject { /** From 00f1245e599f463b2ea16b4e77e85bf73f9cbca5 Mon Sep 17 00:00:00 2001 From: piotr rotynski Date: Tue, 27 Nov 2018 23:22:07 +0100 Subject: [PATCH 374/836] Adding withArgs method to Spy interface as per Jasmine's docs for v3.3 --- types/jasmine/index.d.ts | 1 + types/jasmine/jasmine-tests.ts | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index e9dba1e2cd..a87b8b3a86 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -639,6 +639,7 @@ declare namespace jasmine { calls: Calls; mostRecentCall: { args: any[]; }; argsForCall: any[]; + withArgs(...args: any[]): Spy; } type SpyObj = T & { diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index ba8763ce3d..92f9a21db8 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -469,6 +469,40 @@ describe("A spy, when configured with an alternate implementation", () => { }); }); +describe("A spy, when configured with alternate implementations for specified arguments", () => { + var foo: any, bar: any, fetchedBar: any; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + }, + getBar: () => { + return bar; + } + }; + + spyOn(foo, "getBar") + .withArgs(1, "2") + .and.callFake(() => 1002); + + foo.setBar(123); + fetchedBar = foo.getBar(1, "2"); + }); + + it("tracks that the spy was called", () => { + expect(foo.getBar).toHaveBeenCalled(); + }); + + it("should not effect other functions", () => { + expect(bar).toEqual(123); + }); + + it("when called returns the requested value", () => { + expect(fetchedBar).toEqual(1002); + }); +}); + describe("A spy, when configured to throw a value", () => { var foo: any, bar: any; From c63de7c41921667f3bc0723d6206c78bae4ae230 Mon Sep 17 00:00:00 2001 From: timhwang21 Date: Tue, 27 Nov 2018 18:03:50 -0500 Subject: [PATCH 375/836] [bip39] Add Buffer as valid argument for entropyToMnemonic The function accepts either string or buffer. --- types/bip39/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/bip39/index.d.ts b/types/bip39/index.d.ts index a5d58cf961..6894ac3b30 100644 --- a/types/bip39/index.d.ts +++ b/types/bip39/index.d.ts @@ -17,7 +17,7 @@ export const wordlists: { spanish: string[]; }; -export function entropyToMnemonic(entropyHex: string, wordlist?: string[]): string; +export function entropyToMnemonic(entropyHex: Buffer | string, wordlist?: string[]): string; export function generateMnemonic(strength?: number, rng?: (size: number) => Buffer, wordlist?: string[]): string; From 797f19a5eb36bdf78d82e52ff5651a020b192e48 Mon Sep 17 00:00:00 2001 From: James Ide Date: Tue, 27 Nov 2018 14:50:09 -0800 Subject: [PATCH 376/836] [react-native] Update type definition for requireNativeComponent for 0.57.x requireNativeComponent now only takes a string and returns a string. See the definition here: https://github.com/facebook/react-native/blob/1151c096dab17e5d9a6ac05b61aacecd4305f3db/Libraries/ReactNative/requireNativeComponent.js#L24-L27. The return type here is specified as `React.ReactType`, which is a union type that includes strings. We can't use `string` because TypeScript treats it as an intrinsic element like `div` and thinks it has no props. Updated the corresponding test code too. --- types/react-native/index.d.ts | 29 +++++------------------------ types/react-native/test/index.tsx | 7 +------ 2 files changed, 6 insertions(+), 30 deletions(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 9e68e283a9..6e54b6d7c9 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -9030,34 +9030,15 @@ export const Platform: PlatformStatic; export const PlatformIOS: PlatformIOSStatic; export const PixelRatio: PixelRatioStatic; -export interface ComponentInterface

{ - name?: string; - displayName?: string; - propTypes: PropTypes.ValidationMap

; -} - /** - * Used to create React components that directly wrap native component - * implementations. Config information is extracted from data exported from the - * UIManager module. You should also wrap the native component in a - * hand-written component with full propTypes definitions and other - * documentation - pass the hand-written component in as `componentInterface` to - * verify all the native props are documented via `propTypes`. + * Creates values that can be used like React components which represent native + * view managers. You should create JavaScript modules that wrap these values so + * that the results are memoized. Example: * - * If some native props shouldn't be exposed in the wrapper interface, you can - * pass null for `componentInterface` and call `verifyPropTypes` directly - * with `nativePropsToIgnore`; + * const View = requireNativeComponent('RCTView'); * - * Common types are lined up with the appropriate prop differs with - * `TypeToDifferMap`. Non-scalar types not in the map default to `deepDiffer`. */ -export function requireNativeComponent( - viewName: string, - componentInterface?: ComponentInterface

, - extraConfig?: { nativeOnly?: NP } -): React.ComponentClass< - Partial>> & { [K in keyof NP]?: any} ->; +export function requireNativeComponent(viewName: string): React.ReactType; export function findNodeHandle( componentOrHandle: null | number | React.Component | React.ComponentClass diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 56d6b7035b..b5d7a5faeb 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -822,12 +822,7 @@ class BridgedComponentTest extends React.Component { } } -const NativeBridgedComponent = requireNativeComponent("NativeBridgedComponent", BridgedComponentTest, { - nativeOnly: { - nativeProp: true, - } -}); - +const NativeBridgedComponent = requireNativeComponent("NativeBridgedComponent"); const SwitchColorTest = () => ( From 53771da91e57c816f8f1899c2e4e072a9bcf97f8 Mon Sep 17 00:00:00 2001 From: Chris Arnesen Date: Wed, 28 Nov 2018 14:15:24 +0700 Subject: [PATCH 377/836] Add options arg to "find-versions" --- types/find-versions/find-versions-tests.ts | 3 ++- types/find-versions/index.d.ts | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/find-versions/find-versions-tests.ts b/types/find-versions/find-versions-tests.ts index 81ea6ca974..e92e6d9848 100644 --- a/types/find-versions/find-versions-tests.ts +++ b/types/find-versions/find-versions-tests.ts @@ -1,3 +1,4 @@ import findVersions = require('find-versions'); -findVersions('node v1.0.0'); +findVersions('node v1.0.0'); // $ExpectType string[] +findVersions('1.0', { loose: true }); // $ExpectType string[] diff --git a/types/find-versions/index.d.ts b/types/find-versions/index.d.ts index 449c5a45c3..f22e3796e2 100644 --- a/types/find-versions/index.d.ts +++ b/types/find-versions/index.d.ts @@ -3,5 +3,5 @@ // Definitions by: Leonid Logvinov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function findVersions(version: string): string[]; +declare function findVersions(version: string, options?: { loose: boolean }): string[]; export = findVersions; From 95b52bea5276fb948958f3d8e4929954b27fd39c Mon Sep 17 00:00:00 2001 From: Chris Arnesen Date: Wed, 28 Nov 2018 14:22:42 +0700 Subject: [PATCH 378/836] Update metadata --- types/find-versions/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/find-versions/index.d.ts b/types/find-versions/index.d.ts index f22e3796e2..7151227fb2 100644 --- a/types/find-versions/index.d.ts +++ b/types/find-versions/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for find-versions 2.0 +// Type definitions for find-versions 3.0 // Project: https://github.com/sindresorhus/find-versions // Definitions by: Leonid Logvinov +// Chris Arnesen Date: Wed, 28 Nov 2018 09:36:59 +0200 Subject: [PATCH 379/836] Make sitekey optional in Parameters --- types/grecaptcha/grecaptcha-tests.ts | 6 +++++- types/grecaptcha/index.d.ts | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/types/grecaptcha/grecaptcha-tests.ts b/types/grecaptcha/grecaptcha-tests.ts index 288836d6b3..970660cc6c 100644 --- a/types/grecaptcha/grecaptcha-tests.ts +++ b/types/grecaptcha/grecaptcha-tests.ts @@ -18,11 +18,15 @@ const badge1: ReCaptchaV2.Badge = "bottomleft"; const badge2: ReCaptchaV2.Badge = "bottomright"; const badge3: ReCaptchaV2.Badge = "inline"; -const invisibleParams: ReCaptchaV2.Parameters = { +const invisibleParams1: ReCaptchaV2.Parameters = { sitekey: "siteKey", badge: badge1, }; +const invisibleParams2: ReCaptchaV2.Parameters = { + badge: badge2, +}; + const id1: number = grecaptcha.render("foo"); const id2: number = grecaptcha.render("foo", params); const id3: number = grecaptcha.render(document.getElementById("foo")); diff --git a/types/grecaptcha/index.d.ts b/types/grecaptcha/index.d.ts index c9dedbfb74..4430aa90e9 100644 --- a/types/grecaptcha/index.d.ts +++ b/types/grecaptcha/index.d.ts @@ -46,7 +46,7 @@ declare namespace ReCaptchaV2 { /** * Your sitekey. */ - sitekey: string; + sitekey?: string; /** * Optional. The color theme of the widget. * Accepted values: "light", "dark" From 8ceca9db8f12523151c437f28b885c15686c510f Mon Sep 17 00:00:00 2001 From: Chris Arnesen Date: Wed, 28 Nov 2018 15:29:38 +0700 Subject: [PATCH 380/836] Update types/find-versions/index.d.ts --- types/find-versions/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/find-versions/index.d.ts b/types/find-versions/index.d.ts index 7151227fb2..9531c1628f 100644 --- a/types/find-versions/index.d.ts +++ b/types/find-versions/index.d.ts @@ -1,7 +1,7 @@ // Type definitions for find-versions 3.0 // Project: https://github.com/sindresorhus/find-versions // Definitions by: Leonid Logvinov -// Chris Arnesen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare function findVersions(version: string, options?: { loose: boolean }): string[]; From e8b63b0bdafe5b3f86c1f2eb062e77aef9fe99c6 Mon Sep 17 00:00:00 2001 From: Mathieu Ghennassia Date: Wed, 28 Nov 2018 11:52:15 +0100 Subject: [PATCH 381/836] mongodb: Type parameter update of method findOneAndUpdate --- types/mongodb/index.d.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index ab4d2f4c02..f994ade210 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -79,7 +79,7 @@ export interface ClientSession extends EventEmitter { /** The server id associated with this session */ id: any; /** - * Aborts the currently active transaction in this session. + * Aborts the currently active transaction in this session. * @param {MongoCallback} [cb] Optional callback for completion of this operation */ abortTransaction(cb?: MongoCallback): Promise; @@ -89,7 +89,7 @@ export interface ClientSession extends EventEmitter { */ advanceOperationTime(operamtionTime: Timestamp): void; /** - * Commits the currently active transaction in this session. + * Commits the currently active transaction in this session. * @param {MongoCallback} [cb] Optional callback for completion of this operation */ commitTransaction(cb?: MongoCallback): Promise; @@ -110,7 +110,7 @@ export interface ClientSession extends EventEmitter { * Used to determine if this session equals another * * @param {ClientSession} session A class representing a client session on the server - * @returns {boolean} if the sessions are equal + * @returns {boolean} if the sessions are equal */ equals(session: ClientSession): boolean; @@ -118,13 +118,13 @@ export interface ClientSession extends EventEmitter { incrementTransactionNumber(): void; /** - * @returns {boolean} this session is currently in a transaction or not + * @returns {boolean} this session is currently in a transaction or not */ inTransaction(): boolean; /** * Starts a new transaction with the given options. - * @param {TransactionOptions} options + * @param {TransactionOptions} options * @memberof ClientSession */ startTransaction(options?: TransactionOptions): void; @@ -219,10 +219,10 @@ export class MongoError extends Error { * client/user (eg. "Email address must be unique" instead of "Both email * address and username must be unique") - which caters for a better (app) * user experience. - * + * * Details: https://github.com/Automattic/mongoose/issues/2129 (issue for * mongoose, but the same applies for the native mongodb driver) - * + * * Note that in mongoose (the link above) the prop in question is called * 'message' while in mongodb it is called 'errmsg'. This can be seen in * multiple places in the source code, for example here: @@ -706,9 +706,9 @@ export interface Collection { findOneAndReplace(filter: FilterQuery, replacement: Object, options?: FindOneAndReplaceOption): Promise>; findOneAndReplace(filter: FilterQuery, replacement: Object, options: FindOneAndReplaceOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndUpdate */ - findOneAndUpdate(filter: FilterQuery, update: Object, callback: MongoCallback>): void; - findOneAndUpdate(filter: FilterQuery, update: Object, options?: FindOneAndUpdateOption): Promise>; - findOneAndUpdate(filter: FilterQuery, update: Object, options: FindOneAndUpdateOption, callback: MongoCallback>): void; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, callback: MongoCallback>): void; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, options?: FindOneAndUpdateOption): Promise>; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, options: FindOneAndUpdateOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoHaystackSearch */ geoHaystackSearch(x: number, y: number, callback: MongoCallback): void; geoHaystackSearch(x: number, y: number, options?: GeoHaystackSearchOptions): Promise; From 1bec72c66668b0fd21dc7b23d7a9deae265ffa59 Mon Sep 17 00:00:00 2001 From: Adam Misiorny Date: Wed, 28 Nov 2018 12:56:06 +0100 Subject: [PATCH 382/836] [rosie] Fix sequence definition with builder argument --- types/rosie/index.d.ts | 2 +- types/rosie/rosie-tests.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/types/rosie/index.d.ts b/types/rosie/index.d.ts index 1078b53573..e66e9855eb 100644 --- a/types/rosie/index.d.ts +++ b/types/rosie/index.d.ts @@ -163,7 +163,7 @@ declare namespace rosie { * @param {function(number): *=} builder * @return {Factory} */ - sequence(name: keyof T, dependenciesOrBuilder?: () => any | keyof T[], builder?: Function) : IFactory; + sequence(name: keyof T, dependenciesOrBuilder?: (i: number) => any | keyof T[], builder?: Function) : IFactory; /** * Sets a post-processor callback that will receive built objects and the diff --git a/types/rosie/rosie-tests.ts b/types/rosie/rosie-tests.ts index 6c2152a9e7..86dd049732 100644 --- a/types/rosie/rosie-tests.ts +++ b/types/rosie/rosie-tests.ts @@ -19,6 +19,7 @@ resultObj = Factory.build('some'); Factory.define('coach') .option('buildPlayer', false) .sequence('id') + .sequence('name', (i: number) => `Coach${i}`) .attr('players', ['id', 'buildPlayer'], function(id: any, buildPlayer: boolean) { if (buildPlayer) { return [Factory.build('player', {coach_id: id})]; From 6b8b4cb0b3461847d8b3dc5fa15e7d31ea1a575d Mon Sep 17 00:00:00 2001 From: Geir Sagberg Date: Wed, 28 Nov 2018 12:58:49 +0100 Subject: [PATCH 383/836] [redux-first-router] Update definitions for Options for 2.1 --- types/redux-first-router/index.d.ts | 101 ++++++++++++++++-- .../redux-first-router-tests.ts | 82 ++++++++------ 2 files changed, 140 insertions(+), 43 deletions(-) diff --git a/types/redux-first-router/index.d.ts b/types/redux-first-router/index.d.ts index 2184deed0b..1cf954b69f 100644 --- a/types/redux-first-router/index.d.ts +++ b/types/redux-first-router/index.d.ts @@ -6,6 +6,7 @@ // corydeppen // jscinoz // surgeboris +// geirsagberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -194,25 +195,107 @@ export interface NavigatorsConfig { }; } +export interface Bag { + action: ReceivedAction | Action; + extra: any; +} + export interface Options { - title?: string | SelectTitleState; + /** + * A prefix that will be prepended to the URL. For example, using a basename of '/playground', + * a route with the path '/home' would correspond to the URL path '/playground/home'. + */ + basename?: string; + /** + * Whether or not a trailing delimiter is allowed when matching path. + */ + strict?: boolean; + /** + * The name of the state key or a selector function to specify where in your Redux state tree + * Redux First Router should expect your page location reducer to be attached to. + */ location?: string | SelectLocationState; - notFoundPath?: string; - scrollTop?: boolean; - onBeforeChange?(dispatch: Dispatch, getState: StateGetter): void; - onAfterChange?(dispatch: Dispatch, getState: StateGetter): void; - onBackNext?(dispatch: Dispatch, getState: StateGetter): void; - restoreScroll?(history: History): ScrollBehavior; + /** + * The name of the state key or a selector function to specify where in your Redux state tree + * Redux First Router should expect your page title reducer to be attached to. + * This can be omitted if you attach the reducer at state.title. + */ + title?: string | SelectTitleState; + /** + * Can be set to false to bypass the initial dispatch, so you can do it manually, perhaps after running sagas. + */ initialDispatch?: boolean; - querySerializer?: QuerySerializer; - navigators?: NavigatorsConfig; + /** + * An array of entries to initialise history object. Useful for server side rendering and tests. + */ initialEntries?: HistoryEntries; + /** + * An object with parse and stringify methods, such as the `query-string` or `qs` libraries (or anything handmade). + * This will be used to handle querystrings. Without this option, query strings are ignored silently. + */ + querySerializer?: QuerySerializer; + /** + * The path where users may be redirected in 2 situations: when you dispatch an action with no matching path, + * or if you manually call dispatch(redirect({ type: NOT_FOUND })), where NOT_FOUND is an export from this package. + * The type in actions and state will be NOT_FOUND, which you can use to show a 404 page. + */ + notFoundPath?: string; + /** + * Whether or not window.scrollTo(0, 0) should be run on route changes so the user starts each page at the top. + */ + scrollTop?: boolean; + /** + * A function to update window/elements scroll position. + */ + restoreScroll?(history: History): ScrollBehavior; + /** + * A simple function that will be called before the routes change. + * It's passed your standard `dispatch` and `getState` arguments like a thunk, + * as well as the `bag` object as a third parameter, which contains the dispatched `action` and the configured `extra` value. + */ + onBeforeChange?(dispatch: Dispatch, getState: StateGetter, bag: Bag): void; + /** + * A simple function that will be called after the routes change. + * It's passed your standard `dispatch` and `getState` arguments like a thunk, + * as well as the `bag` object as a third parameter, which contains the dispatched `action` and the configured `extra` value. + */ + onAfterChange?(dispatch: Dispatch, getState: StateGetter, bag: Bag): void; + /** + * A simple function that will be called whenever the user uses the browser back/next buttons. + * It's passed your standard `dispatch` and `getState` arguments like a thunk, + * as well as the `bag` object as a third parameter, which contains the dispatched `action` + * and the configured `extra` value. Actions with kinds `back`, `next`, and `pop` trigger this. + */ + onBackNext?(dispatch: Dispatch, getState: StateGetter, bag: Bag): void; + /** + * A function receiving `message` and `callback` when navigation is blocked with `confirmLeave`. + * The message is the return value from `confirmLeave`. + * The callback can be called with `true` to unblock the navigation, or with `false` to cancel the navigation. + */ + displayConfirmLeave?: DisplayConfirmLeave; + /** + * A function returning a history object compatible with the popular `history` package. + */ createHistory?(): History; + /** + * A map of of your Redux state keys to _React Navigation_ navigators. + */ + navigators?: NavigatorsConfig; + /** + * An optional value that will be passed as part of the third `bag` argument to all options callbacks and routes thunk. + * It works much like the `withExtraArgument` feature of `redux-thunk` or the `context` argument of GraphQL resolvers. + * You can use it to pass any required context to your thunks without having to tightly couple them to it. + * For example, you could pass an instance of an API client initialised with authentication cookies, + * or a function `addReducer` to inject new code split reducers into the store. + */ + extra?: any; } export type Params = object; export type Payload = object; +export type DisplayConfirmLeave = (message: string, callback: (unblock: boolean) => void) => void; + export type ScrollUpdater = (performedByUser: boolean) => void; export const NOT_FOUND: '@@redux-first-router/NOT_FOUND'; diff --git a/types/redux-first-router/redux-first-router-tests.ts b/types/redux-first-router/redux-first-router-tests.ts index 5297be4175..0439f551c7 100644 --- a/types/redux-first-router/redux-first-router-tests.ts +++ b/types/redux-first-router/redux-first-router-tests.ts @@ -7,21 +7,24 @@ import { redirect, Action as ReduxFirstRouterAction, QuerySerializer, - pathToAction + pathToAction, + StateGetter, + Bag, + Navigators, + NavigationAction, + Nullable, + Route } from 'redux-first-router'; import { - AnyAction, createStore, applyMiddleware, Middleware, - MiddlewareAPI, - Store, Dispatch, compose, - Action, - StoreEnhancer, StoreEnhancerStoreCreator, - combineReducers + combineReducers, + AnyAction, + Store } from 'redux'; import { History } from 'history'; @@ -52,28 +55,40 @@ const routesMap: RoutesMap = { } }; -const { - reducer, - middleware, - enhancer, - initialDispatch, - thunk, -} = connectRoutes(routesMap, { - initialDispatch: false, - onBeforeChange: (dispatch, getState) => { - dispatch; // $ExpectType Dispatch - getState; // $ExpectType StateGetter +const { reducer, middleware, enhancer, initialDispatch, thunk } = connectRoutes(routesMap, { + basename: '/base', + strict: false, + location: state => { + const locationState = state.location; // $ExpectType LocationState + return locationState; + }, + title: state => { + const title = state.location.pathname; // $ExpectType string + return title; + }, + initialDispatch: false, + initialEntries: [], + querySerializer: { + stringify: queryString => { + queryString; // $ExpectType object + return ''; }, - location: state => { - const locationState = state.location; // $ExpectType LocationState - return locationState; - }, - title: state => { - const title = state.location.pathname; // $ExpectType string - return title; - }, - createHistory: () => history, - }); + parse: params => { + params; // $ExpectType string + return {}; + } + }, + notFoundPath: 'not-found', + scrollTop: true, + restoreScroll: (history: History) => { + return {}; + }, + onBeforeChange: (dispatch: Dispatch, getState: StateGetter, bag: Bag) => { }, + onAfterChange: (dispatch: Dispatch, getState: StateGetter, bag: Bag) => { }, + onBackNext: (dispatch: Dispatch, getState: StateGetter, bag: Bag) => { }, + displayConfirmLeave: (message: string, callback: (unblock: boolean) => void) => { }, + createHistory: (options?: any) => history +}); const dumbMiddleware: Middleware = store => next => action => next(action); @@ -89,10 +104,9 @@ const combined = combineReducers({ location: reducer }); const store = createStore(combined, storeEnhancer); // Test that `thunk()` has correct state types now that `store` is defined -thunk(store) - .then((t) => { - t = t!; // $ExpectType RouteThunk - }); +thunk(store).then(t => { + t = t!; // $ExpectType RouteThunk +}); const receivedAction: ReceivedAction = { type: 'HOME', @@ -102,8 +116,8 @@ actionToPath(receivedAction, routesMap); // $ExpectType string pathToAction('/', routesMap); // $ExpectType ReceivedAction const querySerializer: QuerySerializer = { - stringify: (params) => '', - parse: (queryString) => ({}) + stringify: params => '', + parse: queryString => ({}) }; actionToPath(receivedAction, routesMap, querySerializer); // $ExpectType string pathToAction('/', routesMap, querySerializer); // $ExpectType ReceivedAction From 843aa82f3d1921ee5a6fbd52196efb3307bc0349 Mon Sep 17 00:00:00 2001 From: Alexander Sidko Date: Wed, 28 Nov 2018 14:01:24 +0200 Subject: [PATCH 384/836] Use pino-pretty options as PrettyOptions --- types/pino/index.d.ts | 31 ++++++++++++++++++++++++------- types/pino/pino-tests.ts | 13 +++++++++++++ 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index bea9987832..8efaa85d33 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -5,6 +5,7 @@ // Christian Rackerseder // GP // Alex Ferrando +// Oleksandr Sidko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -243,13 +244,12 @@ declare namespace P { interface PrettyOptions { /** - * If set to true, it will only covert the unix timestamp to ISO 8601 date format, and reserialize the JSON (equivalent to pino -t). + * Translate the epoch time value into a human readable date and time string. + * This flag also can set the format string to apply when translating the date to human readable format. + * The default format is yyyy-mm-dd HH:MM:ss.l o in UTC. + * For a list of available pattern letters see the {@link https://www.npmjs.com/package/dateformat|dateformat documentation}. */ - timeTransOnly?: boolean; - /** - * A custom function to format the line, is passed the JSON object as an argument and should return a string value. - */ - formatter?(log: LogDescriptor): string; + translateTime?: boolean | string; /** * If set to true, it will print the name of the log level as the first field in the log line. Default: `false`. */ @@ -261,7 +261,24 @@ declare namespace P { /** * If set to true, will add color information to the formatted output message. Default: `false`. */ - forceColor?: boolean; + colorize?: boolean; + /** + * Appends carriage return and line feed, instead of just a line feed, to the formatted log line. + */ + crlf?: boolean; + /** + * Define the log keys that are associated with error like objects. Default: ["err", "error"] + */ + errorLikeObjectKeys?: string[]; + /** + * When formatting an error object, display this list of properties. + * The list should be a comma separated list of properties. Default: '' + */ + errorProps?: string; + /** + * Specify a search pattern according to {@link http://jmespath.org|jmespath} + */ + search?: string; } type Level = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace'; diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index d3203b5dd4..56b28d284c 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -123,3 +123,16 @@ anotherRedacted.info({ msg: 'another logged with redacted properties', anotherPath: 'Not shown' }); + +const pretty = pino({ + prettyPrint: { + colorize: true, + crlf: false, + errorLikeObjectKeys: ['err', 'error'], + errorProps: '', + levelFirst: false, + messageKey: 'msg', + translateTime: 'UTC:h:MM:ss TT Z', + search: 'foo == `bar`' + } +}) From a821fb106f90a104a262a335b67718554a636ced Mon Sep 17 00:00:00 2001 From: Geir Sagberg Date: Wed, 28 Nov 2018 13:25:07 +0100 Subject: [PATCH 385/836] [redux-first-router] Update RouteObject --- types/redux-first-router/index.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/redux-first-router/index.d.ts b/types/redux-first-router/index.d.ts index 1cf954b69f..13b4578322 100644 --- a/types/redux-first-router/index.d.ts +++ b/types/redux-first-router/index.d.ts @@ -25,6 +25,8 @@ export type StateGetter = () => TState; export type RouteString = string; +export type ConfirmLeave = (state: object, action: object) => Nullable; + export type RouteThunk = ( dispatch: Dispatch, getState: StateGetter, @@ -37,6 +39,9 @@ export type RouteObject = TKeys & { thunk?: RouteThunk; fromPath?(path: string, key?: string): string; toPath?(param: string, key?: string): string; + coerceNumbers?: boolean; + confirmLeave?: ConfirmLeave; + meta?: Meta; }; export type Route = RouteString | RouteObject; From d0081bef8b40ab5d104694063131acc928e5f78b Mon Sep 17 00:00:00 2001 From: HarikiRito <35214929+HarikiRito@users.noreply.github.com> Date: Wed, 28 Nov 2018 19:41:26 +0700 Subject: [PATCH 386/836] Export Interface --- types/react-lottie/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/react-lottie/index.d.ts b/types/react-lottie/index.d.ts index 8e4f3b717b..a57da91307 100644 --- a/types/react-lottie/index.d.ts +++ b/types/react-lottie/index.d.ts @@ -7,7 +7,7 @@ import * as React from 'react'; -interface Options { +export interface Options { /** * Defines if the animation should play only once or repeatedly in an endless loop */ @@ -41,7 +41,7 @@ interface Options { }; } -interface EventListener { +export interface EventListener { /** * The event sent by Lottie */ @@ -61,7 +61,7 @@ interface EventListener { callback: () => void; } -interface LottieProps { +export interface LottieProps { /** * Object representing animation settings */ From 0bdba525bac419a9a946a0f4753742a73a0d828d Mon Sep 17 00:00:00 2001 From: Alexander Sidko Date: Wed, 28 Nov 2018 14:42:24 +0200 Subject: [PATCH 387/836] Fix pino tests --- types/pino/pino-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index 56b28d284c..3a6283c3e4 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -135,4 +135,4 @@ const pretty = pino({ translateTime: 'UTC:h:MM:ss TT Z', search: 'foo == `bar`' } -}) +}); From 422ae215527764ce90c03fe262b401bdae07c17d Mon Sep 17 00:00:00 2001 From: Kamontat Chantrachirathumrong Date: Wed, 28 Nov 2018 15:06:11 +0100 Subject: [PATCH 388/836] Update index.d.ts --- types/wikidata-sdk/index.d.ts | 243 ++++++++++++++++++++++++++-------- 1 file changed, 185 insertions(+), 58 deletions(-) diff --git a/types/wikidata-sdk/index.d.ts b/types/wikidata-sdk/index.d.ts index 5810bcc9de..79620ac623 100644 --- a/types/wikidata-sdk/index.d.ts +++ b/types/wikidata-sdk/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for wikidata-sdk 5.15 +// Type definitions for wikidata-sdk 5.15.9 // Project: https://github.com/maxlath/wikidata-sdk // Definitions by: Kamontat Chantrachirathumrong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,20 +7,36 @@ import { WikidataLanguage } from "./def/type/language"; import { WikidataProperty } from "./def/type/property"; import { WikidataSite } from "./def/type/site"; +import { WikidataSiteLink, WikidataSiteLinkSimplify, WikidataSiteLinkWithUrlSimplify } from "./def/object/sitelink"; import { UrlResultFormat } from "./def/type/format"; +import { + WikidataLanguageBaseString, + WikidataLanguageBaseStringSimplify, + WikidataLanguageBaseArrayString, + WikidataLanguageBaseArrayStringSimplify +} from "wikidata-sdk/def/object/language-base-string"; -import { Claim, MainSnak, TimeDataValue, EntityDataValue } from "./def/object/claim"; +import { WikidataClaim, WikidataMainSnak, WikidataTimeDataValue, WikidataEntityDataValue } from "./def/object/claim"; -export type WikidataLanguage = WikidataLanguage; -export type WikidataProperty = WikidataProperty; -export type WikidataSite = WikidataSite; +// ----------------------------------- // +// Export session // +// ----------------------------------- // -export type UrlResultFormat = UrlResultFormat; +export { WikidataLanguage, WikidataProperty, WikidataSite }; -export type Claim = Claim; -export type MainSnak = MainSnak; -export type TimeDataValue = TimeDataValue; -export type EntityDataValue = EntityDataValue; +export { + WikidataLanguageBaseString, + WikidataLanguageBaseStringSimplify, + WikidataLanguageBaseArrayString, + WikidataLanguageBaseArrayStringSimplify, + WikidataSiteLink, + WikidataSiteLinkSimplify, + WikidataSiteLinkWithUrlSimplify +}; + +export { UrlResultFormat }; + +export { WikidataClaim, WikidataMainSnak, WikidataTimeDataValue, WikidataEntityDataValue }; export as namespace sdk; @@ -42,22 +58,22 @@ export as namespace sdk; * @see {@link https://www.wikidata.org/w/api.php?action=help&modules=wbsearchentities | Wikidata[wbsearchentities] } */ export function searchEntities( - search: string, - language?: WikidataLanguage, - limit?: string | number, - format?: UrlResultFormat, - uselang?: WikidataLanguage + search: string, + language?: WikidataLanguage, + limit?: string | number, + format?: UrlResultFormat, + uselang?: WikidataLanguage ): string; /** * @alias searchEntities */ export function searchEntities(opt: { - search: string; - language?: WikidataLanguage; - limit?: string | number; - format?: UrlResultFormat; - uselang?: WikidataLanguage; + search: string; + language?: WikidataLanguage; + limit?: string | number; + format?: UrlResultFormat; + uselang?: WikidataLanguage; }): string; /* ********** @@ -79,20 +95,20 @@ export function searchEntities(opt: { * @see {@link https://www.wikidata.org/w/api.php?action=help&modules=wbgetentities | Wikidata[wbgetentities] } */ export function getEntities( - ids: string | string[], - languages?: WikidataLanguage | WikidataLanguage[], - props?: WikidataProperty | WikidataProperty[], - format?: UrlResultFormat + ids: string | string[], + languages?: WikidataLanguage | WikidataLanguage[], + props?: WikidataProperty | WikidataProperty[], + format?: UrlResultFormat ): string; /** * @alias getEntities */ export function getEntities(a: { - ids: string | string[]; - languages?: WikidataLanguage | WikidataLanguage[]; - props?: WikidataProperty | WikidataProperty[]; - format?: UrlResultFormat; + ids: string | string[]; + languages?: WikidataLanguage | WikidataLanguage[]; + props?: WikidataProperty | WikidataProperty[]; + format?: UrlResultFormat; }): string; /** @@ -101,20 +117,20 @@ export function getEntities(a: { * Without id limitation and return the array of url instead. */ export function getManyEntities( - ids: string | string[], - languages?: WikidataLanguage | WikidataLanguage[], - props?: WikidataProperty | WikidataProperty[], - format?: UrlResultFormat + ids: string | string[], + languages?: WikidataLanguage | WikidataLanguage[], + props?: WikidataProperty | WikidataProperty[], + format?: UrlResultFormat ): string[]; /** * @alias getManyEntities */ export function getManyEntities(a: { - ids: string | string[]; - languages?: WikidataLanguage | WikidataLanguage[]; - props?: WikidataProperty | WikidataProperty[]; - format?: UrlResultFormat; + ids: string | string[]; + languages?: WikidataLanguage | WikidataLanguage[]; + props?: WikidataProperty | WikidataProperty[]; + format?: UrlResultFormat; }): string[]; /** @@ -131,22 +147,22 @@ export function getManyEntities(a: { * @see {@link https://github.com/maxlath/wikidata-sdk/blob/6b0673b9bf0fcaab19db65e2cc77e33c901ef35d/docs/get_entities.md#by-wikipedia-titles | Github[get_entities.md#by-wikipedia-titles] } */ export function getWikidataIdsFromWikipediaTitles( - titles: string | string[], - sites?: string, - languages?: WikidataLanguage | WikidataLanguage[], - props?: WikidataProperty | WikidataProperty[], - format?: UrlResultFormat + titles: string | string[], + sites?: WikidataSite, + languages?: WikidataLanguage | WikidataLanguage[], + props?: WikidataProperty | WikidataProperty[], + format?: UrlResultFormat ): string; /** * @alias getWikidataIdsFromWikipediaTitles */ export function getWikidataIdsFromWikipediaTitles(a: { - titles: string | string[]; - sites?: string; - languages?: WikidataLanguage | WikidataLanguage[]; - props?: WikidataProperty | WikidataProperty[]; - format?: UrlResultFormat; + titles: string | string[]; + sites?: WikidataSite; + languages?: WikidataLanguage | WikidataLanguage[]; + props?: WikidataProperty | WikidataProperty[]; + format?: UrlResultFormat; }): string; /** @@ -167,13 +183,13 @@ export function getWikidataIdsFromWikipediaTitles(a: { * {@link https://github.com/maxlath/wikidata-sdk/blob/6b0673b9bf0fcaab19db65e2cc77e33c901ef35d/docs/get_entities_reverse_claims.md#get-entities-reverse-claims | Github[get-entities-reverse-claims] } */ export function getReverseClaims( - property: string | string[], - value: string | string[], - options?: { - limit?: number; - keepProperties?: boolean; - caseInsensitive?: boolean; - } + property: string | string[], + value: string | string[], + options?: { + limit?: number; + keepProperties?: boolean; + caseInsensitive?: boolean; + } ): string; /** @@ -241,7 +257,7 @@ export function truthyClaims(claims: object): object; * * @see {@link https://www.mediawiki.org/wiki/Wikibase/Indexing/RDF_Dump_Format#Truthy_statements | Truthy} */ -export function truthyPropertyClaims(claims: Claim[]): Claim[]; +export function truthyPropertyClaims(claims: WikidataClaim[]): WikidataClaim[]; /** * This will get the link that represent the site of the title. @@ -252,16 +268,16 @@ export function truthyPropertyClaims(claims: Claim[]): Claim[]; * * @see {@link https://github.com/maxlath/wikidata-sdk/blob/6b0673b9bf0fcaab19db65e2cc77e33c901ef35d/docs/general_helpers.md#getsitelinkurl | Github[getsitelinkurl] } */ -export function getSitelinkUrl(site: string, title: string): string; +export function getSitelinkUrl(site: WikidataSite, title: string): string; /** * @alias getSitelinkUrl */ -export function getSitelinkUrl(a: { site: string; title: string }): string; +export function getSitelinkUrl(a: { site: WikidataSite; title: string }): string; export interface SitelinkData { - lang: string; - project: string; + lang: string; + project: string; } /** * Get the sitelink on english language and the lang of it. @@ -335,3 +351,114 @@ export function wikidataTimeToSimpleDay(a: string | object): string; * @returns URL from a wikimedia commons filename */ export function getImageUrl(a: string, width?: number): string; + +export type SimplifyOption = { + // claims + entityPrefix?: string; + propertyPrefix?: string; + keepRichValues?: boolean; + keepQualifiers?: boolean; + keepReferences?: boolean; + keepIds?: boolean; + keepHashes?: boolean; + keepNonTruthy?: boolean; + // sitelinks + addUrl?: boolean; +}; + +/** + * Helper method, for simplify result object more reasonable + */ +export namespace simplify { + /** + * Applying all simplifiers at once: labels, descriptions, aliases, claims, sitelinks. See next sections for details. + * You can also pass options as a second argument, that will then be passed the subfunctions: + * + * @param entity the entity that receive from {@link getEntities} APIs + * @param opt simlify option. currently only simplify claims and simplify sitelinks. + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-entity | Github[simplify-entity]} + */ + export function entity(entity: T, opt?: SimplifyOption): T; + + /** + * This is a same of {@link entity} method except this input as multiple array of entities. + * + * @param entities entities from {@link getEntities} APIs + * @param opt simlify option. currently only simplify claims and simplify sitelinks. + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-entities | Github[simplify-entities]} + */ + export function entities(entities: T[], opt?: SimplifyOption): T[]; + + /** + * Make label simplifier and easier to understand + * + * @param labels label object, you will receive this from getEntities method + * + * @example + * + * const label = simplify.labels("{ pl: { language: 'pl', value: 'książka' } }"); + * console.log(label) // { pl: 'książka' } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-labels | Github[simplify-labels]} + */ + export function labels(labels: WikidataLanguageBaseString): WikidataLanguageBaseStringSimplify; + + /** + * Make description simplifier and easier to understand + * + * @param descriptions description object, you will receive this from getEntities method + * + * @example + * + * const desc = simplify.descriptions("{ pl: { language: 'pl', value: 'dokument piśmienniczy [...]' } }"); + * console.log(desc) // { pl: 'dokument piśmienniczy [...]' } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-descriptions | Github[simplify-descriptions]} + */ + export function descriptions(descriptions: WikidataLanguageBaseString): WikidataLanguageBaseStringSimplify; + + /** + * Make alias simplifier and easier to understand + * + * @param aliases alias object, you will receive this from getEntities method + * + * @example + * + * const alias = simplify.aliases("{ pl: [ { language: 'pl', value: 'Tom' }, { language: 'pl', value: 'Tomik' } ] }"); + * console.log(alias) // { pl: [ 'Tom', 'Tomik' ] } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-aliases | Github[simplify-aliases]} + */ + export function aliases(aliases: WikidataLanguageBaseArrayString): WikidataLanguageBaseArrayStringSimplify; + + /** + * Make sitelink simplifier and easier to understand + * + * @param sitelinks sitelink object, you will receive this from getEntities method + * + * @example + * + * const site = simplify.sitelinks("{ plwiki: { site: 'plwiki', title: 'Książka', badges: [] } }"); + * console.log(site) // { plwiki: 'Książka' } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-sitelinks | Github[simplify-sitelinks]} + */ + export function sitelinks(sitelinks: WikidataSiteLink): WikidataSiteLinkSimplify; + + /** + * Make sitelink simplifier and easier to understand. include URL in the result. + * + * @param sitelinks sitelink object, you will receive this from getEntities method + * @param options add url to a result + * + * @example + * + * const site = simplify.sitelinks("{ plwiki: { site: 'plwiki', title: 'Książka', badges: [] } }", {addUrl: true}); + * console.log(site) // { plwiki: { title: 'Książka', url: 'https://pl.wikipedia.org/wiki/Książka' } } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#add-sitelinks-urls | Github[simplify-sitelinks-with-url]} + */ + export function sitelinks(sitelinks: WikidataSiteLink, options: { addUrl: true }): WikidataSiteLinkWithUrlSimplify; +} From d284105dcadcce897d96a1d38a5040e396095f35 Mon Sep 17 00:00:00 2001 From: Kamontat Chantrachirathumrong Date: Wed, 28 Nov 2018 15:08:33 +0100 Subject: [PATCH 389/836] Update claim name --- types/wikidata-sdk/def/object/claim.d.ts | 54 ++++++++++++------------ 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/types/wikidata-sdk/def/object/claim.d.ts b/types/wikidata-sdk/def/object/claim.d.ts index c397fcb0df..99ed8bf52c 100644 --- a/types/wikidata-sdk/def/object/claim.d.ts +++ b/types/wikidata-sdk/def/object/claim.d.ts @@ -1,34 +1,34 @@ -export interface TimeDataValue { - type: "time"; - value: { - time: string; - timezone: number; - before: number; - after: number; - precision: number; - calendermodel: string; - }; +export interface WikidataTimeDataValue { + type: "time"; + value: { + time: string; + timezone: number; + before: number; + after: number; + precision: number; + calendermodel: string; + }; } -export interface EntityDataValue { - type: "wikibase-entityid"; - value: { - "numeric-id": number; - "entity-type": string; - }; +export interface WikidataEntityDataValue { + type: "wikibase-entityid"; + value: { + "numeric-id": number; + "entity-type": string; + }; } -export interface MainSnak { - datatype: string; - snaktype: string; - property: string; - hash: string; - datavalue: TimeDataValue | EntityDataValue; +export interface WikidataMainSnak { + datatype: string; + snaktype: string; + property: string; + hash: string; + datavalue: WikidataTimeDataValue | WikidataEntityDataValue; } -export interface Claim { - rank: string; - id: string; - type: string; - mainsnak: MainSnak; +export interface WikidataClaim { + rank: string; + id: string; + type: string; + mainsnak: WikidataMainSnak; } From d5acd49750e454a5ab7f35a452a2f2cd61ea12ea Mon Sep 17 00:00:00 2001 From: Kamontat Chantrachirathumrong Date: Wed, 28 Nov 2018 15:09:17 +0100 Subject: [PATCH 390/836] Add language base string object type --- .../def/object/language-base-string.d.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 types/wikidata-sdk/def/object/language-base-string.d.ts diff --git a/types/wikidata-sdk/def/object/language-base-string.d.ts b/types/wikidata-sdk/def/object/language-base-string.d.ts new file mode 100644 index 0000000000..9f35d4bd8e --- /dev/null +++ b/types/wikidata-sdk/def/object/language-base-string.d.ts @@ -0,0 +1,19 @@ +import { WikidataLanguage } from "wikidata-sdk"; + +export type WikidataLanguageBaseString = { + [Key in WikidataLanguage]?: { + language: Key; + value: string; + } +}; + +export type WikidataLanguageBaseStringSimplify = { [key in WikidataLanguage]?: string }; + +export type WikidataLanguageBaseArrayString = { + [Key in WikidataLanguage]: { + language: Key; + value: string; + }[] +}; + +export type WikidataLanguageBaseArrayStringSimplify = { [key in WikidataLanguage]: string[] }; From 22e936663027c8f82280ce4a3883fe42ea30e8ee Mon Sep 17 00:00:00 2001 From: Kamontat Chantrachirathumrong Date: Wed, 28 Nov 2018 15:09:40 +0100 Subject: [PATCH 391/836] Add sitelink object --- types/wikidata-sdk/def/object/sitelink.d.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 types/wikidata-sdk/def/object/sitelink.d.ts diff --git a/types/wikidata-sdk/def/object/sitelink.d.ts b/types/wikidata-sdk/def/object/sitelink.d.ts new file mode 100644 index 0000000000..4b6aeee23d --- /dev/null +++ b/types/wikidata-sdk/def/object/sitelink.d.ts @@ -0,0 +1,12 @@ +import { WikidataSite } from "wikidata-sdk"; + +export type WikidataSiteLink = { [Key in WikidataSite]: { site: Key; title: string; badges: string[] } }; + +export type WikidataSiteLinkSimplify = { [key in WikidataSite]: string }; + +export type WikidataSiteLinkWithUrlSimplify = { + [key in WikidataSite]: { + title: string; + url: string; + } +}; From 3e65f7972871d987b69b60a2b63587a89e5dbb6f Mon Sep 17 00:00:00 2001 From: feinoujc Date: Wed, 28 Nov 2018 09:10:50 -0500 Subject: [PATCH 392/836] [@pollyjs/core] updates for 1.3 config options --- types/pollyjs__core/index.d.ts | 28 +++++---- types/pollyjs__core/pollyjs__core-tests.ts | 69 +++++++++++++++++++++- 2 files changed, 83 insertions(+), 14 deletions(-) diff --git a/types/pollyjs__core/index.d.ts b/types/pollyjs__core/index.d.ts index 83b6b933b9..4f6d308d0d 100644 --- a/types/pollyjs__core/index.d.ts +++ b/types/pollyjs__core/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/core 1.2 +// Type definitions for @pollyjs/core 1.3 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -12,8 +12,10 @@ export const Timing: { fixed(ms: number): () => Promise; relative(ratio: number): (ms: number) => Promise; }; + +export type MatchBy = (input: T) => R; export interface PollyConfig { - mode?: MODES; + mode?: MODES | string; adapters?: Array; adapterOptions?: any; @@ -34,20 +36,20 @@ export interface PollyConfig { timing?: ((ms: number) => Promise) | (() => Promise); matchRequestsBy?: { - method?: boolean; - headers?: any; - body?: boolean; + method?: boolean | MatchBy; + headers?: boolean | { exclude: string[] } | MatchBy>; + body?: boolean | MatchBy; order?: boolean; url?: { - protocol?: boolean; - username?: boolean; - password?: boolean; - hostname?: boolean; - port?: boolean; - pathname?: boolean; - query?: boolean; - hash?: boolean; + protocol?: boolean | MatchBy; + username?: boolean | MatchBy; + password?: boolean | MatchBy; + hostname?: boolean | MatchBy; + port?: boolean | MatchBy; + pathname?: boolean | MatchBy; + query?: boolean | MatchBy; + hash?: boolean | MatchBy; }; }; } diff --git a/types/pollyjs__core/pollyjs__core-tests.ts b/types/pollyjs__core/pollyjs__core-tests.ts index 22f5516646..0644eff7f4 100644 --- a/types/pollyjs__core/pollyjs__core-tests.ts +++ b/types/pollyjs__core/pollyjs__core-tests.ts @@ -6,7 +6,74 @@ const polly = new Polly('test recording', { recordFailedRequests: true, adapters: ['xhr', 'fetch'], persister: 'rest', - timing: Timing.relative(3) + timing: Timing.relative(3), + matchRequestsBy: { + method: true, + headers: true, + body: true, + order: true, + + url: { + protocol: true, + username: true, + password: true, + hostname: true, + port: true, + pathname: true, + query: true, + hash: false + } + } +}); + +new Polly('test recording', { + mode: 'replay', + recordFailedRequests: true, + adapters: ['xhr', 'fetch'], + persister: 'rest', + timing: Timing.relative(3), + matchRequestsBy: { + method(method) { + return method.toLowerCase(); + }, + headers: 1 === 1 ? { exclude: ['X-Auth'] } : (headers) => { + delete headers['X-Auth']; + return headers; + }, + body(body) { + const json = JSON.parse(body); + + delete json.email; + return JSON.stringify(json); + }, + + url: { + protocol(protocol) { + return protocol === 'http' ? 'https:' : protocol; + }, + username(username) { + return username === 'johndoe' ? 'username' : username; + }, + password(password) { + return password || 'password'; + }, + hostname(hostname) { + return hostname.replace('.com', '.net'); + }, + port(port) { + return port > 80 ? 3000 : 433; + }, + pathname(pathname) { + return pathname.replace('/api/v1', '/api'); + }, + query(query) { + return { ...query, token: '' }; + }, + hash(hash) { + return hash.replace(/token=[0-9]+/, ''); + } + } + } }); function log(_: string) { From 091bd02a320f8984ff9b7045efab32737d631b93 Mon Sep 17 00:00:00 2001 From: Kamontat Chantrachirathumrong Date: Wed, 28 Nov 2018 15:14:48 +0100 Subject: [PATCH 393/836] Fix error --- types/wikidata-sdk/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/wikidata-sdk/index.d.ts b/types/wikidata-sdk/index.d.ts index 79620ac623..98eb893d0c 100644 --- a/types/wikidata-sdk/index.d.ts +++ b/types/wikidata-sdk/index.d.ts @@ -14,7 +14,7 @@ import { WikidataLanguageBaseStringSimplify, WikidataLanguageBaseArrayString, WikidataLanguageBaseArrayStringSimplify -} from "wikidata-sdk/def/object/language-base-string"; +} from "./def/object/language-base-string"; import { WikidataClaim, WikidataMainSnak, WikidataTimeDataValue, WikidataEntityDataValue } from "./def/object/claim"; From 19d012663d76ff38c8ade084095cfef40556fad2 Mon Sep 17 00:00:00 2001 From: Dmitriy Date: Wed, 28 Nov 2018 17:25:18 +0300 Subject: [PATCH 394/836] add on-initial-draw-complete-support --- types/vis/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/vis/index.d.ts b/types/vis/index.d.ts index 0f4a4f0f4e..9967c35061 100644 --- a/types/vis/index.d.ts +++ b/types/vis/index.d.ts @@ -11,6 +11,7 @@ // Oleksii Kachura // dcop // Avraham Essoudry +// Dmitriy Trifonov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { MomentInput, MomentFormatSpecification, Moment } from 'moment'; @@ -244,6 +245,7 @@ export interface TimelineOptions { multiselectPerGroup?: boolean; onAdd?: TimelineOptionsItemCallbackFunction; onAddGroup?: TimelineOptionsGroupCallbackFunction; + onInitialDrawComplete?: () => void; onUpdate?: TimelineOptionsItemCallbackFunction; onMove?: TimelineOptionsItemCallbackFunction; onMoveGroup?: TimelineOptionsGroupCallbackFunction; From 265766df3dfefc749ecd229354e8ca884c8cf818 Mon Sep 17 00:00:00 2001 From: Kamontat Chantrachirathumrong Date: Wed, 28 Nov 2018 15:32:28 +0100 Subject: [PATCH 395/836] [fix] Fix a lot of linter error --- .../def/object/language-base-string.d.ts | 18 +- types/wikidata-sdk/def/object/sitelink.d.ts | 10 +- types/wikidata-sdk/index.d.ts | 320 +++++++++--------- 3 files changed, 176 insertions(+), 172 deletions(-) diff --git a/types/wikidata-sdk/def/object/language-base-string.d.ts b/types/wikidata-sdk/def/object/language-base-string.d.ts index 9f35d4bd8e..8f9606dbb1 100644 --- a/types/wikidata-sdk/def/object/language-base-string.d.ts +++ b/types/wikidata-sdk/def/object/language-base-string.d.ts @@ -1,19 +1,19 @@ -import { WikidataLanguage } from "wikidata-sdk"; +import { WikidataLanguage } from "../type/language"; export type WikidataLanguageBaseString = { - [Key in WikidataLanguage]?: { - language: Key; - value: string; - } + [Key in WikidataLanguage]?: { + language: Key; + value: string; + } }; export type WikidataLanguageBaseStringSimplify = { [key in WikidataLanguage]?: string }; export type WikidataLanguageBaseArrayString = { - [Key in WikidataLanguage]: { - language: Key; - value: string; - }[] + [Key in WikidataLanguage]: Array<{ + language: Key; + value: string; + }> }; export type WikidataLanguageBaseArrayStringSimplify = { [key in WikidataLanguage]: string[] }; diff --git a/types/wikidata-sdk/def/object/sitelink.d.ts b/types/wikidata-sdk/def/object/sitelink.d.ts index 4b6aeee23d..d0eea713e5 100644 --- a/types/wikidata-sdk/def/object/sitelink.d.ts +++ b/types/wikidata-sdk/def/object/sitelink.d.ts @@ -1,12 +1,12 @@ -import { WikidataSite } from "wikidata-sdk"; +import { WikidataSite } from "../type/site"; export type WikidataSiteLink = { [Key in WikidataSite]: { site: Key; title: string; badges: string[] } }; export type WikidataSiteLinkSimplify = { [key in WikidataSite]: string }; export type WikidataSiteLinkWithUrlSimplify = { - [key in WikidataSite]: { - title: string; - url: string; - } + [key in WikidataSite]: { + title: string; + url: string; + } }; diff --git a/types/wikidata-sdk/index.d.ts b/types/wikidata-sdk/index.d.ts index 98eb893d0c..6ed81883cc 100644 --- a/types/wikidata-sdk/index.d.ts +++ b/types/wikidata-sdk/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for wikidata-sdk 5.15.9 +// Type definitions for wikidata-sdk 5.15 // Project: https://github.com/maxlath/wikidata-sdk // Definitions by: Kamontat Chantrachirathumrong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.1 import { WikidataLanguage } from "./def/type/language"; import { WikidataProperty } from "./def/type/property"; @@ -10,10 +10,10 @@ import { WikidataSite } from "./def/type/site"; import { WikidataSiteLink, WikidataSiteLinkSimplify, WikidataSiteLinkWithUrlSimplify } from "./def/object/sitelink"; import { UrlResultFormat } from "./def/type/format"; import { - WikidataLanguageBaseString, - WikidataLanguageBaseStringSimplify, - WikidataLanguageBaseArrayString, - WikidataLanguageBaseArrayStringSimplify + WikidataLanguageBaseString, + WikidataLanguageBaseStringSimplify, + WikidataLanguageBaseArrayString, + WikidataLanguageBaseArrayStringSimplify } from "./def/object/language-base-string"; import { WikidataClaim, WikidataMainSnak, WikidataTimeDataValue, WikidataEntityDataValue } from "./def/object/claim"; @@ -25,19 +25,23 @@ import { WikidataClaim, WikidataMainSnak, WikidataTimeDataValue, WikidataEntityD export { WikidataLanguage, WikidataProperty, WikidataSite }; export { - WikidataLanguageBaseString, - WikidataLanguageBaseStringSimplify, - WikidataLanguageBaseArrayString, - WikidataLanguageBaseArrayStringSimplify, - WikidataSiteLink, - WikidataSiteLinkSimplify, - WikidataSiteLinkWithUrlSimplify + WikidataLanguageBaseString, + WikidataLanguageBaseStringSimplify, + WikidataLanguageBaseArrayString, + WikidataLanguageBaseArrayStringSimplify, + WikidataSiteLink, + WikidataSiteLinkSimplify, + WikidataSiteLinkWithUrlSimplify }; export { UrlResultFormat }; export { WikidataClaim, WikidataMainSnak, WikidataTimeDataValue, WikidataEntityDataValue }; +export interface Json { + [key: string]: any; +} + export as namespace sdk; /* ********** @@ -58,22 +62,22 @@ export as namespace sdk; * @see {@link https://www.wikidata.org/w/api.php?action=help&modules=wbsearchentities | Wikidata[wbsearchentities] } */ export function searchEntities( - search: string, - language?: WikidataLanguage, - limit?: string | number, - format?: UrlResultFormat, - uselang?: WikidataLanguage + search: string, + language?: WikidataLanguage, + limit?: string | number, + format?: UrlResultFormat, + uselang?: WikidataLanguage ): string; /** * @alias searchEntities */ export function searchEntities(opt: { - search: string; - language?: WikidataLanguage; - limit?: string | number; - format?: UrlResultFormat; - uselang?: WikidataLanguage; + search: string; + language?: WikidataLanguage; + limit?: string | number; + format?: UrlResultFormat; + uselang?: WikidataLanguage; }): string; /* ********** @@ -95,20 +99,20 @@ export function searchEntities(opt: { * @see {@link https://www.wikidata.org/w/api.php?action=help&modules=wbgetentities | Wikidata[wbgetentities] } */ export function getEntities( - ids: string | string[], - languages?: WikidataLanguage | WikidataLanguage[], - props?: WikidataProperty | WikidataProperty[], - format?: UrlResultFormat + ids: string | string[], + languages?: WikidataLanguage | WikidataLanguage[], + props?: WikidataProperty | WikidataProperty[], + format?: UrlResultFormat ): string; /** * @alias getEntities */ export function getEntities(a: { - ids: string | string[]; - languages?: WikidataLanguage | WikidataLanguage[]; - props?: WikidataProperty | WikidataProperty[]; - format?: UrlResultFormat; + ids: string | string[]; + languages?: WikidataLanguage | WikidataLanguage[]; + props?: WikidataProperty | WikidataProperty[]; + format?: UrlResultFormat; }): string; /** @@ -117,20 +121,20 @@ export function getEntities(a: { * Without id limitation and return the array of url instead. */ export function getManyEntities( - ids: string | string[], - languages?: WikidataLanguage | WikidataLanguage[], - props?: WikidataProperty | WikidataProperty[], - format?: UrlResultFormat + ids: string | string[], + languages?: WikidataLanguage | WikidataLanguage[], + props?: WikidataProperty | WikidataProperty[], + format?: UrlResultFormat ): string[]; /** * @alias getManyEntities */ export function getManyEntities(a: { - ids: string | string[]; - languages?: WikidataLanguage | WikidataLanguage[]; - props?: WikidataProperty | WikidataProperty[]; - format?: UrlResultFormat; + ids: string | string[]; + languages?: WikidataLanguage | WikidataLanguage[]; + props?: WikidataProperty | WikidataProperty[]; + format?: UrlResultFormat; }): string[]; /** @@ -147,22 +151,22 @@ export function getManyEntities(a: { * @see {@link https://github.com/maxlath/wikidata-sdk/blob/6b0673b9bf0fcaab19db65e2cc77e33c901ef35d/docs/get_entities.md#by-wikipedia-titles | Github[get_entities.md#by-wikipedia-titles] } */ export function getWikidataIdsFromWikipediaTitles( - titles: string | string[], - sites?: WikidataSite, - languages?: WikidataLanguage | WikidataLanguage[], - props?: WikidataProperty | WikidataProperty[], - format?: UrlResultFormat + titles: string | string[], + sites?: WikidataSite, + languages?: WikidataLanguage | WikidataLanguage[], + props?: WikidataProperty | WikidataProperty[], + format?: UrlResultFormat ): string; /** * @alias getWikidataIdsFromWikipediaTitles */ export function getWikidataIdsFromWikipediaTitles(a: { - titles: string | string[]; - sites?: WikidataSite; - languages?: WikidataLanguage | WikidataLanguage[]; - props?: WikidataProperty | WikidataProperty[]; - format?: UrlResultFormat; + titles: string | string[]; + sites?: WikidataSite; + languages?: WikidataLanguage | WikidataLanguage[]; + props?: WikidataProperty | WikidataProperty[]; + format?: UrlResultFormat; }): string; /** @@ -183,13 +187,13 @@ export function getWikidataIdsFromWikipediaTitles(a: { * {@link https://github.com/maxlath/wikidata-sdk/blob/6b0673b9bf0fcaab19db65e2cc77e33c901ef35d/docs/get_entities_reverse_claims.md#get-entities-reverse-claims | Github[get-entities-reverse-claims] } */ export function getReverseClaims( - property: string | string[], - value: string | string[], - options?: { - limit?: number; - keepProperties?: boolean; - caseInsensitive?: boolean; - } + property: string | string[], + value: string | string[], + options?: { + limit?: number; + keepProperties?: boolean; + caseInsensitive?: boolean; + } ): string; /** @@ -248,7 +252,7 @@ export function isSitelinkKey(a: string): boolean; * * @see {@link https://www.mediawiki.org/wiki/Wikibase/Indexing/RDF_Dump_Format#Truthy_statements | Truthy} */ -export function truthyClaims(claims: object): object; +export function truthyClaims(claims: WikidataClaim): WikidataClaim; /** * Filter-out non-truthy claims from an entity.claims[prop] array @@ -276,8 +280,8 @@ export function getSitelinkUrl(site: WikidataSite, title: string): string; export function getSitelinkUrl(a: { site: WikidataSite; title: string }): string; export interface SitelinkData { - lang: string; - project: string; + lang: string; + project: string; } /** * Get the sitelink on english language and the lang of it. @@ -340,7 +344,7 @@ export function wikidataTimeToDateObject(a: string): Date; * @see {@link https://github.com/maxlath/wikidata-sdk/blob/6b0673b9bf0fcaab19db65e2cc77e33c901ef35d/docs/general_helpers.md#wikidatatimetosimpleday | Github[wikidatatimetosimpleday] } * */ -export function wikidataTimeToSimpleDay(a: string | object): string; +export function wikidataTimeToSimpleDay(a: string | Json): string; /** * Get an image URL from a Wikimedia Commons filename @@ -352,113 +356,113 @@ export function wikidataTimeToSimpleDay(a: string | object): string; */ export function getImageUrl(a: string, width?: number): string; -export type SimplifyOption = { - // claims - entityPrefix?: string; - propertyPrefix?: string; - keepRichValues?: boolean; - keepQualifiers?: boolean; - keepReferences?: boolean; - keepIds?: boolean; - keepHashes?: boolean; - keepNonTruthy?: boolean; - // sitelinks - addUrl?: boolean; -}; +export interface SimplifyOption { + // claims + entityPrefix?: string; + propertyPrefix?: string; + keepRichValues?: boolean; + keepQualifiers?: boolean; + keepReferences?: boolean; + keepIds?: boolean; + keepHashes?: boolean; + keepNonTruthy?: boolean; + // sitelinks + addUrl?: boolean; +} /** * Helper method, for simplify result object more reasonable */ export namespace simplify { - /** - * Applying all simplifiers at once: labels, descriptions, aliases, claims, sitelinks. See next sections for details. - * You can also pass options as a second argument, that will then be passed the subfunctions: - * - * @param entity the entity that receive from {@link getEntities} APIs - * @param opt simlify option. currently only simplify claims and simplify sitelinks. - * - * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-entity | Github[simplify-entity]} - */ - export function entity(entity: T, opt?: SimplifyOption): T; + /** + * Applying all simplifiers at once: labels, descriptions, aliases, claims, sitelinks. See next sections for details. + * You can also pass options as a second argument, that will then be passed the subfunctions: + * + * @param entity the entity that receive from {@link getEntities} APIs + * @param opt simlify option. currently only simplify claims and simplify sitelinks. + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-entity | Github[simplify-entity]} + */ + function entity(entity: T, opt?: SimplifyOption): T; - /** - * This is a same of {@link entity} method except this input as multiple array of entities. - * - * @param entities entities from {@link getEntities} APIs - * @param opt simlify option. currently only simplify claims and simplify sitelinks. - * - * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-entities | Github[simplify-entities]} - */ - export function entities(entities: T[], opt?: SimplifyOption): T[]; + /** + * This is a same of {@link entity} method except this input as multiple array of entities. + * + * @param entities entities from {@link getEntities} APIs + * @param opt simlify option. currently only simplify claims and simplify sitelinks. + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-entities | Github[simplify-entities]} + */ + function entities(entities: T[], opt?: SimplifyOption): T[]; - /** - * Make label simplifier and easier to understand - * - * @param labels label object, you will receive this from getEntities method - * - * @example - * - * const label = simplify.labels("{ pl: { language: 'pl', value: 'książka' } }"); - * console.log(label) // { pl: 'książka' } - * - * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-labels | Github[simplify-labels]} - */ - export function labels(labels: WikidataLanguageBaseString): WikidataLanguageBaseStringSimplify; + /** + * Make label simplifier and easier to understand + * + * @param labels label object, you will receive this from getEntities method + * + * @example + * + * const label = simplify.labels("{ pl: { language: 'pl', value: 'książka' } }"); + * console.log(label) // { pl: 'książka' } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-labels | Github[simplify-labels]} + */ + function labels(labels: WikidataLanguageBaseString): WikidataLanguageBaseStringSimplify; - /** - * Make description simplifier and easier to understand - * - * @param descriptions description object, you will receive this from getEntities method - * - * @example - * - * const desc = simplify.descriptions("{ pl: { language: 'pl', value: 'dokument piśmienniczy [...]' } }"); - * console.log(desc) // { pl: 'dokument piśmienniczy [...]' } - * - * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-descriptions | Github[simplify-descriptions]} - */ - export function descriptions(descriptions: WikidataLanguageBaseString): WikidataLanguageBaseStringSimplify; + /** + * Make description simplifier and easier to understand + * + * @param descriptions description object, you will receive this from getEntities method + * + * @example + * + * const desc = simplify.descriptions("{ pl: { language: 'pl', value: 'dokument piśmienniczy [...]' } }"); + * console.log(desc) // { pl: 'dokument piśmienniczy [...]' } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-descriptions | Github[simplify-descriptions]} + */ + function descriptions(descriptions: WikidataLanguageBaseString): WikidataLanguageBaseStringSimplify; - /** - * Make alias simplifier and easier to understand - * - * @param aliases alias object, you will receive this from getEntities method - * - * @example - * - * const alias = simplify.aliases("{ pl: [ { language: 'pl', value: 'Tom' }, { language: 'pl', value: 'Tomik' } ] }"); - * console.log(alias) // { pl: [ 'Tom', 'Tomik' ] } - * - * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-aliases | Github[simplify-aliases]} - */ - export function aliases(aliases: WikidataLanguageBaseArrayString): WikidataLanguageBaseArrayStringSimplify; + /** + * Make alias simplifier and easier to understand + * + * @param aliases alias object, you will receive this from getEntities method + * + * @example + * + * const alias = simplify.aliases("{ pl: [ { language: 'pl', value: 'Tom' }, { language: 'pl', value: 'Tomik' } ] }"); + * console.log(alias) // { pl: [ 'Tom', 'Tomik' ] } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-aliases | Github[simplify-aliases]} + */ + function aliases(aliases: WikidataLanguageBaseArrayString): WikidataLanguageBaseArrayStringSimplify; - /** - * Make sitelink simplifier and easier to understand - * - * @param sitelinks sitelink object, you will receive this from getEntities method - * - * @example - * - * const site = simplify.sitelinks("{ plwiki: { site: 'plwiki', title: 'Książka', badges: [] } }"); - * console.log(site) // { plwiki: 'Książka' } - * - * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-sitelinks | Github[simplify-sitelinks]} - */ - export function sitelinks(sitelinks: WikidataSiteLink): WikidataSiteLinkSimplify; + /** + * Make sitelink simplifier and easier to understand + * + * @param sitelinks sitelink object, you will receive this from getEntities method + * + * @example + * + * const site = simplify.sitelinks("{ plwiki: { site: 'plwiki', title: 'Książka', badges: [] } }"); + * console.log(site) // { plwiki: 'Książka' } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-sitelinks | Github[simplify-sitelinks]} + */ + function sitelinks(sitelinks: WikidataSiteLink): WikidataSiteLinkSimplify; - /** - * Make sitelink simplifier and easier to understand. include URL in the result. - * - * @param sitelinks sitelink object, you will receive this from getEntities method - * @param options add url to a result - * - * @example - * - * const site = simplify.sitelinks("{ plwiki: { site: 'plwiki', title: 'Książka', badges: [] } }", {addUrl: true}); - * console.log(site) // { plwiki: { title: 'Książka', url: 'https://pl.wikipedia.org/wiki/Książka' } } - * - * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#add-sitelinks-urls | Github[simplify-sitelinks-with-url]} - */ - export function sitelinks(sitelinks: WikidataSiteLink, options: { addUrl: true }): WikidataSiteLinkWithUrlSimplify; + /** + * Make sitelink simplifier and easier to understand. include URL in the result. + * + * @param sitelinks sitelink object, you will receive this from getEntities method + * @param options add url to a result + * + * @example + * + * const site = simplify.sitelinks("{ plwiki: { site: 'plwiki', title: 'Książka', badges: [] } }", {addUrl: true}); + * console.log(site) // { plwiki: { title: 'Książka', url: 'https://pl.wikipedia.org/wiki/Książka' } } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#add-sitelinks-urls | Github[simplify-sitelinks-with-url]} + */ + function sitelinks(sitelinks: WikidataSiteLink, options: { addUrl: true }): WikidataSiteLinkWithUrlSimplify; } From b53181d81ab75724f19b0f1fb242525639c1f96f Mon Sep 17 00:00:00 2001 From: Dmitriy Date: Wed, 28 Nov 2018 17:36:58 +0300 Subject: [PATCH 396/836] change void function type --- types/vis/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/vis/index.d.ts b/types/vis/index.d.ts index 9967c35061..84ff769270 100644 --- a/types/vis/index.d.ts +++ b/types/vis/index.d.ts @@ -245,7 +245,7 @@ export interface TimelineOptions { multiselectPerGroup?: boolean; onAdd?: TimelineOptionsItemCallbackFunction; onAddGroup?: TimelineOptionsGroupCallbackFunction; - onInitialDrawComplete?: () => void; + onInitialDrawComplete?: (() => void); onUpdate?: TimelineOptionsItemCallbackFunction; onMove?: TimelineOptionsItemCallbackFunction; onMoveGroup?: TimelineOptionsGroupCallbackFunction; From 0f51eb8eeab7859c7eafbc3506f5ab65d3cfc267 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 28 Nov 2018 16:23:49 +0100 Subject: [PATCH 397/836] Add types for mustache-express --- types/mustache-express/index.d.ts | 23 +++++++++++++++++++ .../mustache-express-tests.ts | 10 ++++++++ types/mustache-express/tsconfig.json | 23 +++++++++++++++++++ types/mustache-express/tslint.json | 1 + 4 files changed, 57 insertions(+) create mode 100644 types/mustache-express/index.d.ts create mode 100644 types/mustache-express/mustache-express-tests.ts create mode 100644 types/mustache-express/tsconfig.json create mode 100644 types/mustache-express/tslint.json diff --git a/types/mustache-express/index.d.ts b/types/mustache-express/index.d.ts new file mode 100644 index 0000000000..ff40de42d7 --- /dev/null +++ b/types/mustache-express/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for mustache-express 1.2 +// Project: https://github.com/bryanburgers/node-mustache-express#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Cache } from 'lru-cache'; + +export = mustacheExpress; + +declare function mustacheExpress( + partialsPath?: string, + partialsExt?: string +): mustacheExpress.ExpessEngine; + +declare namespace mustacheExpress { + interface ExpessEngine { + (path: string, options: any, cb: (...args: any[]) => any): any; + cache: TemplateCache; + } + + type TemplateCache = Cache; +} diff --git a/types/mustache-express/mustache-express-tests.ts b/types/mustache-express/mustache-express-tests.ts new file mode 100644 index 0000000000..9157798c7b --- /dev/null +++ b/types/mustache-express/mustache-express-tests.ts @@ -0,0 +1,10 @@ +import express = require('express'); +import mustacheExpress = require('mustache-express'); + +const app = express(); +app.engine('mustache', mustacheExpress()); +app.engine('mustache', mustacheExpress('/partials')); +app.engine('mustache', mustacheExpress('/partials', '.mst')); + +// $ExpectType Cache +mustacheExpress().cache; diff --git a/types/mustache-express/tsconfig.json b/types/mustache-express/tsconfig.json new file mode 100644 index 0000000000..9afb989b62 --- /dev/null +++ b/types/mustache-express/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", + "mustache-express-tests.ts" + ] +} diff --git a/types/mustache-express/tslint.json b/types/mustache-express/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mustache-express/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 3d022d90e85f41d0fc5914b5f7a034a4da3ff2d9 Mon Sep 17 00:00:00 2001 From: Alan Plum Date: Wed, 28 Nov 2018 17:00:57 +0100 Subject: [PATCH 398/836] Add Collection#name() --- types/arangodb/arangodb-tests.ts | 3 +++ types/arangodb/index.d.ts | 12 ++---------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/types/arangodb/arangodb-tests.ts b/types/arangodb/arangodb-tests.ts index e049a2374d..c2ade4d0bb 100644 --- a/types/arangodb/arangodb-tests.ts +++ b/types/arangodb/arangodb-tests.ts @@ -16,6 +16,9 @@ coll.save({ username: "user" }); const doc = coll.any(); console.log(doc.username); +const coll2 = db._collection(coll.name()); +console.log(coll2 === coll); + const users = coll as ArangoDB.Collection; const admin = users.firstExample({ username: "admin" })!; users.update(admin, { password: md5("hunter2") }); diff --git a/types/arangodb/index.d.ts b/types/arangodb/index.d.ts index 238cea2379..c5e83a1cfc 100644 --- a/types/arangodb/index.d.ts +++ b/types/arangodb/index.d.ts @@ -619,6 +619,7 @@ declare namespace ArangoDB { interface Collection { // Collection + name(): string; checksum( withRevisions?: boolean, withData?: boolean @@ -1503,16 +1504,7 @@ declare module "@arangodb/foxx/queues" { function deleteQueue(name: string): boolean; function get(name: string): Queue; - export { - createQueue as create, - deleteQueue as delete, - get, - JobOptions, - Job, - Queue, - QueueItem, - Script, - }; + export { createQueue as create, deleteQueue as delete, get, JobOptions, Job, Queue, QueueItem, Script, }; } declare module "@arangodb/foxx/graphql" { From 793d709fb22bb195371fd52fa0a8d50a39e4accf Mon Sep 17 00:00:00 2001 From: Lucas Motta Date: Wed, 28 Nov 2018 16:16:54 +0000 Subject: [PATCH 399/836] Include missing type for the method readFile --- types/ssh2-streams/index.d.ts | 24 ++++++++++++++++++++++++ types/ssh2/index.d.ts | 20 ++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/types/ssh2-streams/index.d.ts b/types/ssh2-streams/index.d.ts index a780273591..3eaca56f6f 100644 --- a/types/ssh2-streams/index.d.ts +++ b/types/ssh2-streams/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for ssh2-streams v0.1.9 // Project: https://github.com/mscdex/ssh2-streams // Definitions by: Ron Buckton +// Definitions by: Ron Buckton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -1044,6 +1045,24 @@ export class SFTPStream extends stream.Transform { */ fastPut(localPath: string, remotePath: string, callback: (err: any) => void): void; + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, options: ReadFileOptions, callback: (err: any, handle: Buffer) => void): void; + + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, encoding: string, callback: (err: any, handle: Buffer) => void): void; + + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, callback: (err: any, handle: Buffer) => void): void; + /** * (Client-only) * Returns a new readable stream for `path`. @@ -1612,6 +1631,11 @@ export interface TransferOptions { step?: (total_transferred: number, chunk: number, total: number) => void; } +export interface ReadFileOptions { + encoding?: string + flag?: string +} + export interface ReadStreamOptions { flags?: string; encoding?: string; diff --git a/types/ssh2/index.d.ts b/types/ssh2/index.d.ts index 25bcfef52e..cf88fff5f1 100644 --- a/types/ssh2/index.d.ts +++ b/types/ssh2/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Qubo // Ron Buckton // Will Boyce +// Lucas Motta // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -21,6 +22,7 @@ import { Attributes, Stats, TransferOptions, + ReadFileOptions, ReadStreamOptions, WriteStreamOptions, FileEntry @@ -1273,6 +1275,24 @@ export interface SFTPWrapper extends events.EventEmitter { */ fastPut(localPath: string, remotePath: string, callback: (err: any) => void): void; + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, options: ReadFileOptions, callback: (err: any, handle: Buffer) => void): void; + + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, encoding: string, callback: (err: any, handle: Buffer) => void): void; + + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, callback: (err: any, handle: Buffer) => void): void; + /** * (Client-only) * Returns a new readable stream for `path`. From f857ba9d66d2f430fb2ff06b7e4579fbf61b7673 Mon Sep 17 00:00:00 2001 From: Erik Christensen Date: Wed, 28 Nov 2018 11:17:01 -0500 Subject: [PATCH 400/836] Added CollationDocument type in a couple places that were missed --- types/mongodb/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index a217b0a605..3de97daf60 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -526,7 +526,7 @@ export interface CollectionCreateOptions extends CommonOptions { indexOptionDefaults?: object; viewOn?: string; pipeline?: any[]; - collation?: object; + collation?: CollationDocument; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collection */ @@ -563,7 +563,7 @@ export interface IndexOptions extends CommonOptions { name?: string; // Creates a partial index based on the given filter object (MongoDB 3.2 or higher) partialFilterExpression?: any; - collation?: Object; + collation?: CollationDocument; default_language?: string } From b2133e941c8646b7a5c0581453123054314c2602 Mon Sep 17 00:00:00 2001 From: Lucas Motta Date: Wed, 28 Nov 2018 16:26:08 +0000 Subject: [PATCH 401/836] Fix credit name --- types/ssh2-streams/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/ssh2-streams/index.d.ts b/types/ssh2-streams/index.d.ts index 3eaca56f6f..e80e529ced 100644 --- a/types/ssh2-streams/index.d.ts +++ b/types/ssh2-streams/index.d.ts @@ -1,7 +1,7 @@ // Type definitions for ssh2-streams v0.1.9 // Project: https://github.com/mscdex/ssh2-streams // Definitions by: Ron Buckton -// Definitions by: Ron Buckton +// Definitions by: Lucas Motta // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// From 5cc01bba1447d578d0c0c8b4fe80d599638b9dc0 Mon Sep 17 00:00:00 2001 From: Erik Christensen Date: Wed, 28 Nov 2018 11:37:45 -0500 Subject: [PATCH 402/836] Fixed incorrect type for caseFirst in CollationDocument --- types/mongodb/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 3de97daf60..ef7b7768d8 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -1786,7 +1786,7 @@ export interface CollationDocument { locale: string; strength?: number; caseLevel?: boolean; - caseFirst?: boolean; + caseFirst?: string; numericOrdering?: boolean; alternate?: string; maxVariable?: string; From 1748c8d191505ad7a17165f5078dd45ee8575e9b Mon Sep 17 00:00:00 2001 From: Joe Flateau Date: Wed, 28 Nov 2018 12:14:34 -0500 Subject: [PATCH 403/836] Update types/node-forge/index.d.ts Co-Authored-By: timhwang21 --- types/node-forge/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index 40badbbcf4..1a2b028a90 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for node-forge 0.7.7 +// Type definitions for node-forge 0.7.6 // Project: https://github.com/digitalbazaar/forge // Definitions by: Seth Westphal // Kay Schecker From 99db723f07aec0b37f34137ea71b4c6fc7dd7d01 Mon Sep 17 00:00:00 2001 From: Daniel Hritzkiv Date: Wed, 28 Nov 2018 12:34:36 -0500 Subject: [PATCH 404/836] Fix error type in backoffStrategies interface change `typeof Error` (resolves to `ErrorConstructor`) to just `Error`. This allows accessing actual error instance properties (message, etc.) --- types/bull/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index 6096d98145..dd5723f2d2 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -92,7 +92,7 @@ declare namespace Bull { * Define a custom backoff strategy */ backoffStrategies?: { - [key: string]: (attemptsMade: number, err: typeof Error) => number; + [key: string]: (attemptsMade: number, err: Error) => number; }; /** From be8aa4618958d2c663438aab7fbc28fc1160e8c3 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 28 Nov 2018 10:11:58 -0800 Subject: [PATCH 405/836] Add status badges --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 9a31d73da1..0f8ba84c27 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,9 @@ [![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Are packages being published to npm in less than 10,000 seconds on average? +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) Has typescript-bot been active on DefinitelyTyped in the last two hours? + > The repository for *high quality* TypeScript type definitions. Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date. From 2b17e0bbf1d0c973856be1911ca89615230f163a Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 28 Nov 2018 10:13:52 -0800 Subject: [PATCH 406/836] Move badges to bottom --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0f8ba84c27..129762bd9b 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,6 @@ [![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Are packages being published to npm in less than 10,000 seconds on average? -[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) Has typescript-bot been active on DefinitelyTyped in the last two hours? - > The repository for *high quality* TypeScript type definitions. Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date. @@ -339,3 +336,6 @@ This project is licensed under the MIT license. Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file. [![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) + +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Are packages being published to npm in less than 10,000 seconds on average? +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) Has typescript-bot been active on DefinitelyTyped in the last two hours? From 64e8c6d752ddc75d26fcfed5478e2b5eb0a863f4 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 28 Nov 2018 19:36:59 +0100 Subject: [PATCH 407/836] Add types for timing-safe-equal --- types/timing-safe-equal/index.d.ts | 10 ++++++++ .../timing-safe-equal-tests.ts | 5 ++++ types/timing-safe-equal/tsconfig.json | 23 +++++++++++++++++++ types/timing-safe-equal/tslint.json | 1 + 4 files changed, 39 insertions(+) create mode 100644 types/timing-safe-equal/index.d.ts create mode 100644 types/timing-safe-equal/timing-safe-equal-tests.ts create mode 100644 types/timing-safe-equal/tsconfig.json create mode 100644 types/timing-safe-equal/tslint.json diff --git a/types/timing-safe-equal/index.d.ts b/types/timing-safe-equal/index.d.ts new file mode 100644 index 0000000000..e1bf8f16d8 --- /dev/null +++ b/types/timing-safe-equal/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for timing-safe-equal 1.0 +// Project: https://github.com/crypto-browserify/timing-safe-equal +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = timingSafeEqual; + +declare function timingSafeEqual(a: Buffer, b: Buffer): boolean; diff --git a/types/timing-safe-equal/timing-safe-equal-tests.ts b/types/timing-safe-equal/timing-safe-equal-tests.ts new file mode 100644 index 0000000000..cc8069de3b --- /dev/null +++ b/types/timing-safe-equal/timing-safe-equal-tests.ts @@ -0,0 +1,5 @@ +import timingSafeEqual = require('timing-safe-equal'); + +const buffer: Buffer = new Buffer([1, 2, 3, 4, 5]); +// $ExpectType boolean +timingSafeEqual(buffer, buffer); diff --git a/types/timing-safe-equal/tsconfig.json b/types/timing-safe-equal/tsconfig.json new file mode 100644 index 0000000000..f12ec7b09e --- /dev/null +++ b/types/timing-safe-equal/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", + "timing-safe-equal-tests.ts" + ] +} diff --git a/types/timing-safe-equal/tslint.json b/types/timing-safe-equal/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/timing-safe-equal/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From a6cc14597d068d6312f7434fcf93cdb6b2cd8282 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 28 Nov 2018 11:09:56 -0800 Subject: [PATCH 408/836] Swap types-publisher/typescript-bot status badge links The links were backward, but not the images. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 129762bd9b..9062f4ea00 100644 --- a/README.md +++ b/README.md @@ -337,5 +337,5 @@ Copyrights on the definition files are respective of each contributor listed at [![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) -[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Are packages being published to npm in less than 10,000 seconds on average? -[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) Has typescript-bot been active on DefinitelyTyped in the last two hours? +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) Are packages being published to npm in less than 10,000 seconds on average? +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Has typescript-bot been active on DefinitelyTyped in the last two hours? From 01972623953bfefc9378b829bf1afd21a550d504 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 28 Nov 2018 20:27:35 +0100 Subject: [PATCH 409/836] Add types for diffie-hellman --- types/diffie-hellman/diffie-hellman-tests.ts | 48 ++++++++++++++++++++ types/diffie-hellman/index.d.ts | 8 ++++ types/diffie-hellman/tsconfig.json | 23 ++++++++++ types/diffie-hellman/tslint.json | 1 + 4 files changed, 80 insertions(+) create mode 100644 types/diffie-hellman/diffie-hellman-tests.ts create mode 100644 types/diffie-hellman/index.d.ts create mode 100644 types/diffie-hellman/tsconfig.json create mode 100644 types/diffie-hellman/tslint.json diff --git a/types/diffie-hellman/diffie-hellman-tests.ts b/types/diffie-hellman/diffie-hellman-tests.ts new file mode 100644 index 0000000000..645ebc23bd --- /dev/null +++ b/types/diffie-hellman/diffie-hellman-tests.ts @@ -0,0 +1,48 @@ +import * as dh from 'diffie-hellman'; + +const dh1 = dh.getDiffieHellman('modp1'); +// $ExpectType DiffieHellman +dh1; +// $ExpectType Buffer +dh1.generateKeys(); +// $ExpectType string +dh1.generateKeys('hex'); +// $ExpectType Buffer +dh1.getPrime(); +// $ExpectType string +dh1.getPrime('hex'); +// $ExpectType Buffer +dh1.getGenerator(); +// $ExpectType string +dh1.getGenerator('hex'); +const pk = dh1.getPublicKey(); +// $ExpectType Buffer +pk; +// $ExpectType string +dh1.getPublicKey('hex'); +// $ExpectType Buffer +dh1.getPrivateKey(); +// $ExpectType string +dh1.getPrivateKey('hex'); +// $ExpectType Buffer +dh1.computeSecret(pk); +// $ExpectType Buffer +dh1.computeSecret(pk.toString('hex'), 'hex'); +// $ExpectType string +dh1.computeSecret(pk.toString('hex'), 'hex', 'hex'); + +const dh2 = dh.createDiffieHellman(new Buffer([5])); +// $ExpectType DiffieHellman +dh2; +dh.createDiffieHellman('prime', 'hex'); +dh.createDiffieHellman('prime', 'hex', new Buffer([5])); +dh.createDiffieHellman('prime', 'hex', 5); +dh.createDiffieHellman('prime', 'hex', 'generator', 'hex'); +dh.createDiffieHellman(1); +dh.createDiffieHellman(1, 1); +dh.createDiffieHellman(1, new Buffer([5])); + +dh2.setPublicKey(pk); +dh2.setPublicKey(pk.toString('hex'), 'hex'); +dh2.setPrivateKey(pk); +dh2.setPrivateKey(pk.toString('hex'), 'hex'); diff --git a/types/diffie-hellman/index.d.ts b/types/diffie-hellman/index.d.ts new file mode 100644 index 0000000000..7b59cf9182 --- /dev/null +++ b/types/diffie-hellman/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for diffie-hellman 5.0 +// Project: https://github.com/crypto-browserify/diffie-hellman +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export { createDiffieHellman, getDiffieHellman, DiffieHellman } from 'crypto'; diff --git a/types/diffie-hellman/tsconfig.json b/types/diffie-hellman/tsconfig.json new file mode 100644 index 0000000000..743c9eea4c --- /dev/null +++ b/types/diffie-hellman/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", + "diffie-hellman-tests.ts" + ] +} diff --git a/types/diffie-hellman/tslint.json b/types/diffie-hellman/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/diffie-hellman/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 154a76cccee50c2b789fbff0a60b124d84668f9f Mon Sep 17 00:00:00 2001 From: Dominik Moritz Date: Wed, 28 Nov 2018 11:30:48 -0800 Subject: [PATCH 410/836] Add Vega entry to notNeededPackages.json --- notNeededPackages.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/notNeededPackages.json b/notNeededPackages.json index cf5c9449d7..53ff6a7124 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -1656,6 +1656,12 @@ "sourceRepoURL": "https://github.com/ansman/validate.js", "asOfVersion": "0.11.0" }, + { + "libraryName": "vega", + "typingsPackageName": "vega", + "sourceRepoURL": "https://github.com/vega/vega", + "asOfVersion": "3.2.0" + }, { "libraryName": "vso-node-api", "typingsPackageName": "vso-node-api", From 35b4230318e66ec0851fa81f425ce23ccdc4d0f4 Mon Sep 17 00:00:00 2001 From: Cameron Martin Date: Wed, 28 Nov 2018 19:32:27 +0000 Subject: [PATCH 411/836] [@babel/traverse]: Added null to Scope#getFunctionParent return type. See https://github.com/babel/babel/blob/3fda01b185bfe2a54eb00aaae6b8314ca867df0f/packages/babel-traverse/src/scope/index.js#L845 --- types/babel__traverse/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/babel__traverse/index.d.ts b/types/babel__traverse/index.d.ts index 93c768a913..e35b12780f 100644 --- a/types/babel__traverse/index.d.ts +++ b/types/babel__traverse/index.d.ts @@ -99,7 +99,7 @@ export class Scope { getProgramParent(): Scope; - getFunctionParent(): Scope; + getFunctionParent(): Scope | null; getBlockParent(): Scope; From ebb848491a767717f82c852b21af81df56ad8b80 Mon Sep 17 00:00:00 2001 From: Bradley Hill Date: Wed, 28 Nov 2018 13:37:09 -0600 Subject: [PATCH 412/836] fabric - update the TextBox.getSelectionStyles signature to latest fabricjs --- types/fabric/fabric-impl.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 485a603966..39b3e45757 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -3467,7 +3467,7 @@ export class IText extends Object { * @param [endIndex] End index to get styles at * @return styles Style object at a specified (or current) index */ - getSelectionStyles(startIndex: number, endIndex: number): any; + getSelectionStyles(startIndex: number, endIndex: number, complete?: boolean): any; /** * Sets style of a current selection * @param [styles] Styles object From eba6a5aa15795302ece5ad2016ef095dc1310ced Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Wed, 28 Nov 2018 21:32:20 +0100 Subject: [PATCH 413/836] [node] Add missing alpnProtocol and createConnection --- types/node/index.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 0f6698035d..ee51a5fd0f 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -6258,6 +6258,13 @@ declare module "tls" { * May be used to distinguish TLS sockets from regular ones. */ encrypted: boolean; + + /** + * String containing the selected ALPN protocol. + * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol?: string; + /** * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. * @returns Returns an object representing the cipher name @@ -8303,6 +8310,7 @@ declare module "http2" { peerMaxConcurrentStreams?: number; selectPadding?: (frameLen: number, maxFrameLen: number) => number; settings?: Settings; + createConnection?: (option: SessionOptions) => stream.Duplex; } export type ClientSessionOptions = SessionOptions; From 6a96d327accc0e3de24bcc3db0a1ab38eaf9b47b Mon Sep 17 00:00:00 2001 From: Alex Jerabek Date: Wed, 28 Nov 2018 13:59:00 -0800 Subject: [PATCH 414/836] Add DialogOptions.promptBeforeOpen --- types/office-js/index.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index ceb6f2263b..dc4d0c2cb4 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -1157,6 +1157,13 @@ declare namespace Office { * This is best for user experience and performance. */ displayInIframe?: boolean + /** + * Determines if the pop-up blocker dialog will be shown to the user. Defaults to true. + * + * `true` - The framework displays a pop-up to trigger the navigation and avoid the browser's pop-up blocker. + * `false` - The dialog will not be shown and the developer will handle pop-ups (usually by providing a user artifact to trigger the navigation). + */ + promptBeforeOpen?: boolean; /** * A user-defined item of any type that is returned, unchanged, in the asyncContext property of the AsyncResult object that is passed to a callback. */ From 75cbccb548c1778e72b848ae6c818aabbb145129 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 28 Nov 2018 14:02:28 -0800 Subject: [PATCH 415/836] Nope, the images were backward too --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9062f4ea00..eba170c493 100644 --- a/README.md +++ b/README.md @@ -337,5 +337,5 @@ Copyrights on the definition files are respective of each contributor listed at [![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) -[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) Are packages being published to npm in less than 10,000 seconds on average? -[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Has typescript-bot been active on DefinitelyTyped in the last two hours? +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) Are packages being published to npm in less than 10,000 seconds on average? +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Has typescript-bot been active on DefinitelyTyped in the last two hours? From eccc7f9c6d6fd7b06165aa588252703c6fde6b06 Mon Sep 17 00:00:00 2001 From: Alex Jerabek Date: Wed, 28 Nov 2018 14:09:42 -0800 Subject: [PATCH 416/836] Grammar fix --- types/office-js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index dc4d0c2cb4..7c637c3ccc 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -1161,7 +1161,7 @@ declare namespace Office { * Determines if the pop-up blocker dialog will be shown to the user. Defaults to true. * * `true` - The framework displays a pop-up to trigger the navigation and avoid the browser's pop-up blocker. - * `false` - The dialog will not be shown and the developer will handle pop-ups (usually by providing a user artifact to trigger the navigation). + * `false` - The dialog will not be shown and the developer must handle pop-ups (by providing a user interface artifact to trigger the navigation). */ promptBeforeOpen?: boolean; /** From e228d2d09b79adfcdb8992735644e6d447bc2914 Mon Sep 17 00:00:00 2001 From: Alex Jerabek Date: Wed, 28 Nov 2018 14:38:39 -0800 Subject: [PATCH 417/836] Remove redundant text --- types/office-js/index.d.ts | 56 +++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index ceb6f2263b..1390c616cc 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -50829,7 +50829,7 @@ declare namespace Word { getRange(rangeLocation?: "Whole" | "Start" | "End" | "Before" | "After" | "Content"): Word.Range; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.2] * @@ -50839,7 +50839,7 @@ declare namespace Word { insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.2] * @@ -50856,7 +50856,7 @@ declare namespace Word { insertContentControl(): Word.ContentControl; /** * - * Inserts a document at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a document at the specified location. * * [Api set: WordApi 1.2] * @@ -50866,7 +50866,7 @@ declare namespace Word { insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation): Word.Range; /** * - * Inserts a document at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a document at the specified location. * * [Api set: WordApi 1.2] * @@ -50876,7 +50876,7 @@ declare namespace Word { insertFileFromBase64(base64File: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts HTML at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts HTML at the specified location. * * [Api set: WordApi 1.2] * @@ -50886,7 +50886,7 @@ declare namespace Word { insertHtml(html: string, insertLocation: Word.InsertLocation): Word.Range; /** * - * Inserts HTML at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts HTML at the specified location. * * [Api set: WordApi 1.2] * @@ -50916,7 +50916,7 @@ declare namespace Word { insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.InlinePicture; /** * - * Inserts OOXML at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts OOXML at the specified location. * * [Api set: WordApi 1.2] * @@ -50926,7 +50926,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: Word.InsertLocation): Word.Range; /** * - * Inserts OOXML at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts OOXML at the specified location. * * [Api set: WordApi 1.2] * @@ -50936,7 +50936,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.2] * @@ -50946,7 +50946,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.2] * @@ -50956,7 +50956,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * - * Inserts text at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts text at the specified location. * * [Api set: WordApi 1.2] * @@ -50966,7 +50966,7 @@ declare namespace Word { insertText(text: string, insertLocation: Word.InsertLocation): Word.Range; /** * - * Inserts text at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts text at the specified location. * * [Api set: WordApi 1.2] * @@ -51777,7 +51777,7 @@ declare namespace Word { getTextRanges(endingMarks: string[], trimSpacing?: boolean): Word.RangeCollection; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.1] * @@ -51787,7 +51787,7 @@ declare namespace Word { insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.1] * @@ -51884,7 +51884,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.1] * @@ -51894,7 +51894,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.1] * @@ -51904,7 +51904,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -51916,7 +51916,7 @@ declare namespace Word { insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation, values?: string[][]): Word.Table; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -52355,7 +52355,7 @@ declare namespace Word { getTextRanges(endingMarks: string[], trimSpacing?: boolean): Word.RangeCollection; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.1] * @@ -52365,7 +52365,7 @@ declare namespace Word { insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.1] * @@ -52462,7 +52462,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.1] * @@ -52472,7 +52472,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.1] * @@ -52482,7 +52482,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -52494,7 +52494,7 @@ declare namespace Word { insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation, values?: string[][]): Word.Table; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -53357,7 +53357,7 @@ declare namespace Word { insertContentControl(): Word.ContentControl; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.3] * @@ -53367,7 +53367,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.3] * @@ -53377,7 +53377,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -53389,7 +53389,7 @@ declare namespace Word { insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation, values?: string[][]): Word.Table; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * From c0f3e556bb8b958a337c691d6fb9962b130b93dd Mon Sep 17 00:00:00 2001 From: Alex Jerabek Date: Wed, 28 Nov 2018 15:10:50 -0800 Subject: [PATCH 418/836] Clarify formula behavior for data validation rules --- types/office-js/index.d.ts | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index ceb6f2263b..7dd1437b13 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -21758,18 +21758,19 @@ declare namespace Excel { interface BasicDataValidation { /** * - * Gets or sets the Formula1, i.e. minimum value or value depending of the operator. - When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). - When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. + * Specifies the right-hand operand when the operator property is set to a binary operator such as GreaterThan (the left-hand operand is the value the user tries to enter in the cell). With the ternary operators Between and NotBetween, specifies the lower bound operand. + * For example, setting formula1 to 10 and operator to GreaterThan means that valid data for the range must be greater than 10. + * When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). + * When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. * * [Api set: ExcelApi 1.8] */ formula1: string | number | Range; /** * - * Gets or sets the Formula2, i.e. maximum value or value depending of the operator. - When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). - When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. + * With the ternary operators Between and NotBetween, specifies the upper bound operand. Is not used with the binary operators, such as GreaterThan. + * When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). + * When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. * * [Api set: ExcelApi 1.8] */ @@ -21791,18 +21792,18 @@ declare namespace Excel { interface DateTimeDataValidation { /** * - * Gets or sets the Formula1, i.e. minimum value or value depending of the operator. - When setting the value, it can be passed in as a Date, a Range object, or a string formula (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). - When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. + * Specifies the right-hand operand when the operator property is set to a binary operator such as GreaterThan (the left-hand operand is the value the user tries to enter in the cell). With the ternary operators Between and NotBetween, specifies the lower bound operand. + * When setting the value, it can be passed in as a Date, a Range object, or a string formula (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). + * When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. * * [Api set: ExcelApi 1.8] */ formula1: string | Date | Range; /** * - * Gets or sets the Formula2, i.e. maximum value or value depending of the operator. - When setting the value, it can be passed in as a Date, a Range object, or a string (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). - When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. + * With the ternary operators Between and NotBetween, specifies the upper bound operand. Is not used with the binary operators, such as GreaterThan. + * When setting the value, it can be passed in as a Date, a Range object, or a string (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). + * When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. * * [Api set: ExcelApi 1.8] */ From 7ea37092f0ef3fea36ce5730a02e468ff9abf91a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20D=C3=BCfel?= Date: Thu, 29 Nov 2018 00:03:42 +0100 Subject: [PATCH 419/836] Callbacks have to return Promise --- types/bull/bull-tests.tsx | 8 ++- types/bull/index.d.ts | 121 +++++++++++--------------------------- 2 files changed, 40 insertions(+), 89 deletions(-) diff --git a/types/bull/bull-tests.tsx b/types/bull/bull-tests.tsx index dd484ce1d1..46c146272e 100644 --- a/types/bull/bull-tests.tsx +++ b/types/bull/bull-tests.tsx @@ -98,11 +98,17 @@ const pdfQueue = new Queue('pdf transcoding', { // ////////////////////////////////////////////////////////////////////////////////// -pdfQueue.process((job) => { +pdfQueue.process((job: Queue.Job) => { // Processors can also return promises instead of using the done callback return Promise.resolve(); }); +async function pfdPromise(job: Queue.Job) { + return Promise.resolve(); +} + +pdfQueue.process(1, pfdPromise); + videoQueue.add({ video: 'http://example.com/video1.mov' }, { jobId: 1 }) .then((video1Job) => { // When job has successfully be placed in the queue the job is returned diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index dd5723f2d2..c08048f1d7 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -12,6 +12,7 @@ // Alec Brunelle // Dan Manastireanu // Kjell-Morten Bratsberg Thorsen +// Christian D. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -342,50 +343,39 @@ declare namespace Bull { * The callback is called everytime a job is placed in the queue. * It is passed an instance of the job as first argument. * + * If the callback signature contains the second optional done argument, + * the callback will be passed a done callback to be called after the job has been completed. * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. - */ - process(callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a processing function for the jobs placed into a given Queue. + * or with a result as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; results, as a second argument to the "completed" event. * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * The callback can also be defined as the string path to a module - * exporting the callback function. Using a path has several advantages: - * - The process is sandboxed so if it crashes it does not affect the worker. - * - You can run blocking code without affecting the queue (jobs will not stall). - * - Much better utilization of multi-core CPUs. - * - Less connections to redis. - * - * A promise must be returned to signal job completion. + * If, however, the callback signature does not contain the done argument, + * a promise must be returned to signal job completion. * If the promise is rejected, the error will be passed as a second argument to the "failed" event. * If it is resolved, its value will be the "completed" event's second argument. */ - process(callback: ((job: Job) => void) | string): Promise; + process(callback: ((job: Job, done: DoneCallback) => void) | ((job: Job) => Promise) | string): void; /** * Defines a processing function for the jobs placed into a given Queue. * * The callback is called everytime a job is placed in the queue. * It is passed an instance of the job as first argument. - * The callback can also be defined as the string path to a module - * exporting the callback function. Using a path has several advantages: - * - The process is sandboxed so if it crashes it does not affect the worker. - * - You can run blocking code without affecting the queue (jobs will not stall). - * - Much better utilization of multi-core CPUs. - * - Less connections to redis. * - * A promise must be returned to signal job completion. + * If the callback signature contains the second optional done argument, + * the callback will be passed a done callback to be called after the job has been completed. + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; results, as a second argument to the "completed" event. + * + * If, however, the callback signature does not contain the done argument, + * a promise must be returned to signal job completion. * If the promise is rejected, the error will be passed as a second argument to the "failed" event. * If it is resolved, its value will be the "completed" event's second argument. * - * @param concurrency Bull will then call you handler in parallel respecting this max number. + * @param concurrency Bull will then call your handler in parallel respecting this maximum value. */ - process(concurrency: number, callback: ((job: Job) => void) | string): Promise; + process(concurrency: number, callback: ((job: Job, done: DoneCallback) => void) | ((job: Job) => Promise) | string): void; /** * Defines a processing function for the jobs placed into a given Queue. @@ -393,35 +383,21 @@ declare namespace Bull { * The callback is called everytime a job is placed in the queue. * It is passed an instance of the job as first argument. * + * If the callback signature contains the second optional done argument, + * the callback will be passed a done callback to be called after the job has been completed. * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. + * or with a result as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; results, as a second argument to the "completed" event. * - * @param concurrency Bull will then call you handler in parallel respecting this max number. - */ - process(concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a named processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * The callback can also be defined as the string path to a module - * exporting the callback function. Using a path has several advantages: - * - The process is sandboxed so if it crashes it does not affect the worker. - * - You can run blocking code without affecting the queue (jobs will not stall). - * - Much better utilization of multi-core CPUs. - * - Less connections to redis. - * - * A promise must be returned to signal job completion. + * If, however, the callback signature does not contain the done argument, + * a promise must be returned to signal job completion. * If the promise is rejected, the error will be passed as a second argument to the "failed" event. * If it is resolved, its value will be the "completed" event's second argument. * * @param name Bull will only call the handler if the job name matches */ // tslint:disable-next-line:unified-signatures - process(name: string, callback: ((job: Job) => void) | string): Promise; + process(name: string, callback: ((job: Job, done: DoneCallback) => void) | ((job: Job) => Promise) | string): void; /** * Defines a processing function for the jobs placed into a given Queue. @@ -429,52 +405,21 @@ declare namespace Bull { * The callback is called everytime a job is placed in the queue. * It is passed an instance of the job as first argument. * + * If the callback signature contains the second optional done argument, + * the callback will be passed a done callback to be called after the job has been completed. * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. + * or with a result as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; results, as a second argument to the "completed" event. * - * @param name Bull will only call the handler if the job name matches - */ - // tslint:disable-next-line:unified-signatures - process(name: string, callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a named processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * The callback can also be defined as the string path to a module - * exporting the callback function. Using a path has several advantages: - * - The process is sandboxed so if it crashes it does not affect the worker. - * - You can run blocking code without affecting the queue (jobs will not stall). - * - Much better utilization of multi-core CPUs. - * - Less connections to redis. - * - * A promise must be returned to signal job completion. + * If, however, the callback signature does not contain the done argument, + * a promise must be returned to signal job completion. * If the promise is rejected, the error will be passed as a second argument to the "failed" event. * If it is resolved, its value will be the "completed" event's second argument. * * @param name Bull will only call the handler if the job name matches - * @param concurrency Bull will then call you handler in parallel respecting this max number. + * @param concurrency Bull will then call your handler in parallel respecting this maximum value. */ - process(name: string, concurrency: number, callback: ((job: Job) => void) | string): Promise; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. - * - * @param name Bull will only call the handler if the job name matches - * @param concurrency Bull will then call you handler in parallel respecting this max number. - */ - process(name: string, concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; + process(name: string, concurrency: number, callback: ((job: Job, done: DoneCallback) => void) | ((job: Job) => Promise) | string): void; /** * Creates a new job and adds it to the queue. From 47a20469245d7c747192ac25ab769e8d23e2b5ac Mon Sep 17 00:00:00 2001 From: Elizabeth Craig Date: Wed, 28 Nov 2018 18:37:23 -0800 Subject: [PATCH 420/836] Add definitions for jju --- types/jju/index.d.ts | 213 ++++++++++++++++++++++++++++++++++++++++ types/jju/jju-tests.ts | 4 + types/jju/tsconfig.json | 23 +++++ types/jju/tslint.json | 1 + 4 files changed, 241 insertions(+) create mode 100644 types/jju/index.d.ts create mode 100644 types/jju/jju-tests.ts create mode 100644 types/jju/tsconfig.json create mode 100644 types/jju/tslint.json diff --git a/types/jju/index.d.ts b/types/jju/index.d.ts new file mode 100644 index 0000000000..46fbf2f77b --- /dev/null +++ b/types/jju/index.d.ts @@ -0,0 +1,213 @@ +// Type definitions for jju 1.4 +// Project: https://github.com/rlidwka/jju +// Definitions by: Elizabeth Craig +// Alex Kocharin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Disabling unified-signatures rule so different documentation can be provided for each signature. +// tslint:disable:unified-signatures + +export interface ParseOptions { + /** + * What to do with reserved keys (default 'ignore'). + * - "ignore" - ignore reserved keys + * - "throw" - throw SyntaxError in case of reserved keys + * - "replace" - replace reserved keys, this is the default JSON.parse behaviour, unsafe + */ + reserved_keys?: 'ignore' | 'throw' | 'replace'; + + /** + * Create object as `Object.create(null)` instead of `{}`. + * - If reserved_keys != 'replace', default is false. + * - If reserved_keys == 'replace', default is true. + * + * It is usually unsafe and not recommended to change this option to false in the last case. + */ + null_prototype?: boolean; + + /** + * Reviver function (follows the JSON spec). This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ + reviver?: (key: any, value: any) => any; + + /** + * Operation mode (default 'json5'). Set to 'json' if you want to throw on non-strict json files. + */ + mode?: 'json5' | 'json' | 'cjson'; +} + +export interface StringifyOptions { + /** + * Output ascii only (default false). + * If this option is enabled, output will not have any characters except 0x20-0x7f. + */ + ascii?: boolean; + + /** + * This option follows JSON specification. + * @default '\t' + */ + indent?: string | number | boolean; + + /** + * Enquoting char. + * - If `mode` is 'json', default is " + * - Otherwise, default is ' + */ + quote?: '"' | "'"; + + /** + * Whether keys quoting in objects is required or not. + * If you want `{"q": 1}` instead of `{q: 1}`, set it to true. + * - If `mode` is 'json', default is true + * - Otherwise, default is false + */ + quote_keys?: boolean; + + /** + * Sort all keys while stringifying. + * By default sort order will depend on implementation--with v8 it's insertion order. + * If set to true, all keys (but not arrays) will be sorted alphabetically. + * You can provide your own sorting function as well. + * @default false + */ + sort_keys?: boolean | ((a: any, b: any) => number); + + /** + * Replacer function or array. This option follows JSON specification. + * If a function, used to transform the results. + * If an array, acts as a approved list for selecting the object properties that will be stringified. + */ + replacer?: ((key: string, value: any) => any) | Array; + + /** + * Don't output trailing comma. If this option is set, arrays like `[1,2,3,]` will never be generated. + * Otherwise they may be generated for pretty printing. + * - If `mode` is JSON, default is true + * - Otherwise, default is false + */ + no_trailing_comma?: boolean; + + /** + * Operation mode. Set it to 'json' if you want correct json in the output. + * If it is 'json', following options are implied: + * - options.quote = '"' + * - options.no_trailing_comma = true + * - options.quote_keys = true + * - '\x' literals are not used + */ + mode?: 'json' | 'json5' | 'cjson'; +} + +/** + * Represents a token in a JSON file. + */ +export interface Token { + /** Raw text of this token. If you join all raws, you will get the original document. */ + raw: string; + /** Type of the token. */ + type: 'whitespace' | 'comment' | 'key' | 'literal' | 'separator' | 'newline'; + /** Path to the current token in the syntax tree. */ + stack: string[]; + /** Value of the token if token is a key or literal. */ + value?: any; +} + +/** + * Object defining a programming style in which the JSON document was written. + */ +export interface JsonStyle { + /** Preferred indentation. */ + indent: string; + /** Preferred newline. */ + newline: string; + /** " or ' depending on which quote is preferred. */ + quote: string; + /** True if unquoted keys were used at least once. */ + quote_keys: boolean; + /** True if input has a whitespace token. */ + has_whitespace: boolean; + /** True if input has a comment token. */ + has_comments: boolean; + /** True if input has a newline token. */ + has_newlines: boolean; + /** True if input has at least one trailing comma. */ + has_trailing_comma: boolean; +} + +/** + * Parse json/json5 text and returns a javascript value it corresponds to. + * @param text Text to parse + * @param options Parser options + */ +export function parse(text: string, options?: ParseOptions): any; +/** + * Compatibility syntax (follows JSON specification). + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ +export function parse(text: string, reviver?: (key: any, value: any) => any): any; + +/** + * Convert javascript value to an appropriate json/json5 text. + * @param value Value to serialize + * @param options Serializer options + */ +export function stringify(value: any, options?: StringifyOptions): string; +/** + * Compatibility syntax (follows JSON specification). + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ +export function stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; +/** + * Compatibility syntax (follows JSON specification). + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ +export function stringify(value: any, replacer?: Array | null, space?: string | number): string; + +/** + * Parse json/json5 text and return an array of tokens it consists of. + * @param text Text to tokenize + * @param options Parser options + */ +export function tokenize(text: string, options?: ParseOptions): Token[]; + +/** + * Parse json/json5 text and try to guess indentation, quoting style, etc. + * @param text Text to analyze + * @param options Parser options + */ +export function analyze(text: string, options?: ParseOptions): JsonStyle; + +/** + * Change json/json5 text, preserving original formatting as much as possible. + * @param text Original text + * @param new_value New value you want to set + * @param options Parser or stringifier options + * + * @example + * // here is your original JSON document: + * var input = '{"foo": "bar", "baz": 123}' + * + * // you need to parse it first: + * var json = jju.parse(input, {mode: 'json'}) + * // json is { foo: 'bar', baz: 123 } + * + * // then you can change it as you like: + * json.foo = 'quux' + * json.hello = 'world' + * + * // then you run an update function to change the original json: + * var output = jju.update(input, json, {mode: 'json'}) + * // output is '{"foo": "quux", "baz": 123, "hello": "world"}' + */ +export function update(text: string, new_value: any, options?: ParseOptions | StringifyOptions): string; diff --git a/types/jju/jju-tests.ts b/types/jju/jju-tests.ts new file mode 100644 index 0000000000..0de4d973b1 --- /dev/null +++ b/types/jju/jju-tests.ts @@ -0,0 +1,4 @@ +import * as jju from 'jju'; + +jju.parse('{}'); // $ExpectType any +jju.stringify({}); // $ExpectType string diff --git a/types/jju/tsconfig.json b/types/jju/tsconfig.json new file mode 100644 index 0000000000..08bb6638c7 --- /dev/null +++ b/types/jju/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", + "jju-tests.ts" + ] +} diff --git a/types/jju/tslint.json b/types/jju/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jju/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 5068c7952765e6d19337c6fedaa58dba6195ff9d Mon Sep 17 00:00:00 2001 From: Elizabeth Craig Date: Wed, 28 Nov 2018 20:29:55 -0800 Subject: [PATCH 421/836] Allow parse and stringify options for update() --- types/jju/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/jju/index.d.ts b/types/jju/index.d.ts index 46fbf2f77b..f8bf96d639 100644 --- a/types/jju/index.d.ts +++ b/types/jju/index.d.ts @@ -192,7 +192,7 @@ export function analyze(text: string, options?: ParseOptions): JsonStyle; * Change json/json5 text, preserving original formatting as much as possible. * @param text Original text * @param new_value New value you want to set - * @param options Parser or stringifier options + * @param options Parser and stringifier options * * @example * // here is your original JSON document: @@ -210,4 +210,4 @@ export function analyze(text: string, options?: ParseOptions): JsonStyle; * var output = jju.update(input, json, {mode: 'json'}) * // output is '{"foo": "quux", "baz": 123, "hello": "world"}' */ -export function update(text: string, new_value: any, options?: ParseOptions | StringifyOptions): string; +export function update(text: string, new_value: any, options?: ParseOptions & StringifyOptions): string; From 12b2403208f432eab01af6d45acd095fdcfb9ea6 Mon Sep 17 00:00:00 2001 From: Jessica Date: Thu, 29 Nov 2018 13:57:50 +0900 Subject: [PATCH 422/836] Simplify css attribute declaration, add jsdoc --- types/styled-components/index.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index ee64b37772..2f3b6b4ec5 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -454,6 +454,11 @@ declare module "react" { // nature of this declaration. // If you are writing this inline you already have access to all the attributes anyway, // no need for the extra indirection. - css?: import(".").CSSIntrinsicAttributeType; // tslint:disable-line whitespace + /** + * If present, this React element will be converted by + * `babel-plugin-styled-components` into a styled component + * with the given css as its styles. + */ + css?: CSSIntrinsicAttributeType; } } From e70908a9cd8d584fcb9374e8a772ee30e13da6aa Mon Sep 17 00:00:00 2001 From: muzea Date: Thu, 29 Nov 2018 13:12:55 +0800 Subject: [PATCH 423/836] fix: lint error --- types/babel__core/babel__core-tests.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/babel__core/babel__core-tests.ts b/types/babel__core/babel__core-tests.ts index eb19bc69b3..ba51ac21be 100644 --- a/types/babel__core/babel__core-tests.ts +++ b/types/babel__core/babel__core-tests.ts @@ -39,4 +39,3 @@ babel.transformFromAstAsync(parsedAst!, sourceCode, options).then(transformFromA const { code, map, ast } = transformFromAstAsyncResult!; const { body } = ast!.program; }); - From f8a55ca2b6d82464c53dccbf01e75971ecdff5c0 Mon Sep 17 00:00:00 2001 From: taoqf Date: Thu, 29 Nov 2018 13:48:15 +0800 Subject: [PATCH 424/836] add definition baidu-app --- types/baidu-app/baidu-app-tests.ts | 2007 ++++++++++++ types/baidu-app/index.d.ts | 4758 ++++++++++++++++++++++++++++ types/baidu-app/tsconfig.json | 24 + types/baidu-app/tslint.json | 7 + 4 files changed, 6796 insertions(+) create mode 100644 types/baidu-app/baidu-app-tests.ts create mode 100644 types/baidu-app/index.d.ts create mode 100644 types/baidu-app/tsconfig.json create mode 100644 types/baidu-app/tslint.json diff --git a/types/baidu-app/baidu-app-tests.ts b/types/baidu-app/baidu-app-tests.ts new file mode 100644 index 0000000000..9987a650ee --- /dev/null +++ b/types/baidu-app/baidu-app-tests.ts @@ -0,0 +1,2007 @@ +(() => { + swan.request({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址 + method: 'GET', + dataType: 'json', + data: { + key: 'value' + }, + header: { + 'content-type': 'application/json' // 默认值 + }, + success(res) { + console.log(res.data); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + const requestTask = swan.request({ + url: 'test.php', // 仅为示例,并非真实的接口地址 + data: { + x: '', + y: '' + }, + header: { + 'content-type': 'application/json' + }, + success(res) { + console.log(res.data); + } + }); + // 取消请求任务 + requestTask.abort(); +})(); + +(() => { + swan.chooseImage({ + success(res) { + swan.uploadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址 + filePath: res.tempFilePaths[0], // 要上传文件资源的路径 + name: 'myfile', + success(res) { + console.log(res.statusCode); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + } + }); +})(); + +(() => { + const uploadTask = swan.uploadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 开发者服务器 url + filePath: '', // res.tempFilePaths[0], // 要上传文件资源的路径 + name: 'myfile', + success(res) { + console.log(res.statusCode); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + uploadTask.onProgressUpdate(res => { + console.log('上传进度', res.progress); + console.log('已经上传的数据长度', res.totalBytesSent); + console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend); + }); + + uploadTask.abort(); // 取消上传任务 +})(); + +(() => { + swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源 + success(res) { + // 下载成功 + if (res.statusCode === 200) { + console.log("临时文件路径" + res.tempFilePath); + } + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const downloadTask = swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源 + success(res) { + console.log(res.tempFilePath); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + downloadTask.onProgressUpdate(res => { + console.log('下载进度', res.progress); + console.log('已经下载的数据长度', res.totalBytesWritten); + console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite); + }); + + downloadTask.abort(); // 取消下载任务 +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen((res) => { + console.log('WebSocket连接已打开!', res.header); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' // 仅为示例,并非真实的服务地址 + }); + swan.onSocketError((res) => { + console.log('WebSocket连接打开失败,请检查!'); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen(() => { + swan.sendSocketMessage({ + data: 'baidu' + }); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen(() => { + swan.sendSocketMessage({ + data: 'baidu' + }); + }); + swan.onSocketMessage((res) => { + console.log('收到服务器内容:', res.data); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com', + success(res) { + swan.closeSocket(); + } + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + + swan.onSocketClose((res) => { + console.log('WebSocket 已关闭!'); + }); + + swan.onSocketOpen(() => { + swan.closeSocket(); + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrIdCard({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrBankCard({ + image, + success(res) { + console.log(res.result.bank_name); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrDrivingLicense({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrVehicleLicense({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); +})(); + +(() => { + swan.ai.textReview({ + content: '', + success(res) { + console.log(res.result.spam); // 0 表示审核通过 + } + }); +})(); + +(() => { + swan.ai.textToAudio({ + ctp: '1', + lan: 'zh', + tex: '这是一段测试文字', + success(res) { + console.log(res.filePath); + } + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.imageAudit({ + image, + success(res) { + console.log(res.conclusionType); // 1 为合规 + } + }); + } + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.advancedGeneralIdentify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.objectDetectIdentify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.carClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.dishClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.logoClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.animalClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.plantClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); +})(); + +(() => { + const voiceRecognizer = swan.ai.getVoiceRecognizer(); + + voiceRecognizer.onStart(() => { + console.log('voice start'); + }); + voiceRecognizer.onRecognize(res => { + console.log('voice recognize', res); + }); + voiceRecognizer.onFinish(res => { + console.log('voice end', res); + }); + voiceRecognizer.onError(err => { + console.log('voice error', err); + }); + + const options = { + mode: 'dnn', + longSpeech: false + }; + + voiceRecognizer.start(options); +})(); + +(() => { + swan.chooseImage({ + count: 1, + sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 + sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 + success(res) { + // 成功则返回图片的本地文件路径列表 tempFilePaths + console.log(res.tempFilePaths); + // 文件列表对象 + console.log(res.tempFiles); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.previewImage({ + current: '', // 当前显示图片的http链接 + urls: [], // 需要预览的图片http链接列表 + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + swan.getImageInfo({ + src: '/xxx/xxx.jpg', + success(res) { + // 成功则返回图片高,宽,本地路径 + console.log(res.width); + console.log(res.height); + console.log(res.path); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + swan.saveImageToPhotosAlbum({ + filePath: '/xxx/xxx.jpg', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const recorderManager = swan.getRecorderManager(); + + recorderManager.onStart(() => { + // 开始录音事件 + console.log('recorder start'); + }); + recorderManager.onPause(() => { + // 暂停录音事件 + console.log('recorder pause'); + }); + recorderManager.onStop((res) => { + // 停止录音事件 + console.log('recorder stop', res); + const { tempFilePath } = res; + }); + + const options = { + duration: 10000, + sampleRate: 44100, + numberOfChannels: 1, + encodeBitRate: 96000, + format: 'aac' + }; + + recorderManager.start(options); +})(); + +(() => { + const backgroundAudioManager = swan.getBackgroundAudioManager(); + + backgroundAudioManager.title = '此时此刻'; + backgroundAudioManager.epname = '此时此刻'; + backgroundAudioManager.singer = '许巍'; + backgroundAudioManager.coverImgUrl = 'xxx'; + backgroundAudioManager.src = 'xxx'; +})(); + +(() => { + const innerAudioContext = swan.createInnerAudioContext(); + innerAudioContext.src = 'xxx'; + innerAudioContext.autoplay = true; + innerAudioContext.seek({ + position: 10 + }); + innerAudioContext.onPlay((res) => { + console.log('开始播放'); + }); +})(); + +(() => { + Page({ + data: { + sourceType: ['album', 'camera'], + compressed: false, + maxDuration: 60, + src: '' + }, + + chooseVideo() { + const self = this; + swan.chooseVideo({ + sourceType: this.getData('sourceType'), + compressed: this.getData('compressed'), + maxDuration: this.getData('maxDuration'), + success(res) { + // 成功返回选定视频的临时文件路径 + self.setData('src', res.tempFilePath); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + } + }); + swan.saveVideoToPhotosAlbum({ + filePath: 'bdfile://xxx', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const myVideo = swan.createVideoContext('myVideo'); + myVideo.play(); +})(); + +(() => { + swan.chooseImage({ + count: 1, + success(res) { + const tempFilePaths = res.tempFilePaths; + swan.saveFile({ + tempFilePath: tempFilePaths[0], + success(res) { + const savedFilePath = res.savedFilePath; + } + }); + } + }); + swan.getFileInfo({ + filePath: 'bdfile://somefile', + success(res) { + console.log(res.size); + console.log(res.digest); + } + }); + swan.getSavedFileList({ + success(res) { + const fileList = res.fileList; + } + }); + swan.getSavedFileInfo({ + filePath: 'bdfile://somefile', + success(res) { + console.log(res.size); + console.log(res.createTime); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.getSavedFileList({ + success(res) { + if (res.fileList.length > 0) { + swan.removeSavedFile({ + filePath: res.fileList[0].filePath, + success(res) { + console.log(res.filePath); + } + }); + } + } + }); +})(); + +(() => { + swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx.pdf', + success(res) { + const filePath = res.tempFilePath; + swan.openDocument({ + filePath, + success(res) { + console.log('打开文档成功'); + } + }); + } + }); +})(); + +(() => { + swan.setStorage({ + key: 'key', + data: 'value' + }); +})(); + +(() => { + try { + swan.setStorageSync('key', 'value'); + } catch (e) { + } + swan.getStorage({ + key: 'key', + success(res) { + console.log(res.data); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + const result = swan.getStorageSync('key'); + } catch (e) { + } + swan.getStorageInfo({ + success(res) { + console.log(res.keys); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + const result = swan.getStorageInfoSync(); + console.log(result); + } catch (e) { + } +})(); + +(() => { + swan.removeStorage({ + key: 'key', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + swan.removeStorageSync('key'); + } catch (e) { + } + try { + swan.clearStorageSync(); + } catch (e) { + } +})(); + +(() => { + swan.getLocation({ + type: 'gcj02', + success(res) { + console.log('纬度:' + res.latitude); + console.log('经度:' + res.longitude); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.getLocation({ + type: 'gcj02', + success(res) { + swan.openLocation({ + latitude: res.latitude, + longitude: res.longitude, + scale: 18 + }); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + let mapContext: swan.MapContext; + Page({ + data: { + latitude: '40.042500', + longitude: '116.274040', + }, + onReady() { + mapContext = swan.createMapContext('myMap'); + }, + getCenterLocation() { + mapContext.getCenterLocation({ + success(res) { + console.log("经度" + res.longitude); + console.log("纬度" + res.latitude); + } + }); + }, + moveToLocation() { + mapContext.moveToLocation(); + }, + translateMarker() { + mapContext.translateMarker({ + markerId: 0, + rotate: 90, + autoRotate: true, + duration: 1000, + destination: { + latitude: 23.10229, + longitude: 113.3345211, + }, + animationEnd() { + console.log('animation end'); + } + }); + }, + includePoints() { + mapContext.includePoints({ + padding: [10], + points: [{ + latitude: 23, + longitude: 113.33, + }, { + latitude: 23, + longitude: 113.3345211, + }] + }); + }, + getRegion() { + mapContext.getRegion({ + success(res) { + console.log("西南角的经纬度" + res.southwest); + console.log("东北角的经纬度" + res.northeast); + } + }); + } + }); +})(); + +(() => { + Page({ + onReady() { + const ctx = this.createCanvasContext('myCanvas'); + ctx.setFillStyle('#ff0000'); + ctx.arc(100, 100, 50, 0, 2 * Math.PI); + ctx.fill(); + ctx.draw(); + } + }); + Page({ + onReady() { + const ctx = this.createCanvasContext('myCanvas'); + } + }); + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('#ff0000'); + ctx.arc(100, 100, 50, 0, 2 * Math.PI); + ctx.fill(); + + ctx.draw(); + + swan.canvasGetImageData({ + canvasId: 'myCanvas', + x: 0, + y: 0, + width: 100, + height: 100, + success(res) { + console.log(res); + } + }); + const data = new Uint8ClampedArray([255, 0, 0, 1]); + swan.canvasPutImageData({ + canvasId: 'myCanvas', + data, + x: 0, + y: 0, + width: 1, + height: 2, + success(res) { + console.log('success'); + } + }); + swan.canvasToTempFilePath({ + x: 100, + y: 200, + width: 50, + height: 50, + destWidth: 100, + destHeight: 100, + canvasId: 'myCanvas', + success(res) { + console.log(res.tempFilePath); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.setShadow(10, 50, 50, 'red'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create linear gradient + const grd = ctx.createLinearGradient(0, 0, 200, 0); + grd.addColorStop(0, 'blue'); + grd.addColorStop(1, 'red'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create circular gradient + const grd = ctx.createCircularGradient(75, 50, 50); + grd.addColorStop(0, 'red'); + grd.addColorStop(1, 'blue'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create circular gradient + const grd = ctx.createLinearGradient(30, 10, 120, 10); + grd.addColorStop(0, 'red'); + grd.addColorStop(0.16, 'orange'); + grd.addColorStop(0.33, 'yellow'); + grd.addColorStop(0.5, 'green'); + grd.addColorStop(0.66, 'cyan'); + grd.addColorStop(0.83, 'blue'); + grd.addColorStop(1, 'purple'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(30, 10); + ctx.lineTo(200, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(5); + ctx.moveTo(50, 30); + ctx.lineTo(200, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.moveTo(70, 50); + ctx.lineTo(200, 50); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.moveTo(90, 70); + ctx.lineTo(200, 70); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(30, 10); + ctx.lineTo(200, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('butt'); + ctx.setLineWidth(10); + ctx.moveTo(50, 30); + ctx.lineTo(200, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('round'); + ctx.setLineWidth(10); + ctx.moveTo(70, 50); + ctx.lineTo(200, 50); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('square'); + ctx.setLineWidth(10); + ctx.moveTo(90, 70); + ctx.lineTo(200, 70); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('bevel'); + ctx.setLineWidth(10); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('round'); + ctx.setLineWidth(10); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('miter'); + ctx.setLineWidth(10); + ctx.moveTo(130, 10); + ctx.lineTo(220, 50); + ctx.lineTo(130, 90); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setLineDash([10, 20], 5); + ctx.beginPath(); + ctx.moveTo(0, 100); + ctx.lineTo(400, 100); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(1); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(2); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(3); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(4); + ctx.moveTo(130, 10); + ctx.lineTo(220, 50); + ctx.lineTo(130, 90); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.rect(30, 30, 150, 75); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setStrokeStyle('blue'); + ctx.strokeRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('red'); + ctx.fillRect(0, 0, 150, 200); + ctx.setFillStyle('blue'); + ctx.fillRect(150, 0, 150, 200); + ctx.clearRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.rect(10, 10, 100, 30); + ctx.setFillStyle('red'); + ctx.fill(); + ctx.beginPath(); + ctx.rect(10, 40, 100, 30); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 70, 100, 30); + ctx.rect(10, 100, 100, 30); + ctx.setFillStyle('green'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.closePath(); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(10, 10); + ctx.lineTo(100, 10); + ctx.moveTo(10, 100); + ctx.lineTo(100, 100); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(10, 10); + ctx.rect(10, 10, 100, 50); + ctx.lineTo(110, 60); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.arc(100, 75, 50, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(10, 10, 25, 15); + ctx.scale(2, 2); + ctx.strokeRect(10, 10, 25, 15); + ctx.scale(2, 2); + ctx.strokeRect(10, 10, 25, 15); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(100, 10, 150, 100); + ctx.rotate(20 * Math.PI / 180); + ctx.strokeRect(100, 10, 150, 100); + ctx.rotate(20 * Math.PI / 180); + ctx.strokeRect(100, 10, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(10, 10, 150, 100); + ctx.translate(20, 20); + ctx.strokeRect(10, 10, 150, 100); + ctx.translate(20, 20); + ctx.strokeRect(10, 10, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + swan.downloadFile({ + url: 'https://b.bdstatic.com/searchbox/icms/searchbox/img/LOGO300x300.jpg', + success(res) { + ctx.save(); + ctx.beginPath(); + ctx.arc(50, 50, 25, 0, 2 * Math.PI); + ctx.clip(); + ctx.drawImage(res.tempFilePath, 25, 25); + ctx.restore(); + ctx.draw(); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFontSize(20); + ctx.fillText('20', 20, 20); + ctx.setFontSize(30); + ctx.fillText('30', 40, 40); + ctx.setFontSize(40); + ctx.fillText('40', 60, 60); + ctx.setFontSize(50); + ctx.fillText('50', 90, 90); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFontSize(20); + ctx.fillText('Hello', 20, 20); + ctx.fillText('World', 100, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setStrokeStyle('red'); + ctx.moveTo(150, 20); + ctx.lineTo(150, 170); + ctx.stroke(); + + ctx.setFontSize(15); + ctx.setTextAlign('left'); + ctx.fillText('textAlign=left', 150, 60); + + ctx.setTextAlign('center'); + ctx.fillText('textAlign=center', 150, 80); + + ctx.setTextAlign('right'); + ctx.fillText('textAlign=right', 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setStrokeStyle('red'); + ctx.moveTo(5, 75); + ctx.lineTo(295, 75); + ctx.stroke(); + + ctx.setFontSize(20); + + ctx.setTextBaseline('top'); + ctx.fillText('top', 5, 75); + + ctx.setTextBaseline('middle'); + ctx.fillText('middle', 50, 75); + + ctx.setTextBaseline('bottom'); + ctx.fillText('bottom', 120, 75); + + ctx.setTextBaseline('normal'); + ctx.fillText('normal', 200, 75); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + swan.chooseImage({ + success(res) { + ctx.drawImage(res.tempFilePaths[0], 0, 0, 150, 100); + ctx.draw(); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFillStyle('red'); + ctx.fillRect(10, 10, 150, 100); + ctx.setGlobalAlpha(0.2); + ctx.setFillStyle('blue'); + ctx.fillRect(50, 50, 150, 100); + ctx.setFillStyle('yellow'); + ctx.fillRect(100, 100, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.font = 'italic bold 20px cursive'; + const metrics = ctx.measureText('Hello World'); + console.log(metrics.width); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + const pattern = ctx.createPattern('/path/to/image', 'repeat-x'); + ctx.fillStyle = pattern; + ctx.fillRect(0, 0, 300, 150); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // Draw quadratic curve + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.bezierCurveTo(20, 100, 200, 100, 200, 20); + ctx.setStrokeStyle('black'); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // Draw quadratic curve + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.quadraticCurveTo(20, 100, 200, 20); + ctx.setStrokeStyle('blue'); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // save the default fill style + ctx.save(); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + + // restore to the previous saved state + ctx.restore(); + ctx.fillRect(50, 50, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // save the default fill style + ctx.save(); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + + // restore to the previous saved state + ctx.restore(); + ctx.fillRect(50, 50, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + ctx.draw(); + ctx.fillRect(30, 30, 150, 100); + ctx.draw(); +})(); + +(() => { + swan.showToast({ + title: '我是标题', + icon: 'loading', + duration: 1000, + }); + swan.showLoading({ + title: '加载中', + mask: 'true' + }); + + setTimeout(() => { + swan.hideLoading(); + }, 2000); + + swan.showModal({ + title: '提示', + content: '这是一个模态弹窗', + cancelColor: '#999999', + confirmColor: '#0099cc', + success(res) { + if (res.confirm) { + console.log('用户点击了确定'); + } else if (res.cancel) { + console.log('用户点击了取消'); + } + } + }); + swan.showActionSheet({ + itemList: ['同意', '一般', '不同意'], + success(res) { + console.log(`用户点击了第${(res.tapIndex + 1)}个按钮`); + } + }); +})(); + +(() => { + swan.setNavigationBarTitle({ + title: '我是页面标题' + }); + swan.setNavigationBarColor({ + frontColor: '#ffffff', + backgroundColor: '#ff0000', + animation: { + duration: 500, + timingFunc: 'linear' + } + }); +})(); + +(() => { + swan.setTabBarBadge({ + index: 0, + text: '文本' + }); + swan.removeTabBarBadge({ + index: 0 + }); + swan.showTabBarRedDot({ + index: 0 + }); + swan.hideTabBarRedDot({ + index: 0 + }); + swan.setTabBarStyle({ + color: '#FFFFBD', + selectedColor: '#FFFFBD', + backgroundColor: '#FFFFBD', + borderStyle: 'white' + }); + swan.setTabBarItem({ + index: 0, + text: '文本', + // 图片路径 + iconPath: '/images/component_normal.png', + // 选中图片路径 + selectedIconPath: '/images/component_selected.png', + }); + swan.showTabBar({ + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + swan.hideTabBar({ + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.navigateTo({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); + swan.redirectTo({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); + swan.switchTab({ + url: '/list', + }); + // 注意:调用 navigateTo 跳转时,调用页面会被加入堆栈,而 redirectTo 方法则不会。见下方示例代码 + + // 当前是首页 + swan.navigateTo({ + url: 'list?key=value' + }); + + // 当前是列表页 + swan.navigateTo({ + url: 'detail?key=value' + }); + + // 在详情页内 navigateBack,将返回首页 + swan.navigateBack({ + delta: 2 + }); + swan.reLaunch({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); +})(); + +(() => { + const animation = swan.createAnimation({ + transformOrigin: "50% 50%", + duration: 1000, + timingFunction: "ease", + delay: 0 + }); + Page({ + data: { + animationData: {} + }, + starttoanimate() { + const animation = swan.createAnimation(); + animation.rotate(90).translateY(10).step(); + animation.rotate(-90).translateY(-10).step(); + this.setData({ + animationData: animation.export() + }); + } + }); +})(); + +(() => { + swan.pageScrollTo({ + scrollTop: 0, + duration: 300 + }); +})(); + +(() => { + Page({ + onPullDownRefresh() { + // do something + } + }); + swan.startPullDownRefresh(); + swan.stopPullDownRefresh(); +})(); + +(() => { + swan.createIntersectionObserver({} as any, { + selectAll: true + }).relativeTo('.container') + .observe('.ball', res => { + console.log(res.intersectionRect); // 相交区域 + console.log(res.intersectionRect.left); // 相交区域的左边界坐标 + console.log(res.intersectionRect.top); // 相交区域的上边界坐标 + console.log(res.intersectionRect.width); // 相交区域的宽度 + console.log(res.intersectionRect.height); // 相交区域的高度 + }); + Page({ + queryMultipleNodes() { + const query = swan.createSelectorQuery(); + query.select('#the-id').boundingClientRect(); + query.selectViewport().scrollOffset(); + query.exec((res) => { + // res[0].top, // #the-id节点的上边界坐标 + // res[1].scrollTop // 显示区域的竖直滚动位置 + }); + } + }); + Component({ + // queryMultipleNodes() { + // const query = swan.createSelectorQuery().in(this); + // query.select('#the-id').boundingClientRect((res) => { + // // res.top // 这个组件内 #the-id 节点的上边界坐标 + // }).exec(); + // } + }); + Page({ + getRect() { + swan.createSelectorQuery().select('#the-id').boundingClientRect((res) => { + const rect = res as swan.NodesRefRect; + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }).exec(); + }, + getAllRects() { + swan.createSelectorQuery().selectAll('.a-class').boundingClientRect((rects) => { + (rects as swan.NodesRefRect[]).forEach((rect) => { + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }); + }).exec(); + } + }); + Page({ + getScrollOffset() { + swan.createSelectorQuery().selectViewport().scrollOffset((res) => { + res.id; // 节点的ID + res.dataset; // 节点的dataset + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + }).exec(); + } + }); + Page({ + getFields() { + swan.createSelectorQuery().select('#the-id').fields({ + dataset: true, + size: true, + scrollOffset: true, + properties: ['scrollX', 'scrollY'], + computedStyle: ['margin', 'backgroundColor'] + }, (res) => { + res.dataset; // 节点的dataset + res.width; // 节点的宽度 + res.height; // 节点的高度 + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + res.scrollX; // 节点 scroll-x 属性的当前值 + res.scrollY; // 节点 scroll-y 属性的当前值 + // 此处返回指定要返回的样式名 + res.margin; + res.backgroundColor; + }).exec(); + } + }); +})(); + +(() => { + swan.getSystemInfo({ + success(res) { + console.log(res.model); + console.log(res.pixelRatio); + console.log(res.windowWidth); + console.log(res.windowHeight); + console.log(res.language); + console.log(res.version); + console.log(res.platform); + } + }); + try { + const res = swan.getSystemInfoSync(); + console.log(res.model); + console.log(res.pixelRatio); + console.log(res.windowWidth); + console.log(res.windowHeight); + console.log(res.language); + console.log(res.version); + console.log(res.platform); + } catch (e) { + // Do something when catch error + } + try { + const res = swan.getEnvInfoSync(); + console.log(res.appKey); + console.log(res.appName); + console.log(res.lastAppURL); + console.log(res.sdkVersion); + console.log(res.scheme); + } catch (e) { + // Do something when catch error + } + swan.canIUse('view.hover-class'); + swan.canIUse('scroll-view.scroll-x'); + swan.canIUse('cover-view'); + swan.canIUse('button.size.default'); + swan.canIUse('button.size.default'); + swan.canIUse('request.object.success.data'); + swan.canIUse('getSavedFileList'); + swan.canIUse('getSavedFileList.object'); + swan.canIUse('getSavedFileList.object.success'); +})(); + +(() => { + swan.onMemoryWarning((res) => { + console.log('onMemoryWarningReceive'); + }); +})(); + +(() => { + swan.getNetworkType({ + success(res) { + console.log(res.networkType); + } + }); + swan.onNetworkStatusChange((res) => { + console.log(res.isConnected); + console.log(res.networkType); + }); +})(); + +(() => { + swan.onAccelerometerChange((res) => { + console.log(res.x); + console.log(res.y); + console.log(res.z); + }); + swan.startAccelerometer({ + interval: 'ui' + }); + swan.stopAccelerometer(); +})(); + +(() => { + swan.onCompassChange((res) => { + console.log(res.direction); + }); + swan.startCompass(); + swan.stopCompass(); +})(); + +(() => { + swan.scanCode({ + success(res) { + console.log(res.result); + console.log(res.scanType); + } + }); +})(); + +(() => { + swan.onUserCaptureScreen(() => { + console.log('用户截屏了'); + }); +})(); + +(() => { + swan.makePhoneCall({ + phoneNumber: '000000' // 仅为示例,并非真实的电话号码 + }); +})(); + +(() => { + swan.setClipboardData({ + data: 'baidu', + success(res) { + swan.getClipboardData({ + success(res) { + console.log(res.data); // baidu + } + }); + } + }); + swan.getClipboardData({ + success(res) { + console.log(res.data); + } + }); +})(); + +(() => { + swan.getExtConfig({ + success(res) { + console.log(res.extConfig); + } + }); + const data = swan.getExtConfigSync(); + console.log(data.extConfig); +})(); + +(() => { + swan.login({ + success(res) { + swan.request({ + url: 'https://xxx/xxx', // 开发者服务器地址 + data: { + code: res.code + } + }); + }, + fail(err) { + console.log('login fail', err); + } + }); + swan.checkSession({ + success(res) { + console.log('登录态有效'); + swan.getUserInfo({ + success(res) { + console.log('用户名', res.userInfo.nickName); + swan.request({ + url: "https://xxx/decrypt_user_data", // 开发者服务器地址,对 data 进行解密 + data: { + data: res.data, + iv: res.iv + } + }); + } + }); + }, + fail(err) { + console.log('登录态无效'); + swan.login({ + success(res) { + swan.request({ + url: 'https://xxx/xxx', // 开发者服务器地址,用 code 换取 session_key + data: { + code: res.code + } + }); + }, + fail(err) { + console.log('登录失败', err); + } + }); + } + }); + + try { + const result = swan.isLoginSync(); + console.log('isLoginSync', result); + } catch (e) { + console.log('error', e); + } +})(); + +(() => { + swan.authorize({ + scope: 'scope.userLocation', + success(res) { + // 用户已经同意智能小程序使用定位功能 + swan.getLocation(); + } + }); +})(); + +(() => { + swan.getSwanId({ + success(res) { + console.log(res.data.swanid); + } + }); + swan.getUserInfo({ + success(res) { + console.log('用户名', res.userInfo.nickName); + } + }); +})(); + +(() => { + swan.openSetting({ + success(res) { + console.log(res.authSetting['scope.userInfo']); + console.log(res.authSetting['scope.userLocation']); + } + }); + swan.getSetting({ + success(res) { + console.log(res.authSetting['scope.userInfo']); + console.log(res.authSetting['scope.userLocation']); + } + }); +})(); + +(() => { + Page({ + onShareAppMessage() { + return { + title: '智能小程序示例', + content: '世界很复杂,百度更懂你', + path: '/pages/openShare/openShare?key=value' + }; + } + }); + swan.openShare({ + title: '智能小程序示例', + content: '世界很复杂,百度更懂你', + path: '/pages/openShare/openShare?key=value' + }); +})(); + +(() => { + swan.chooseAddress({ + success(res) { + console.log(res.userName); + console.log(res.postalCode); + console.log(res.provinceName); + console.log(res.cityName); + console.log(res.countyName); + console.log(res.detailInfo); + console.log(res.telNumber); + } + }); +})(); + +(() => { + swan.requestPolymerPayment({ + orderInfo: { + dealId: "470193086", + appKey: "MMMabc", + totalAmount: "1", + tpOrderId: "3028903626", + dealTitle: "智能小程序Demo支付测试", + signFieldsRange: 1, + rsaSign: '', + bizInfo: '' + }, + success(res) { + swan.showToast({ + title: '支付成功', + icon: 'success' + }); + }, + fail(err) { + swan.showToast({ + title: JSON.stringify(err) + }); + console.log('pay fail', err); + } + }); +})(); + +(() => { + swan.chooseInvoiceTitle({ + success(res) { + console.log(res.type); + console.log(res.title); + console.log(res.taxNumber); + console.log(res.companyAddress); + console.log(res.telephone); + console.log(res.bankName); + console.log(res.bankAccount); + } + }); +})(); + +(() => { + swan.navigateToSmartProgram({ + appKey: '4fecoAqgCIUtzIyA4FAPgoyrc4oUc25c', // 要打开的小程序 App Key + path: '', // 打开的页面路径,如果为空则打开首页 + extraData: { + foo: 'baidu' + }, + success(res) { + // 打开成功 + } + }); + swan.navigateBackSmartProgram({ + extraData: { + foo: 'baidu' + }, + success(res) { + // 返回成功 + } + }); +})(); + +(() => { + if (swan.setMetaDescription) { + swan.setMetaDescription({ + content: '当前小程序页面描述信息', + success(res) { + console.log('设置成功'); + }, + fail(res) { + console.log('设置失败'); + }, + complete(res) { + console.log('设置失败'); + } + }); + } + if (swan.setMetaKeywords) { + swan.setMetaKeywords({ + content: '小程序, 关键字', + success(res) { + console.log('设置成功'); + }, + fail(res) { + console.log('设置失败'); + }, + complete(res) { + console.log('设置失败'); + } + }); + } + if (swan.setDocumentTitle) { + swan.setDocumentTitle({ + title: '我是页面标题' + }); + } +})(); + +(() => { + swan.loadSubPackage({ + root: 'subpackage', + success(res) { + console.log('下载成功', res); + }, + fail(err) { + console.log('下载失败', err); + } + }); +})(); + +(() => { + const updateManager = swan.getUpdateManager(); + + updateManager.onCheckForUpdate((res) => { + // 请求完新版本信息的回调 + console.log(res.hasUpdate); + }); + + updateManager.onUpdateReady((res) => { + swan.showModal({ + title: '更新提示', + content: '新版本已经准备好,是否重启应用?', + success(res) { + if (res.confirm) { + // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 + updateManager.applyUpdate(); + } + } + }); + }); + + updateManager.onUpdateFailed((res) => { + // 新的版本下载失败 + }); +})(); + +(() => { + // 打开调试 + swan.setEnableDebug({ + enableDebug: true + }); + + // 关闭调试 + swan.setEnableDebug({ + enableDebug: false + }); +})(); + +(() => { + swan.reportAnalytics('purchase', { + price: 120, + color: 'red' + }); +})(); diff --git a/types/baidu-app/index.d.ts b/types/baidu-app/index.d.ts new file mode 100644 index 0000000000..244e9dd473 --- /dev/null +++ b/types/baidu-app/index.d.ts @@ -0,0 +1,4758 @@ +// Type definitions for swan-app 2.2 +// Project: https://smartprogram.baidu.com/docs/develop/tutorial/codedir/ +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.8 + +declare namespace swan { + // #region 基本参数 + interface DataResponse { + /** 回调函数返回的内容 */ + data: string | ArrayBuffer; + statusCode: number; + header: any; + result: string; + } + interface ErrMsgResponse { + /** 成功:ok,错误:详细信息 */ + errMsg: "ok" | string; + } + interface TempFileResponse { + /** 文件的临时路径 */ + tempFilePath: string; + /** 开发者服务器返回的 HTTP 状态码 */ + statusCode: number; + } + interface BaseOptions { + /** 接口调用成功的回调函数 */ + success?(res: R): void; + /** 接口调用失败的回调函数 */ + fail?(res: E): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(res: any): void; + } + interface ErrCodeResponse { + errCode: number; + } + // #endregion + // #region 网络API列表 + // 发起请求 + interface RequestHeader { + [key: string]: string; + } + interface RequestOptions extends BaseOptions { + /** 开发者服务器接口地址 */ + url: string; + /** 请求的参数 */ + data?: string | object; + /** 设置请求的 header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: + | "GET" + | "OPTIONS" + | "GET" + | "HEAD" + | "POST" + | "PUT" + | "DELETE"; + /** 如果设为json,会尝试对返回的数据做一次 JSON.parse 默认值为json */ + dataType?: string; + /** + * 设置响应的数据类型。合法值:text、arraybuffer 默认值为text + * @version 1.7.0 + */ + responseType?: string; + /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ + success?(res: DataResponse): void; + fail?(err: { errCode: number; errMsg: string; }): void; + } + /** + * swan.request发起的是https请求。一个微信小程序,同时只能有5个网络请求连接。 + */ + function request(options: RequestOptions): RequestTask; + + /** + * 返回一个 requestTask 对象,通过 requestTask,可中断请求任务。 + */ + interface RequestTask { + abort(): void; + } + + interface UploadTask { + /** + * 监听上传进度变化 + * @version 1.4.0 + */ + onProgressUpdate( + callback?: ( + res: { + /** 上传进度百分比 */ + progress: number; + /** 已经上传的数据长度,单位 Bytes */ + totalBytesSent: number; + /** 预期需要上传的数据总长度,单位 Bytes */ + totalBytesExpectedToSend: number; + } + ) => void + ): void; + /** + * 中断下载任务 + * @version 1.4.0 + */ + abort(): void; + } + // 上传下载 + interface UploadFileOptions extends BaseOptions { + /** 开发者服务器 url */ + url: string; + /** 要上传文件资源的路径 */ + filePath: string; + /** 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ + name: string; + /** HTTP 请求 Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** HTTP 请求中其他额外的 form data */ + formData?: any; + } + interface UploadFileResponse { + data: string; // 开发者服务器返回的数据 + statusCode: number; // 开发者服务器返回的 HTTP 状态码 + } + /** + * 将本地资源上传到开发者服务器。 + * 如页面通过 swan.chooseImage 等接口获取到一个本地资源的临时文件路径后, + * 可通过此接口将本地资源上传到指定服务器。 + * 客户端发起一个 HTTPS POST 请求, + * 其中 Content-Type 为 multipart/form-data 。 + */ + function uploadFile(options: UploadFileOptions): UploadTask; + interface DownloadTask { + /** + * 监听下载进度变化 + * @version 1.4.0 + */ + onProgressUpdate( + callback?: ( + res: { + /** 下载进度百分比 */ + progress: number; + /** 已经下载的数据长度,单位 Bytes */ + totalBytesWritten: number; + /** 预期需要下载的数据总长度,单位 Bytes */ + totalBytesExpectedToWrite: number; + } + ) => void + ): void; + /** + * 中断下载任务 + * @version 1.4.0 + */ + abort(): void; + } + interface DownloadFileOptions extends BaseOptions { + /** 下载资源的 url */ + url: string; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 下载文件资源到本地。客户端直接发起一个 HTTP GET 请求, + * 把下载到的资源根据 type 进行处理,并返回文件的本地临时路径。 + */ + function downloadFile(options: DownloadFileOptions): DownloadTask; + // WebSocket + interface ConnectSocketOptions extends BaseOptions { + /** 开发者服务器接口地址,必须是 HTTPS 协议,且域名必须是后台配置的合法域名 */ + url: string; + /** HTTP Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认是GET,有效值为: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: string; + /** + * 子协议数组 + * @version 1.4.0 + */ + protocols?: string[]; + } + /** + * 创建一个 WebSocket 连接; + * 一个微信小程序同时只能有一个 WebSocket 连接, + * 如果当前已存在一个 WebSocket 连接, + * 会自动关闭该连接,并重新创建一个 WebSocket 连接。 + */ + function connectSocket(options: ConnectSocketOptions): void; + /** 监听WebSocket连接打开事件。 */ + function onSocketOpen(callback: (res: any) => void): void; + /** 监听WebSocket错误。 */ + function onSocketError(callback: (error: any) => void): void; + interface SendSocketMessageOptions extends BaseOptions { + /** 需要发送的内容 */ + data: string | ArrayBuffer; + } + /** + * 通过 WebSocket 连接发送数据,需要先 swan.connectSocket, + * 并在 swan.onSocketOpen 回调之后才能发送。 + */ + function sendSocketMessage(options: SendSocketMessageOptions): void; + /** + * 监听WebSocket接受到服务器的消息事件。 + */ + function onSocketMessage(callback: (res: DataResponse) => void): void; + /** + * 关闭WebSocket连接。 + */ + interface CloseSocketOptions extends BaseOptions { + code?: number; // 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭) 1.4.0 + reason?: string; // 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符) + } + + /** + * 关闭WebSocket连接。 + */ + function closeSocket(options?: CloseSocketOptions): void; + /** 监听WebSocket关闭。 */ + function onSocketClose(callback: (res: any) => void): void; + /** + * 在接入AI之前需要使用管理员权限操作详细情况官网 + * https://smartprogram.baidu.com/docs/develop/api/ai/ + */ + // #region AI + namespace ai { + /** + * 用户向服务请求识别身份证,身份证识别包括正面和背面。 + */ + interface ocrIdCardOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true; false: 不检测旋转角度,默认不检测。 + id_card_side?: string; // front:身份证含照片的一面;back:身份证带国徽的一面。 + detect_risk?: boolean; // 是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)功能,默认不开启,即:false。可选值:true-开启;false-不开启。 + success?(res: ocrIdCardResponse): void; + } + /** + * 识别银行卡并返回卡号、发卡行和卡片类型。 + */ + interface ocrBankCardOptions extends BaseOptions { + image: string; // 图片资源地址 + success?(res: ocrBankCardResponse): void; + } + /** + * 对机动车驾驶证所有关键字段进行识别。 + */ + interface ocrDrivingLicenseOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true;false:不检测旋转角度,默认不检测。 + unified_valid_period?: boolean; // true: 归一化格式输出;false 或无此参数按非归一化格式输出。 + success?(res: ocrDrivingLicenseResponse): void; + } + /** + * 对机动车行驶证正本所有关键字段进行识别 + */ + interface ocrVehicleLicenseOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true; false:不检测旋转角度,默认不检测。 + accuracy?: string; // normal 使用快速服务,1200ms左右时延;缺省或其它值使用高精度服务,1600ms左右时延。 + success?(res: ocrVehicleLicenseResponse): void; + } + interface ocrIdCardResponse { + direction: number; // 图像方向,当 detect_direction=true 时存在。-1: 未定义,0: 正向,1: 逆时针90度,2: 逆时针180度,3: 逆时针270度。 + image_status: string; // normal-识别正常;reversed_side-身份证正反面颠倒;non_idcard-上传的图片中不包含身份证;blurred-身份证模糊;other_type_card-其他类型证照;over_exposure-身份证关键字段反光或过曝;unknown-未知状态。 + risk_type: string; // 输入参数 detect_risk = true 时,则返回该字段识别身份证类型: normal-正常身份证;copy-复印件;temporary-临时身份证;screen-翻拍;unknown-其他未知情况。 + edit_tool: string; // 如果参数 detect_risk = true 时,则返回此字段。如果检测身份证被编辑过,该字段指定编辑软件名称,如:Adobe Photoshop CC 2014 (Macintosh),如果没有被编辑过则返回值无此参数。 + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示words_result的元素个数。 + words_result: { // 定位和识别结果 + [key: string]: { + location: { // 位置数组(坐标0点为左上角) + left: number; // 表示定位位置的长方形左上顶点的水平坐标。 + top: number; // 表示定位位置的长方形左上顶点的垂直坐标。 + width: number; // 表示定位位置的长方形的宽度。 + height: number; // 表示定位位置的长方形的高。 + } + words: string; // 识别结果字符串 + } + }; + } + interface ocrBankCardResponse { + log_id: string; // 请求标识码,随机数,唯一。 + result: { // 返回结果 + bank_card_number: string; // 银行卡卡号 + bank_name: string; // 银行名,不能识别时为空 。 + bank_card_type: string; // 银行卡类型,0: 不能识别; 1: 借记卡; 2: 信用卡 。 + }; + } + interface ocrDrivingLicenseResponse { + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示 words_result 的元素个数。 + words_result: { + [key: string]: { words: string }; + }; + } + interface ocrVehicleLicenseResponse { + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示 words_result 的元素个数。 + words_result: { + [key: string]: { words: string }; + }; + } + /** + * 用户向服务请求识别身份证,身份证识别包括正面和背面。 + */ + function ocrIdCard(options: ocrIdCardOptions): void; + /** + * 识别银行卡并返回卡号、发卡行和卡片类型。 + */ + function ocrBankCard(options: ocrBankCardOptions): void; + /** + * 对机动车驾驶证所有关键字段进行识别。 + */ + function ocrDrivingLicense(options: ocrDrivingLicenseOptions): void; + /** + * 对机动车行驶证正本所有关键字段进行识别 + */ + function ocrVehicleLicense(options: ocrVehicleLicenseOptions): void; + /** + * 运用业界领先的深度学习技术,判断一段文本内容是否符合网络发文规范,实现 + * 自动化、智能化的文本审核。 + */ + interface textReviewOptions extends BaseOptions { + content: string; // 待审核文本,UTF-8,不可为空,不超过20000字节。 + success?(res: textReviewResponse): void; + } + interface textReviewResponse { + log_id: string; // 唯一的log id,用于问题定位。 + result: { // 审核结果详情 + spam: number; // 请求中是否包含违禁,0表示非违禁,1表示违禁,2表示建议人工复审 。 + reject: any[]; // 审核未通过的类别列表与详情 + review: any[]; // 待人工复审的类别列表与详情 + pass: Array<{ // 审核通过的类别列表与详情 + label: number; // 请求中的违禁类型 + score: number; // 违禁检测分,范围 0~1,数值从低到高代表风险程度的高低 。 + hit: string[]; // 违禁类型对应命中的违禁词集合,可能为空 。 + }>; + }; + /** + * 违禁labels类型说明: + * 值 说明 + * 1 暴恐违禁 + * 2 文本色情 + * 3 政治敏感 + * 4 恶意推广 + * 5 低俗辱骂 + */ + } + /** + * 运用业界领先的深度学习技术,判断一段文本内容是否符合网络发文规范,实现 + * 自动化、智能化的文本审核。 + */ + function textReview(options: textReviewOptions): void; + /** + * 将文本转换为可以播放的mp3文件。 + */ + interface textToAudioOptions extends BaseOptions { + tex: string; // 合成的文本,使用UTF-8编码,小于512个中文字或者英文数字(文本在百度服务器内转换为GBK后,长度必须小于1024字节)。 + ctp?: string | number; // 客户端类型选择,Web端填写固定值1。 + lan?: string; // 固定值zh。语言选择,目前只有中英文混合模式,填写固定值zh。 + spd?: string; // 语速,取值0-9,默认为5中语速。 + pit?: string; // 音调,取值0-9,默认为5中语调。 + vol?: string; // 音量,取值0-9,默认为5中音量。 + per?: string; // 发音人选择, 0为普通女声,1为普通男生,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女声。 + success?(res: textToAudioResponse): void; + } + interface textToAudioResponse { + filePath: string; + } + /** + * 将文本转换为可以播放的mp3文件。 + */ + function textToAudio(options: textToAudioOptions): void; + /** + * 自定义图像审核。 + */ + interface imageAuditOptions extends BaseOptions { + image: string; // 图像资源地址 + imgUrl?: string; // 网图URL地址,以网图形式请求,图片Url需要做UrlEncode,不能与image并存。 + success?(res: imageAuditResponse): void; + } + interface imageAuditResponse { + log_id: string; // 请求唯一id + conclusion: string; // 审核结果描述,成功才返回,失败不返回。 + conclusionType: number; // 审核结果标识,成功才返回,失败不返回。 + data: imageAuditdata[]; + // 审核项详细信息,响应成功并且conclusion为疑似或不合规时才返回,响应失败或conclusion为合规是不返回。 + } + interface imageAuditdata { + type: number; + msg: number; + probability: number; + stars: imageAuditdata[]; + words: number; + } + /** + * 自定义图像审核。 + */ + function imageAudit(options: imageAuditOptions): void; + /** + * 通用物体及场景识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多个物体及场景标签。 + */ + interface GeneralIdentifyOptions extends BaseOptions { + image: string; // 图像资源地址 + success?(res: GeneralIdentifyResponse): void; + } + interface GeneralIdentifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 返回结果数目,及result数组中的元素个数。 + result: Array<{ // 标签结果数组 + keyword: string; // 图片中的物体或场景名称 + score: number; // 置信度,0-1 + root: string; // 识别结果的上层标签,有部分钱币、动漫、烟酒等tag无上层标签。 + }>; + } + /** + * 通用物体及场景识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多个物体及场景标签。 + */ + function advancedGeneralIdentify(options: GeneralIdentifyOptions): void; + /** + * 用户向服务请求检测图像中的主体位置。 + */ + interface DetectIdentifyOptions extends BaseOptions { + image: string; // 图像资源地址 + with_face?: number; // 如果检测主体是人,主体区域是否带上人脸部分,0-不带人脸区域,其他-带人脸区域,裁剪类需求推荐带人脸,检索/识别类需求推荐不带人脸。默认取1,带人脸。 + success?(res: DetectIdentifyResponse): void; + } + interface DetectIdentifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: { // 裁剪结果 + left: number; // 表示定位位置的长方形左上顶点的水平坐标。 + top: number; // 表示定位位置的长方形左上顶点的垂直坐标。 + width: number; // 表示定位位置的长方形的宽度。 + height: number; // 表示定位位置的长方形的高度。 + }; + } + /** + * 用户向服务请求检测图像中的主体位置。 + */ + function objectDetectIdentify(options: DetectIdentifyOptions): void; + /** + * 用于检测一张车辆图片的具体车型,即对于输入的一张图片(可正常解码,且长 + * 宽比适宜),输出图片的车辆品牌及型号、颜色及年份、位置信息。 + */ + interface carClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + color_result?: string; // 颜色 + top_num?: number; // 返回结果top n,默认5。 + success?(res: carClassifyResponse): void; + } + interface carClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: Array<{ + name: string; // 车型名称,示例:宝马x6 + score: number; // 置信度,示例:0.5321 + year: string; // 年份 + }>; + location_result: { // 车在图片中的位置信息 + left: number; // 左起像素位置 + top: number; // 上起像素位置 + width: number; // 像素宽 + height: number; // 像素高 + }; + } + /** + * 用于检测一张车辆图片的具体车型,即对于输入的一张图片(可正常解码,且长 + * 宽比适宜),输出图片的车辆品牌及型号、颜色及年份、位置信息。 + */ + function carClassify(options: carClassifyOptions): void; + /** + * 用于菜品识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图 + * 片的菜品名称、卡路里信息、置信度。 + */ + interface dishClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + filter_threshold?: number; // 默认0.95,可以通过该参数调节识别效果,降低非菜识别率. + top_num?: number; // 返回结果top n,默认5。 + success?(res: dishClassifyResponse): void; + } + interface dishClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 返回结果数目,及result数组中的元素个数。 + result: Array<{ // 菜品识别结果数组 + name: string; // 菜名,示例:鱼香肉丝。 + calorie: number; // 卡路里,每100g的卡路里含量。 + probability: number; // 识别结果中每一行的置信度值,0-1。 + }>; + } + /** + * 用于菜品识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图 + * 片的菜品名称、卡路里信息、置信度。 + */ + function dishClassify(options: dishClassifyOptions): void; + /** + * 用于检测和识别图片中的品牌 LOGO 信息 + */ + interface logoClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + custom_lib?: boolean; // 是否只检索用户子库,true则只检索用户子库,false(默认)为检索底库+用户子库。 + success?(res: logoClassifyResponse): void; + } + interface logoClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 识别结果数,标识返回结果数目。 + result: Array<{ // 菜品识别结果数组 + type: number; // type=0 为1千种高优商标识别结果;type=1 为2万类logo库的结果;其它type为自定义logo库结果。 + name: number; // 识别的品牌名称 + probability: number; // 分类结果置信度(0–1.0) + location: { + left: number; // 左起像素位置 + top: number; // 上起像素位置 + width: number; // 像素宽 + height: number; // 像素高 + }; // 位置信息(左起像素位置、上起像素位置、像素宽、像素高) + }>; + } + /** + * 用于检测和识别图片中的品牌 LOGO 信息 + */ + function logoClassify(options: logoClassifyOptions): void; + /** + * 用于检测和识别图片中的动物信息 + */ + interface animalClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + top_num?: number; // 返回预测得分top结果数,默认为6 + success?(res: animalClassifyResponse): void; + } + interface animalClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 识别结果数,标识返回结果数目。 + result: Array<{ // 菜品识别结果数组 + name: number; // 动物名称,示例:蒙古马。 + score: number; // 置信度,示例:0.5321。 + }>; + } + /** + * 用于检测和识别图片中的动物信息 + */ + function animalClassify(options: animalClassifyOptions): void; + /** + * 用于检测和识别图片中的植物信息 + */ + interface plantClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + success?(res: plantClassifyResponse): void; + } + interface plantClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: Array<{ // 菜品识别结果数组 + name: number; // 植物名称,示例:吉娃莲。 + score: number; // 置信度,示例:0.5321。 + }>; + } + /** + * 用于检测和识别图片中的植物信息 + */ + function plantClassify(options: plantClassifyOptions): void; + + /** + * 获取全局唯一的语音识别器voiceRecognizer。 + */ + interface VoiceRecognizerStart { + mode?: string; // 听音模式,有效值dnn/touch + longSpeech?: boolean; // 是否开启长语音 + context?: string; // 语音识别所用的场景值,有效值见下表格。 + } + interface VoiceRecognizeResponse { + result: string; // 小程序语音识别过程中的返回内容 + } + interface VoiceErrorResponse { + result: string; // 小程序语音识别过程中的返回内容 + } + interface VoiceRecognizerTask { + start(options: VoiceRecognizerStart): void; // 开始; + stop(): void; // 停止; + cancel(): void; // 取消; + onStart(callback: () => void): void; // 引擎准备就绪,可以开始说话; + onRecognize(callback: (res: VoiceRecognizeResponse) => void): void; // ;有识别结果返回 + onFinish(callback: (res: DataResponse) => void): void; // 识别完成; + onError(callback: (res: VoiceErrorResponse) => void): void; // 识别遇到错;误 + } + /** + * 获取全局唯一的语音识别器voiceRecognizer。 + */ + function getVoiceRecognizer(): VoiceRecognizerTask; + } + // #endregion + + // #endregion + // #region 媒体API列表 + // 媒体-----图片 + type ImageSizeType = "original" | "compressed"; + type ImageSourceType = "album" | "camera"; + type VideoSourceType = "album" | "camera"; + type CameraDevice = "front" | "back"; + interface TempFile { + /** 本地文件路径 */ + path: string; + /** 本地文件大小,单位:B */ + size: number; + } + interface TempFilesData { + /** 文件的临时路径 */ + tempFilePaths: string; + /** + * 图片的本地文件列表,每一项是一个 File 对象 + * @version 1.2.0 + */ + tempFiles: TempFile[]; + } + interface ChooseImageOptions extends BaseOptions { + /** 最多可以选择的图片张数,默认9 */ + count?: number; + /** original 原图,compressed 压缩图,默认二者都有 */ + sizeType?: ImageSizeType[]; + /** album 从相册选图,camera 使用相机,默认二者都有 */ + sourceType?: ImageSourceType[]; + /** 成功则返回图片的本地文件路径列表 tempFilePaths */ + success(res: TempFilesData): void; + } + /** + * 从本地相册选择图片或使用相机拍照。 + */ + function chooseImage(options: ChooseImageOptions): void; + interface PreviewImageOptions extends BaseOptions { + /** 当前显示图片的链接,不填则默认为 urls 的第一张 */ + current?: string; + /** 需要预览的图片链接列表 */ + urls: string[]; + } + /** + * 预览图片。 + */ + function previewImage(options: PreviewImageOptions): void; + interface GetImageInfoOptions extends BaseOptions { + /** + * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 + */ + src: string; + } + /** + * 获取图片信息 + */ + function getImageInfo(options: GetImageInfoOptions): void; + interface SaveImageToPhotosAlbumOptions extends BaseOptions { + /** + * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 + */ + filePath: string; + success(res: { errMsg: string }): void; + } + /** + * 保存图片到系统相册。 + * 需要用户授权 scope.writePhotosAlbum + * @version 1.2.0 + */ + function saveImageToPhotosAlbum(options: SaveImageToPhotosAlbumOptions): void; + // 媒体-----录音 + interface StartRecordAudioOptions extends BaseOptions { + /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 开始录音。当主动调用swan.stopRecord, + * 或者录音超过1分钟时自动结束录音,返回录音文件的临时文件路径。 + * 注:文件的临时路径,在小程序本次启动期间可以正常使用, + * 如需持久保存,需在主动调用swan.saveFile,在小程序下次启动时才能访问得到。 + * @deprecated 1.6.0 + */ + function startRecord(options: StartRecordAudioOptions): void; + + interface StopRecordAudioOptions extends BaseOptions { + success?(res: TempFileResponse): void; + } + /** + * 主动调用停止录音。 + */ + function stopRecord(options?: StopRecordAudioOptions): void; + type EncodeBitRate = + | 8000 + | 11025 + | 12000 + | 16000 + | 22050 + | 24000 + | 32000 + | 44100 + | 48000; + interface RecorderManagerStartOptions { + /** + * 指定录音的时长,单位 ms + * 如果传入了合法的 duration + * 在到达指定的 duration 后会自动停止录音,最大值 600000(10 分钟),默认值 60000(1 分钟) + */ + duration?: number; + /** + * 采样率,有效值 8000/16000/44100 + */ + sampleRate?: number; + /** + * 否 录音通道数,有效值 1/2 + */ + numberOfChannels?: number; + /** + * 编码码率 + * 采样率和码率有一定要求,具体有效值如下: + * 采样率 编码码率 + * + 8000 16000 ~ 48000 + * + 11025 16000 ~ 48000 + * + 12000 24000 ~ 64000 + * + 16000 24000 ~ 96000 + * + 22050 32000 ~ 128000 + * + 24000 32000 ~ 128000 + * + 32000 48000 ~ 192000 + * + 44100 64000 ~ 320000 + * + 48000 64000 ~ 320000 + */ + encodeBitRate: number; + /** 音频格式,有效值 aac/mp3 */ + format: string; + } + interface OnRecorderManagerStopOptions { + tempFilePath: string; + } + interface OnFrameRecordedOptions { + /** 录音分片结果数据 */ + frameBuffer: ArrayBuffer; + /** 当前帧是否正常录音结束前的最后一帧 */ + isLastFrame: boolean; + } + interface RecorderManager { + /** 开始录音 */ + start(options?: RecorderManagerStartOptions): void; + /** 暂停录音 */ + pause(): void; + /** 继续录音 */ + resume(): void; + /** 停止录音 */ + stop(): void; + /** 录音开始事件 */ + onStart(callback?: () => void): void; + /** 录音暂停事件 */ + onPause(callback?: () => void): void; + /** 录音恢复事件 */ + onResume(callback?: () => void): void; + /** 录音停止事件,会回调文件地址 */ + onStop(callback?: (options: OnRecorderManagerStopOptions) => void): void; + /** 已录制完指定帧大小的文件,会回调录音分片结果数据。如果设置了 frameSize ,则会回调此事件 */ + onFrameRecorded(callback?: (options: OnFrameRecordedOptions) => void): void; + /** 录音错误事件, 会回调错误信息 */ + onError(callback?: (err: ErrMsgResponse) => void): void; + } + /** + * 获取全局唯一的录音管理器 recorderManager + * @version 1.6.0 + */ + function getRecorderManager(): RecorderManager; + // 媒体-----音频播放控制 + interface PlayVoiceOptions extends BaseOptions { + /** 需要播放的语音文件的文件路径 */ + filePath: string; + } + /** + * 开始播放语音,同时只允许一个语音文件正在播放, + * 如果前一个语音文件还没播放完,将中断前一个语音播放。 + * @deprecated 1.6.0 + */ + function playVoice(options: PlayVoiceOptions): void; + /** + * 暂停正在播放的语音。 + * 再次调用swan.playVoice播放同一个文件时,会从暂停处开始播放。 + * 如果想从头开始播放,需要先调用 swan.stopVoice。 + * @deprecated 1.6.0 + */ + function pauseVoice(): void; + /** + * 结束播放语音。 + * @deprecated 1.6.0 + */ + function stopVoice(): void; + // 媒体-----音乐播放控制 + interface BackgroundAudioPlayerState { + /** 选定音频的长度(单位:s),只有在当前有音乐播放时返回 */ + duration: number; + /** 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回 */ + currentPosition: number; + /** 播放状态(2:没有音乐在播放,1:播放中,0:暂停中) */ + status: number; + /** 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回 */ + downloadPercent: number; + /** 歌曲数据链接,只有在当前有音乐播放时返回 */ + dataUrl: string; + } + interface GetBackgroundAudioPlayerStateOptions extends BaseOptions { + /** 接口调用成功的回调函数 */ + success?(state: BackgroundAudioPlayerState): void; + /** 接口调用失败的回调函数 */ + fail?(): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(): void; + } + /** + * 获取音乐播放状态。 + * @deprecated 1.2.0 + */ + function getBackgroundAudioPlayerState( + options: GetBackgroundAudioPlayerStateOptions + ): void; + interface PlayBackgroundAudioOptions extends BaseOptions { + /** 音乐链接 */ + dataUrl: string; + /** 音乐标题 */ + title?: string; + /** 封面URL */ + coverImgUrl?: string; + } + /** + * 播放音乐,同时只能有一首音乐正在播放。 + * @deprecated 1.2.0 + */ + function playBackgroundAudio(options: PlayBackgroundAudioOptions): void; + /** + * 暂停播放音乐。 + * @deprecated 1.2.0 + */ + function pauseBackgroundAudio(options?: PlayBackgroundAudioOptions): void; + interface SeekBackgroundAudioOptions extends BaseOptions { + /** 音乐位置,单位:秒 */ + position: number; + } + /** + * 控制音乐播放进度。 + * @deprecated 1.2.0 + */ + function seekBackgroundAudio(options: SeekBackgroundAudioOptions): void; + /** + * 停止播放音乐。 + * @deprecated 1.2.0 + */ + function stopBackgroundAudio(options?: PlayBackgroundAudioOptions): void; + /** + * 监听音乐播放。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioPlay(callback: () => void): void; + /** + * 监听音乐暂停。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioPause(callback: () => void): void; + /** + * 监听音乐停止。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioStop(callback: () => void): void; + interface BackgroundAudioManager { + /** 当前音频的长度(单位:s),只有在当前有合法的 src 时返回 */ + readonly duration: number; + /** 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回 */ + readonly currentTime: number; + /** 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放 */ + readonly paused: boolean; + /** 音频的数据源,默认为空字符串,当设置了新的 src 时,会自动开始播放 ,目前支持的格式有 m4a, aac, mp3, wav */ + src?: string; + /** 音频开始播放的位置(单位:s) */ + startTime?: number; + /** 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲。 是 */ + buffered: number; + /** 音频标题,用于做原生音频播放器音频标题。原生音频播放器中的分享功能,分享出去的卡片标题,也将使用该值。 */ + title?: string; + /** 专辑名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ + epname?: string; + /** 歌手名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ + singer?: string; + /** 封面图url,用于做原生音频播放器背景图。原生音频播放器中的分享功能,分享出去的卡片配图及背景也将使用该图。 */ + coverImgUrl?: string; + /** 播放 */ + play(): void; + /** 暂停 */ + pause(): void; + /** 停止 */ + stop(): void; + /** 跳转到指定位置,单位 s */ + seek(position: number): void; + /** 背景音频进入可以播放状态,但不保证后面可以流畅播放 */ + onCanplay(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放事件 */ + onPlay(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频暂停事件 */ + onPause(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频停止事件 */ + onStop(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频自然播放结束事件 */ + onEnded(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放进度更新事件 */ + onTimeUpdate(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放错误事件 */ + onError(callback: (res: ErrCodeResponse) => void): void; + /** 音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 */ + onWaiting(callback: (res: ErrCodeResponse) => void): void; + } + /** + * 获取全局唯一的背景音频管理器 backgroundAudioManager。 + * @version 1.2.0 + */ + function getBackgroundAudioManager(): BackgroundAudioManager; + // 媒体-----音频组件控制 + /** + * audioContext 通过 audioId 跟一个

{ } diff --git a/types/react-leaflet-markercluster/react-leaflet-markercluster-tests.tsx b/types/react-leaflet-markercluster/react-leaflet-markercluster-tests.tsx new file mode 100644 index 0000000000..9fc901c527 --- /dev/null +++ b/types/react-leaflet-markercluster/react-leaflet-markercluster-tests.tsx @@ -0,0 +1,30 @@ +import * as React from 'react'; +import * as Leaflet from 'leaflet'; +import MarkerClusterGroup from 'react-leaflet-markercluster'; + +const MarkerCluster = ( + Leaflet.divIcon({ html: `${cluster.getChildCount()}` }) }/> +); diff --git a/types/react-leaflet-markercluster/tsconfig.json b/types/react-leaflet-markercluster/tsconfig.json new file mode 100644 index 0000000000..071c9c734d --- /dev/null +++ b/types/react-leaflet-markercluster/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-leaflet-markercluster-tests.tsx" + ] +} diff --git a/types/react-leaflet-markercluster/tslint.json b/types/react-leaflet-markercluster/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-leaflet-markercluster/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 2437acbc1cad793b1596fc0e3e5ed5318b0a8da9 Mon Sep 17 00:00:00 2001 From: IanStorm Date: Mon, 19 Nov 2018 19:33:40 +0100 Subject: [PATCH 101/836] Generated required package structure by running `dts-gen --dt` --- types/list-stream/index.d.ts | 39 ++++++++++++++++++++++++++ types/list-stream/list-stream-tests.ts | 0 types/list-stream/tsconfig.json | 22 +++++++++++++++ types/list-stream/tslint.json | 1 + 4 files changed, 62 insertions(+) create mode 100644 types/list-stream/index.d.ts create mode 100644 types/list-stream/list-stream-tests.ts create mode 100644 types/list-stream/tsconfig.json create mode 100644 types/list-stream/tslint.json diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts new file mode 100644 index 0000000000..f331fcf838 --- /dev/null +++ b/types/list-stream/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for list-stream 1.0 +// Project: https://github.com/rvagg/list-stream +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/*~ If this module is a UMD module that exposes a global variable 'myLib' when + *~ loaded outside a module loader environment, declare that global here. + *~ Otherwise, delete this declaration. + */ +export as namespace myLib; + +/*~ If this module has methods, declare them as functions like so. + */ +export function myMethod(a: string): string; +export function myOtherMethod(a: number): number; + +/*~ You can declare types that are available via importing the module */ +export interface someType { + name: string; + length: number; + extras?: string[]; +} + +/*~ You can declare properties of the module using const, let, or var */ +export const myField: number; + +/*~ If there are types, properties, or methods inside dotted names + *~ of the module, declare them inside a 'namespace'. + */ +export namespace subProp { + /*~ For example, given this definition, someone could write: + *~ import { subProp } from 'yourModule'; + *~ subProp.foo(); + *~ or + *~ import * as yourMod from 'yourModule'; + *~ yourMod.subProp.foo(); + */ + export function foo(): void; +} \ No newline at end of file diff --git a/types/list-stream/list-stream-tests.ts b/types/list-stream/list-stream-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/list-stream/tsconfig.json b/types/list-stream/tsconfig.json new file mode 100644 index 0000000000..ce92e0529c --- /dev/null +++ b/types/list-stream/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "list-stream-tests.ts" + ] +} diff --git a/types/list-stream/tslint.json b/types/list-stream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/list-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 4b09a1e10024bbf4852f6b210066dae080fc39f8 Mon Sep 17 00:00:00 2001 From: IanStorm Date: Mon, 19 Nov 2018 19:35:07 +0100 Subject: [PATCH 102/836] Editing author information --- types/list-stream/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts index f331fcf838..4024bd51ee 100644 --- a/types/list-stream/index.d.ts +++ b/types/list-stream/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for list-stream 1.0 // Project: https://github.com/rvagg/list-stream -// Definitions by: My Self +// Definitions by: IanStorm // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /*~ If this module is a UMD module that exposes a global variable 'myLib' when From 1074143fd85b1e4e1cc17b8ace89cf2c9c8a5b07 Mon Sep 17 00:00:00 2001 From: IanStorm Date: Mon, 19 Nov 2018 20:34:19 +0100 Subject: [PATCH 103/836] Added actual type definition and tests --- types/list-stream/index.d.ts | 47 ++++++++++---------------- types/list-stream/list-stream-tests.ts | 37 ++++++++++++++++++++ 2 files changed, 55 insertions(+), 29 deletions(-) diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts index 4024bd51ee..8b97483cdb 100644 --- a/types/list-stream/index.d.ts +++ b/types/list-stream/index.d.ts @@ -3,37 +3,26 @@ // Definitions by: IanStorm // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/*~ If this module is a UMD module that exposes a global variable 'myLib' when - *~ loaded outside a module loader environment, declare that global here. - *~ Otherwise, delete this declaration. - */ -export as namespace myLib; +/// -/*~ If this module has methods, declare them as functions like so. - */ -export function myMethod(a: string): string; -export function myOtherMethod(a: number): number; -/*~ You can declare types that are available via importing the module */ -export interface someType { - name: string; - length: number; - extras?: string[]; +import { Duplex, DuplexOptions } from "stream"; + +declare namespace ListStream { } -/*~ You can declare properties of the module using const, let, or var */ -export const myField: number; +declare class ListStream extends Duplex { + constructor(callback?: (err: Error, data: any[]) => void); + constructor(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void); -/*~ If there are types, properties, or methods inside dotted names - *~ of the module, declare them inside a 'namespace'. - */ -export namespace subProp { - /*~ For example, given this definition, someone could write: - *~ import { subProp } from 'yourModule'; - *~ subProp.foo(); - *~ or - *~ import * as yourMod from 'yourModule'; - *~ yourMod.subProp.foo(); - */ - export function foo(): void; -} \ No newline at end of file + static obj(callback?: (err: Error, data: any[]) => void): ListStream; + static obj(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream; + + append(chunk: any): void; + duplicate(): ListStream; + end(): void; + get(index: number): any; + length: number; +} + +export = ListStream; diff --git a/types/list-stream/list-stream-tests.ts b/types/list-stream/list-stream-tests.ts index e69de29bb2..aefb41bf0c 100644 --- a/types/list-stream/list-stream-tests.ts +++ b/types/list-stream/list-stream-tests.ts @@ -0,0 +1,37 @@ +import * as ListStream from "list-stream"; + +let chunk: any = "chunk"; +let listStream: ListStream; +let num: number = 1; + +listStream = new ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream.obj((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); + +listStream.append(chunk); + +listStream = listStream.duplicate(); + +listStream.end(); + +chunk = listStream.get(num); + +num = listStream.length; From 8bd0adc2267e15543719193222ccf5d202234646 Mon Sep 17 00:00:00 2001 From: IanStorm Date: Mon, 19 Nov 2018 20:46:35 +0100 Subject: [PATCH 104/836] Added `strictFunctionTypes` inside `tsconfig.json` as required for Merge Request --- types/list-stream/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/types/list-stream/tsconfig.json b/types/list-stream/tsconfig.json index ce92e0529c..52ec1c73e1 100644 --- a/types/list-stream/tsconfig.json +++ b/types/list-stream/tsconfig.json @@ -7,6 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" From 0ee6ec5d83ce1b1be83a95f67674afc39998d871 Mon Sep 17 00:00:00 2001 From: IanStorm Date: Mon, 19 Nov 2018 21:04:02 +0100 Subject: [PATCH 105/836] Fixed issues raised by `npm test`: * `no-consecutive-blank-lines` * `no-inferrable-types` --- types/list-stream/index.d.ts | 1 - types/list-stream/list-stream-tests.ts | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts index 8b97483cdb..226d4c09ab 100644 --- a/types/list-stream/index.d.ts +++ b/types/list-stream/index.d.ts @@ -5,7 +5,6 @@ /// - import { Duplex, DuplexOptions } from "stream"; declare namespace ListStream { diff --git a/types/list-stream/list-stream-tests.ts b/types/list-stream/list-stream-tests.ts index aefb41bf0c..4b7fc2a6ab 100644 --- a/types/list-stream/list-stream-tests.ts +++ b/types/list-stream/list-stream-tests.ts @@ -2,7 +2,7 @@ import * as ListStream from "list-stream"; let chunk: any = "chunk"; let listStream: ListStream; -let num: number = 1; +let num = 1; listStream = new ListStream((err: Error, data: any[]) => { if (err) { throw err; } From e32a1cd583291d44c2faf36a296007d65db79636 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 19 Nov 2018 22:16:27 +0100 Subject: [PATCH 106/836] Add types for dicer --- types/dicer/dicer-tests.ts | 81 ++++++++++++++++++ types/dicer/index.d.ts | 167 +++++++++++++++++++++++++++++++++++++ types/dicer/tsconfig.json | 23 +++++ types/dicer/tslint.json | 1 + 4 files changed, 272 insertions(+) create mode 100644 types/dicer/dicer-tests.ts create mode 100644 types/dicer/index.d.ts create mode 100644 types/dicer/tsconfig.json create mode 100644 types/dicer/tslint.json diff --git a/types/dicer/dicer-tests.ts b/types/dicer/dicer-tests.ts new file mode 100644 index 0000000000..cd7f7a4251 --- /dev/null +++ b/types/dicer/dicer-tests.ts @@ -0,0 +1,81 @@ +import Dicer = require("dicer"); +import * as fs from "fs"; +import * as stream from "stream"; + +function testDicerSyntax() { + const opts: Dicer.Config = { + boundary: "testing", + }; + const dicer = new Dicer(opts); + const opts2: Dicer.Config = { + headerFirst: true, + maxHeaderPairs: 1, + }; + const opts3: Dicer.Config = { + boundary: "more-testing", + headerFirst: false, + maxHeaderPairs: 8, + }; + dicer.setBoundary("new-testing-boundary"); + dicer.on("part", handleDicerPartStream); + dicer.on("finish", () => { + console.log("dicer parsing finished"); + }); + dicer.on("preamble", part => { + console.log("dicer preamble to new part"); + }); + dicer.on("trailer", data => { + console.log(`dicer trailing data found: ${data.length} bytes`); + }); + dicer.on("close", () => { + console.log("dicer close"); + }); + dicer.on("drain", () => { + console.log("dicer drain"); + }); + dicer.on("error", err => { + console.error(`dicer error: ${err.message || JSON.stringify(err)}`); + }); + dicer.on("finish", () => { + console.log("dicer finish"); + }); + dicer.on("pipe", (src: stream.Readable) => { + console.log("dicer pipe"); + }); + dicer.on("unpipe", (src: stream.Readable) => { + console.log("dicer unpipe"); + }); + const inputFileStream = fs.createReadStream("in-test-file.txt"); + inputFileStream.pipe(dicer); +} +/** + * Handle a part found by a Dicer parser + * + * @param part Part found + */ +function handleDicerPartStream(part: Dicer.PartStream) { + console.log("dicer part found"); + const outputFileStream = fs.createWriteStream("out-test-file.txt"); + part.on("readable", () => { + console.log("part readable"); + }); + part.on("header", header => { + console.log(`part header found:\n${JSON.stringify(header)}`); + }); + part.on("data", () => { + console.log("part data"); + }); + part.on("finish", () => { + console.log("part finished"); + }); + part.on("error", err => { + console.error(`part error: ${err.message || JSON.stringify(err)}`); + }); + part.on("end", () => { + console.log("part ended"); + }); + part.on("close", () => { + console.log("part closed"); + }); + part.pipe(outputFileStream); +} diff --git a/types/dicer/index.d.ts b/types/dicer/index.d.ts new file mode 100644 index 0000000000..319768a2cd --- /dev/null +++ b/types/dicer/index.d.ts @@ -0,0 +1,167 @@ +// Type definitions for dicer 0.2 +// Project: https://github.com/mscdex/dicer +// Definitions by: Robin Goupil +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +/// + +export = Dicer; + +import stream = require("stream"); + +// tslint:disable:unified-signatures + +/** + * A very fast streaming multipart parser for node.js. + * Dicer is a WritableStream + * + * Dicer (special) events: + * - on('finish', ()) - Emitted when all parts have been parsed and the Dicer instance has been ended. + * - on('part', (stream: PartStream)) - Emitted when a new part has been found. + * - on('preamble', (stream: PartStream)) - Emitted for preamble if you should happen to need it (can usually be ignored). + * - on('trailer', (data: Buffer)) - Emitted when trailing data was found after the terminating boundary (as with the preamble, this can usually be ignored too). + */ +declare class Dicer extends stream.Writable { + /** + * Creates and returns a new Dicer instance with the following valid config settings: + * + * @param config The configuration to use + */ + constructor(config: Dicer.Config); + /** + * Sets the boundary to use for parsing and performs some initialization needed for parsing. + * You should only need to use this if you set headerFirst to true in the constructor and are parsing the boundary from the preamble header. + * + * @param boundary The boundary to use + */ + setBoundary(boundary: string): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + addListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + addListener(event: "trailer", listener: (data: Buffer) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "part", listener: (stream: Dicer.PartStream) => void): this; + on(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + on(event: "trailer", listener: (data: Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "part", listener: (stream: Dicer.PartStream) => void): this; + once(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + once(event: "trailer", listener: (data: Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + prependListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + prependListener(event: "trailer", listener: (data: Buffer) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + prependOnceListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + prependOnceListener(event: "trailer", listener: (data: Buffer) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + removeListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + removeListener(event: "trailer", listener: (data: Buffer) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pipe", listener: (src: stream.Readable) => void): this; + removeListener(event: "unpipe", listener: (src: stream.Readable) => void): this; +} + +declare namespace Dicer { + interface Config { + /** + * This is the boundary used to detect the beginning of a new part. + */ + boundary?: string; + /** + * If true, preamble header parsing will be performed first. + */ + headerFirst?: boolean; + /** + * The maximum number of header key=>value pairs to parse Default: 2000 (same as node's http). + */ + maxHeaderPairs?: number; + } + + /** + * PartStream is a _ReadableStream_ + * + * PartStream (special) events: + * - on('header', (header: object)) - An object containing the header for this particular part. Each property value is an array of one or more string values. + */ + interface PartStream extends stream.Readable { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "header", listener: (header: object) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "header", listener: (header: object) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "header", listener: (header: object) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "header", listener: (header: object) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "header", listener: (header: object) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: "header", listener: (header: object) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + } +} diff --git a/types/dicer/tsconfig.json b/types/dicer/tsconfig.json new file mode 100644 index 0000000000..09c2832cb1 --- /dev/null +++ b/types/dicer/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", + "dicer-tests.ts" + ] +} diff --git a/types/dicer/tslint.json b/types/dicer/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dicer/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 75eafa5a64bc327ae8715ac973824d600e563ccd Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 19 Nov 2018 22:36:14 +0100 Subject: [PATCH 107/836] Add types for detect-character-encoding --- .../detect-character-encoding-tests.ts | 10 ++++++++ types/detect-character-encoding/index.d.ts | 17 ++++++++++++++ types/detect-character-encoding/tsconfig.json | 23 +++++++++++++++++++ types/detect-character-encoding/tslint.json | 1 + 4 files changed, 51 insertions(+) create mode 100644 types/detect-character-encoding/detect-character-encoding-tests.ts create mode 100644 types/detect-character-encoding/index.d.ts create mode 100644 types/detect-character-encoding/tsconfig.json create mode 100644 types/detect-character-encoding/tslint.json diff --git a/types/detect-character-encoding/detect-character-encoding-tests.ts b/types/detect-character-encoding/detect-character-encoding-tests.ts new file mode 100644 index 0000000000..42f21a688e --- /dev/null +++ b/types/detect-character-encoding/detect-character-encoding-tests.ts @@ -0,0 +1,10 @@ +import detectCharacterEncoding = require("detect-character-encoding"); + +const buf: Buffer = null as any; + +const result: detectCharacterEncoding.Result | null = detectCharacterEncoding(buf); + +if (result) { + const str: string = result.encoding; + const num: number = result.confidence; +} diff --git a/types/detect-character-encoding/index.d.ts b/types/detect-character-encoding/index.d.ts new file mode 100644 index 0000000000..123a7659eb --- /dev/null +++ b/types/detect-character-encoding/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for detect-character-encoding 0.7 +// Project: https://github.com/sonicdoe/detect-character-encoding#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = detectCharacterEncoding; + +declare function detectCharacterEncoding(buf: Buffer): detectCharacterEncoding.Result | null; + +declare namespace detectCharacterEncoding { + interface Result { + encoding: string; + confidence: number; + } +} diff --git a/types/detect-character-encoding/tsconfig.json b/types/detect-character-encoding/tsconfig.json new file mode 100644 index 0000000000..e2adad72dd --- /dev/null +++ b/types/detect-character-encoding/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", + "detect-character-encoding-tests.ts" + ] +} diff --git a/types/detect-character-encoding/tslint.json b/types/detect-character-encoding/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/detect-character-encoding/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 3ee44a1fedd5bd80235385f24d1149f29425f203 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 19 Nov 2018 20:44:56 +0100 Subject: [PATCH 108/836] Add types for stream-to-string --- types/stream-to-string/index.d.ts | 20 ++++++++++++++++ .../stream-to-string-tests.ts | 15 ++++++++++++ types/stream-to-string/tsconfig.json | 23 +++++++++++++++++++ types/stream-to-string/tslint.json | 1 + 4 files changed, 59 insertions(+) create mode 100644 types/stream-to-string/index.d.ts create mode 100644 types/stream-to-string/stream-to-string-tests.ts create mode 100644 types/stream-to-string/tsconfig.json create mode 100644 types/stream-to-string/tslint.json diff --git a/types/stream-to-string/index.d.ts b/types/stream-to-string/index.d.ts new file mode 100644 index 0000000000..89df48b3ff --- /dev/null +++ b/types/stream-to-string/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for stream-to-string 1.1 +// Project: https://github.com/jasonpincin/stream-to-string +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = streamToString; + +// tslint:disable:unified-signatures + +declare function streamToString(stream: NodeJS.ReadableStream): Promise; +declare function streamToString(stream: NodeJS.ReadableStream, cb: Callback): Promise; +declare function streamToString( + stream: NodeJS.ReadableStream, + enc: string, + cb?: Callback +): Promise; + +type Callback = (error: Error | undefined, str: string) => void; diff --git a/types/stream-to-string/stream-to-string-tests.ts b/types/stream-to-string/stream-to-string-tests.ts new file mode 100644 index 0000000000..3d601a53db --- /dev/null +++ b/types/stream-to-string/stream-to-string-tests.ts @@ -0,0 +1,15 @@ +import streamToString = require("stream-to-string"); + +const stream = (null as any) as NodeJS.ReadableStream; +let convertedString: Promise; + +convertedString = streamToString(stream); +convertedString = streamToString(stream, "hex"); +streamToString(stream, (err, msg) => { + const e: Error | undefined = err; + const str: string = msg; +}); +streamToString(stream, "hex", (err, msg) => { + const e: Error | undefined = err; + const str: string = msg; +}); diff --git a/types/stream-to-string/tsconfig.json b/types/stream-to-string/tsconfig.json new file mode 100644 index 0000000000..81628c9480 --- /dev/null +++ b/types/stream-to-string/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", + "stream-to-string-tests.ts" + ] +} diff --git a/types/stream-to-string/tslint.json b/types/stream-to-string/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/stream-to-string/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 95930ad595d00dd54f4a63628c929181b55cc177 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andi=20P=C3=A4tzold?= Date: Mon, 19 Nov 2018 22:55:47 +0100 Subject: [PATCH 109/836] feat(mailgun-js) add types for email validation --- types/mailgun-js/index.d.ts | 28 ++++++++++++++++++++++++++++ types/mailgun-js/mailgun-js-tests.ts | 25 +++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/types/mailgun-js/index.d.ts b/types/mailgun-js/index.d.ts index 3244639aed..82a75913cf 100644 --- a/types/mailgun-js/index.d.ts +++ b/types/mailgun-js/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for mailgun-js 0.16 // Project: https://github.com/bojand/mailgun-js // Definitions by: Sampson Oliver +// Andi Pätzold // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -126,7 +127,17 @@ declare namespace Mailgun { } interface ValidateResponse { + address: string; + did_you_mean: string | null; + is_disposable_address: boolean; + is_role_address: boolean; is_valid: boolean; + mailbox_verification: "true" | "false" | "unknown" | null; + parts: { + display_name: string | null; + domain: string; + local_part: string; + }; } } @@ -149,6 +160,23 @@ declare namespace Mailgun { address: string, callback?: (error: Error, body: validation.ValidateResponse) => void ): Promise; + validate( + address: string, + isPrivate: boolean, + callback?: (error: Error, body: validation.ValidateResponse) => void + ): Promise; + validate( + address: string, + // tslint:disable-next-line unified-signatures + opts: { [key: string]: any }, + callback?: (error: Error, body: validation.ValidateResponse) => void + ): Promise; + validate( + address: string, + isPrivate: boolean, + opts: { [key: string]: any }, + callback?: (error: Error, body: validation.ValidateResponse) => void + ): Promise; } interface Lists { diff --git a/types/mailgun-js/mailgun-js-tests.ts b/types/mailgun-js/mailgun-js-tests.ts index 8a625bc8ef..e2bef4cab3 100644 --- a/types/mailgun-js/mailgun-js-tests.ts +++ b/types/mailgun-js/mailgun-js-tests.ts @@ -29,3 +29,28 @@ const exampleSendData: mailgunFactory.messages.SendData = { }; mailgun.messages().send(exampleSendData, (err, body) => {}); + +const validationResult1: Promise = + mailgun.validate("foo@mailgun.net"); +const validationResult2: Promise = + mailgun.validate("foo@mailgun.net", (error, body) => {}); +const validationResult3: Promise = + mailgun.validate("foo@mailgun.net", true); +const validationResult4: Promise = + mailgun.validate("foo@mailgun.net", true, (error, body) => {}); +const validationResult5: Promise = + mailgun.validate("foo@mailgun.net", true, { option: "option" }, (error, body) => {}); + +const validationResult6: mailgunFactory.validation.ValidateResponse = { + address: "foo@mailgun.net", + did_you_mean: "bar@mailgun.net", + is_disposable_address: false, + is_role_address: true, + is_valid: true, + mailbox_verification: "true", + parts: { + display_name: "foo", + domain: "mailgun.net", + local_part: "foo" + } +}; From 8e69c7755ddd2a33058b50779d0f2a8d0e4e2b51 Mon Sep 17 00:00:00 2001 From: bangbang93 Date: Tue, 20 Nov 2018 10:38:33 +0800 Subject: [PATCH 110/836] fix typo for "Mock.county" --- types/mockjs/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mockjs/index.d.ts b/types/mockjs/index.d.ts index 9be645b791..25d6cac833 100644 --- a/types/mockjs/index.d.ts +++ b/types/mockjs/index.d.ts @@ -198,7 +198,7 @@ declare namespace mockjs { city(prefix?: B): S; // Random.county - country(prefix?: B): S; + county(prefix?: B): S; // Random.zip zip(prefix?: B): S; From 8ab49bf4cac1baa67375fac46e74d1e20f6a4d88 Mon Sep 17 00:00:00 2001 From: Shingo Sato Date: Tue, 20 Nov 2018 14:17:40 +0900 Subject: [PATCH 111/836] Update react-paginate --- types/react-paginate/index.d.ts | 16 ++- types/react-paginate/react-paginate-tests.tsx | 1 + types/react-paginate/v5/index.d.ts | 126 ++++++++++++++++++ .../v5/react-paginate-tests.tsx | 33 +++++ types/react-paginate/v5/tsconfig.json | 25 ++++ types/react-paginate/v5/tslint.json | 1 + 6 files changed, 197 insertions(+), 5 deletions(-) create mode 100644 types/react-paginate/v5/index.d.ts create mode 100644 types/react-paginate/v5/react-paginate-tests.tsx create mode 100644 types/react-paginate/v5/tsconfig.json create mode 100644 types/react-paginate/v5/tslint.json diff --git a/types/react-paginate/index.d.ts b/types/react-paginate/index.d.ts index 83a03ac838..4b73f0cf14 100644 --- a/types/react-paginate/index.d.ts +++ b/types/react-paginate/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for react-paginate 5.2 +// Type definitions for react-paginate 6.0 // Project: https://github.com/AdeleD/react-paginate // Definitions by: Simon Hartcher // Wouter Hardeman // pegel03 // Simon Archer // Yasunori Ohoka +// Shingo Sato // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -29,22 +30,22 @@ interface ReactPaginateProps { /** * Label for the `previous` button. */ - previousLabel?: string | JSX.Element; + previousLabel?: React.ReactNode; /** * Label for the `next` button. */ - nextLabel?: string | JSX.Element; + nextLabel?: React.ReactNode; /** * Label for ellipsis. */ - breakLabel?: string | JSX.Element; + breakLabel?: string | React.ReactNode; /** * The classname on tag `li` of the ellipsis element. */ - breakClassName?: string | JSX.Element; + breakClassName?: string; /** * The method to call when a page is clicked. Exposes the current page object as an argument. @@ -86,6 +87,11 @@ interface ReactPaginateProps { */ activeClassName?: string; + /** + * The classname for the active link. + */ + activeLinkClassName?: string; + /** * The classname on tag `li` of the `previous` button. */ diff --git a/types/react-paginate/react-paginate-tests.tsx b/types/react-paginate/react-paginate-tests.tsx index a98e8702a4..90a8718c52 100644 --- a/types/react-paginate/react-paginate-tests.tsx +++ b/types/react-paginate/react-paginate-tests.tsx @@ -20,6 +20,7 @@ class Test extends React.Component { pageClassName={'page-li'} pageLinkClassName={'page-a'} activeClassName={'active'} + activeLinkClassName={'active'} previousClassName={'previous-li'} nextClassName={'next-li'} previousLinkClassName={'previous-a'} diff --git a/types/react-paginate/v5/index.d.ts b/types/react-paginate/v5/index.d.ts new file mode 100644 index 0000000000..83a03ac838 --- /dev/null +++ b/types/react-paginate/v5/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for react-paginate 5.2 +// Project: https://github.com/AdeleD/react-paginate +// Definitions by: Simon Hartcher +// Wouter Hardeman +// pegel03 +// Simon Archer +// Yasunori Ohoka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +interface ReactPaginateProps { + /** + * The total number of pages. + */ + pageCount: number; + + /** + * The range of pages displayed. + */ + pageRangeDisplayed: number; + + /** + * The number of pages to display for margins. + */ + marginPagesDisplayed: number; + + /** + * Label for the `previous` button. + */ + previousLabel?: string | JSX.Element; + + /** + * Label for the `next` button. + */ + nextLabel?: string | JSX.Element; + + /** + * Label for ellipsis. + */ + breakLabel?: string | JSX.Element; + + /** + * The classname on tag `li` of the ellipsis element. + */ + breakClassName?: string | JSX.Element; + + /** + * The method to call when a page is clicked. Exposes the current page object as an argument. + */ + onPageChange?(selectedItem: { selected: number }): void; + + /** + * The initial page selected. + */ + initialPage?: number; + + /** + * To override selected page with parent prop. + */ + forcePage?: number; + + /** + * Disable onPageChange callback with initial page. Default: false + */ + disableInitialCallback?: boolean; + + /** + * The classname of the pagination container. + */ + containerClassName?: string; + + /** + * The classname on tag `li` of each page element. + */ + pageClassName?: string; + + /** + * The classname on tag `a` of each page element. + */ + pageLinkClassName?: string; + + /** + * The classname for the active page. + */ + activeClassName?: string; + + /** + * The classname on tag `li` of the `previous` button. + */ + previousClassName?: string; + + /** + * The classname on tag `li` of the `next` button. + */ + nextClassName?: string; + + /** + * The classname on tag `a` of the `previous` button. + */ + previousLinkClassName?: string; + + /** + * The classname on tag `a` of the `next` button. + */ + nextLinkClassName?: string; + + /** + * The classname for disabled `previous` and `next` buttons. + */ + disabledClassName?: string; + + /** + * The method is called to generate the href attribute value on tag a of each page element. + */ + hrefBuilder?(pageIndex: number): void; + + /** + * Extra context to add to the aria-label HTML attribute. + */ + extraAriaContext?: string; +} + +declare const ReactPaginate: React.ComponentClass; +export default ReactPaginate; diff --git a/types/react-paginate/v5/react-paginate-tests.tsx b/types/react-paginate/v5/react-paginate-tests.tsx new file mode 100644 index 0000000000..a98e8702a4 --- /dev/null +++ b/types/react-paginate/v5/react-paginate-tests.tsx @@ -0,0 +1,33 @@ +import * as React from 'react'; +import ReactPaginate from 'react-paginate'; + +class Test extends React.Component { + render() { + return ( + null} + initialPage={2} + forcePage={3} + disableInitialCallback={false} + containerClassName={'container'} + pageClassName={'page-li'} + pageLinkClassName={'page-a'} + activeClassName={'active'} + previousClassName={'previous-li'} + nextClassName={'next-li'} + previousLinkClassName={'previous-a'} + nextLinkClassName={'next-a'} + disabledClassName={'disabled'} + hrefBuilder={(pageIndex: number) => null} + extraAriaContext={'aria'} + /> + ); + } +} diff --git a/types/react-paginate/v5/tsconfig.json b/types/react-paginate/v5/tsconfig.json new file mode 100644 index 0000000000..5c49c56d9e --- /dev/null +++ b/types/react-paginate/v5/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-paginate-tests.tsx" + ] + } diff --git a/types/react-paginate/v5/tslint.json b/types/react-paginate/v5/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-paginate/v5/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From ca65601d0fd234d3d8aed8763de0e471404ccb99 Mon Sep 17 00:00:00 2001 From: Shingo Sato Date: Tue, 20 Nov 2018 15:07:31 +0900 Subject: [PATCH 112/836] Fix tsconfig --- types/react-paginate/v5/tsconfig.json | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/types/react-paginate/v5/tsconfig.json b/types/react-paginate/v5/tsconfig.json index 5c49c56d9e..9ff370a729 100644 --- a/types/react-paginate/v5/tsconfig.json +++ b/types/react-paginate/v5/tsconfig.json @@ -9,10 +9,15 @@ "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, - "baseUrl": "../", + "baseUrl": "../../", "typeRoots": [ - "../" + "../../" ], + "paths": { + "react-paginate": [ + "react-paginate/v5" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true, From a735e1c1df6d7b694a85dad74e95eba7d2b8af7c Mon Sep 17 00:00:00 2001 From: Konch Roman <300konya@gmail.com> Date: Tue, 20 Nov 2018 12:26:28 +0300 Subject: [PATCH 113/836] Fix echarts options definition in npm package Details: npm package has no its own tsconfig so we should reference to options manually --- types/echarts/index.d.ts | 1 + types/echarts/options/index.d.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 types/echarts/options/index.d.ts diff --git a/types/echarts/index.d.ts b/types/echarts/index.d.ts index 207b8366ef..adc4a2a24e 100644 --- a/types/echarts/index.d.ts +++ b/types/echarts/index.d.ts @@ -9,6 +9,7 @@ // TypeScript Version: 2.3 /// +/// declare namespace echarts { /** diff --git a/types/echarts/options/index.d.ts b/types/echarts/options/index.d.ts new file mode 100644 index 0000000000..fded0ed4c7 --- /dev/null +++ b/types/echarts/options/index.d.ts @@ -0,0 +1,28 @@ +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// From ea2fd32b95c0fe3e3dcd2e174ab95b2141a88c7f Mon Sep 17 00:00:00 2001 From: Shervin Sarain Date: Wed, 7 Nov 2018 16:11:49 +0100 Subject: [PATCH 114/836] Added type definitions for kerberos npm package --- types/kerberos/index.d.ts | 190 +++++++++++++++++++++++++++++++ types/kerberos/kerberos-tests.ts | 94 +++++++++++++++ types/kerberos/tsconfig.json | 23 ++++ types/kerberos/tslint.json | 1 + 4 files changed, 308 insertions(+) create mode 100644 types/kerberos/index.d.ts create mode 100644 types/kerberos/kerberos-tests.ts create mode 100644 types/kerberos/tsconfig.json create mode 100644 types/kerberos/tslint.json diff --git a/types/kerberos/index.d.ts b/types/kerberos/index.d.ts new file mode 100644 index 0000000000..eaebdb5a84 --- /dev/null +++ b/types/kerberos/index.d.ts @@ -0,0 +1,190 @@ +// Type definitions for kerberos 1.1 +// Project: https://github.com/mongodb-js/kerberos#readme +// Definitions by: Shervin Sarain +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const GSS_C_DELEG_FLAG: number; +export const GSS_C_MUTUAL_FLAG: number; +export const GSS_C_REPLAY_FLAG: number; +export const GSS_C_SEQUENCE_FLAG: number; +export const GSS_C_CONF_FLAG: number; +export const GSS_C_INTEG_FLAG: number; +export const GSS_C_ANON_FLAG: number; +export const GSS_C_PROT_READY_FLAG: number; +export const GSS_C_TRANS_FLAG: number; + +export const GSS_C_NO_OID: number; +export const GSS_MECH_OID_KRB5: number; +export const GSS_MECH_OID_SPNEGO: number; + +// Interfaces for configuration objects +/** + * @description Optional settings for *KerberosClient.wrap* method + */ +export interface WrapOptions { + /** + * @description The user to authorize + */ + user?: string; +} + +/** + * @description Optional settings for *KerberosClient.wrap* method + */ +export interface InitializeClientOptions { + /** + * @description Optional string containing the client principal in the form '`user@realm`' + */ + principal?: string; + /** + * @description Optional integer used to set GSS flags. (e.g. GSS_C_DELEG_FLAG|GSS_C_MUTUAL_FLAG|GSS_C_SEQUENCE_FLAG will allow for forwarding credentials to the remote host) + */ + gssFlag?: number; + /** + * @description Optional GSS mech OID. Defaults to None (GSS_C_NO_OID). Other possible values are `GSS_MECH_OID_KRB5`, `GSS_MECH_OID_SPNEGO` + */ + mechOID?: number; +} + +export class KerberosClient { + /** + * @description The username used for authentication + */ + username: string; + /** + * @description The last response received during authentication steps + */ + response: string; + /** + * @description Indicates whether confidentiality was applied or not (GSSAPI only) + */ + responseConf: string; + /** + * @description Indicates that authentication has successfully completed or not + */ + contextComplete: boolean; + + /** + * Processes a single kerberos client-side step using the supplied server challenge. + * + * @param challenge A string containing the base64-encoded server data (which may be empty for the first step) + * @param callback + * @return returns Promise if no callback passed + */ + step(challenge: string): Promise; + step(challenge: string, callback: (err: string, clientResponse: string) => any): void; + + /** + * Perform the client side kerberos wrap step. + * + * @param challenge The response returned after calling `unwrap` + * @param options Optional settings + * @param [callback] + * @return returns Promise if no callback passed + */ + wrap(challenge: string, options?: WrapOptions): Promise; + wrap(challenge: string, callback: (err: string, challengeResponse: string) => any): void; + wrap(challenge: string, options: WrapOptions, callback: (err: string, challengeResponse: string) => any): void; + + /** + * Perform the client side kerberos unwrap step + * + * @param challenge A string containing the base64-encoded server data + * @param callback + * @return returns Promise if no callback passed + */ + unwrap(challenge: string): Promise; + unwrap(challenge: string, callback: (err: string, challengeResponse: string) => any): void; +} + +export class KerberosServer { + /** + * @description The username used for authentication + */ + username: string; + /** + * @description The last response received during authentication steps + */ + response: string; + /** + * @description The target used for authentication + */ + targetName: string; + /** + * @description Indicates that authentication has successfully completed or not + */ + contextComplete: boolean; + + /** + * Processes a single kerberos server-side step using the supplied client data. + * + * @param challenge A string containing the base64-encoded client data + * @param callback + * @return returns Promise if no callback passed + */ + step(challenge: string): Promise; + step(challenge: string, callback: (err: string, serverResponse: string) => any): void; +} + +/** + * This function provides a simple way to verify that a user name and password + * match those normally used for Kerberos authentication. + * It does this by checking that the supplied user name and password can be + * used to get a ticket for the supplied service. + * If the user name does not contain a realm, then the default realm supplied + * is used. + * + * For this to work properly the Kerberos must be configured properly on this + * machine. + * That will likely mean ensuring that the edu.mit.Kerberos preference file + * has the correct realms and KDCs listed. + * + * IMPORTANT: This method is vulnerable to KDC spoofing attacks and it should + * only be used for testing. Do not use this in any production system - your + * security could be compromised if you do. + * + * @param username The Kerberos user name. If no realm is supplied, then the `defaultRealm` will be used. + * @param password The password for the user. + * @param service The Kerberos service to check access for. + * @param defaultRealm The default realm to use if one is not supplied in the user argument. + * @param callback + * @return returns Promise if no callback passed + */ +export function checkPassword(name: string, password: string, service: string, defaultRealm?: string): Promise; +export function checkPassword(name: string, password: string, service: string, callback: (err: string) => any): void; +export function checkPassword(name: string, password: string, service: string, defaultRealm: string, callback: (err: string) => any): void; + +/** + * This function returns the service principal for the server given a service type and hostname. + * + * Details are looked up via the `/etc/keytab` file. + * + * @param service The Kerberos service type for the server. + * @param hostname The hostname of the server. + * @param callback + * @return returns Promise if no callback passed + */ +export function principalDetails(service: string, hostname: string): Promise; +export function principalDetails(service: string, hostname: string, callback: (err: string, details: string) => any): void; + +/** + * Initializes a context for client-side authentication with the given service principal. + * + * @param service A string containing the service principal in the form '`type@fqdn`'. + * @param [options] Optional settings + * @param callback + * @return returns Promise if no callback passed + */ +export function initializeClient(service: string, options?: InitializeClientOptions): Promise; +export function initializeClient(service: string, callback: (err: string, client: KerberosClient) => any): void; +export function initializeClient(service: string, options: InitializeClientOptions, callback: (err: string, client: KerberosClient) => any): void; + +/** + * Initializes a context for server-side authentication with the given service principal. + * + * @param service A string containing the service principal in the form 'type@fqdn' (e.g. 'imap@mail.apple.com'). + * @param callback + * @return returns Promise if no callback passed + */ +export function initializeServer(service: string): Promise; +export function initializeServer(service: string, callback: (err: string, server: KerberosServer) => any): void; diff --git a/types/kerberos/kerberos-tests.ts b/types/kerberos/kerberos-tests.ts new file mode 100644 index 0000000000..8d016515c0 --- /dev/null +++ b/types/kerberos/kerberos-tests.ts @@ -0,0 +1,94 @@ +import * as kerberos from 'kerberos'; + +// environment variables +const username = 'administrator'; +const password = 'Password01'; +const realm = 'example.com'; +const hostname = 'hostname.example.com'; +const port = '80'; +let service: string; + +kerberos.principalDetails('HTTP', hostname, (err, details) => { + if (!err) { + return err; + } + return details; +}); + +kerberos.principalDetails('HTTP', hostname).then(details => { + return details; +}).catch(err => { + return err; +}); + +service = `HTTP/${hostname}`; +kerberos.checkPassword(username, password, service, realm.toUpperCase(), err => { + if (!err) { + return true; + } + return err; +}); + +kerberos.checkPassword(username, password, service, realm.toUpperCase()).then(() => { + return true; +}).catch(err => { + return err; +}); + +service = `HTTP@${hostname}`; +kerberos.initializeClient(service, {}, (err, client) => { + kerberos.initializeServer(service, (err, server) => { + client.step('', (err, clientResponse) => { + server.step(clientResponse, (err, serverResponse) => { + client.unwrap(clientResponse, (err, challengeResponse) => { + client.wrap(challengeResponse, { user : "user" }, (err, challengeResponse2) => { + return challengeResponse2; + }); + }); + }); + }); + }); +}); + +service = `HTTP@${hostname}`; +kerberos.initializeClient(service, {}).then(client => { + kerberos.initializeServer(service).then(server => { + client.step('').then(clientResponse => { + server.step(clientResponse).then(serverResponse => { + client.unwrap(clientResponse).then(challengeResponse => { + client.wrap(challengeResponse, { user : "user" }).then(challengeResponse2 => { + return challengeResponse2; + }); + }); + }); + }); + }); +}); + +service = `HTTP@${hostname}`; +const url = `http://${hostname}:${port}/`; + +const mechOID = kerberos.GSS_MECH_OID_KRB5; +kerberos.initializeClient(service, { mechOID }, (err, client) => { + client.step('', (err, kerberosToken) => { + return kerberosToken; + }); +}); + +kerberos.initializeClient(service, { mechOID }).then(client => { + client.step('', (err, kerberosToken) => { + return kerberosToken; + }); +}); + +kerberos.initializeClient(service, (err, client) => { + client.step('', (err, kerberosToken) => { + return kerberosToken; + }); +}); + +kerberos.initializeClient(service).then(client => { + client.step('', (err, kerberosToken) => { + return kerberosToken; + }); +}); diff --git a/types/kerberos/tsconfig.json b/types/kerberos/tsconfig.json new file mode 100644 index 0000000000..c0e3913b2b --- /dev/null +++ b/types/kerberos/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "strictFunctionTypes": true, + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "kerberos-tests.ts" + ] +} diff --git a/types/kerberos/tslint.json b/types/kerberos/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/kerberos/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 58ab88a2b4b47553bb8ed3fc372a03630003f0c2 Mon Sep 17 00:00:00 2001 From: Flo Luccioni Date: Tue, 20 Nov 2018 12:06:47 +0100 Subject: [PATCH 115/836] feat(mapbox): add missing styleLayer definition --- types/mapbox/index.d.ts | 15 +++++++++++++++ types/mapbox/mapbox-tests.ts | 2 ++ 2 files changed, 17 insertions(+) diff --git a/types/mapbox/index.d.ts b/types/mapbox/index.d.ts index 334d644e21..97da469e4a 100644 --- a/types/mapbox/index.d.ts +++ b/types/mapbox/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for Mapbox 1.6 // Project: https://www.mapbox.com/mapbox.js/ // Definitions by: Maxime Fabre +// Florian Luccioni // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -153,6 +154,20 @@ declare global { getGeoJSON(): any; } + // StyleLayer + ////////////////////////////////////////////////////////////////////// + + /** + * L.mapbox.styleLayer provides a way to integrate styles created with Mapbox Studio into your map. + */ + function styleLayer(url: string, options?: StyleLayerOptions): StyleLayer; + + interface StyleLayerOptions extends Leaflet.TileLayerOptions { + sanitizer?(template: string): string; + } + + type StyleLayer = Leaflet.TileLayer; + ////////////////////////////////////////////////////////////////////// ////////////////////////////// GEOCODING ///////////////////////////// ////////////////////////////////////////////////////////////////////// diff --git a/types/mapbox/mapbox-tests.ts b/types/mapbox/mapbox-tests.ts index ab9ad6c5de..a9610ba5c4 100644 --- a/types/mapbox/mapbox-tests.ts +++ b/types/mapbox/mapbox-tests.ts @@ -4,6 +4,8 @@ const mapboxTiles = L.tileLayer('https://{s}.tiles.mapbox.com/v3/examples.map-i8 const map = L.map('map').addLayer(mapboxTiles).setView(new L.LatLng([42.3610, -71.0587]), 15); +const lightTiles = L.mapbox.styleLayer('mapbox://styles/mapbox/light-v9').addTo(map); + const coordinates = document.getElementById('coordinates'); const marker = L.marker(new L.LatLng([0, 0]), { From 52185a5dc8897b7c716020b7c39679e617edb712 Mon Sep 17 00:00:00 2001 From: Jan Bevers Date: Tue, 20 Nov 2018 15:10:31 +0100 Subject: [PATCH 116/836] [react-big-calendar] Improvements to toolbar and eventwrapper props --- types/react-big-calendar/index.d.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index 9d9b62881c..790a5887cb 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -11,9 +11,9 @@ import { Validator } from 'prop-types'; import * as React from 'react'; -export type DayPropGetter = (date: Date) => { className?: string, style?: object }; +export type DayPropGetter = (date: Date) => { className?: string, style?: React.CSSProperties }; export type EventPropGetter = (event: T, start: stringOrDate, end: stringOrDate, isSelected: boolean) => { className?: string, style?: React.CSSProperties }; -export type SlotPropGetter = (date: Date) => { className?: string, style?: object }; +export type SlotPropGetter = (date: Date) => { className?: string, style?: React.CSSProperties }; export type stringOrDate = string | Date; export type ViewKey = 'MONTH' | 'WEEK' | 'WORK_WEEK' | 'DAY' | 'AGENDA'; export type View = 'month' | 'week' | 'work_week' | 'day' | 'agenda'; @@ -114,14 +114,14 @@ export interface HeaderProps { export interface Components { event?: React.SFC | React.Component | React.ComponentClass | JSX.Element; - eventWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + eventWrapper?: React.ComponentType; dayWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dateCellWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; /** * component used as a header for each column in the TimeGridHeader */ header?: React.ComponentType; - toolbar?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + toolbar?: React.ComponentType; agenda?: { date?: React.SFC | React.Component | React.ComponentClass | JSX.Element; time?: React.SFC | React.Component | React.ComponentClass | JSX.Element; @@ -154,6 +154,7 @@ export interface ToolbarProps { } export interface EventWrapperProps { + // https://github.com/intljusticemission/react-big-calendar/blob/27a2656b40ac8729634d24376dff8ea781a66d50/src/TimeGridEvent.js#L28 style?: React.CSSProperties & { xOffset: number }; className: string; event: T; From 6556eb615fad17f3c819bd8ea25e1f441dd2ae88 Mon Sep 17 00:00:00 2001 From: Shrujal Shah Date: Tue, 20 Nov 2018 22:15:19 +0530 Subject: [PATCH 117/836] Add missing explorer option in column chart --- types/google.visualization/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/google.visualization/index.d.ts b/types/google.visualization/index.d.ts index e5e400bc44..878e17a011 100644 --- a/types/google.visualization/index.d.ts +++ b/types/google.visualization/index.d.ts @@ -597,6 +597,7 @@ declare namespace google { chartArea?: ChartArea; colors?: string[]; enableInteractivity?: boolean; + explorer?: ChartExplorer; focusTarget?: string; fontSize?: number; fontName?: string; From 845918b6a86a6190c23da22b4d8def7ac9adeffb Mon Sep 17 00:00:00 2001 From: Esteban Ibarra Date: Tue, 20 Nov 2018 12:15:15 -0500 Subject: [PATCH 118/836] Add types for react-native-draggable-flatlist --- .../index.d.ts | 59 +++++++++++++++++++ .../react-native-draggable-flatlist-tests.tsx | 44 ++++++++++++++ .../tsconfig.json | 24 ++++++++ .../tslint.json | 1 + 4 files changed, 128 insertions(+) create mode 100644 types/react-native-draggable-flatlist/index.d.ts create mode 100644 types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx create mode 100644 types/react-native-draggable-flatlist/tsconfig.json create mode 100644 types/react-native-draggable-flatlist/tslint.json diff --git a/types/react-native-draggable-flatlist/index.d.ts b/types/react-native-draggable-flatlist/index.d.ts new file mode 100644 index 0000000000..0b96f0b3cd --- /dev/null +++ b/types/react-native-draggable-flatlist/index.d.ts @@ -0,0 +1,59 @@ +// Type definitions for react-native-draggable-flatlist 1.1 +// Project: https://github.com/computerjazz/react-native-draggable-flatlist#readme +// Definitions by: Stack Builders +// Esteban Ibarra +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { VirtualizedListWithoutRenderItemProps } from "react-native"; +import { Component } from "react"; + +export interface RenderItemInfo { + item: ItemR; + index: number; + move: () => void; + moveEnd: () => void; + isActive: boolean; +} + +export interface OnMoveEndInfo { + data: ReadonlyArray | null; + to: number; + from: number; + row: ItemM; +} + +interface DraggableFlatListProps extends VirtualizedListWithoutRenderItemProps { + /** + * Items to be rendered. + */ + data: ReadonlyArray | null; + + /** + * Function that returns updated ordering of data + */ + onMoveEnd?: (info: OnMoveEndInfo) => void; + + /** + * Function that is called when row becomes active. + */ + onMoveBegin?: (index: number) => void; + + /** + * Sets where scrolling begins. + * + * Default is 5 + */ + scrollPercent?: number; + + /** + * Function that calls move when the row should become active (in an onPress, onLongPress, etc). Calls moveEnd when the gesture is complete (in onPressOut). + */ + renderItem: (info: RenderItemInfo) => React.ReactElement | null; +} + +declare class DraggableFlatList extends Component> { + constructor(props: DraggableFlatListProps); +} + +export default DraggableFlatList; diff --git a/types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx b/types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx new file mode 100644 index 0000000000..40d613e4ea --- /dev/null +++ b/types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx @@ -0,0 +1,44 @@ +import * as React from 'react'; +import { TouchableOpacity, Text } from 'react-native'; +import DraggableFlatList, { RenderItemInfo } from 'react-native-draggable-flatlist'; + +interface Item { + name: string; + mail: string; +} + +class Example extends React.Component { + state = { + data: [ + { name: 'Esteban', mail: 'foo@foo.com' }, + { name: 'Xavier', mail: 'foo2@foo.com' }, + ] + }; + + renderItem({ item, index, move, moveEnd, isActive }: RenderItemInfo) { + return ( + + {index} + {item.name} + {item.mail} + + ); + } + + render() { + const { data } = this.state; + return ( + `draggable-item-${index}`} + scrollPercent={10} + onMoveEnd={({ data }) => this.setState({ data })} + ListFooterComponent={{'Hello'}} + /> + ); + } +} diff --git a/types/react-native-draggable-flatlist/tsconfig.json b/types/react-native-draggable-flatlist/tsconfig.json new file mode 100644 index 0000000000..b3c009feac --- /dev/null +++ b/types/react-native-draggable-flatlist/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react-native" + }, + "files": [ + "index.d.ts", + "react-native-draggable-flatlist-tests.tsx" + ] +} diff --git a/types/react-native-draggable-flatlist/tslint.json b/types/react-native-draggable-flatlist/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-draggable-flatlist/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From ba61ea8fd2dfbfa313d3786480ced0992dcea729 Mon Sep 17 00:00:00 2001 From: Alexander Date: Tue, 20 Nov 2018 21:22:05 +0200 Subject: [PATCH 119/836] add changes based on pr feedback --- types/nise/index.d.ts | 553 +++++++++++++++++++++--------------------- 1 file changed, 272 insertions(+), 281 deletions(-) diff --git a/types/nise/index.d.ts b/types/nise/index.d.ts index d01ad3303d..f054bad373 100644 --- a/types/nise/index.d.ts +++ b/types/nise/index.d.ts @@ -4,288 +4,279 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -declare namespace Nise { - interface FakeUploadProgress { - eventListeners: { - progress: any[]; - load: any[]; - abort: any[]; - error: any[]; - }; +export interface FakeUploadProgress { + eventListeners: { + progress: any[]; + load: any[]; + abort: any[]; + error: any[]; + }; - addEventListener(event: string, listener: (e: Event) => any): void; - removeEventListener(event: string, listener: (e: Event) => any): void; - dispatchEvent(event: Event): void; - } - - interface FakeXMLHttpRequest { - /** - * The URL set on the request object. - */ - url: string; - /** - * The request method as a string. - */ - method: string; - /** - * An object of all request headers, i.e.: - */ - requestHeaders: any; - /** - * The request body - */ - requestBody: string; - /** - * The request’s status code. - * undefined if the request has not been handled (see respond below) - */ - status: number; - /** - * Only populated if the respond method is called (see below). - */ - statusText: string; - /** - * Whether or not the request is asynchronous. - */ - async: boolean; - /** - * Username, if any. - */ - username: string; - /** - * Password, if any. - */ - password: string; - withCredentials: boolean; - upload: FakeUploadProgress; - /** - * When using respond, this property is populated with a parsed document if response headers indicate as much (see the spec) - */ - responseXML: Document; - /** - * The value of the given response header, if the request has been responded to (see respond). - * @param header - */ - getResponseHeader(header: string): string; - /** - * All response headers as an object. - */ - getAllResponseHeaders(): any; - - /** - * Sets response headers (e.g. { "Content-Type": "text/html", ... }, updates the readyState property and fires onreadystatechange. - * @param headers - */ - setResponseHeaders(headers: any): void; - /** - * Sets the respond body, updates the readyState property and fires onreadystatechange. - * Additionally, populates responseXML with a parsed document if response headers indicate as much. - */ - setResponseBody(body: string): void; - /** - * Calls the above three methods. - */ - respond(status: number, headers?: any, body?: string): void; - autoRespond(ms: number): void; - /** - * Simulates a network error on the request. The onerror handler will be called and the status will be 0. - */ - error(): void; - - onloadstart(e: Event): void; - onprogress(e: Event): void; - ontimeout(e: Event): void; - onloadend(e: Event): void; - onerror(e: Event): void; - onabort(e: Event): void; - onload(e: Event): void; - } - - interface FakeServerOptions { - /** - * When set to true, causes the server to automatically respond to incoming requests after a timeout. - * The default timeout is 10ms but you can control it through the autoRespondAfter property. - * Note that this feature is intended to help during mockup development, and is not suitable for use in tests. - */ - autoRespond: boolean; - /** - * When autoRespond is true, respond to requests after this number of milliseconds. Default is 10. - */ - autoRespondAfter: number; - /** - * If set to true, server will find _method parameter in POST body and recognize that as the actual method. - * Supports a pattern common to Ruby on Rails applications. For custom HTTP method faking, override server.getHTTPMethod(request). - */ - fakeHTTPMethods: boolean; - /** - * If set, the server will respond to every request immediately and synchronously. - * This is ideal for faking the server from within a test without having to call server.respond() after each request made in that test. - * As this is synchronous and immediate, this is not suitable for simulating actual network latency in tests or mockups. - * To simulate network latency with automatic responses, see server.autoRespond and server.autoRespondAfter. - */ - respondImmediately: boolean; - } - - interface FakeServer extends FakeServerOptions { - lastRequest: FakeXMLHttpRequest | undefined; - firstRequest: FakeXMLHttpRequest | undefined; - secondRequest: FakeXMLHttpRequest | undefined; - thirdRequest: FakeXMLHttpRequest | undefined; - - /** - * Used internally to determine the HTTP method used with the provided request. - * By default this method simply returns request.method. - * When server.fakeHTTPMethods is true, the method will return the value of the _method parameter if the method is “POST”. - * This method can be overridden to provide custom behavior. - * @param request - */ - getHTTPMethod(request: FakeXMLHttpRequest): string; - - /** - * You can inspect the server.requests to verify request ordering, find unmatched requests or check that no requests has been done. - * server.requests is an array of all the FakeXMLHttpRequest objects that have been created. - */ - requests: FakeXMLHttpRequest[]; - - /** - * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. - * A String representing the response body - * An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"] - * A Function. - * Default status is 200 and default headers are none. - * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. - * @param body A String representing the response body - */ - respondWith(body: string): void; - /** - * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. - * Default status is 200 and default headers are none. - * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. - * @param response An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"] - */ - respondWith(response: any[]): void; - /** - * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. - * Default status is 200 and default headers are none. - * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. - * @param fn A Function. - */ - respondWith(fn: (xhr: FakeXMLHttpRequest) => void): void; - /** - * Responds to all requests to given URL, e.g. /posts/1. - */ - respondWith(url: string, body: string): void; - /** - * Responds to all requests to given URL, e.g. /posts/1. - */ - respondWith(url: string, response: any[]): void; - /** - * Responds to all requests to given URL, e.g. /posts/1. - */ - respondWith(url: string, fn: (xhr: FakeXMLHttpRequest) => void): void; - /** - * Responds to all method requests to the given URL with the given response. - * method is an HTTP verb. - */ - respondWith(method: string, url: string, body: string): void; - /** - * Responds to all method requests to the given URL with the given response. - * method is an HTTP verb. - */ - respondWith(method: string, url: string, response: any[]): void; - /** - * Responds to all method requests to the given URL with the given response. - * method is an HTTP verb. - */ - respondWith(method: string, url: string, fn: (xhr: FakeXMLHttpRequest) => void): void; - /** - * URL may be a regular expression, e.g. /\\/post\\//\\d+ - * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: - */ - respondWith(url: RegExp, body: string): void; - /** - * URL may be a regular expression, e.g. /\\/post\\//\\d+ - * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: - */ - respondWith(url: RegExp, response: any[]): void; - /** - * URL may be a regular expression, e.g. /\\/post\\//\\d+ - * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: - */ - respondWith(url: RegExp, fn: (xhr: FakeXMLHttpRequest) => void): void; - /** - * Responds to all method requests to URLs matching the regular expression. - */ - respondWith(method: string, url: RegExp, body: string): void; - /** - * Responds to all method requests to URLs matching the regular expression. - */ - respondWith(method: string, url: RegExp, response: any[]): void; - /** - * Responds to all method requests to URLs matching the regular expression. - */ - respondWith(method: string, url: RegExp, fn: (xhr: FakeXMLHttpRequest) => void): void; - respondWith(...args: any[]): void; - - /** - * Causes all queued asynchronous requests to receive a response. - * If none of the responses added through respondWith match, the default response is [404, {}, ""]. - * Synchronous requests are responded to immediately, so make sure to call respondWith upfront. - * If called with arguments, respondWith will be called with those arguments before responding to requests. - */ - respond(): void; - restore(): void; - - getRequest(): FakeXMLHttpRequest | undefined; - reset(): void; - resetBehavior(): void; - resetHistory(): void; - } - - interface FakeXMLHttpRequestStatic { - new(): FakeXMLHttpRequest; - /** - * Default false. - * When set to true, Sinon will check added filters if certain requests should be “unfaked” - */ - useFilters: boolean; - /** - * Add a filter that will decide whether or not to fake a request. - * The filter will be called when xhr.open is called, with the exact same arguments (method, url, async, username, password). - * If the filter returns true, the request will not be faked. - * @param filter - */ - addFilter(filter: (method: string, url: string, async: boolean, username: string, password: string) => boolean): void; - /** - * By assigning a function to the onCreate property of the returned object from useFakeXMLHttpRequest() - * you can subscribe to newly created FakeXMLHttpRequest objects. See below for the fake xhr object API. - * Using this observer means you can still reach objects created by e.g. jQuery.ajax (or other abstractions/frameworks). - * @param xhr - */ - onCreate(xhr: FakeXMLHttpRequest): void; - /** - * Restore original function(s). - */ - restore(): void; - } - - interface FakeServerStatic { - create(options?: Partial): FakeServer; - } - - interface FakeXHR { - useFakeXMLHttpRequest(): FakeXMLHttpRequestStatic; - FakeXMLHttpRequest: FakeXMLHttpRequestStatic; - } - - interface API { - fakeServerWithClock: FakeServerStatic; - fakeServer: FakeServerStatic; - fakeXhr: FakeXHR; - } + addEventListener(event: string, listener: (e: Event) => any): void; + removeEventListener(event: string, listener: (e: Event) => any): void; + dispatchEvent(event: Event): void; } -declare const Nise: Nise.API; +export interface FakeXMLHttpRequest { + /** + * The URL set on the request object. + */ + url: string; + /** + * The request method as a string. + */ + method: string; + /** + * An object of all request headers, i.e.: + */ + requestHeaders: any; + /** + * The request body + */ + requestBody: string; + /** + * The request’s status code. + * undefined if the request has not been handled (see respond below) + */ + status: number; + /** + * Only populated if the respond method is called (see below). + */ + statusText: string; + /** + * Whether or not the request is asynchronous. + */ + async: boolean; + /** + * Username, if any. + */ + username: string; + /** + * Password, if any. + */ + password: string; + withCredentials: boolean; + upload: FakeUploadProgress; + /** + * When using respond, this property is populated with a parsed document if response headers indicate as much (see the spec) + */ + responseXML: Document; + /** + * The value of the given response header, if the request has been responded to (see respond). + * @param header + */ + getResponseHeader(header: string): string; + /** + * All response headers as an object. + */ + getAllResponseHeaders(): any; -export = Nise; -export as namespace nise; + /** + * Sets response headers (e.g. { "Content-Type": "text/html", ... }, updates the readyState property and fires onreadystatechange. + * @param headers + */ + setResponseHeaders(headers: any): void; + /** + * Sets the respond body, updates the readyState property and fires onreadystatechange. + * Additionally, populates responseXML with a parsed document if response headers indicate as much. + */ + setResponseBody(body: string): void; + /** + * Calls the above three methods. + */ + respond(status: number, headers?: any, body?: string): void; + autoRespond(ms: number): void; + /** + * Simulates a network error on the request. The onerror handler will be called and the status will be 0. + */ + error(): void; + + onloadstart(e: Event): void; + onprogress(e: Event): void; + ontimeout(e: Event): void; + onloadend(e: Event): void; + onerror(e: Event): void; + onabort(e: Event): void; + onload(e: Event): void; +} + +export interface FakeServerOptions { + /** + * When set to true, causes the server to automatically respond to incoming requests after a timeout. + * The default timeout is 10ms but you can control it through the autoRespondAfter property. + * Note that this feature is intended to help during mockup development, and is not suitable for use in tests. + */ + autoRespond: boolean; + /** + * When autoRespond is true, respond to requests after this number of milliseconds. Default is 10. + */ + autoRespondAfter: number; + /** + * If set to true, server will find _method parameter in POST body and recognize that as the actual method. + * Supports a pattern common to Ruby on Rails applications. For custom HTTP method faking, override server.getHTTPMethod(request). + */ + fakeHTTPMethods: boolean; + /** + * If set, the server will respond to every request immediately and synchronously. + * This is ideal for faking the server from within a test without having to call server.respond() after each request made in that test. + * As this is synchronous and immediate, this is not suitable for simulating actual network latency in tests or mockups. + * To simulate network latency with automatic responses, see server.autoRespond and server.autoRespondAfter. + */ + respondImmediately: boolean; +} + +export interface FakeServer extends FakeServerOptions { + lastRequest: FakeXMLHttpRequest | undefined; + firstRequest: FakeXMLHttpRequest | undefined; + secondRequest: FakeXMLHttpRequest | undefined; + thirdRequest: FakeXMLHttpRequest | undefined; + + /** + * Used internally to determine the HTTP method used with the provided request. + * By default this method simply returns request.method. + * When server.fakeHTTPMethods is true, the method will return the value of the _method parameter if the method is “POST”. + * This method can be overridden to provide custom behavior. + * @param request + */ + getHTTPMethod(request: FakeXMLHttpRequest): string; + + /** + * You can inspect the server.requests to verify request ordering, find unmatched requests or check that no requests has been done. + * server.requests is an array of all the FakeXMLHttpRequest objects that have been created. + */ + requests: FakeXMLHttpRequest[]; + + /** + * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. + * A String representing the response body + * An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"] + * A Function. + * Default status is 200 and default headers are none. + * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. + * @param body A String representing the response body + */ + respondWith(body: string): void; + /** + * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. + * Default status is 200 and default headers are none. + * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. + * @param response An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"] + */ + respondWith(response: any[]): void; + /** + * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. + * Default status is 200 and default headers are none. + * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. + * @param fn A Function. + */ + respondWith(fn: (xhr: FakeXMLHttpRequest) => void): void; + /** + * Responds to all requests to given URL, e.g. /posts/1. + */ + respondWith(url: string, body: string): void; + /** + * Responds to all requests to given URL, e.g. /posts/1. + */ + respondWith(url: string, response: any[]): void; + /** + * Responds to all requests to given URL, e.g. /posts/1. + */ + respondWith(url: string, fn: (xhr: FakeXMLHttpRequest) => void): void; + /** + * Responds to all method requests to the given URL with the given response. + * method is an HTTP verb. + */ + respondWith(method: string, url: string, body: string): void; + /** + * Responds to all method requests to the given URL with the given response. + * method is an HTTP verb. + */ + respondWith(method: string, url: string, response: any[]): void; + /** + * Responds to all method requests to the given URL with the given response. + * method is an HTTP verb. + */ + respondWith(method: string, url: string, fn: (xhr: FakeXMLHttpRequest) => void): void; + /** + * URL may be a regular expression, e.g. /\\/post\\//\\d+ + * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: + */ + respondWith(url: RegExp, body: string): void; + /** + * URL may be a regular expression, e.g. /\\/post\\//\\d+ + * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: + */ + respondWith(url: RegExp, response: any[]): void; + /** + * URL may be a regular expression, e.g. /\\/post\\//\\d+ + * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: + */ + respondWith(url: RegExp, fn: (xhr: FakeXMLHttpRequest) => void): void; + /** + * Responds to all method requests to URLs matching the regular expression. + */ + respondWith(method: string, url: RegExp, body: string): void; + /** + * Responds to all method requests to URLs matching the regular expression. + */ + respondWith(method: string, url: RegExp, response: any[]): void; + /** + * Responds to all method requests to URLs matching the regular expression. + */ + respondWith(method: string, url: RegExp, fn: (xhr: FakeXMLHttpRequest) => void): void; + respondWith(...args: any[]): void; + + /** + * Causes all queued asynchronous requests to receive a response. + * If none of the responses added through respondWith match, the default response is [404, {}, ""]. + * Synchronous requests are responded to immediately, so make sure to call respondWith upfront. + * If called with arguments, respondWith will be called with those arguments before responding to requests. + */ + respond(): void; + restore(): void; + + getRequest(): FakeXMLHttpRequest | undefined; + reset(): void; + resetBehavior(): void; + resetHistory(): void; +} + +export interface FakeXMLHttpRequestStatic { + new(): FakeXMLHttpRequest; + /** + * Default false. + * When set to true, Sinon will check added filters if certain requests should be “unfaked” + */ + useFilters: boolean; + /** + * Add a filter that will decide whether or not to fake a request. + * The filter will be called when xhr.open is called, with the exact same arguments (method, url, async, username, password). + * If the filter returns true, the request will not be faked. + * @param filter + */ + addFilter(filter: (method: string, url: string, async: boolean, username: string, password: string) => boolean): void; + /** + * By assigning a function to the onCreate property of the returned object from useFakeXMLHttpRequest() + * you can subscribe to newly created FakeXMLHttpRequest objects. See below for the fake xhr object API. + * Using this observer means you can still reach objects created by e.g. jQuery.ajax (or other abstractions/frameworks). + * @param xhr + */ + onCreate(xhr: FakeXMLHttpRequest): void; + /** + * Restore original function(s). + */ + restore(): void; +} + +export interface FakeServerStatic { + create(options?: Partial): FakeServer; +} + +export interface FakeXHR { + useFakeXMLHttpRequest(): FakeXMLHttpRequestStatic; + FakeXMLHttpRequest: FakeXMLHttpRequestStatic; +} + +export const fakeServerWithClock: FakeServerStatic; +export const fakeServer: FakeServerStatic; +export const fakeXhr: FakeXHR; From 97c198362b7ab34c42f49ef95200826162a23524 Mon Sep 17 00:00:00 2001 From: Fabio Berta Date: Tue, 20 Nov 2018 21:01:56 +0100 Subject: [PATCH 120/836] fix indention --- types/react-map-gl/index.d.ts | 75 +++++++++++++++++------------------ 1 file changed, 36 insertions(+), 39 deletions(-) diff --git a/types/react-map-gl/index.d.ts b/types/react-map-gl/index.d.ts index 4522ddf729..3fea6a3ea9 100644 --- a/types/react-map-gl/index.d.ts +++ b/types/react-map-gl/index.d.ts @@ -19,11 +19,8 @@ export interface ViewState { } export interface MapError { - error?: { - message: string; + error?: { message: string; status: number }; status: number; - }; - status: number; } export interface MapRequest { @@ -81,7 +78,7 @@ export interface ExtraState { } export interface PositionInput { - pos: [number, number]; + pos: [number, number]; } export interface MapControllerOptions { @@ -99,47 +96,47 @@ export interface MapControllerOptions { } export interface ViewportProps { - width: number; - height: number; - latitude: number; - longitude: number; - zoom: number; - bearing: number; - pitch: number; - altitude: number; - maxZoom: number; - minZoom: number; - maxPitch: number; - minPitch: number; - transitionDuration?: number; - transitionInterpolator?: TransitionInterpolator; - transitionInterruption?: TRANSITION_EVENTS; - transitionEasing?: EasingFunction; + width: number; + height: number; + latitude: number; + longitude: number; + zoom: number; + bearing: number; + pitch: number; + altitude: number; + maxZoom: number; + minZoom: number; + maxPitch: number; + minPitch: number; + transitionDuration?: number; + transitionInterpolator?: TransitionInterpolator; + transitionInterruption?: TRANSITION_EVENTS; + transitionEasing?: EasingFunction; } export interface InteractiveState { - startPanLngLat?: [number, number]; - startZoomLngLat?: [number, number]; - startBearing?: number; - startPitch?: number; - startZoom?: number; + startPanLngLat?: [number, number]; + startZoomLngLat?: [number, number]; + startBearing?: number; + startPitch?: number; + startZoom?: number; } export type MapStateProps = Partial; export class MapState { - constructor(props: MapStateProps); - getViewportProps(): ViewportProps; - getInteractiveState(): InteractiveState; - panStart(input: PositionInput): MapState; - pan(input: PositionInput & { startPos?: [number, number] }): MapState; - panEnd(): MapState; - rotateStart(input: PositionInput): MapState; - rotate(input: { deltaScaleX?: number; deltaScaleY?: number }): MapState; - rotateEnd(): MapState; - zoomStart(input: PositionInput): MapState; - zoom(input: PositionInput & { scale: number; startPos?: [number, number] }): MapState; - zoomEnd(): MapState; + constructor(props: MapStateProps); + getViewportProps(): ViewportProps; + getInteractiveState(): InteractiveState; + panStart(input: PositionInput): MapState; + pan(input: PositionInput & { startPos?: [number, number] }): MapState; + panEnd(): MapState; + rotateStart(input: PositionInput): MapState; + rotate(input: { deltaScaleX?: number; deltaScaleY?: number }): MapState; + rotateEnd(): MapState; + zoomStart(input: PositionInput): MapState; + zoom(input: PositionInput & { scale: number; startPos?: [number, number] }): MapState; + zoomEnd(): MapState; } export interface Center { @@ -202,7 +199,7 @@ export class LinearInterpolator extends TransitionInterpolator { export class FlyToInterpolator extends TransitionInterpolator {} export interface ViewStateChangeInfo { - viewState: ViewState; + viewState: ViewState; } export interface InteractiveMapProps extends StaticMapProps { From ca53c065a52c288b7d8d3fb3bde5709c6d496f7c Mon Sep 17 00:00:00 2001 From: Esteban Ibarra Date: Tue, 20 Nov 2018 15:18:30 -0500 Subject: [PATCH 121/836] Revert changes of react-native-draggable-flatlist --- .../index.d.ts | 59 ------------------- .../react-native-draggable-flatlist-tests.tsx | 44 -------------- .../tsconfig.json | 24 -------- .../tslint.json | 1 - 4 files changed, 128 deletions(-) delete mode 100644 types/react-native-draggable-flatlist/index.d.ts delete mode 100644 types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx delete mode 100644 types/react-native-draggable-flatlist/tsconfig.json delete mode 100644 types/react-native-draggable-flatlist/tslint.json diff --git a/types/react-native-draggable-flatlist/index.d.ts b/types/react-native-draggable-flatlist/index.d.ts deleted file mode 100644 index 0b96f0b3cd..0000000000 --- a/types/react-native-draggable-flatlist/index.d.ts +++ /dev/null @@ -1,59 +0,0 @@ -// Type definitions for react-native-draggable-flatlist 1.1 -// Project: https://github.com/computerjazz/react-native-draggable-flatlist#readme -// Definitions by: Stack Builders -// Esteban Ibarra -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import { VirtualizedListWithoutRenderItemProps } from "react-native"; -import { Component } from "react"; - -export interface RenderItemInfo { - item: ItemR; - index: number; - move: () => void; - moveEnd: () => void; - isActive: boolean; -} - -export interface OnMoveEndInfo { - data: ReadonlyArray | null; - to: number; - from: number; - row: ItemM; -} - -interface DraggableFlatListProps extends VirtualizedListWithoutRenderItemProps { - /** - * Items to be rendered. - */ - data: ReadonlyArray | null; - - /** - * Function that returns updated ordering of data - */ - onMoveEnd?: (info: OnMoveEndInfo) => void; - - /** - * Function that is called when row becomes active. - */ - onMoveBegin?: (index: number) => void; - - /** - * Sets where scrolling begins. - * - * Default is 5 - */ - scrollPercent?: number; - - /** - * Function that calls move when the row should become active (in an onPress, onLongPress, etc). Calls moveEnd when the gesture is complete (in onPressOut). - */ - renderItem: (info: RenderItemInfo) => React.ReactElement | null; -} - -declare class DraggableFlatList extends Component> { - constructor(props: DraggableFlatListProps); -} - -export default DraggableFlatList; diff --git a/types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx b/types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx deleted file mode 100644 index 40d613e4ea..0000000000 --- a/types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import * as React from 'react'; -import { TouchableOpacity, Text } from 'react-native'; -import DraggableFlatList, { RenderItemInfo } from 'react-native-draggable-flatlist'; - -interface Item { - name: string; - mail: string; -} - -class Example extends React.Component { - state = { - data: [ - { name: 'Esteban', mail: 'foo@foo.com' }, - { name: 'Xavier', mail: 'foo2@foo.com' }, - ] - }; - - renderItem({ item, index, move, moveEnd, isActive }: RenderItemInfo) { - return ( - - {index} - {item.name} - {item.mail} - - ); - } - - render() { - const { data } = this.state; - return ( - `draggable-item-${index}`} - scrollPercent={10} - onMoveEnd={({ data }) => this.setState({ data })} - ListFooterComponent={{'Hello'}} - /> - ); - } -} diff --git a/types/react-native-draggable-flatlist/tsconfig.json b/types/react-native-draggable-flatlist/tsconfig.json deleted file mode 100644 index b3c009feac..0000000000 --- a/types/react-native-draggable-flatlist/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true, - "jsx": "react-native" - }, - "files": [ - "index.d.ts", - "react-native-draggable-flatlist-tests.tsx" - ] -} diff --git a/types/react-native-draggable-flatlist/tslint.json b/types/react-native-draggable-flatlist/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/react-native-draggable-flatlist/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } From c907a148f89eefc1c82ed74c8392367835f7bfbb Mon Sep 17 00:00:00 2001 From: Andrew Goodale Date: Tue, 20 Nov 2018 14:11:05 -0500 Subject: [PATCH 122/836] Add declarations for XMLHttpRequest from DOM lib --- types/react-native/globals.d.ts | 89 +++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/types/react-native/globals.d.ts b/types/react-native/globals.d.ts index f5dcb25382..39723fcde1 100644 --- a/types/react-native/globals.d.ts +++ b/types/react-native/globals.d.ts @@ -119,3 +119,92 @@ type HeadersInit_ = Headers | string[][] | { [key: string]: string }; type RequestCredentials_ = "omit" | "same-origin" | "include"; type RequestMode_ = "navigate" | "same-origin" | "no-cors" | "cors"; type ResponseType_ = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; + +// +// XMLHttpRequest +// + +interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { + "readystatechange": Event; +} + +interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { +// msCaching: string; + onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null; + readonly readyState: number; + readonly response: any; + readonly responseText: string; + responseType: XMLHttpRequestResponseType; + readonly responseURL: string; + readonly responseXML: Document | null; + readonly status: number; + readonly statusText: string; + timeout: number; + readonly upload: XMLHttpRequestUpload; + withCredentials: boolean; + abort(): void; + getAllResponseHeaders(): string; + getResponseHeader(header: string): string | null; +// msCachingEnabled(): boolean; + open(method: string, url: string, async?: boolean, user?: string | null, password?: string | null): void; + overrideMimeType(mime: string): void; + send(data?: any): void; + setRequestHeader(header: string, value: string): void; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any): void; +// addEventListener(type: string, listener: EventListenerOrEventListenerObject): void; + removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any): void; +// removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void; +} + +declare var XMLHttpRequest: { + prototype: XMLHttpRequest; + new(): XMLHttpRequest; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; +}; + +interface XMLHttpRequestEventTargetEventMap { + "abort": Event; + "error": Event; + "load": Event; + "loadend": Event; + "loadstart": Event; + "progress": Event; + "timeout": Event; +} + +interface XMLHttpRequestEventTarget { + onabort: ((this: XMLHttpRequest, ev: Event) => any) | null; + onerror: ((this: XMLHttpRequest, ev: Event) => any) | null; + onload: ((this: XMLHttpRequest, ev: Event) => any) | null; + onloadend: ((this: XMLHttpRequest, ev: Event) => any) | null; + onloadstart: ((this: XMLHttpRequest, ev: Event) => any) | null; + onprogress: ((this: XMLHttpRequest, ev: Event) => any) | null; + ontimeout: ((this: XMLHttpRequest, ev: Event) => any) | null; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any): void; +// addEventListener(type: string, listener: EventListenerOrEventListenerObject): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any): void; +// removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void; +} + +interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { + addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any): void; +// addEventListener(type: string, listener: EventListenerOrEventListenerObject): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any): void; +// removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void; +} + +declare var XMLHttpRequestUpload: { + prototype: XMLHttpRequestUpload; + new(): XMLHttpRequestUpload; +}; + +type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; From 1a8e6368f6165ba14733ebc272188d6a7d192b03 Mon Sep 17 00:00:00 2001 From: "jan@pidgin" Date: Tue, 20 Nov 2018 21:41:55 +0100 Subject: [PATCH 123/836] Fixing dynamic validation schema and typing. --- types/vuelidate/vue.d.ts | 15 ++++----- types/vuelidate/vuelidate-tests.ts | 53 +++++++++++++++--------------- 2 files changed, 34 insertions(+), 34 deletions(-) diff --git a/types/vuelidate/vue.d.ts b/types/vuelidate/vue.d.ts index d1ef01e7bc..8232d96038 100644 --- a/types/vuelidate/vue.d.ts +++ b/types/vuelidate/vue.d.ts @@ -5,20 +5,18 @@ import { ValidationRule } from './lib/validators' import { Validation } from './vuelidate' declare module 'vue/types/vue' { - type ValidationProperties = { - [P in keyof V]?: Validation + type ValidationProperties = { + [P in keyof V]?: Validation & ValidationProperties } - interface ValidationGroups { - [groupName: string]: ValidationProperties + interface ValidationGroups { + [groupName: string]: Validation & ValidationProperties } interface Vue { - $v: ValidationProperties & ValidationGroups & Validation + $v: ValidationProperties & ValidationGroups & Validation delayTouch(v: Validation): void - - validations(): any // unknown } } @@ -35,11 +33,12 @@ declare module 'vue/types/options' { type GroupDecl = string[] type AsyncDecl = (...args: any[]) => boolean | Promise type NestedDecl = RuleDecl + type DynamicDecl = () => RuleDecl interface RuleDecl { [rule: string]: ValidationDecl | GroupDecl | AsyncDecl | NestedDecl } interface ComponentOptions { - validations?: RuleDecl + validations?: RuleDecl | DynamicDecl } } diff --git a/types/vuelidate/vuelidate-tests.ts b/types/vuelidate/vuelidate-tests.ts index 20e320b3a7..43cf5f5648 100644 --- a/types/vuelidate/vuelidate-tests.ts +++ b/types/vuelidate/vuelidate-tests.ts @@ -116,19 +116,23 @@ export class ValidComponent extends Vue { myField = '' touchMap = new WeakMap() - delayTouch($v: Validation) { - $v.$reset() - if (this.touchMap.has($v)) { - clearTimeout(this.touchMap.get($v)) + delayTouch(v: Validation) { + v.$reset() + if (this.touchMap.has(v)) { + clearTimeout(this.touchMap.get(v)) } - this.touchMap.set($v, setTimeout($v.$touch, 1000)) + this.touchMap.set(v, setTimeout(v.$touch, 1000)) } accessValidatorParams() { - console.log(this.$v.$params.username) - if (this.$v.username) { - console.log(this.$v.username.$params) + console.log(this.$v.$params.form) + + if (this.$v.form) { + console.log(this.$v.form.$params) + console.log(this.$v.form.$params.nestedA) + console.log(this.$v.form.nestedA) } + console.log(this.$v.validationGroup.$params) } accessGroups() { @@ -140,25 +144,22 @@ export class ValidComponent extends Vue { } hasDescription = false - validations() { - if (!this.hasDescription) { - return { - name: { - required - } - } - } else { - return { - name: { - required - }, - description: { - required - } - } - } - } + get isRepoValid() { return !this.$v.$invalid } } + +@Component({ + validations() { + const self = this as Valid2Component // assert + return self.myToggle + ? { myField1: required, myField2: contains('maybe') } + : { myField1: contains('maybe'), myField2: required } + } +}) +export class Valid2Component extends Vue { + myToggle = false + myField1 = '' + myField2 = '' +} From 91af0af03949ade47e77370d04b3922e543550ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andi=20P=C3=A4tzold?= Date: Tue, 20 Nov 2018 21:54:08 +0100 Subject: [PATCH 124/836] fix(mailgun-js) fix validate return value for callbacks --- types/mailgun-js/index.d.ts | 36 +++++++++------------------- types/mailgun-js/mailgun-js-tests.ts | 19 +++++++-------- 2 files changed, 20 insertions(+), 35 deletions(-) diff --git a/types/mailgun-js/index.d.ts b/types/mailgun-js/index.d.ts index 82a75913cf..eaa210e6e1 100644 --- a/types/mailgun-js/index.d.ts +++ b/types/mailgun-js/index.d.ts @@ -126,6 +126,8 @@ declare namespace Mailgun { unparseable: string[]; } + type ValidationCallback = (error: Error, body: ValidateResponse) => void; + interface ValidateResponse { address: string; did_you_mean: string | null; @@ -151,32 +153,16 @@ declare namespace Mailgun { bodySignature: string ): boolean; - parse( - addressList: string[], - callback?: (error: Error, body: validation.ValidateResponse) => void - ): Promise; + parse(addressList: string[], callback?: validation.ValidationCallback): Promise; - validate( - address: string, - callback?: (error: Error, body: validation.ValidateResponse) => void - ): Promise; - validate( - address: string, - isPrivate: boolean, - callback?: (error: Error, body: validation.ValidateResponse) => void - ): Promise; - validate( - address: string, - // tslint:disable-next-line unified-signatures - opts: { [key: string]: any }, - callback?: (error: Error, body: validation.ValidateResponse) => void - ): Promise; - validate( - address: string, - isPrivate: boolean, - opts: { [key: string]: any }, - callback?: (error: Error, body: validation.ValidateResponse) => void - ): Promise; + validate(address: string, callback: validation.ValidationCallback): void; + validate(address: string, opts: { [key: string]: any }, callback: validation.ValidationCallback): void; + // tslint:disable-next-line unified-signatures + validate(address: string, isPrivate: boolean, callback: validation.ValidationCallback): void; + validate(address: string, isPrivate: boolean, opts: { [key: string]: any }, callback: validation.ValidationCallback): void; + + validate(address: string, isPrivate?: boolean, opts?: { [key: string]: any }): Promise; + validate(address: string, opts: { [key: string]: any }): Promise; } interface Lists { diff --git a/types/mailgun-js/mailgun-js-tests.ts b/types/mailgun-js/mailgun-js-tests.ts index e2bef4cab3..12bf18e437 100644 --- a/types/mailgun-js/mailgun-js-tests.ts +++ b/types/mailgun-js/mailgun-js-tests.ts @@ -30,16 +30,15 @@ const exampleSendData: mailgunFactory.messages.SendData = { mailgun.messages().send(exampleSendData, (err, body) => {}); -const validationResult1: Promise = - mailgun.validate("foo@mailgun.net"); -const validationResult2: Promise = - mailgun.validate("foo@mailgun.net", (error, body) => {}); -const validationResult3: Promise = - mailgun.validate("foo@mailgun.net", true); -const validationResult4: Promise = - mailgun.validate("foo@mailgun.net", true, (error, body) => {}); -const validationResult5: Promise = - mailgun.validate("foo@mailgun.net", true, { option: "option" }, (error, body) => {}); +let validationResultPromise: Promise; +validationResultPromise = mailgun.validate("foo@mailgun.net"); +validationResultPromise = mailgun.validate("foo@mailgun.net", true); +validationResultPromise = mailgun.validate("foo@mailgun.net", true, { option: "option" }); +validationResultPromise = mailgun.validate("foo@mailgun.net", { option: "option" }); +mailgun.validate("foo@mailgun.net", (error, body) => {}); +mailgun.validate("foo@mailgun.net", true, (error, body) => {}); +mailgun.validate("foo@mailgun.net", true, { option: "option" }, (error, body) => {}); +mailgun.validate("foo@mailgun.net", { option: "option" }, (error, body) => {}); const validationResult6: mailgunFactory.validation.ValidateResponse = { address: "foo@mailgun.net", From 35bca8038a202d1676cd68ce5c05409a2ee151a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andi=20P=C3=A4tzold?= Date: Tue, 20 Nov 2018 22:06:08 +0100 Subject: [PATCH 125/836] feat(mailgun-js) specify validation options --- types/mailgun-js/index.d.ts | 19 +++++++++++++++---- types/mailgun-js/mailgun-js-tests.ts | 8 ++++---- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/types/mailgun-js/index.d.ts b/types/mailgun-js/index.d.ts index eaa210e6e1..0c6ef0eef3 100644 --- a/types/mailgun-js/index.d.ts +++ b/types/mailgun-js/index.d.ts @@ -128,6 +128,15 @@ declare namespace Mailgun { type ValidationCallback = (error: Error, body: ValidateResponse) => void; + interface ValidationOptionsPublic { + api_key?: string; + mailbox_verification?: boolean | "true" | "false"; + } + + interface ValidationOptionsPrivate { + mailbox_verification?: boolean | "true" | "false"; + } + interface ValidateResponse { address: string; did_you_mean: string | null; @@ -156,13 +165,15 @@ declare namespace Mailgun { parse(addressList: string[], callback?: validation.ValidationCallback): Promise; validate(address: string, callback: validation.ValidationCallback): void; - validate(address: string, opts: { [key: string]: any }, callback: validation.ValidationCallback): void; + validate(address: string, opts: validation.ValidationOptionsPublic, callback: validation.ValidationCallback): void; // tslint:disable-next-line unified-signatures validate(address: string, isPrivate: boolean, callback: validation.ValidationCallback): void; - validate(address: string, isPrivate: boolean, opts: { [key: string]: any }, callback: validation.ValidationCallback): void; + validate(address: string, isPrivate: false, opts: validation.ValidationOptionsPublic, callback: validation.ValidationCallback): void; + validate(address: string, isPrivate: true, opts: validation.ValidationOptionsPrivate, callback: validation.ValidationCallback): void; - validate(address: string, isPrivate?: boolean, opts?: { [key: string]: any }): Promise; - validate(address: string, opts: { [key: string]: any }): Promise; + validate(address: string, opts?: validation.ValidationOptionsPublic): Promise; + validate(address: string, isPrivate: false, opts?: validation.ValidationOptionsPublic): Promise; + validate(address: string, isPrivate: true, opts?: validation.ValidationOptionsPrivate): Promise; } interface Lists { diff --git a/types/mailgun-js/mailgun-js-tests.ts b/types/mailgun-js/mailgun-js-tests.ts index 12bf18e437..e06e683248 100644 --- a/types/mailgun-js/mailgun-js-tests.ts +++ b/types/mailgun-js/mailgun-js-tests.ts @@ -33,12 +33,12 @@ mailgun.messages().send(exampleSendData, (err, body) => {}); let validationResultPromise: Promise; validationResultPromise = mailgun.validate("foo@mailgun.net"); validationResultPromise = mailgun.validate("foo@mailgun.net", true); -validationResultPromise = mailgun.validate("foo@mailgun.net", true, { option: "option" }); -validationResultPromise = mailgun.validate("foo@mailgun.net", { option: "option" }); +validationResultPromise = mailgun.validate("foo@mailgun.net", true, { mailbox_verification: true }); +validationResultPromise = mailgun.validate("foo@mailgun.net", { mailbox_verification: false, api_key: "..." }); mailgun.validate("foo@mailgun.net", (error, body) => {}); mailgun.validate("foo@mailgun.net", true, (error, body) => {}); -mailgun.validate("foo@mailgun.net", true, { option: "option" }, (error, body) => {}); -mailgun.validate("foo@mailgun.net", { option: "option" }, (error, body) => {}); +mailgun.validate("foo@mailgun.net", true, { mailbox_verification: true }, (error, body) => {}); +mailgun.validate("foo@mailgun.net", { mailbox_verification: false, api_key: "..." }, (error, body) => {}); const validationResult6: mailgunFactory.validation.ValidateResponse = { address: "foo@mailgun.net", From 02ac8504a80ccb230ca6daae11ddb8b42325bbeb Mon Sep 17 00:00:00 2001 From: Kenza Iraki Date: Tue, 20 Nov 2018 16:28:33 -0500 Subject: [PATCH 126/836] Fixed @feathersjs/feathers find service method return type --- types/feathersjs__feathers/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/feathersjs__feathers/index.d.ts b/types/feathersjs__feathers/index.d.ts index 53cdf182a1..5948eadc27 100644 --- a/types/feathersjs__feathers/index.d.ts +++ b/types/feathersjs__feathers/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @feathersjs/feathers 3.0 +// Type definitions for @feathersjs/feathers 3.1 // Project: http://feathersjs.com/ // Definitions by: Jan Lohage // Abraao Alves @@ -138,7 +138,7 @@ export interface HooksObject { // todo: figure out what to do: These methods don't actually need to be implemented, so they can be undefined at runtime. Yet making them optional gets cumbersome in strict mode. export interface ServiceMethods { - find(params?: Params): Promise>; + find(params?: Params): Promise>; get(id: Id, params?: Params): Promise; From 73cfb3d8b8cf0752eca211124922fdfd140a8439 Mon Sep 17 00:00:00 2001 From: Ulrich Buchgraber Date: Tue, 20 Nov 2018 13:26:05 +0100 Subject: [PATCH 127/836] Add `spawn()` overload which takes `options` but no `args` --- types/node/index.d.ts | 1 + types/node/node-tests.ts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index fdda9e948a..0f6698035d 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -2655,6 +2655,7 @@ declare module "child_process" { windowsHide?: boolean; } + function spawn(command: string, options?: SpawnOptions): ChildProcess; function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; interface ExecOptions { diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 20159c70d9..c59ed08064 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -2636,6 +2636,8 @@ async function asyncStreamPipelineFinished() { { childProcess.exec("echo test"); childProcess.exec("echo test", { windowsHide: true }); + childProcess.spawn("echo"); + childProcess.spawn("echo", { windowsHide: true }); childProcess.spawn("echo", ["test"], { windowsHide: true }); childProcess.spawn("echo", ["test"], { windowsHide: true, argv0: "echo-test" }); childProcess.spawn("echo", ["test"], { stdio: [0xdeadbeef, "inherit", undefined, "pipe"] }); From 1b9be406451a0a5a51d8d9fc3f365644c4e6dcce Mon Sep 17 00:00:00 2001 From: Kenza Iraki Date: Tue, 20 Nov 2018 16:48:36 -0500 Subject: [PATCH 128/836] Fixed missing/inaccurate properties in analytics-node --- types/analytics-node/index.d.ts | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/types/analytics-node/index.d.ts b/types/analytics-node/index.d.ts index 6834087ff7..cc9e5386e2 100644 --- a/types/analytics-node/index.d.ts +++ b/types/analytics-node/index.d.ts @@ -22,8 +22,8 @@ declare namespace AnalyticsNode { }, timestamp?: Date; messageId?: string; - anonymousId: string | number; - userId: string | number; + anonymousId?: string | number; + userId?: string | number; } interface Data { @@ -47,7 +47,8 @@ declare namespace AnalyticsNode { /* The identify method lets you tie a user to their actions and record traits about them. */ identify(message: { - userId: string | number; + userId?: string | number; + anonymousId?: string | number; traits?: Object; timestamp?: Date; context?: Object; @@ -56,7 +57,8 @@ declare namespace AnalyticsNode { /* The track method lets you record the actions your users perform. */ track(message: { - userId: string | number; + userId?: string | number; + anonymousId?: string | number; event: string; properties?: Object; timestamp?: Date; @@ -67,7 +69,8 @@ declare namespace AnalyticsNode { /* The page method lets you record page views on your website, along with optional extra information about the page being viewed. */ page(message: { - userId: string | number; + userId?: string | number; + anonymousId?: string | number; category?: string; name?: string; properties?: Object; @@ -79,19 +82,20 @@ declare namespace AnalyticsNode { /* alias is how you associate one identity with another. */ alias(message: { previousId: string | number; - userId: string | number; + userId?: string | number; + anonymousId?: string | number; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; /* Group calls can be used to associate individual users with shared accounts or companies. */ group(message: { - userId: string | number; + userId?: string | number; + anonymousId?: string | number; groupId: string | number; traits?: Object; context?: Object; timestamp?: Date; - anonymous_id?: string | number; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; From ea41934fb03b6253b574329347192fa34c7a185e Mon Sep 17 00:00:00 2001 From: Boris Sergeyev Date: Tue, 20 Nov 2018 22:41:35 +0100 Subject: [PATCH 129/836] [react-redux] improved linting --- types/react-redux/index.d.ts | 110 ++--- types/react-redux/react-redux-tests.tsx | 567 +++++++++++------------- types/react-redux/tslint.json | 80 +--- 3 files changed, 302 insertions(+), 455 deletions(-) diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index d1889b54fe..2f919581f4 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-redux 6.0.5 +// Type definitions for react-redux 6.0 // Project: https://github.com/reduxjs/react-redux // Definitions by: Qubo , // Kenzie Togami , @@ -43,15 +43,14 @@ import { } from 'redux'; // Omit taken from https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html -type Omit = Pick>; +export type Omit = Pick>; export interface DispatchProp { dispatch: Dispatch; } -interface AdvancedComponentDecorator { - (component: ComponentType): ComponentClass; -} +export type AdvancedComponentDecorator = + (component: ComponentType) => ComponentClass; /** * A property P will be present if: @@ -65,7 +64,7 @@ interface AdvancedComponentDecorator { * - if property P is present in InjectedProps but does not extend the * DecorationTargetProps[P] definition, its definition will be that of InjectedProps[P] */ -type Matching = { +export type Matching = { [P in keyof DecorationTargetProps]: P extends keyof InjectedProps ? InjectedProps[P] extends DecorationTargetProps[P] ? DecorationTargetProps[P] @@ -83,7 +82,7 @@ type Matching = { * required by the decorated (right hand side) component. * But any property required by the decorated component must be satisfied by the injected property. */ -type Shared< +export type Shared< InjectedProps, DecorationTargetProps extends Shared > = { @@ -91,43 +90,41 @@ type Shared< }; // Infers prop type from component C -type GetProps = C extends ComponentType ? P : never; +export type GetProps = C extends ComponentType ? P : never; // Applies LibraryManagedAttributes (proper handling of defaultProps // and propTypes), as well as defines WrappedComponent. -type ConnectedComponentClass = ComponentClass> & { +export type ConnectedComponentClass = ComponentClass> & { WrappedComponent: C; -} +}; // Injects props and removes them from the prop requirements. // Will not pass through the injected props if they are passed in during // render. Also adds new prop requirements from TNeedsProps. -export interface InferableComponentEnhancerWithProps { - >>>( +export type InferableComponentEnhancerWithProps = + >>>( component: C - ): ConnectedComponentClass, keyof Shared>> & TNeedsProps> -} + ) => ConnectedComponentClass, keyof Shared>> & TNeedsProps>; // Injects props and removes them from the prop requirements. // Will not pass through the injected props if they are passed in during // render. export type InferableComponentEnhancer = - InferableComponentEnhancerWithProps + InferableComponentEnhancerWithProps; -type HandleThunkActionCreator = +export type HandleThunkActionCreator = TActionCreator extends (...args: any[]) => (...args: any[]) => any ? ReturnType - : TActionCreator + : TActionCreator; // redux-thunk middleware returns thunk's return value from dispatch call // https://github.com/reduxjs/redux-thunk#composition -type WithThunkActionCreators = +export type WithThunkActionCreators = TDispatchProps extends { [key: string]: any } ? { [C in keyof TDispatchProps]: HandleThunkActionCreator } - : TDispatchProps - + : TDispatchProps; /** * Connects a React component to a Redux store. @@ -149,6 +146,7 @@ type WithThunkActionCreators = * @param options */ export interface Connect { + // tslint:disable:no-unnecessary-generics (): InferableComponentEnhancer; ( @@ -193,6 +191,7 @@ export interface Connect { mapStateToProps: MapStateToPropsParam, mapDispatchToProps: MapDispatchToPropsParam, mergeProps: MergeProps, + options?: Options ): InferableComponentEnhancerWithProps; ( @@ -221,48 +220,37 @@ export interface Connect { TStateProps & WithThunkActionCreators, TOwnProps >; - - ( - mapStateToProps: MapStateToPropsParam, - mapDispatchToProps: MapDispatchToPropsParam, - mergeProps: MergeProps, - options: Options - ): InferableComponentEnhancerWithProps; + // tslint:enable:no-unnecessary-generics } /** * The connect function. See {@type Connect} for details. */ -export declare const connect: Connect; +export const connect: Connect; -interface MapStateToProps { - (state: State, ownProps: TOwnProps): TStateProps; -} +export type MapStateToProps = + (state: State, ownProps: TOwnProps) => TStateProps; -interface MapStateToPropsFactory { - (initialState: State, ownProps: TOwnProps): MapStateToProps; -} +export type MapStateToPropsFactory = + (initialState: State, ownProps: TOwnProps) => MapStateToProps; -type MapStateToPropsParam = MapStateToPropsFactory | MapStateToProps | null | undefined; +export type MapStateToPropsParam = MapStateToPropsFactory | MapStateToProps | null | undefined; -interface MapDispatchToPropsFunction { - (dispatch: Dispatch, ownProps: TOwnProps): TDispatchProps; -} +export type MapDispatchToPropsFunction = + (dispatch: Dispatch, ownProps: TOwnProps) => TDispatchProps; -type MapDispatchToProps = +export type MapDispatchToProps = MapDispatchToPropsFunction | TDispatchProps; -interface MapDispatchToPropsFactory { - (dispatch: Dispatch, ownProps: TOwnProps): MapDispatchToProps; -} +export type MapDispatchToPropsFactory = + (dispatch: Dispatch, ownProps: TOwnProps) => MapDispatchToProps; -type MapDispatchToPropsParam = MapDispatchToPropsFactory | MapDispatchToProps; +export type MapDispatchToPropsParam = MapDispatchToPropsFactory | MapDispatchToProps; -interface MergeProps { - (stateProps: TStateProps, dispatchProps: TDispatchProps, ownProps: TOwnProps): TMergedProps; -} +export type MergeProps = + (stateProps: TStateProps, dispatchProps: TDispatchProps, ownProps: TOwnProps) => TMergedProps; -interface Options extends ConnectOptions { +export interface Options extends ConnectOptions { /** * If true, implements shouldComponentUpdate and shallowly compares the result of mergeProps, * preventing unnecessary updates, assuming that the component is a “pure” component @@ -303,11 +291,12 @@ interface OptionsselectorFactory in the factoryOptions argument. */ -export declare function connectAdvanced( +export function connectAdvanced( + // tslint:disable-next-line no-unnecessary-generics selectorFactory: SelectorFactory, connectOptions?: ConnectOptions & TFactoryOptions ): AdvancedComponentDecorator; @@ -320,13 +309,10 @@ export declare function connectAdvancedselector to return that * previous object when appropriate. */ -export interface SelectorFactory { - (dispatch: Dispatch, factoryOptions: TFactoryOptions): Selector -} +export type SelectorFactory = + (dispatch: Dispatch, factoryOptions: TFactoryOptions) => Selector; -export interface Selector { - (state: S, ownProps: TOwnProps): TProps -} +export type Selector = (state: S, ownProps: TOwnProps) => TProps; export interface ConnectOptions { /** @@ -336,13 +322,13 @@ export interface ConnectOptions { * @default name => 'ConnectAdvanced('+name+')' * @param componentName */ - getDisplayName?: (componentName: string) => string + getDisplayName?: (componentName: string) => string; /** * Shown in error messages. Usually overridden by wrapper functions. * * @default 'connectAdvanced' */ - methodName?: string + methodName?: string; /** * If defined, a property named this value will be added to the props passed to the wrapped component. Its value * will be the number of times the component has been rendered, which can be useful for tracking down unnecessary @@ -350,27 +336,27 @@ export interface ConnectOptions { * * @default undefined */ - renderCountProp?: string + renderCountProp?: string; /** * Controls whether the connector component subscribes to redux store state changes. If set to false, it will only * re-render on componentWillReceiveProps. * * @default true */ - shouldHandleStateChanges?: boolean + shouldHandleStateChanges?: boolean; /** * The key of props/context to get the store. You probably only need this if you are in the inadvisable position of * having multiple stores. * * @default 'store' */ - storeKey?: string + storeKey?: string; /** * If true, stores a ref to the wrapped component instance and makes it available via getWrappedInstance() method. * * @default false */ - withRef?: boolean + withRef?: boolean; } export interface ProviderProps { @@ -392,4 +378,4 @@ export class Provider extends Component {} + class TestComponent extends React.Component {} - const Test = connect()(TestComponent) + const Test = connect()(TestComponent); - const verify = + const verify = ; } -namespace MapState { - interface OwnProps { foo: string } - interface StateProps { bar: number } +function MapState() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapStateToProps = (_: any) => ({ bar: 1 - }) + }); const Test = connect( mapStateToProps - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapStateWithDispatchProp { - interface OwnProps { foo: string } - interface StateProps { bar: number, dispatch: Dispatch } +function MapStateWithDispatchProp() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; dispatch: Dispatch; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapStateToProps = (_: any) => ({ bar: 1 - }) + }); const Test = connect( mapStateToProps - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapStateFactory { - interface OwnProps { foo: string } - interface StateProps { bar: number } +function MapStateFactory() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapStateToProps = () => () => ({ bar: 1 - }) + }); const Test = connect( mapStateToProps - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapDispatch { - interface OwnProps { foo: string } - interface DispatchProps { onClick: () => void } +function MapDispatch() { + interface OwnProps { foo: string; } + interface DispatchProps { onClick: () => void; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapDispatchToProps = () => ({ onClick: () => {} - }) + }); const TestNull = connect( null, mapDispatchToProps, - )(TestComponent) + )(TestComponent); - const verifyNull = + const verifyNull = ; const TestUndefined = connect( undefined, mapDispatchToProps, - )(TestComponent) + )(TestComponent); - const verifyUndefined = + const verifyUndefined = ; } - -namespace MapDispatchWithThunkActionCreators { - class TestComponent extends Component<{ +function MapDispatchWithThunkActionCreators() { + class TestComponent extends React.Component<{ foo: string, onClick(): void, thunkAction(): Promise - }>{} + }> {} const mapDispatchToProps = () => ({ onClick: () => {}, thunkAction: () => async () => {} - }) + }); const Test = connect( null, mapDispatchToProps, - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } - -namespace MapStateAndDispatchObject { - interface ClickPayload { count: number } +function MapStateAndDispatchObject() { + interface ClickPayload { count: number; } const onClick: ActionCreator = () => ({ count: 1 }); const dispatchToProps = { onClick, }; - interface OwnProps { foo: string } - interface StateProps { bar: number } - interface DispatchProps { onClick: ActionCreator } + interface OwnProps { foo: string; } + interface StateProps { bar: number; } + interface DispatchProps { onClick: ActionCreator; } const mapStateToProps = (_: any, __: OwnProps): StateProps => ({ bar: 1 - }) + }); - class TestComponent extends Component {} + class TestComponent extends React.Component {} const Test = connect( mapStateToProps, dispatchToProps, - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapDispatchFactory { - interface OwnProps { foo: string } - interface DispatchProps { onClick: () => void } +function MapDispatchFactory() { + interface OwnProps { foo: string; } + interface DispatchProps { onClick: () => void; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapDispatchToPropsFactory = () => () => ({ onClick: () => {} - }) + }); const TestNull = connect( null, mapDispatchToPropsFactory, - )(TestComponent) + )(TestComponent); - const verifyNull = + const verifyNull = ; const TestUndefined = connect( undefined, mapDispatchToPropsFactory, - )(TestComponent) + )(TestComponent); - const verifyUndefined = + const verifyUndefined = ; } -namespace MapStateAndDispatch { - interface OwnProps { foo: string } - interface StateProps { bar: number } - interface DispatchProps { onClick: () => void } +function MapStateAndDispatch() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; } + interface DispatchProps { onClick: () => void; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapStateToProps = () => ({ bar: 1 - }) + }); const mapDispatchToProps = () => ({ onClick: () => {} - }) + }); const Test = connect( mapStateToProps, mapDispatchToProps, - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapStateFactoryAndDispatch { - interface OwnProps { foo: string } - interface StateProps { bar: number } - interface DispatchProps { onClick: () => void } +function MapStateFactoryAndDispatch() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; } + interface DispatchProps { onClick: () => void; } - const mapStateToPropsFactory = () => () =>({ + const mapStateToPropsFactory = () => () => ({ bar: 1 - }) + }); const mapDispatchToProps = () => ({ onClick: () => {} - }) + }); - class TestComponent extends Component {} + class TestComponent extends React.Component {} const Test = connect( mapStateToPropsFactory, mapDispatchToProps, - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapStateFactoryAndDispatchFactory { - interface OwnProps { foo: string } - interface StateProps { bar: number } - interface DispatchProps { onClick: () => void } +function MapStateFactoryAndDispatchFactory() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; } + interface DispatchProps { onClick: () => void; } - const mapStateToPropsFactory = () => () =>({ + const mapStateToPropsFactory = () => () => ({ bar: 1 - }) + }); const mapDispatchToPropsFactory = () => () => ({ onClick: () => {} - }) + }); - class TestComponent extends Component {} + class TestComponent extends React.Component {} const Test = connect( mapStateToPropsFactory, mapDispatchToPropsFactory, - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapStateAndDispatchAndMerge { - interface OwnProps { foo: string } - interface StateProps { bar: number } - interface DispatchProps { onClick: () => void } +function MapStateAndDispatchAndMerge() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; } + interface DispatchProps { onClick: () => void; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapStateToProps = () => ({ bar: 1 - }) + }); const mapDispatchToProps = () => ({ onClick: () => {} - }) + }); const mergeProps = (stateProps: StateProps, dispatchProps: DispatchProps) => ( - Object.assign({}, stateProps, dispatchProps) - ) + { ...stateProps, ...dispatchProps } + ); const Test = connect( mapStateToProps, mapDispatchToProps, mergeProps, - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapStateAndOptions { +function MapStateAndOptions() { interface State { state: string; } - interface OwnProps { foo: string } - interface StateProps { bar: number } - interface DispatchProps { dispatch: Dispatch } + interface OwnProps { foo: string; } + interface StateProps { bar: number; } + interface DispatchProps { dispatch: Dispatch; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapStateToProps = (state: State) => ({ bar: 1 - }) + }); const areStatePropsEqual = (next: StateProps, current: StateProps) => true; @@ -290,17 +290,17 @@ namespace MapStateAndOptions { pure: true, areStatePropsEqual, } - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } interface CounterState { counter: number; } -declare var increment: Function; +declare var increment: () => { type: string }; -class Counter extends Component { +class Counter extends React.Component { render() { return ( -