diff --git a/node-gettext/index.d.ts b/node-gettext/index.d.ts new file mode 100644 index 0000000000..735f8db84b --- /dev/null +++ b/node-gettext/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for node-gettext 2.0 +// Project: http://github.com/alexanderwallin/node-gettext +// Definitions by: Sameer K.C. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = GetText; +declare class GetText { + constructor(options?: { debug: boolean; }); + addTranslations(locale: string, domain: string, translations: object): void; + dgettext(domain: string, msgid: string): string; + dngettext(domain: string, msgid: string, msgidPlural: string, count: number): string; + dnpgettext(domain: string, msgctxt: string, msgid: string, msgidPlural: string, count: number): string; + dpgettext(domain: string, msgctxt: string, msgid: string): string; + emit(eventName: string, eventData: any): void; + getComment(domain: string, msgctxt: string, msgid: string): object | boolean; + gettext(msgid: string): string; + ngettext(msgid: string, msgidPlural: string, count: number): string; + npgettext(msgctxt: string, msgid: string, msgidPlural: string, count: number): string; + off(eventName: string, callback: (params: any) => void): string; + on(eventName: string, callback: (params: any) => void): void; + pgettext(msgctxt: string, msgid: string): string; + setLocale(locale: string): void; + setTextDomain(domain: string): void; + static getLanguageCode(locale: string): string; + textdomain(domain: string): void; + warn(message: string): void; +} diff --git a/node-gettext/node-gettext-tests.ts b/node-gettext/node-gettext-tests.ts new file mode 100644 index 0000000000..e20e6aacac --- /dev/null +++ b/node-gettext/node-gettext-tests.ts @@ -0,0 +1,34 @@ +// with tsc v 2.7 & esModuleInterop & allowSyntheticDefaultImports enabled in tsconfig.json +import Gettext from 'node-gettext'; +// or without +// import Gettext = require('node-getttext'); + +const translations = {}; +const gt = new Gettext({ debug: true }); +const msgid = 'Get translation'; +const msgidPlural = 'Get translations'; +const domain = 'domain'; +const msgctxt = 'context'; +const count = 2; + +gt.addTranslations('en-US', 'messages', translations); +gt.setTextDomain(domain); +gt.textdomain(domain); +gt.setLocale('en-US'); +gt.gettext(msgid); +gt.dgettext('', msgid); +gt.dngettext(domain, msgid, msgidPlural, count); +gt.dnpgettext(domain, msgctxt, msgid, msgidPlural, count); +gt.dpgettext(domain, msgctxt, msgid); +gt.getComment(domain, msgctxt, msgid); +gt.ngettext(msgid, msgidPlural, count); +gt.npgettext(msgctxt, msgid, msgidPlural, count); +gt.pgettext(msgctxt, msgid); +Gettext.getLanguageCode('en-US'); +gt.warn('warning'); +const errorListener = (error: string) => { + // do something; +}; +gt.on('error', errorListener); +gt.emit('error', 'Error occurred'); +gt.off('error', errorListener); diff --git a/node-gettext/tsconfig.json b/node-gettext/tsconfig.json new file mode 100644 index 0000000000..9306d23426 --- /dev/null +++ b/node-gettext/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true + }, + "files": [ + "index.d.ts", + "node-gettext-tests.ts" + ] +} diff --git a/types/hibp/tslint.json b/node-gettext/tslint.json similarity index 100% rename from types/hibp/tslint.json rename to node-gettext/tslint.json diff --git a/notNeededPackages.json b/notNeededPackages.json index 251442309d..4acd790e24 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -684,6 +684,12 @@ "sourceRepoURL": "https://handsontable.com/", "asOfVersion": "0.35.0" }, + { + "libraryName": "hibp", + "typingsPackageName": "hibp", + "sourceRepoURL": "https://github.com/wKovacs64/hibp", + "asOfVersion": "7.3.0" + }, { "libraryName": "homeworks", "typingsPackageName": "homeworks", @@ -1482,6 +1488,12 @@ "sourceRepoURL": "https://github.com/zeh/simplesignal", "asOfVersion": "1.0.0" }, + { + "libraryName": "sip.js", + "typingsPackageName": "sip.js", + "sourceRepoURL": "https://github.com/onsip/SIP.js", + "asOfVersion": "0.12.0" + }, { "libraryName": "smooth-scrollbar", "typingsPackageName": "smooth-scrollbar", diff --git a/types/accept/accept-tests.ts b/types/accept/accept-tests.ts index 011216ede4..659d05c174 100644 --- a/types/accept/accept-tests.ts +++ b/types/accept/accept-tests.ts @@ -14,6 +14,8 @@ accept.language("en;q=0.7, en-GB;q=0.8", ["en-gb"]); // language === "en-GB" const languages = accept.languages("da, en;q=0.7, en-GB;q=0.8"); // languages === ["da", "en-GB", "en"] languages.lastIndexOf(''); +accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1"); +accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1", ["application/json", "text/html"]); const mediaTypes = accept.mediaTypes("text/plain, application/json;q=0.5, text/html, */*;q=0.1"); // mediaTypes === ["text/plain", "text/html", "application/json", "*/*"] mediaTypes.lastIndexOf(''); diff --git a/types/accept/index.d.ts b/types/accept/index.d.ts index b067ea4306..886193a01e 100644 --- a/types/accept/index.d.ts +++ b/types/accept/index.d.ts @@ -10,6 +10,7 @@ export function encoding(encodingHeader?: string, preferences?: string[]): strin export function encodings(encodingHeader?: string): string[]; export function language(languageHeader?: string, preferences?: string[]): string; export function languages(languageHeader?: string): string[]; +export function mediaType(mediaTypeHeader?: string, preferences?: string[]): string; export function mediaTypes(mediaTypeHeader?: string): string[]; export function parseAll( headers: Record diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts index cd20b57f05..2588539c0c 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -549,6 +549,16 @@ declare namespace AceAjax { getFoldsInRange(range: Range): any; highlight(text: string): void; + + + /** + * Highlight lines from `startRow` to `EndRow`. + * @param startRow Define the start line of the highlight + * @param endRow Define the end line of the highlight + * @param clazz Set the CSS class for the marker + * @param inFront Set to `true` to establish a front marker + **/ + highlightLines(startRow:number, endRow: number, clazz: string, inFront: boolean): Range; /** * Sets the `EditSession` to point to a new `Document`. If a `BackgroundTokenizer` exists, it also points to `doc`. diff --git a/types/ali-oss/index.d.ts b/types/ali-oss/index.d.ts index 13f7f56ff9..e4f9e09e7c 100644 --- a/types/ali-oss/index.d.ts +++ b/types/ali-oss/index.d.ts @@ -18,6 +18,7 @@ declare namespace OSS { 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 + cname?: boolean; // use custom domain name } interface Bucket { @@ -29,7 +30,7 @@ declare namespace OSS { type StorageType = "Standard" | "IA" | "Archive"; - type ACLType = "public-read-write" | "public-read" | "and private"; + type ACLType = "public-read-write" | "public-read" | "private"; type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT"; @@ -174,6 +175,7 @@ declare namespace OSS { 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; + headers?: object; } interface PutObjectResult { @@ -188,6 +190,7 @@ declare namespace OSS { mime: string; // custom mime, will send with Content-Type entity header meta: UserMeta; callback: ObjectCallback; + headers?: object; } interface AppendObjectOptions { diff --git a/types/bandagedbd__bdapi/bandagedbd__bdapi-tests.ts b/types/bandagedbd__bdapi/bandagedbd__bdapi-tests.ts new file mode 100644 index 0000000000..3966aa3d1e --- /dev/null +++ b/types/bandagedbd__bdapi/bandagedbd__bdapi-tests.ts @@ -0,0 +1,6 @@ +import { BdApi } from 'bandagedbd__bdapi'; + +BdApi.React; // $ExpectType typeof React +BdApi.ReactDOM.render; // $ExpectType Renderer +BdApi.alert('foo', 'bar'); // $ExpectType void +BdApi.showToast('hello', { timeout: 2000 }); // $ExpectType void diff --git a/types/bandagedbd__bdapi/index.d.ts b/types/bandagedbd__bdapi/index.d.ts new file mode 100644 index 0000000000..4792992374 --- /dev/null +++ b/types/bandagedbd__bdapi/index.d.ts @@ -0,0 +1,176 @@ +// Type definitions for bdapi 0.2 +// Project: https://github.com/rauenzi/BetterDiscordApp +// Definitions by: Ari Seyhun +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 +// Documentation: https://github.com/rauenzi/BetterDiscordApp/wiki/Creating-Plugins#bdapi + +import * as ReactInstance from 'react'; +import * as ReactDOMInstance from 'react-dom'; + +export const BdApi: typeof BdApiModule; + +/** + * Function with no arguments and no return value that may be called to revert changes made by monkeyPatch method, + * restoring (unpatching) original method. + */ +export type CancelPatch = () => void; + +/** + * A callback that modifies method logic. + * This callback is called on each call of the original method and is provided all data about original call. + * Any of the data can be modified if necessary, but do so wisely. + */ +export type PatchFunction = (data: PatchData) => any; + +/** + * A callback that modifies method logic. + * This callback is called on each call of the original method and is provided all data about original call. + * Any of the data can be modified if necessary, but do so wisely. + */ +export interface PatchData { + thisObject: object; + methodArguments: any[]; + CancelPatch: CancelPatch; + originalMethod: () => void; + callOriginalMethod: () => void; + returnValue: any; +} + +export interface MonkeyPatchOptions { + once?: boolean; + silent?: boolean; + displayName?: string; + before?: PatchFunction; + after?: PatchFunction; + instead?: PatchFunction; +} + +export interface ToastOptions { + type?: string; + icon?: boolean; + timeout?: number; +} + +export namespace BdApiModule { + /** + * The React module being used inside Discord. + */ + const React: typeof ReactInstance; + + /** + * The ReactDOM module being used inside Discord. + */ + const ReactDOM: typeof ReactDOMInstance; + + /** + * Creates an shows an alert modal to the user. A preview of how it may look can be found [here](https://i.zackrauen.com/7qnnNC.png). + */ + function alert(title: string, content: string): void; + + /** + * Removes a style added with [`injectCSS`](#injectcssid-css) below. + */ + function clearCSS(id: string): void; + + /** + * Deletes some saved data for plugin `pluginName` with key `key`. + */ + function deleteData(pluginName: string, key: string): void; + + /** + * Searches for an internal Discord webpack module based on `filter`. + */ + function findModule(filter: () => void): any; + + /** + * Searches for multiple internal Discord webpack module based on `filter`. It's the same as [`findModule`](#findmodulefilter) but will return all matches + */ + function findAllModules(filter: () => void): any[]; + + /** + * Searches for an internal Discord webpack module that has every property passed. + */ + function findModuleByProps(...props: string[]): any; + + /** + * Returns BandagedBD's instance of the core module. Only use this if you know what you are doing. + */ + function getCore(): any; // TODO: This should not return 'any' but instead 'Core' + + /** + * Alias for [loadData(pluginName, key)](#loaddatapluginname-key) + */ + function getData(pluginName: string, key: string): any; + + /** + * Gets the internal react instance for a particular node. + */ + function getInternalInstance(node: HTMLElement): object|undefined; + + /** + * Gets the instance of another plugin with the name `name`. + */ + function getPlugin(name: string): object|null; + + /** + * Adds a block of css to the current document's `head`. + */ + function injectCSS(id: string, css: string): object|null; + + /** + * Links some remote JavaScript to be added to the page. Useful for libraries like `Sortable.js`. + */ + function linkJS(id: string, url: string): void; + + /** + * Gets some saved data for plugin `pluginName` with key `key`. Data can be saved with [`saveData`](#savedatapluginname-key-data). + */ + function loadData(pluginName: string, key: string): any; + + /** + * This function monkey-patches a method on an object. The patching callback may be run before, after or instead of target method. + * - Be careful when monkey-patching. Think not only about original functionality of target method and your changes, + * but also about developers of other plugins, who may also patch this method before or after you. + * Try to change target method behaviour as little as possible, and avoid changing method signatures. + * - Display name of patched method is changed, so you can see if a function has been patched (and how many times) while debugging or in the stack trace. + * Also, patched methods have property `__monkeyPatched` set to `true`, in case you want to check something programmatically. + */ + function monkeyPatch(module: object, methodName: string, options: MonkeyPatchOptions): CancelPatch; + + /** + * Adds a listener for when the node is removed from the document body. + */ + function onRemoved(node: HTMLElement, callback: () => void): void; + + /** + * Saved some `data` for plugin `pluginName` under `key` key. Gets saved in the plugins folder under `pluginName.config.json`. Data can be saved with [`loadData`](#loaddatapluginname-key). + */ + function saveData(pluginName: string, key: string, data: any): void; + + /** + * Alias for [saveData(pluginName, key, data)](#savedatapluginname-key-data) + * + */ + function setData(pluginName: string, key: string, data: any): void; + + /** + * Shows a simple toast message similar to on Android. An example of the `success` toast can be seen [here](https://i.zackrauen.com/zIagVa.png). + */ + function showToast(content: string, options?: ToastOptions): void; + + /** + * Wraps a function in a try catch block. + */ + function suppressErrors(method: () => void, message?: string): () => void; + + /** + * Determines if the input is valid and parseable JSON. + */ + function testJSON(data: string): boolean; + + /** + * Removes some previously linked JS by [`linkJS`](#linkjsid-url). + */ + function unlinkJS(id: string): void; +} diff --git a/types/bandagedbd__bdapi/tsconfig.json b/types/bandagedbd__bdapi/tsconfig.json new file mode 100644 index 0000000000..7e35378a67 --- /dev/null +++ b/types/bandagedbd__bdapi/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", + "bandagedbd__bdapi-tests.ts" + ] +} diff --git a/types/bandagedbd__bdapi/tslint.json b/types/bandagedbd__bdapi/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bandagedbd__bdapi/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bytebuffer/index.d.ts b/types/bytebuffer/index.d.ts index 4423d7872b..bafed6edf8 100644 --- a/types/bytebuffer/index.d.ts +++ b/types/bytebuffer/index.d.ts @@ -146,7 +146,7 @@ declare class ByteBuffer /** * Concatenates multiple ByteBuffers into one. */ - static concat( buffers: Array, encoding?: string | boolean, litteEndian?: boolean, noAssert?: boolean ): ByteBuffer; + static concat( buffers: Array, encoding?: string | boolean, litteEndian?: boolean, noAssert?: boolean ): ByteBuffer; /** * Decodes a base64 encoded string to a ByteBuffer. @@ -185,7 +185,7 @@ declare class ByteBuffer * @param littleEndian Whether to use little or big endian byte order. Defaults to ByteBuffer.DEFAULT_ENDIAN. * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteBuffer.DEFAULT_NOASSERT. */ - static wrap( buffer: ByteBuffer | ArrayBuffer | Uint8Array | string, enc?: string | boolean, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; + static wrap( buffer: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, enc?: string | boolean, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; /** * Decodes a zigzag encoded signed 32bit integer. @@ -220,7 +220,7 @@ declare class ByteBuffer /** * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended data's length. */ - append( source: ByteBuffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer; + append( source: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer; /** * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents behind the specified offset up to the length of this ByteBuffer's data. @@ -291,7 +291,7 @@ declare class ByteBuffer /** * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly. */ - prepend( source: ByteBuffer | string | ArrayBuffer, encoding?: string | number, offset?: number ): ByteBuffer; + prepend( source: ByteBuffer | string | ArrayBuffer | Buffer, encoding?: string | number, offset?: number ): ByteBuffer; /** * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly. @@ -480,7 +480,7 @@ declare class ByteBuffer /** * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will transparently ByteBuffer#flip this ByteBuffer if offset > limit but the actual offsets remain untouched. */ - toBuffer( forceCopy?: boolean ): ArrayBuffer; + toBuffer( forceCopy?: boolean ): Buffer; /** *Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are: @@ -517,7 +517,7 @@ declare class ByteBuffer /** * Writes an array of bytes. This is an alias for append */ - writeBytes( source: ByteBuffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer; + writeBytes( source: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer; /** * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL characters itself. diff --git a/types/chromecast-caf-receiver/cast.framework.messages.d.ts b/types/chromecast-caf-receiver/cast.framework.messages.d.ts index c3dc4a405f..1846fd4840 100644 --- a/types/chromecast-caf-receiver/cast.framework.messages.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.messages.d.ts @@ -1372,12 +1372,12 @@ export interface MediaInformation { * is playing or ones that receiver will play shortly after; instead of sending * whole list of clips. This is to avoid overflow of MediaStatus message. */ - breakClips: BreakClip[]; + breakClips?: BreakClip[]; /** * List of breaks. */ - breaks: Break[]; + breaks?: Break[]; /** * Typically the url of the media. @@ -1414,12 +1414,18 @@ export interface MediaInformation { /** * The format of the HLS media segment. */ - hlsSegmentFormat: HlsSegmentFormat; + hlsSegmentFormat?: HlsSegmentFormat; /** * The media metadata. */ - metadata: MediaMetadata; + metadata?: + | MediaMetadata + | GenericMediaMetadata + | MovieMediaMetadata + | MusicTrackMediaMetadata + | PhotoMediaMetadata + | TvShowMediaMetadata; /** * The stream type. @@ -1429,12 +1435,12 @@ export interface MediaInformation { /** * The style of text track. */ - textTrackStyle: TextTrackStyle; + textTrackStyle?: TextTrackStyle; /** * The media tracks. */ - tracks: Track[]; + tracks?: Track[]; } /** diff --git a/types/classnames/bind.d.ts b/types/classnames/bind.d.ts index 4af94d1835..9befbabd4c 100644 --- a/types/classnames/bind.d.ts +++ b/types/classnames/bind.d.ts @@ -1,3 +1,3 @@ -import * as cn from "./index"; +import classNames = require('./index'); -export function bind(styles: Record): typeof cn; +export function bind(styles: Record): typeof classNames; diff --git a/types/classnames/tsconfig.json b/types/classnames/tsconfig.json index f9b03432fc..0e8475e613 100644 --- a/types/classnames/tsconfig.json +++ b/types/classnames/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/cordova-plugin-x-socialsharing/index.d.ts b/types/cordova-plugin-x-socialsharing/index.d.ts index a5105c898c..d1a4740b58 100644 --- a/types/cordova-plugin-x-socialsharing/index.d.ts +++ b/types/cordova-plugin-x-socialsharing/index.d.ts @@ -1,13 +1,13 @@ -// Type definitions for SocialSharing-PhoneGap-Plugin v5.1.8 +// Type definitions for SocialSharing-PhoneGap-Plugin v5.1.9 // Project: https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin // Definitions by: Markus Wagner , Larry Bahr // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Window { - plugins: Plugins; + plugins: CordovaPlugins; } -interface Plugins { +interface CordovaPlugins { socialsharing: SocialSharingPlugin.SocialSharing; } diff --git a/types/d3-dsv/d3-dsv-tests.ts b/types/d3-dsv/d3-dsv-tests.ts index 259180632f..8e05b04e61 100644 --- a/types/d3-dsv/d3-dsv-tests.ts +++ b/types/d3-dsv/d3-dsv-tests.ts @@ -21,6 +21,9 @@ const csvTestStringWithHeader = `Year,Make,Model,Length\n${csvTestString}`; const tsvTestStringWithHeader = `Year\tMake\tModel\tLength\n${tsvTestString}`; const pipedTestStringWithHeader = `Year|Make|Model|Length\n${pipedTestString}`; +type Headers = "Year" | "Make" | "Model" | "Length"; +type ParsedHeaders = "year" | "make" | "model" | "length"; + interface ParsedTestObject { year: Date | null; make: string; @@ -28,17 +31,56 @@ interface ParsedTestObject { length: number; } -let parseArray: d3Dsv.DSVParsedArray; -let parseMappedArray: d3Dsv.DSVParsedArray; - let parseRowsArray: string[][]; let parseRowsMappedArray: ParsedTestObject[]; - let parsedTestObject: ParsedTestObject; -let columns: string[]; + +let num: number; let str: string; let strMaybe: string | undefined; +let columns: string[]; +let headers: Headers[]; +let parsedHeaders: ParsedHeaders[]; + +// ------------------------------------------------------------------------------------------ +// Test Shared Types and Interfaces +// ------------------------------------------------------------------------------------------ + +declare let row: d3Dsv.DSVRowString; +strMaybe = row.property; + +declare let row2: d3Dsv.DSVRowString; +strMaybe = row2.Make; +strMaybe = row2.Property; // $ExpectError + +declare let raw: d3Dsv.DSVRaw; +strMaybe = raw.make; +strMaybe = raw.property; // $ExpectError + +declare let rowArray: d3Dsv.DSVRowArray; +strMaybe = rowArray[0].property; +columns = rowArray.columns; +num = rowArray.length; + +declare let rowArrayHeader: d3Dsv.DSVRowArray; +strMaybe = rowArrayHeader[0].Make; +strMaybe = rowArrayHeader[0].Property; // $ExpectError +headers = rowArrayHeader.columns; +num = rowArrayHeader.length; + +declare let parseMappedArray: d3Dsv.DSVParsedArray; +strMaybe = parseMappedArray[0].make; +strMaybe = parseMappedArray[0].property; // $ExpectError +parsedTestObject = parseMappedArray[0]; +parsedHeaders = parseMappedArray.columns; +num = parseMappedArray.length; + +declare let parseArray: d3Dsv.DSVParsedArray; +strMaybe = parseArray[0].property; +columns = parseArray.columns; +num = parseArray.length; + // ------------------------------------------------------------------------------------------ // Test CSV // ------------------------------------------------------------------------------------------ @@ -48,8 +90,7 @@ let strMaybe: string | undefined; // without row mapper ----------------------------------------------------------------------- parseArray = d3Dsv.csvParse(csvTestStringWithHeader); -columns = parseArray.columns; -strMaybe = parseArray[0].Year; +rowArrayHeader = d3Dsv.csvParse(csvTestStringWithHeader); // with row mapper --------------------------------------------------------------------------- @@ -73,8 +114,12 @@ parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, (rawRow, index, colum return pr; }); -columns = parseMappedArray.columns; -parsedTestObject = parseMappedArray[0]; +parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, (rawRow, index, columns) => { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: Headers[] = columns; + return parsedTestObject; +}); // csvParseRows(...) ============================================================================ @@ -108,12 +153,11 @@ parseRowsMappedArray = d3Dsv.csvParseRows(csvTestString, (rawRow, index) => { str = d3Dsv.csvFormat(parseRowsMappedArray); str = d3Dsv.csvFormat(parseRowsMappedArray, ["year", "length"]); -// $ExpectError -str = d3Dsv.csvFormat(parseRowsMappedArray, ["year", "unknown"]); +str = d3Dsv.csvFormat(parseRowsMappedArray, ["year", "unknown"]); // $ExpectError // csvFormatRows(...) ======================================================================== -str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d, i) => [ +str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d) => [ d.year ? d.year.getFullYear().toString() : '', d.make, d.model, @@ -129,8 +173,7 @@ str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d, i) => [ // without row mapper ----------------------------------------------------------------------- parseArray = d3Dsv.tsvParse(tsvTestStringWithHeader); -columns = parseArray.columns; -strMaybe = parseArray[0].Year; +rowArrayHeader = d3Dsv.tsvParse(csvTestStringWithHeader); // with row mapper --------------------------------------------------------------------------- @@ -154,8 +197,12 @@ parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, (rawRow, index, colum return pr; }); -columns = parseMappedArray.columns; -parsedTestObject = parseMappedArray[0]; +parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, (rawRow, index, columns) => { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: Headers[] = columns; + return parsedTestObject; +}); // tsvParseRows(...) ============================================================================ @@ -189,12 +236,11 @@ parseRowsMappedArray = d3Dsv.tsvParseRows(tsvTestString, (rawRow, index) => { str = d3Dsv.tsvFormat(parseRowsMappedArray); str = d3Dsv.tsvFormat(parseRowsMappedArray, ["year", "length"]); -// $ExpectError -str = d3Dsv.tsvFormat(parseRowsMappedArray, ["year", "unknown"]); +str = d3Dsv.tsvFormat(parseRowsMappedArray, ["year", "unknown"]); // $ExpectError // tsvFormatRows(...) ======================================================================== -str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map((d, i) => [ +str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map((d) => [ d.year ? d.year.getFullYear().toString() : '', d.make, d.model, @@ -215,8 +261,7 @@ dsv = d3Dsv.dsvFormat('|'); // without row mapper ----------------------------------------------------------------------- parseArray = dsv.parse(pipedTestStringWithHeader); -columns = parseArray.columns; -strMaybe = parseArray[0].Year; +rowArrayHeader = dsv.parse(csvTestStringWithHeader); // with row mapper --------------------------------------------------------------------------- @@ -240,8 +285,12 @@ parseMappedArray = dsv.parse(pipedTestStringWithHeader, (rawRow, index, columns) return pr; }); -columns = parseMappedArray.columns; -parsedTestObject = parseMappedArray[0]; +parseMappedArray = dsv.parse(pipedTestStringWithHeader, (rawRow, index, columns) => { + const rr: d3Dsv.DSVRowString = rawRow; + const i: number = index; + const c: Headers[] = columns; + return parsedTestObject; +}); // parseRows(...) ============================================================================ @@ -275,12 +324,11 @@ parseRowsMappedArray = dsv.parseRows(pipedTestString, (rawRow, index) => { str = dsv.format(parseRowsMappedArray); str = dsv.format(parseRowsMappedArray, ["year", "length"]); -// $ExpectError -str = dsv.format(parseRowsMappedArray, ["year", "unknown"]); +str = dsv.format(parseRowsMappedArray, ["year", "unknown"]); // $ExpectError // formatRows(...) ======================================================================== -str = dsv.formatRows(parseRowsMappedArray.map((d, i) => [ +str = dsv.formatRows(parseRowsMappedArray.map((d) => [ d.year ? d.year.getFullYear().toString() : '', d.make, d.model, diff --git a/types/d3-dsv/index.d.ts b/types/d3-dsv/index.d.ts index bdebc5ca01..fcfaa67339 100644 --- a/types/d3-dsv/index.d.ts +++ b/types/d3-dsv/index.d.ts @@ -15,21 +15,41 @@ /** * An object representing a DSV parsed row with values represented as strings. + * When the DSV content is not well-structured and some column-values are missing, `undefined` is used as value. */ -export interface DSVRowString { - [key: string]: string | undefined; -} +export type DSVRowString = { + [key in Columns]: string | undefined; +}; + +/** + * An object in raw format before parsing, that is with only string values. + * When the DSV content is not well-structured and some column-values are missing, `undefined` is used as value. + */ +export type DSVRaw = { + [key in keyof T]: string | undefined; +}; /** * An object representing a DSV parsed row with values represented as an arbitrary datatype, depending * on the performed parsed row mapping. * - * @deprecated + * @deprecated Use `object` instead. */ export interface DSVRowAny { [key: string]: any; } +/** + * An array object representing all deserialized rows. The array is enhanced with a property listing + * the names of the parsed columns. + */ +export interface DSVRowArray extends Array> { + /** + * List of column names. + */ + columns: Columns[]; +} + /** * An array object representing all parsed rows. The array is enhanced with a property listing * the names of the parsed columns. @@ -38,7 +58,7 @@ export interface DSVParsedArray extends Array { /** * List of column names. */ - columns: string[]; + columns: Array; } // ------------------------------------------------------------------------------------------ @@ -55,11 +75,12 @@ export interface DSVParsedArray extends Array { * * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). * - * Equivalent to dsvFormat(",").parse. + * Equivalent to `dsvFormat(",").parse`. * * @param csvString A string, which must be in the comma-separated values format. */ -export function csvParse(csvString: string): DSVParsedArray; +// tslint:disable-next-line:no-unnecessary-generics +export function csvParse(csvString: string): DSVRowArray; /** * Parses the specified string, which must be in the comma-separated values format, returning an array of objects representing the parsed rows. * @@ -68,7 +89,7 @@ export function csvParse(csvString: string): DSVParsedArray; * * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). * - * Equivalent to dsvFormat(",").parse. + * Equivalent to `dsvFormat(",").parse`. * * @param csvString A string, which must be in the comma-separated values format. * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), @@ -76,9 +97,9 @@ export function csvParse(csvString: string): DSVParsedArray; * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function csvParse( +export function csvParse( csvString: string, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): DSVParsedArray; // csvParseRows(...) ======================================================================== @@ -92,7 +113,7 @@ export function csvParse( * If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. * In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function. * - * Equivalent to dsvFormat(",").parseRows. + * Equivalent to `dsvFormat(",").parseRows`. * * @param csvString A string, which must be in the comma-separated values format. */ @@ -103,7 +124,7 @@ export function csvParseRows(csvString: string): string[][]; * Unlike csvParse, this method treats the header line as a standard row, and should be used whenever CSV content does not contain a header. * Each row is represented as an array rather than an object. Rows may have variable length. * - * Equivalent to dsvFormat(",").parseRows. + * Equivalent to `dsvFormat(",").parseRows`. * * @param csvString A string, which must be in the comma-separated values format. * @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i) @@ -127,7 +148,7 @@ export function csvParseRows( * If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows; * the order of columns is nondeterministic. * - * Equivalent to dsvFormat(",").format. + * Equivalent to `dsvFormat(",").format`. * * @param rows Array of object rows. * @param columns An array of strings representing the column names. @@ -145,7 +166,7 @@ export function csvFormat(rows: T[], columns?: Array) * To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map. * If you like, you can also array.concat this result with an array of column names to generate the first row. * - * Equivalent to dsvFormat(",").formatRows. + * Equivalent to `dsvFormat(",").formatRows`. * * @param rows An array of array of string rows. */ @@ -165,11 +186,12 @@ export function csvFormatRows(rows: string[][]): string; * * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). * - * Equivalent to dsvFormat("\t").parse. + * Equivalent to `dsvFormat("\t").parse`. * * @param tsvString A string, which must be in the tab-separated values format. */ -export function tsvParse(tsvString: string): DSVParsedArray; +// tslint:disable-next-line:no-unnecessary-generics +export function tsvParse(tsvString: string): DSVRowArray; /** * Parses the specified string, which must be in the tab-separated values format, returning an array of objects representing the parsed rows. * @@ -178,7 +200,7 @@ export function tsvParse(tsvString: string): DSVParsedArray; * * The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). * - * Equivalent to dsvFormat("\t").parse. + * Equivalent to `dsvFormat("\t").parse`. * * @param tsvString A string, which must be in the tab-separated values format. * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), @@ -186,10 +208,10 @@ export function tsvParse(tsvString: string): DSVParsedArray; * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function tsvParse( +export function tsvParse( tsvString: string, - row: (rawRow: DSVRowString, index: number, columns: string[]) => MappedRow | undefined | null -): DSVParsedArray; + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null +): DSVParsedArray; // tsvParseRows(...) ======================================================================== @@ -202,7 +224,7 @@ export function tsvParse( * If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. * In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function. * - * Equivalent to dsvFormat("\t").parseRows. + * Equivalent to `dsvFormat("\t").parseRows`. * * @param tsvString A string, which must be in the tab-separated values format. */ @@ -213,7 +235,7 @@ export function tsvParseRows(tsvString: string): string[][]; * Unlike tsvParse, this method treats the header line as a standard row, and should be used whenever TSV content does not contain a header. * Each row is represented as an array rather than an object. Rows may have variable length. * - * Equivalent to dsvFormat("\t").parseRows. + * Equivalent to `dsvFormat("\t").parseRows`. * * @param tsvString A string, which must be in the tab-separated values format. * @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i) @@ -221,10 +243,10 @@ export function tsvParseRows(tsvString: string): string[][]; * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function tsvParseRows( +export function tsvParseRows( tsvString: string, - row: (rawRow: string[], index: number) => MappedRow | undefined | null -): MappedRow[]; + row: (rawRow: string[], index: number) => ParsedRow | undefined | null +): ParsedRow[]; // tsvFormat(...) ============================================================================ @@ -237,7 +259,7 @@ export function tsvParseRows( * If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows; * the order of columns is nondeterministic. * - * Equivalent to dsvFormat("\t").format. + * Equivalent to `dsvFormat("\t").format`. * * @param rows Array of object rows. * @param columns An array of strings representing the column names. @@ -255,7 +277,7 @@ export function tsvFormat(rows: T[], columns?: Array) * To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map. * If you like, you can also array.concat this result with an array of column names to generate the first row. * - * Equivalent to dsvFormat("\t").formatRows. + * Equivalent to `dsvFormat("\t").formatRows`. * * @param rows An array of array of string rows. */ @@ -279,7 +301,8 @@ export interface DSV { * * @param dsvString A string, which must be in the delimiter-separated values format with the appropriate delimiter. */ - parse(dsvString: string): DSVParsedArray; + // tslint:disable-next-line:no-unnecessary-generics + parse(dsvString: string): DSVRowArray; /** * Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of objects representing the parsed rows. * @@ -294,9 +317,9 @@ export interface DSV { * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ - parse( + parse( dsvString: string, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): DSVParsedArray; /** diff --git a/types/d3-fetch/d3-fetch-tests.ts b/types/d3-fetch/d3-fetch-tests.ts index 4d49d86a7f..8d6b862afc 100644 --- a/types/d3-fetch/d3-fetch-tests.ts +++ b/types/d3-fetch/d3-fetch-tests.ts @@ -1,62 +1,158 @@ import * as d3Fetch from 'd3-fetch'; -import { DSVParsedArray, DSVRowString } from 'd3-dsv'; +import { DSVParsedArray, DSVRaw, DSVRowString } from 'd3-dsv'; -interface MyType { - foo: string; +// ---------------------------------------------------------------------------- +// Preparatory Steps +// ---------------------------------------------------------------------------- + +type Headers = "Year" | "Make" | "Model" | "Length"; + +interface Car { + year: Date; + make: string; + model: string; + length: number; } -const url = 'foo.bar'; - -const init: RequestInit = {}; - -let p1: Promise = d3Fetch.blob(url); -p1 = d3Fetch.blob(url, init); - -let p2: Promise = d3Fetch.buffer(url); -p2 = d3Fetch.buffer(url, init); - -let p3: Promise = d3Fetch.image(url); -const imageProperties = { - width: '300px', - height: '500px' -}; -p3 = d3Fetch.image(url, imageProperties); - -let p4: Promise = d3Fetch.json(url); -p4 = d3Fetch.json(url, init); -let p5: Promise = d3Fetch.json(url); -p5 = d3Fetch.json(url, init); - -let myString: Promise; -myString = d3Fetch.text(url); -myString = d3Fetch.text(url, init); - -const parseRow = (rawRow: DSVRowString, index: number, columns: string[]): (MyType | undefined | null) => { - const myType: MyType | null = rawRow['foo'] ? { foo: rawRow['foo'] + '+ bar' } : null; - return myType; -}; -let promise1: Promise>; -let promise2: Promise>; -promise1 = d3Fetch.csv(url); -promise1 = d3Fetch.csv(url, init); -promise2 = d3Fetch.csv(url, parseRow); -promise2 = d3Fetch.csv(url, init, parseRow); -promise1 = d3Fetch.dsv(';', url); -promise1 = d3Fetch.dsv(';', url, init); -promise2 = d3Fetch.dsv(';', url, parseRow); -promise2 = d3Fetch.dsv(';', url, init, parseRow); -promise1 = d3Fetch.tsv(url); -promise1 = d3Fetch.tsv(url, init); -promise2 = d3Fetch.tsv(url, parseRow); -promise2 = d3Fetch.tsv(url, init, parseRow); - +let anyPromise: Promise; +let arrayPromise: Promise; +let blobPromise: Promise; let docPromise: Promise; +let imagePromise: Promise; +let carPromise: Promise; +let stringPromise: Promise; +let xmlDocPromise: Promise; + +const url = 'example.org'; +const init: RequestInit = {}; +const map = new Map(); + +const imageProperties = { + width: 300, + height: 500, + crossOrigin: "anonymous", +}; + +// ---------------------------------------------------------------------------- +// Non DSV file format +// ---------------------------------------------------------------------------- + +blobPromise = d3Fetch.blob(url); +blobPromise = d3Fetch.blob(url, init); + +arrayPromise = d3Fetch.buffer(url); +arrayPromise = d3Fetch.buffer(url, init); + +imagePromise = d3Fetch.image(url); +imagePromise = d3Fetch.image(url, imageProperties); +// $ExpectError +imagePromise = d3Fetch.image(url, {width: "500px"}); // fails, string not assignable to number | undefined + +anyPromise = d3Fetch.json(url); +anyPromise = d3Fetch.json(url, init); + +carPromise = d3Fetch.json(url); +carPromise = d3Fetch.json(url, init); + +stringPromise = d3Fetch.text(url); +stringPromise = d3Fetch.text(url, init); + docPromise = d3Fetch.html(url); docPromise = d3Fetch.html(url, init); docPromise = d3Fetch.svg(url); docPromise = d3Fetch.svg(url, init); -let xmlDocPromise: Promise; xmlDocPromise = d3Fetch.xml(url); xmlDocPromise = d3Fetch.xml(url, init); + +// ---------------------------------------------------------------------------- +// DSV file format +// ---------------------------------------------------------------------------- + +let rawPromise: Promise>; +let rawPromiseHeader: Promise>>; +let parsedPromise: Promise>; + +declare const parseRowString: (rawRow: DSVRowString, index: number, columns: string[]) => Car | undefined | null; + +const parseRow = (d: DSVRowString, index: number, columns: Headers[]): Car | undefined | null => { + const item: string | undefined = d[columns[0]]; + const car = d.Make === 'Ford' ? null : + { + year: new Date(+d.Make!, 0, 1), + make: d.Make!, + model: d.Model!, + length: +d.Length!, + }; + return index % 2 === 0 ? undefined : car; +}; + +const parseRowSimple = (d: DSVRaw) => { + return { + year: new Date(+d.make!, 0, 1), + make: d.make!, + model: d.model!, + length: +d.length!, + }; +}; + +// CSV + +rawPromise = d3Fetch.csv(url); +rawPromise = d3Fetch.csv(url, init); + +rawPromiseHeader = d3Fetch.csv(url); +rawPromiseHeader = d3Fetch.csv(url, init); + +parsedPromise = d3Fetch.csv(url, parseRowString); +parsedPromise = d3Fetch.csv(url, init, parseRowString); + +parsedPromise = d3Fetch.csv(url, parseRow); +parsedPromise = d3Fetch.csv(url, init, parseRow); + +parsedPromise = d3Fetch.csv(url, parseRow); +parsedPromise = d3Fetch.csv(url, init, parseRow); +parsedPromise = d3Fetch.csv(url, parseRowSimple); + +anyPromise = d3Fetch.csv(url, (d: DSVRaw) => map.set(d.model!, +d.year!)); + +// DSV + +rawPromise = d3Fetch.dsv("|", url); +rawPromise = d3Fetch.dsv("|", url, init); + +rawPromiseHeader = d3Fetch.dsv("|", url); +rawPromiseHeader = d3Fetch.dsv("|", url, init); + +parsedPromise = d3Fetch.dsv("|", url, parseRowString); +parsedPromise = d3Fetch.dsv("|", url, init, parseRowString); + +parsedPromise = d3Fetch.dsv("|", url, parseRow); +parsedPromise = d3Fetch.dsv("|", url, init, parseRow); + +parsedPromise = d3Fetch.dsv("|", url, parseRow); +parsedPromise = d3Fetch.dsv("|", url, init, parseRow); +parsedPromise = d3Fetch.dsv("|", url, parseRowSimple); + +anyPromise = d3Fetch.dsv("|", url, (d: DSVRaw) => map.set(d.model!, +d.year!)); + +// TSV + +rawPromise = d3Fetch.tsv(url); +rawPromise = d3Fetch.tsv(url, init); + +rawPromiseHeader = d3Fetch.tsv(url); +rawPromiseHeader = d3Fetch.tsv(url, init); + +parsedPromise = d3Fetch.tsv(url, parseRowString); +parsedPromise = d3Fetch.tsv(url, init, parseRowString); + +parsedPromise = d3Fetch.tsv(url, parseRow); +parsedPromise = d3Fetch.tsv(url, init, parseRow); + +parsedPromise = d3Fetch.tsv(url, parseRow); +parsedPromise = d3Fetch.tsv(url, init, parseRow); +parsedPromise = d3Fetch.tsv(url, parseRowSimple); + +anyPromise = d3Fetch.csv(url, (d: DSVRaw) => map.set(d.model!, +d.year!)); diff --git a/types/d3-fetch/index.d.ts b/types/d3-fetch/index.d.ts index f6dc317784..4110ba4a7b 100644 --- a/types/d3-fetch/index.d.ts +++ b/types/d3-fetch/index.d.ts @@ -1,12 +1,13 @@ // Type definitions for d3-fetch 1.1 // Project: https://d3js.org/d3-fetch/ // Definitions by: Hugues Stefanski +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 // Last module patch version validated against: 1.1.0 -import { DSVParsedArray, DSVRowString } from 'd3-dsv'; +import { DSVParsedArray, DSVRowArray, DSVRowString } from "d3-dsv"; /** * Fetches the binary file at the specified input URL and returns it as a Promise of a Blob. @@ -33,13 +34,15 @@ export function buffer(url: string, init?: RequestInit): Promise; * * If init is specified, it is passed along to the underlying call to fetch. * + * The generic parameter describes the column names as a union of string literal types. + * * @param url A valid URL string. * @param init An optional request initialization object. */ -export function csv( +export function csv( url: string, - init?: RequestInit, -): Promise>; + init?: RequestInit +): Promise>; /** * Fetches the CSV file at the specified input URL and returns * a promise of an array of objects representing the parsed rows. @@ -47,7 +50,8 @@ export function csv( * The specified row conversion function is used to map and filter row objects to a more-specific representation; * see dsv.csvParse for details. * - * The generic parameter describes the type of the object representation of a parsed row. + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. * * @param url A valid URL string. * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), @@ -55,9 +59,9 @@ export function csv( * the row is skipped and will be omitted from the array returned by dsv.csvParse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function csv( +export function csv( url: string, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): Promise>; /** * Fetches the CSV file at the specified input URL and returns @@ -68,7 +72,8 @@ export function csv( * The specified row conversion function is used to map and filter row objects to a more-specific representation; * see dsv.csvParse for details. * - * The generic parameter describes the type of the object representation of a parsed row. + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. * * @param url A valid URL string. * @param init An request initialization object. @@ -77,10 +82,10 @@ export function csv( * the row is skipped and will be omitted from the array returned by dsv.csvParse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function csv( +export function csv( url: string, init: RequestInit, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): Promise>; /** @@ -90,15 +95,17 @@ export function csv( * * If init is specified, it is passed along to the underlying call to fetch. * + * The generic parameter describes the column names as a union of string literal types. + * * @param delimiter The delimiter character used in the DSV file to be fetched. * @param url A valid URL string. * @param init An optional request initialization object. */ -export function dsv( +export function dsv( delimiter: string, url: string, - init?: RequestInit, -): Promise>; + init?: RequestInit +): Promise>; /** * Fetches the DSV file with the specified delimiter character at the specified input URL and returns * a promise of an array of objects representing the parsed rows. @@ -106,7 +113,8 @@ export function dsv( * The specified row conversion function is used to map and filter row objects to a more-specific representation; * see dsv.parse for details. * - * The generic parameter describes the type of the object representation of a parsed row. + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. * * @param delimiter The delimiter character used in the DSV file to be fetched. * @param url A valid URL string. @@ -115,10 +123,10 @@ export function dsv( * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function dsv( +export function dsv( delimiter: string, url: string, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): Promise>; /** * Fetches the DSV file with the specified delimiter character at the specified input URL and returns @@ -129,7 +137,8 @@ export function dsv( * The specified row conversion function is used to map and filter row objects to a more-specific representation; * see dsv.parse for details. * - * The generic parameter describes the type of the object representation of a parsed row. + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. * * @param delimiter The delimiter character used in the DSV file to be fetched. * @param url A valid URL string. @@ -139,11 +148,11 @@ export function dsv( * the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function dsv( +export function dsv( delimiter: string, url: string, init: RequestInit, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): Promise>; /** @@ -164,7 +173,7 @@ export function html(url: string, init?: RequestInit): Promise; * @param url A valid URL string. * @param init An optional object of image properties to set. */ -export function image(url: string, init?: {[key: string]: any}): Promise; +export function image(url: string, init?: Partial): Promise; /** * Fetches the json file at the specified input URL and returns it as a Promise of a parsed JSON object. @@ -204,13 +213,15 @@ export function text(url: string, init?: RequestInit): Promise; * * If init is specified, it is passed along to the underlying call to fetch. * + * The generic parameter describes the column names as a union of string literal types. + * * @param url A valid URL string. * @param init An optional request initialization object. */ -export function tsv( +export function tsv( url: string, - init?: RequestInit, -): Promise>; + init?: RequestInit +): Promise>; /** * Fetches the TSV file at the specified input URL and returns * a promise of an array of objects representing the parsed rows. The values of the properties of the parsed row @@ -219,7 +230,8 @@ export function tsv( * The specified row conversion function is used to map and filter row objects to a more-specific representation; * see dsv.tsvParse for details. * - * The generic parameter describes the type of the object representation of a parsed row. + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. * * @param url A valid URL string. * @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d), @@ -227,9 +239,9 @@ export function tsv( * the row is skipped and will be omitted from the array returned by dsv.tsvParse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function tsv( +export function tsv( url: string, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): Promise>; /** * Fetches the TSV file at the specified input URL and returns @@ -240,7 +252,8 @@ export function tsv( * The specified row conversion function is used to map and filter row objects to a more-specific representation; * see dsv.tsvParse for details. * - * The generic parameter describes the type of the object representation of a parsed row. + * The first generic parameter describes the type of the object representation of a parsed row. + * The second generic parameter describes the column names as a union of string literal types. * * @param url A valid URL string. * @param init An request initialization object. @@ -249,10 +262,10 @@ export function tsv( * the row is skipped and will be omitted from the array returned by dsv.tsvParse; otherwise, the returned value defines the corresponding row object. * In effect, row is similar to applying a map and filter operator to the returned rows. */ -export function tsv( +export function tsv( url: string, init: RequestInit, - row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null + row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null ): Promise>; /** diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 57e028e8bf..481c1b27c4 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -47,6 +47,7 @@ import { Region, registerRootComponent, ScreenOrientation, + SecureStore, Svg, Updates } from 'expo'; @@ -484,6 +485,30 @@ async () => { isString(queryParams2['y'] || ''); }; +// #region securestore +async () => { + await SecureStore.setItemAsync('some-key', 'some-val', { + keychainService: "some-service", + keychainAccessible: SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY, + }); + const result = await SecureStore.getItemAsync('some-key', { keychainService: "some-service" }); + if (result != null) { + result.slice() === 'some-val'; + } + await SecureStore.deleteItemAsync('some-key', { keychainService: "some-service" }); +}; + +const allSecureStoreKeychainAccessibleValues: number[] = [ + SecureStore.WHEN_UNLOCKED, + SecureStore.AFTER_FIRST_UNLOCK, + SecureStore.ALWAYS, + SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY, + SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY, + SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY, + SecureStore.ALWAYS_THIS_DEVICE_ONLY, +]; +// #endregion + () => ( // Pavel Ihm // Bartosz Dotryw +// Jason Killian // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -2301,12 +2302,23 @@ export namespace ScreenOrientation { export namespace SecureStore { interface SecureStoreOptions { keychainService?: string; + } + + interface SecureStoreSetOptions extends SecureStoreOptions { keychainAccessible?: number; } - function setItemAsync(key: string, value: string, options?: SecureStoreOptions): Promise; + function setItemAsync(key: string, value: string, options?: SecureStoreSetOptions): Promise; function getItemAsync(key: string, options?: SecureStoreOptions): Promise; function deleteItemAsync(key: string, options?: SecureStoreOptions): Promise; + + const WHEN_UNLOCKED: number; + const AFTER_FIRST_UNLOCK: number; + const ALWAYS: number; + const WHEN_UNLOCKED_THIS_DEVICE_ONLY: number; + const WHEN_PASSCODE_SET_THIS_DEVICE_ONLY: number; + const AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: number; + const ALWAYS_THIS_DEVICE_ONLY: number; } /** diff --git a/types/express-jwt/index.d.ts b/types/express-jwt/index.d.ts index 1187f4fbca..d1029849cc 100644 --- a/types/express-jwt/index.d.ts +++ b/types/express-jwt/index.d.ts @@ -58,10 +58,3 @@ declare namespace jwt { constructor(code: ErrorCode, error: { message: string }); } } -declare global { - namespace Express { - export interface Request { - user?: any - } - } -} diff --git a/types/express-rate-limit/express-rate-limit-tests.ts b/types/express-rate-limit/express-rate-limit-tests.ts index aa5c51a016..4b94ef6b05 100644 --- a/types/express-rate-limit/express-rate-limit-tests.ts +++ b/types/express-rate-limit/express-rate-limit-tests.ts @@ -3,7 +3,19 @@ import RateLimit = require("express-rate-limit"); const apiLimiter = new RateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, - delayMs: 0 // disabled + headers: false, + skipFailedRequests: false, + skipSuccessfulRequests: true, +}); + +const apiLimiterWithMaxFn = new RateLimit({ + windowMs: 15 * 60 * 1000, + max: () => 5, +}); + +const apiLimiterWithMaxPromiseFn = new RateLimit({ + windowMs: 15 * 60 * 1000, + max: () => Promise.resolve(5), }); const apiLimiterWithMessageObject = new RateLimit({ @@ -17,8 +29,6 @@ const apiLimiterWithMessageObject = new RateLimit({ const createAccountLimiter = new RateLimit({ windowMs: 60 * 60 * 1000, // 1 hour window - delayAfter: 1, // begin slowing down responses after the first request - delayMs: 3 * 1000, // slow down subsequent responses by 3 seconds per request max: 5, // start blocking after 5 requests message: "Too many accounts created from this IP, please try again after an hour", handler: (req, _, next) => next(new Error(`TooManyRequests: ${req.ip}`)) diff --git a/types/express-rate-limit/index.d.ts b/types/express-rate-limit/index.d.ts index b3f074f28d..9d3459e21b 100644 --- a/types/express-rate-limit/index.d.ts +++ b/types/express-rate-limit/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for express-rate-limit 2.9 +// Type definitions for express-rate-limit 3.3 // Project: https://github.com/nfriedly/express-rate-limit -// Definitions by: Cyril Schumacher , makepost +// Definitions by: Cyril Schumacher +// makepost +// Jeremy Forsythe // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -21,19 +23,80 @@ declare namespace RateLimit { [key: string]: any; } + type MaxValueFn = () => number | Promise; + interface Options { - delayAfter?: number; - delayMs?: number; + /** + * The funciton to handle requests once `max` is exceeded. It receives the request and response objects. + * The "next" param is available if you need to pass to the next middleware. The `req.rateLimit` object + * has `limit`, `current`, and `remaining` number of requests, and if the store provides it, a `resetTime` + * Date object. + * Default: `(req, res, next) => res.status(options.statusCode).send(options.message)` + */ handler?(req: express.Request, res: express.Response, next: express.NextFunction): any; + + /** + * Enable headers for request limit (`X-RateLimit-Limit`) and current usage (`X-RateLimit-Remaining`) on all + * responses andtime to wait before retrying (`Retry-After`) when `max` is exceeded. Defaults to `true`. + */ headers?: boolean; + + /** + * Function used to generate keys. Defaults to using `req.ip`. + * Default: `(req, res) => req.ip` + */ keyGenerator?(req: express.Request, res: express.Response): string; - max?: number; + + /** + * Max number of connections during `windowMs` before sending a 429 response. May be a `number` or + * a function that returns a `number` or a `Promise`. Defaults to `5`. Set to `0` to disable. + */ + max?: number | MaxValueFn; + + /** + * Error message sent to user when `max` is exceeded. May be a `string`, JSON object, or any other value + * that Express's `req.send()` supports. Defaults to `'Too many requests, please try again later.'`. + */ message?: string | Buffer | Message; - skip?(req: express.Request, res: express.Response): boolean; - skipFailedRequests?: boolean; - statusCode?: number; - store?: Store; + + /** + * Function that is called the first time `max` is exceeded. The `req.rateLimit` object has `limit`, `current`, + * and `remaining` number of requests and, if the store provides it, a `resetTime` Date object. Default is + * an empty function. + * Default: `(req, res, opts) => {}` + */ onLimitReached?(req: express.Request, res: express.Response, optionsUsed: Options): void; + + /** + * Function used to skip requests. Returning `true` from the function will skip limiting for that request. Defaults to + * always `false` (count all requests). + * Default: `(req, res) => false` + */ + skip?(req: express.Request, res: express.Response): boolean; + + /** + * When set to `true`, failed requests (status >= 400, request canceled or errored) won't be counted. Defaults to `false`. + */ + skipFailedRequests?: boolean; + + /** + * When set to `true`, successful requests (status < 400) won't be counted. Defaults to `false`. + */ + skipSuccessfulRequests?: boolean; + + /** + * HTTP status code returned when `max` is exceeded. Defaults to `429`. + */ + statusCode?: number; + + /** + * The storage to use when persisting rate limit attempts. + */ + store?: Store; + + /** + * How long in milliseconds to keep records of requests in memory. Defaults to `60000` (1 minute). + */ windowMs?: number; } } diff --git a/types/express-rate-limit/v2/express-rate-limit-tests.ts b/types/express-rate-limit/v2/express-rate-limit-tests.ts new file mode 100644 index 0000000000..aa5c51a016 --- /dev/null +++ b/types/express-rate-limit/v2/express-rate-limit-tests.ts @@ -0,0 +1,39 @@ +import RateLimit = require("express-rate-limit"); + +const apiLimiter = new RateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, + delayMs: 0 // disabled +}); + +const apiLimiterWithMessageObject = new RateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, + message: { + status: 429, + message: 'To many requests, try again later' + } +}); + +const createAccountLimiter = new RateLimit({ + windowMs: 60 * 60 * 1000, // 1 hour window + delayAfter: 1, // begin slowing down responses after the first request + delayMs: 3 * 1000, // slow down subsequent responses by 3 seconds per request + max: 5, // start blocking after 5 requests + message: "Too many accounts created from this IP, please try again after an hour", + handler: (req, _, next) => next(new Error(`TooManyRequests: ${req.ip}`)) +}); + +const callbackWithFewerParams = new RateLimit({ + handler: (req, res) => res.status(429).json(`TooManyRequests: ${req.ip}`) +}); + +class SomeStore implements RateLimit.Store { + incr(key: string, cb: RateLimit.StoreIncrementCallback) { } + decrement(key: string) { } + resetKey(key: string) { } +} + +const limiterWithStore = new RateLimit({ + store: new SomeStore() +}); diff --git a/types/express-rate-limit/v2/index.d.ts b/types/express-rate-limit/v2/index.d.ts new file mode 100644 index 0000000000..b3f074f28d --- /dev/null +++ b/types/express-rate-limit/v2/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for express-rate-limit 2.9 +// Project: https://github.com/nfriedly/express-rate-limit +// Definitions by: Cyril Schumacher , makepost +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import express = require("express"); + +declare namespace RateLimit { + type StoreIncrementCallback = (err?: {}, hits?: number) => void; + + interface Store { + incr(key: string, cb: StoreIncrementCallback): void; + decrement(key: string): void; + resetKey(key: string): void; + } + + interface Message { + status: number; + message: string; + [key: string]: any; + } + + interface Options { + delayAfter?: number; + delayMs?: number; + handler?(req: express.Request, res: express.Response, next: express.NextFunction): any; + headers?: boolean; + keyGenerator?(req: express.Request, res: express.Response): string; + max?: number; + message?: string | Buffer | Message; + skip?(req: express.Request, res: express.Response): boolean; + skipFailedRequests?: boolean; + statusCode?: number; + store?: Store; + onLimitReached?(req: express.Request, res: express.Response, optionsUsed: Options): void; + windowMs?: number; + } +} + +declare var RateLimit: new (options: RateLimit.Options) => express.RequestHandler; +export = RateLimit; diff --git a/types/express-rate-limit/v2/tsconfig.json b/types/express-rate-limit/v2/tsconfig.json new file mode 100644 index 0000000000..0e9b4d2ad4 --- /dev/null +++ b/types/express-rate-limit/v2/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "express-rate-limit": ["express-rate-limit/v2"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-rate-limit-tests.ts" + ] +} diff --git a/types/express-rate-limit/v2/tslint.json b/types/express-rate-limit/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-rate-limit/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/express-slow-down/express-slow-down-tests.ts b/types/express-slow-down/express-slow-down-tests.ts new file mode 100644 index 0000000000..e7d049bd7d --- /dev/null +++ b/types/express-slow-down/express-slow-down-tests.ts @@ -0,0 +1,31 @@ +import slowDown = require("express-slow-down"); + +const slowerAllDefaults = slowDown({}); + +const slowerWithOptions = slowDown({ + windowMs: 15 * 60 * 1000, // 15 minutes, + delayAfter: 1, + delayMs: 0, // disabled + skipFailedRequests: false, + skipSuccessfulRequests: true, +}); + +const slowerWithCallbacks = slowDown({ + keyGenerator: (req, res) => req.ip, + skip: (req, res) => false, + onLimitReached: (req, res, opts) => { + console.log(req.slowDown.current); + console.log(req.slowDown.remaining); + console.log(req.slowDown.limit); + }, +}); + +class MockStore implements slowDown.Store { + incr(key: string, cb: slowDown.StoreIncrementCallback) { } + decrement(key: string) { } + resetKey(key: string) { } +} + +const slowerWithStore = slowDown({ + store: new MockStore() +}); diff --git a/types/express-slow-down/index.d.ts b/types/express-slow-down/index.d.ts new file mode 100644 index 0000000000..f7aeab76fd --- /dev/null +++ b/types/express-slow-down/index.d.ts @@ -0,0 +1,111 @@ +// Type definitions for express-slow-down 1.1 +// Project: https://github.com/nfriedly/express-slow-down +// Definitions by: Jeremy Forsythe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import express = require("express"); + +declare namespace SlowDown { + type StoreIncrementCallback = (err?: {}, hits?: number) => void; + + interface SlowDownRequestAugmentation { + /** + * The `options.delayAfter` value + */ + limit: number; + + /** + * The number of requests in the current window + */ + current: number; + + /** + * the number of requests remaining before rate-limiting begins + */ + remaining: number; + + /** + * When the window will reset, `current` will return to `0`, and `remaining` will return + * to limit. Represents milliseconds since epoch (compare to `Date.now()`). This field + * depends on store support. It will be `undefined` if the store does not provide the value. + */ + resetTime?: number; + + /** + * Amount of delay imposed on current request in milliseconds + */ + delay: number; + } + + /** + * Express Request with the added `slowDown` property + */ + interface RequestWithSlowDown extends express.Request { + slowDown: SlowDownRequestAugmentation; + } + + interface Store { + incr(key: string, cb: StoreIncrementCallback): void; + decrement(key: string): void; + resetKey(key: string): void; + } + + /** + * express-slow-down options + */ + interface Options { + /** + * How long to keep records of requests in memory. Defaults to `60000` (1 minute) + */ + windowMs?: number; + + /** + * Max number of connections during `windowMs` before starting to delay responses. + * Defaults to `1`. Set to `0` to disable delaying. + */ + delayAfter?: number; + + /** + * How long to delay the response, multiplied by `(number recent hits - delayAfter)`. + * Defaults to `1000` (1 second). Set to `0` to disable delaying. + */ + delayMs?: number; + + /** + * When `true` failed requests (response status >= 400) won't be counted. Defaults to `false`. + */ + skipFailedRequests?: boolean; + + /** + * When `true` successful requests (response status < 400) won't be counted. Defaults to `false`. + */ + skipSuccessfulRequests?: boolean; + + /** + * Function used to generate keys. By default user IP address (`req.ip`) is used. + * Default: `(req, res) => req.ip` + */ + keyGenerator?(req: express.Request, res: express.Response): string; + + /** + * Function used to skip requests. Returning `true` from the function will skip delaying for that request. + * Default: `(req, res) => false` + */ + skip?(req: express.Request, res: express.Response): boolean; + + /** + * Function to execute the first time the limit is reached within `windowMs`. + * Default: `(req, res, opts) => {}` + */ + onLimitReached?(req: RequestWithSlowDown, res: express.Response, optionsUsed: Options): void; + + /** + * The storage to use when persisting request attempts. By default, the MemoryStore is used. + */ + store?: Store; + } +} + +declare function SlowDown(options: SlowDown.Options): express.RequestHandler; +export = SlowDown; diff --git a/types/express-slow-down/tsconfig.json b/types/express-slow-down/tsconfig.json new file mode 100644 index 0000000000..9973398566 --- /dev/null +++ b/types/express-slow-down/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", + "express-slow-down-tests.ts" + ] +} diff --git a/types/express-slow-down/tslint.json b/types/express-slow-down/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/express-slow-down/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/firefox-webext-browser/index.d.ts b/types/firefox-webext-browser/index.d.ts index 84dc4f15e7..9b318f9b4b 100644 --- a/types/firefox-webext-browser/index.d.ts +++ b/types/firefox-webext-browser/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for WebExtension Development in FireFox 64.0 +// Type definitions for WebExtension Development in FireFox 65.0 // Project: https://developer.mozilla.org/en-US/Add-ons/WebExtensions // Definitions by: Jasmin Bom // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -178,6 +178,8 @@ declare namespace browser._manifest { alternate_urls?: string[]; /** @deprecated Unsupported on Firefox. */ prepopulated_id?: number; + /** Encoding of the search term. */ + encoding?: string; /** Sets the default engine to a built-in engine only. */ is_default?: boolean; /** @@ -455,14 +457,17 @@ declare namespace browser._manifest { interface ThemeType { images?: { additional_backgrounds?: ImageDataOrExtensionURL[]; + /** @deprecated Please use _theme.images.theme_frame_, this alias will be removed in Firefox 69. */ headerURL?: ImageDataOrExtensionURL; theme_frame?: ImageDataOrExtensionURL; }; colors?: { tab_selected?: ThemeColor; + /** @deprecated Please use _theme.colors.frame_, this alias will be removed in Firefox 69. */ accentcolor?: ThemeColor; frame?: ThemeColor; frame_inactive?: ThemeColor; + /** @deprecated Please use _theme.colors.tab_background_text_, this alias will be removed in Firefox 69. */ textcolor?: ThemeColor; tab_background_text?: ThemeColor; tab_background_separator?: ThemeColor; @@ -470,6 +475,7 @@ declare namespace browser._manifest { tab_text?: ThemeColor; tab_line?: ThemeColor; toolbar?: ThemeColor; + /** @deprecated Please use _theme.colors.bookmark_text_, this alias will be removed in Firefox 69. */ toolbar_text?: ThemeColor; bookmark_text?: ThemeColor; toolbar_field?: ThemeColor; @@ -3535,11 +3541,6 @@ declare namespace browser.userScripts { unregister(): Promise; } - /** A set of API methods provided by the extensions to its userScripts */ - interface ExportedAPIMethods { - [key: string]: (...args: any[]) => any; - } - /* userScripts functions */ /** * Register a user script programmatically given its `userScripts.UserScriptOptions`, and resolves to a @@ -3547,12 +3548,28 @@ declare namespace browser.userScripts { */ function register(userScriptOptions: UserScriptOptions): Promise; + /* userScripts events */ /** - * Provides a set of custom API methods available to the registered userScripts + * Event called when a new userScript global has been created * * Allowed in: Content scripts only */ - function setScriptAPIs(exportedAPIMethods: ExportedAPIMethods): void; + const onBeforeScript: WebExtEvent<(userScript: { + /** The userScript metadata (as set in userScripts.register) */ + metadata: any; + /** The userScript global */ + global: any; + /** + * Exports all the properties of a given plain object as userScript globals + * @param sourceObject A plain object whose properties are exported as userScript globals + */ + defineGlobals: (sourceObject: object) => void; + /** + * Convert a given value to make it accessible to the userScript code + * @param value A value to convert into an object accessible to the userScript + */ + export: (value: any) => any; + }) => void>; } /** @@ -5570,16 +5587,24 @@ declare namespace browser.geckoProfiler { | "stackwalk" | "tasktracer" | "threads" - | "trackopts"; + | "trackopts" + | "jstracer"; + + type Supports = "windowLength"; /* geckoProfiler functions */ /** Starts the profiler with the specified settings. */ function start(settings: { /** - * The size in bytes of the buffer used to store profiling data. A larger value allows capturing a profile that - * covers a greater amount of time. + * The maximum size in bytes of the buffer used to store profiling data. A larger value allows capturing a + * profile that covers a greater amount of time. */ bufferSize: number; + /** + * The length of the window of time that's kept in the buffer. Any collected samples are discarded as soon as + * they are older than the number of seconds specified in this setting. Zero means no duration restriction. + */ + windowLength?: number; /** * Interval in milliseconds between samples of profiling data. A smaller value will increase the detail of the * profiles captured. @@ -5821,6 +5846,8 @@ declare namespace browser.contextMenus { * context where there is no current page, such as in a launcher context menu. */ pageUrl?: string; + /** The id of the frame of the element where the context menu was clicked. */ + frameId?: number; /** The URL of the frame of the element where the context menu was clicked, if it was in a frame. */ frameUrl?: string; /** The text for the context selection, if any. */ @@ -6100,6 +6127,8 @@ declare namespace browser.menus { * context where there is no current page, such as in a launcher context menu. */ pageUrl?: string; + /** The id of the frame of the element where the context menu was clicked. */ + frameId?: number; /** The URL of the frame of the element where the context menu was clicked, if it was in a frame. */ frameUrl?: string; /** The text for the context selection, if any. */ @@ -6939,6 +6968,8 @@ declare namespace browser.tabs { sharingState?: SharingState; /** Whether the tab is drawing attention. */ attention?: boolean; + /** The ID of this tab's successor, if any; `tabs.TAB_ID_NONE` otherwise. */ + successorTabId?: number; } /** @@ -7320,6 +7351,10 @@ declare namespace browser.tabs { openerTabId?: number; /** Whether the load should replace the current history entry for the tab. */ loadReplace?: boolean; + /** + * The ID of this tab's successor. If specified, the successor tab must be in the same window as this tab. + */ + successorTabId?: number; }): Promise; /** * Modifies the properties of a tab. Properties that are not specified in `updateProperties` are not modified. @@ -7349,6 +7384,10 @@ declare namespace browser.tabs { openerTabId?: number; /** Whether the load should replace the current history entry for the tab. */ loadReplace?: boolean; + /** + * The ID of this tab's successor. If specified, the successor tab must be in the same window as this tab. + */ + successorTabId?: number; }): Promise; /** @@ -7517,6 +7556,29 @@ declare namespace browser.tabs { */ function hide(tabIds: number | number[]): Promise; + /** + * Removes an array of tabs from their lines of succession and prepends or appends them in a chain to another tab. + * @param tabIds An array of tab IDs to move in the line of succession. For each tab in the array, the tab's + * current predecessors will have their successor set to the tab's current successor, and each tab will then be + * set to be the successor of the previous tab in the array. Any tabs not in the same window as the tab + * indicated by the second argument (or the first tab in the array, if no second argument) will be skipped. + * @param [tabId] The ID of a tab to set as the successor of the last tab in the array, or `tabs.TAB_ID_NONE` to + * leave the last tab without a successor. If options.append is true, then this tab is made the predecessor of + * the first tab in the array instead. + */ + function moveInSuccession(tabIds: number[], tabId?: number, options?: { + /** Whether to move the tabs before (false) or after (true) tabId in the succession. Defaults to false. */ + append?: boolean; + /** + * Whether to link up the current predecessors or successor (depending on options.append) of tabId to the other + * side of the chain after it is prepended or appended. If true, one of the following happens: if + * options.append is false, the first tab in the array is set as the successor of any current predecessors of + * tabId; if options.append is true, the current successor of tabId is set as the successor of the last tab in + * the array. Defaults to false. + */ + insert?: boolean; + }): Promise; + /* tabs events */ /** * Fired when a tab is created. Note that the tab's URL may not be set at the time this event fired, but you can @@ -7571,6 +7633,8 @@ declare namespace browser.tabs { const onActivated: WebExtEvent<(activeInfo: { /** The ID of the tab that has become active. */ tabId: number; + /** The ID of the tab that was previously active, if that tab is still open. */ + previousTabId?: number; /** The ID of the window the active tab changed inside of. */ windowId: number; }) => void>; diff --git a/types/google-apps-script/google-apps-script.data-studio.d.ts b/types/google-apps-script/google-apps-script.data-studio.d.ts index 572e4284e1..d4c9d15cde 100644 --- a/types/google-apps-script/google-apps-script.data-studio.d.ts +++ b/types/google-apps-script/google-apps-script.data-studio.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-12-26 +// Type definitions for Google Apps Script 2019-01-06 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -50,6 +50,8 @@ declare namespace GoogleAppsScript { FieldType: typeof FieldType; getConfig(): Config; getFields(): Fields; + newDebugError(): DebugError; + newUserError(): UserError; } /** @@ -83,6 +85,21 @@ declare namespace GoogleAppsScript { createCommunityConnector(): CommunityConnector; } + /** + * An error that is only visible to admins of the connector. + * + * var cc = DataStudioApp.createCommunityConnector(); + * + * cc.newDebugError() + * .setText("This is the debug error text.") + * .throwException(); + */ + export interface DebugError { + printJson(): string; + setText(text: string): DebugError; + throwException(): void; + } + /** * Contains field-related data. Its properties determine how the field is used in Data Studio. * @@ -295,6 +312,23 @@ declare namespace GoogleAppsScript { setPlaceholder(placeholder: string): TextInput; } + /** + * An error that is shown to users of the connector. + * + * var cc = DataStudioApp.createCommunityConnector(); + * + * cc.newUserError() + * .setText("This is the debug error text.") + * .setDebugText("This text is only shown to admins.") + * .throwException(); + */ + export interface UserError { + printJson(): string; + setDebugText(text: string): UserError; + setText(text: string): UserError; + throwException(): void; + } + } } diff --git a/types/google-apps-script/google-apps-script.slides.d.ts b/types/google-apps-script/google-apps-script.slides.d.ts index f1c3a6fdae..1619d92369 100644 --- a/types/google-apps-script/google-apps-script.slides.d.ts +++ b/types/google-apps-script/google-apps-script.slides.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Google Apps Script 2018-12-26 +// Type definitions for Google Apps Script 2019-01-06 // Project: https://developers.google.com/apps-script/ // Definitions by: motemen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -322,6 +322,8 @@ declare namespace GoogleAppsScript { insertTable(numRows: Integer, numColumns: Integer): Table; insertTable(numRows: Integer, numColumns: Integer, left: Number, top: Number, width: Number, height: Number): Table; insertTable(table: Table): Table; + insertTextBox(text: string): Shape; + insertTextBox(text: string, left: Number, top: Number, width: Number, height: Number): Shape; insertVideo(videoUrl: string): Video; insertVideo(videoUrl: string, left: Number, top: Number, width: Number, height: Number): Video; insertVideo(video: Video): Video; @@ -576,6 +578,8 @@ declare namespace GoogleAppsScript { insertTable(numRows: Integer, numColumns: Integer): Table; insertTable(numRows: Integer, numColumns: Integer, left: Number, top: Number, width: Number, height: Number): Table; insertTable(table: Table): Table; + insertTextBox(text: string): Shape; + insertTextBox(text: string, left: Number, top: Number, width: Number, height: Number): Shape; insertVideo(videoUrl: string): Video; insertVideo(videoUrl: string, left: Number, top: Number, width: Number, height: Number): Video; insertVideo(video: Video): Video; @@ -682,6 +686,8 @@ declare namespace GoogleAppsScript { insertTable(numRows: Integer, numColumns: Integer): Table; insertTable(numRows: Integer, numColumns: Integer, left: Number, top: Number, width: Number, height: Number): Table; insertTable(table: Table): Table; + insertTextBox(text: string): Shape; + insertTextBox(text: string, left: Number, top: Number, width: Number, height: Number): Shape; insertVideo(videoUrl: string): Video; insertVideo(videoUrl: string, left: Number, top: Number, width: Number, height: Number): Video; insertVideo(video: Video): Video; @@ -880,6 +886,7 @@ declare namespace GoogleAppsScript { appendSlide(layout: Layout): Slide; appendSlide(predefinedLayout: PredefinedLayout): Slide; appendSlide(slide: Slide): Slide; + appendSlide(slide: Slide, linkingMode: SlideLinkingMode): Slide; getEditors(): Base.User[]; getId(): string; getLayouts(): Layout[]; @@ -900,6 +907,7 @@ declare namespace GoogleAppsScript { insertSlide(insertionIndex: Integer, layout: Layout): Slide; insertSlide(insertionIndex: Integer, predefinedLayout: PredefinedLayout): Slide; insertSlide(insertionIndex: Integer, slide: Slide): Slide; + insertSlide(insertionIndex: Integer, slide: Slide, linkingMode: SlideLinkingMode): Slide; removeEditor(emailAddress: string): Presentation; removeEditor(user: Base.User): Presentation; removeViewer(emailAddress: string): Presentation; @@ -1102,6 +1110,9 @@ declare namespace GoogleAppsScript { getPlaceholders(): PageElement[]; getShapes(): Shape[]; getSheetsCharts(): SheetsChart[]; + getSlideLinkingMode(): SlideLinkingMode; + getSourcePresentationId(): string; + getSourceSlideObjectId(): string; getTables(): Table[]; getVideos(): Video[]; getWordArts(): WordArt[]; @@ -1127,17 +1138,26 @@ declare namespace GoogleAppsScript { insertTable(numRows: Integer, numColumns: Integer): Table; insertTable(numRows: Integer, numColumns: Integer, left: Number, top: Number, width: Number, height: Number): Table; insertTable(table: Table): Table; + insertTextBox(text: string): Shape; + insertTextBox(text: string, left: Number, top: Number, width: Number, height: Number): Shape; insertVideo(videoUrl: string): Video; insertVideo(videoUrl: string, left: Number, top: Number, width: Number, height: Number): Video; insertVideo(video: Video): Video; insertWordArt(wordArt: WordArt): WordArt; move(index: Integer): void; + refreshSlide(): void; remove(): void; replaceAllText(findText: string, replaceText: string): Integer; replaceAllText(findText: string, replaceText: string, matchCase: boolean): Integer; selectAsCurrentPage(): void; + unlink(): void; } + /** + * The mode of links between slides. + */ + export enum SlideLinkingMode { UNSUPPORTED, LINKED, NOT_LINKED } + /** * The relative position of a Slide. */ diff --git a/types/got/got-tests.ts b/types/got/got-tests.ts index 1626cae86a..d80d0aadcf 100644 --- a/types/got/got-tests.ts +++ b/types/got/got-tests.ts @@ -286,3 +286,75 @@ got('http://todomvc.com', { // Test got.TimeoutError. got('http://todomvc.com', {timeout: 1}).catch((err) => err instanceof got.TimeoutError); + +// Test hooks. +got('example.com', { + hooks: { + beforeRedirect: [ + options => { + if (options.hostname === 'deadSite') { + options.hostname = 'fallbackSite'; + } + } + ] + } +}); +got('example.com', { + hooks: { + beforeRetry: [ + (options, error, retryCount) => { + if (error instanceof got.HTTPError && error.statusCode === 413) { // Payload too large + options.body = 'new body'; + } + } + ] + } +}); +got('example.com', { + hooks: { + afterResponse: [ + (response, retryWithMergedOptions) => { + if (response.statusCode === 401) { // Unauthorized + const updatedOptions = { + headers: { + token: 'new token' // Refresh the access token + } + }; + + // Make a new retry + return retryWithMergedOptions(updatedOptions); + } + + // No changes otherwise + return response; + } + ] + } +}); +// Test async hooks. +{ + const doSomethingAsync = (): Promise => { + throw new Error('unimplemented'); + }; + + got('example.com', { + hooks: { + beforeRedirect: [ + async () => { + await doSomethingAsync(); + } + ], + beforeRetry: [ + async () => { + await doSomethingAsync(); + } + ], + afterResponse: [ + async (response) => { + await doSomethingAsync(); + return response; + } + ] + } + }); +} diff --git a/types/got/index.d.ts b/types/got/index.d.ts index 079e84ff62..09b451f4bb 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for got 9.2 +// Type definitions for got 9.3 // Project: https://github.com/sindresorhus/got#readme // Definitions by: BendingBender // Linus Unnebäck @@ -102,12 +102,50 @@ declare namespace got { type GotUrl = string | https.RequestOptions | Url | URL; - type Hook = (options: T) => any; - type Hooks = Record<'beforeRequest', Array>>; + /** + * Hooks allow modifications during the request lifecycle. Hook functions may be async and are + * run serially. + * + * @see https://github.com/sindresorhus/got#hooks + * @template Options Request options. + * @template Body Response body type. + */ + interface Hooks { + beforeRequest?: Array>; + beforeRedirect?: Array>; + beforeRetry?: Array>; + afterResponse?: Array>; + } + + /** + * @param options Normalized request options. + */ + type BeforeRequestHook = (options: Options) => any; + + /** + * @param options Normalized request options. + */ + type BeforeRedirectHook = (options: Options) => any; + + /** + * @param options Normalized request options. + * @param error Request error. + * @param retryCount Number of retry. + */ + type BeforeRetryHook = (options: Options, error: GotError, retryCount: number) => any; + + /** + * @param response Response object. + * @param retryWithMergedOptions Retries request with the updated options. + */ + type AfterResponseHook = ( + response: Response, + retryWithMergedOptions: (updateOptions: Options) => GotPromise + ) => Response | Promise>; interface GotBodyOptions extends GotOptions { body?: string | Buffer | nodeStream.Readable; - hooks?: Hooks>; + hooks?: Hooks, string | Buffer | nodeStream.Readable>; } interface GotJSONOptions extends GotOptions { @@ -115,14 +153,14 @@ declare namespace got { body?: object; form?: boolean; json: true; - hooks?: Hooks; + hooks?: Hooks; } interface GotFormOptions extends GotOptions { - body?: {[key: string]: any}; + body?: Record; form: true; json?: boolean; - hooks?: Hooks>; + hooks?: Hooks, Record>; } interface GotOptions extends InternalRequestOptions { diff --git a/types/hibp/hibp-tests.ts b/types/hibp/hibp-tests.ts deleted file mode 100644 index cdcd1851bf..0000000000 --- a/types/hibp/hibp-tests.ts +++ /dev/null @@ -1,17 +0,0 @@ -import * as hibp from 'hibp'; - -hibp -.search('someAccountOrEmail') -.then(data => { - if (data.breaches || data.pastes) { - // Bummer... - console.log(data); - } else { - // Phew! We're clear. - console.log('Good news — no pwnage found!'); - } -}) -.catch(err => { - // Something went wrong. - console.log(err.message); -}); diff --git a/types/hibp/index.d.ts b/types/hibp/index.d.ts deleted file mode 100644 index 27819f1c96..0000000000 --- a/types/hibp/index.d.ts +++ /dev/null @@ -1,97 +0,0 @@ -// Type definitions for hibp 7.2 -// Project: https://github.com/wkovacs64/hibp -// Definitions by: Silas Rech -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -/// - -export interface BreachOptions { - domain?: string; - truncate?: boolean; -} - -export interface Breach { - Name: string; - Title: string; - Domain: string; - BreachDate: string; - AddedDate: string; - ModifiedDate: string; - PwnCount: number; - Description: string; - LogoPath: string; - DataClasses: string[]; - IsVerified: boolean; - IsFabricated: boolean; - IsSensitive: boolean; - IsRetired: boolean; - IsSpamList: boolean; -} - -export interface Paste { - Id: string; - Source: string; - Title: string; - Date: string; - EmailCount: number; -} - -export interface Range { - suffix: string; - count: number; -} - -/** - * Fetches data for a specific breach event. - */ -export function breach(breachName: string): Promise; - -/** - * Fetches breach data for a specific account. - */ -export function breachedAccount(account: string, options?: BreachOptions): Promise; - -/** - * Fetches all breach events in the system. - */ -export function breaches(options?: { domain?: string }): Promise; - -/** - * Fetches all data classes in the system. - */ -export function dataClasses(): Promise; - -/** - * Fetches paste data for a specific email address. - */ -export function pasteAccount(email: string): Promise; - -/** - * Fetches the number of times the the given password has been exposed in a breach (0 indicating no exposure). - * The password is given in plain text, but only the first 5 characters of its SHA-1 hash will be submitted to the API. - */ -export function pwnedPassword(password: string): Promise; - -/** - * Fetches the SHA-1 hash suffixes for the given 5-character SHA-1 hash prefix. - * - * When a password hash with the same first 5 characters is found in the Pwned Passwords repository, - * the API will respond with an HTTP 200 and include the suffix of every hash beginning with the specified prefix, - * followed by a count of how many times it appears in the data set. - * - * This function parses the response and returns a more structured format. - */ -export function pwnedPasswordRange(prefix: string): Promise; - -/** - * Fetches all breaches and all pastes associated with the provided account (email address or username). - * - * Note that the remote API does not support querying pastes by username (only email addresses), - * so in the event the provided account is not a valid email address, - * only breach data is queried and the "pastes" field of the resulting object will always be null. - * - * This is exactly how searching via the current web interface behaves, which this convenience method is designed to mimic. - * - */ -export function search(account: string, options?: BreachOptions): Promise<{ breaches?: Breach[], pastes?: Paste[] }>; diff --git a/types/hls.js/hls.js-tests.ts b/types/hls.js/hls.js-tests.ts index 934ee1fd9c..90176ae6b7 100644 --- a/types/hls.js/hls.js-tests.ts +++ b/types/hls.js/hls.js-tests.ts @@ -23,7 +23,14 @@ class pLoader extends Hls.DefaultConfig.loader { if (Hls.isSupported()) { const video = document.getElementById('video'); - const hls = new Hls({ pLoader, startFragPrefetch: true }); + const hls = new Hls({ + pLoader, + startFragPrefetch: true, + debug: { + log: (...args: any[]) => console.log(...args) + } + }); + const version: string = Hls.version; hls.loadSource('http://www.streambox.fr/playlists/test_001/stream.m3u8'); hls.attachMedia(video); diff --git a/types/hls.js/index.d.ts b/types/hls.js/index.d.ts index 721f4a3dce..9b7986b99f 100644 --- a/types/hls.js/index.d.ts +++ b/types/hls.js/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for hls.js 0.10 +// Type definitions for hls.js 0.12 // Project: https://github.com/video-dev/hls.js // Definitions by: John G. Gainfort, Jr. +// Johan Brook // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.4 // Event Keys type K_MEDIA_ATTACHING = "hlsMediaAttaching"; @@ -307,6 +308,16 @@ declare namespace Hls { // interface SubtitleTracks {} + type CustomLogger = (...args: any[]) => void; + + interface CustomLoggerObject { + warn?: CustomLogger; + info?: CustomLogger; + log?: CustomLogger; + debug?: CustomLogger; + error?: CustomLogger; + } + interface Config { /** * (default: false) @@ -319,7 +330,7 @@ declare namespace Hls { * setting config.debug = true; will turn on debug logs on JS console. * a logger object could also be provided for custom logging: config.debug = customLogger; */ - debug: boolean; + debug: boolean | CustomLoggerObject; /** * (default: true) * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event @@ -475,6 +486,14 @@ declare namespace Hls { * Android Google Chrome, etc. set this value to true. */ liveDurationInfinity: boolean; + /** + * (default: Infinity) + * Sets the maximum length of the buffer, in seconds, to keep during a live stream. Any video + * buffered past this time will be evicted. Infinity means no restriction on back buffer length; + * 0 keeps the minimum amount. The minimum amount is equal to the target duration of a segment + * to ensure that current playback is not interrupted. + */ + liveBackBufferLength: number; /** * (default: true) * Enable WebWorker (if available on browser) for TS demuxing/MP4 remuxing, to improve performance and avoid lag/frame drops. diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index 314d8c8e30..81381d801d 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -828,10 +828,12 @@ declare global { ca: Array; } + type MessagePayload = string | Record; + /** Callback information for a passed message */ interface MessageCallbackInfo { /** The original message payload */ - message: string | object; + message: MessagePayload; /** ID of this callback */ id: number; // ??? @@ -839,14 +841,13 @@ declare global { /** 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; + message: MessagePayload; /** The source of this message */ from: string; /** ID of this message */ @@ -1038,8 +1039,8 @@ declare global { * @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; + sendTo(instanceName: string, message: MessagePayload, callback?: MessageCallback | MessageCallbackInfo): void; + sendTo(instanceName: string, command: string, message: MessagePayload, callback?: MessageCallback | MessageCallbackInfo): void; /** * Sends a message to a specific instance or all instances of some specific adapter. * @param instanceName The instance to send this message to. @@ -1048,18 +1049,18 @@ declare global { * @param command (optional) Command name of the target instance. Default: "send" * @param message The message (e.g. params) to send. */ - sendToAsync(instanceName: string, message: string | object): Promise; - sendToAsync(instanceName: string, command: string, message: string | object): Promise; + sendToAsync(instanceName: string, message: MessagePayload): Promise; + sendToAsync(instanceName: string, command: string, message: MessagePayload): Promise; /** * 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; + sendToHost(hostName: string, message: MessagePayload, callback?: MessageCallback | MessageCallbackInfo): void; + sendToHost(hostName: string, command: string, message: MessagePayload, callback?: MessageCallback | MessageCallbackInfo): void; /** * Sends a message to a specific host or all hosts. */ - sendToHostAsync(hostName: string, message: string | object): Promise; - sendToHostAsync(hostName: string, command: string, message: string | object): Promise; + sendToHostAsync(hostName: string, message: MessagePayload): Promise; + sendToHostAsync(hostName: string, command: string, message: MessagePayload): Promise; /** Convert ID to {device: D, channel: C, state: S} */ idToDCS(id: string): { @@ -1125,9 +1126,9 @@ declare global { getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, options: unknown, callback: GetObjectsCallback): void; // tslint:enable:unified-signatures /** Get foreign objects by pattern, by specific type and resolve their enums. */ - getForeignObjectsAsync(pattern: string, options?: unknown): Promise>; - getForeignObjectsAsync(pattern: string, type: ObjectType, options?: unknown): Promise>; - getForeignObjectsAsync(pattern: string, type: ObjectType, enums: EnumList, options?: unknown): Promise>; + getForeignObjectsAsync(pattern: string, options?: unknown): Promise>; + getForeignObjectsAsync(pattern: string, type: ObjectType, options?: unknown): Promise>; + getForeignObjectsAsync(pattern: string, type: ObjectType, enums: EnumList, options?: unknown): Promise>; /** Creates or overwrites an object (which might not belong to this adapter) in the object db */ setForeignObject(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; setForeignObject(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; @@ -1591,6 +1592,8 @@ declare global { // TODO: Redefine callbacks as subclass of GenericCallback type GenericCallback = (err: string | null, result?: T) => void; + type MessageCallback = (response?: Message) => void; + type SetObjectCallback = (err: string | null, obj: { id: string }) => void; type GetObjectCallback = (err: string | null, obj: ioBroker.Object | null | undefined) => void; type GetEnumCallback = (err: string | null, enums: Record, requestedEnum: string) => void; diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index fcdc4d5c9e..f49eb34576 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -99,7 +99,8 @@ function messageHandler(msg: ioBroker.Message) { msg.callback.time.toFixed(); msg.command.toLowerCase(); msg.from.toLowerCase(); - msg.message.toString(); + typeof msg.message === "object" && msg.message.anything; + typeof msg.message === "string" && msg.message.toLowerCase(); } function unloadHandler(callback: ioBroker.EmptyCallback) { @@ -170,6 +171,9 @@ adapter.getForeignObject("obj.id", (err, obj) => { }); adapter.getObjectAsync("obj.id").then(obj => obj._id.toLowerCase()); adapter.getForeignObjectAsync("obj.id").then(obj => obj._id.toLowerCase()); +adapter.getForeignObjects("*", (err, objs) => objs["foo"]._id.toLowerCase()); +adapter.getForeignObjectsAsync("*").then(objs => objs["foo"]._id.toLowerCase()); + adapter.subscribeObjects("*"); adapter.subscribeStates("*"); adapter.subscribeForeignObjects("*"); @@ -195,3 +199,45 @@ switch (adapter.log.level) { default: assertNever(adapter.log.level); } + +adapter.sendTo("foo.0", "command", "message"); +adapter.sendTo("foo.0", "message"); +adapter.sendTo("foo.0", "command", {msg: "message"}); +adapter.sendTo("foo.0", {msg: "message"}); + +function handleMessageResponse(response?: ioBroker.Message) { + if (!response) return; + response._id.toFixed(); + response.callback.ack.valueOf(); + response.callback.id.toFixed(); + response.callback.message.toString(); + response.callback.time.toFixed(); + response.command.toLowerCase(); + response.from.toLowerCase(); + typeof response.message === "object" && response.message.anything; + typeof response.message === "string" && response.message.toLowerCase(); +} +adapter.sendTo("foo.0", "command", "message", handleMessageResponse); +adapter.sendTo("foo.0", "message", handleMessageResponse); +adapter.sendTo("foo.0", "command", {msg: "message"}, handleMessageResponse); +adapter.sendTo("foo.0", {msg: "message"}, handleMessageResponse); + +adapter.sendToAsync("foo.0", "command", "message").then(handleMessageResponse); +adapter.sendToAsync("foo.0", "message").then(handleMessageResponse); +adapter.sendToAsync("foo.0", "command", {msg: "message"}).then(handleMessageResponse); +adapter.sendToAsync("foo.0", {msg: "message"}).then(handleMessageResponse); + +adapter.sendToHost("host-foo", "command", "message"); +adapter.sendToHost("host-foo", "message"); +adapter.sendToHost("host-foo", "command", {msg: "message"}); +adapter.sendToHost("host-foo", {msg: "message"}); + +adapter.sendToHost("host-foo", "command", "message", handleMessageResponse); +adapter.sendToHost("host-foo", "message", handleMessageResponse); +adapter.sendToHost("host-foo", "command", {msg: "message"}, handleMessageResponse); +adapter.sendToHost("host-foo", {msg: "message"}, handleMessageResponse); + +adapter.sendToHostAsync("host-foo", "command", "message").then(handleMessageResponse); +adapter.sendToHostAsync("host-foo", "message").then(handleMessageResponse); +adapter.sendToHostAsync("host-foo", "command", {msg: "message"}).then(handleMessageResponse); +adapter.sendToHostAsync("host-foo", {msg: "message"}).then(handleMessageResponse); diff --git a/types/is-valid-path/index.d.ts b/types/is-valid-path/index.d.ts new file mode 100644 index 0000000000..2aa54e3e99 --- /dev/null +++ b/types/is-valid-path/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for is-valid-path 0.1 +// Project: https://github.com/jonschlinkert/is-valid-path +// Definitions by: Zlatko Andonovski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function isValidPath(path?: string | null): boolean; + +export = isValidPath; diff --git a/types/is-valid-path/is-valid-path-tests.ts b/types/is-valid-path/is-valid-path-tests.ts new file mode 100644 index 0000000000..a0ca7ac1a9 --- /dev/null +++ b/types/is-valid-path/is-valid-path-tests.ts @@ -0,0 +1,18 @@ +// Tests are from the NPM README (https://www.npmjs.com/package/is-valid-path). + +import isValid = require('is-valid-path'); + +isValid('abc.js'); +isValid('abc/def/ghi.js'); +isValid('foo.js'); + +isValid(); +isValid(null); +isValid('!foo.js'); +isValid('*.js'); +isValid('**/abc.js'); +isValid('abc/*.js'); +isValid('abc/(aaa|bbb).js'); +isValid('abc/[a-z].js'); +isValid('abc/{a,b}.js'); +isValid('abc/?.js'); diff --git a/types/is-valid-path/tsconfig.json b/types/is-valid-path/tsconfig.json new file mode 100644 index 0000000000..da95d11317 --- /dev/null +++ b/types/is-valid-path/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", + "is-valid-path-tests.ts" + ] +} diff --git a/types/is-valid-path/tslint.json b/types/is-valid-path/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-valid-path/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 6fb82e76b2..4073e21087 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -39,11 +39,15 @@ interface NodeRequire { /** * Returns the actual module instead of a mock, bypassing all checks on * whether the module should receive a mock implementation or not. + * + * @deprecated Use `jest.requireActual` instead. */ requireActual(moduleName: string): any; /** * Returns a mock module instead of the actual module, bypassing all checks * on whether the module should be required normally or not. + * + * @deprecated Use `jest.requireMock`instead. */ requireMock(moduleName: string): any; } @@ -127,6 +131,16 @@ declare namespace jest { * Mocks a module with an auto-mocked version when it is being required. */ function mock(moduleName: string, factory?: any, options?: MockOptions): typeof jest; + /** + * Returns the actual module instead of a mock, bypassing all checks on + * whether the module should receive a mock implementation or not. + */ + function requireActual(moduleName: string): any; + /** + * Returns a mock module instead of the actual module, bypassing all checks + * on whether the module should be required normally or not. + */ + function requireMock(moduleName: string): any; /** * Resets the module registry - the cache of all required modules. This is * useful to isolate modules where local state might conflict between tests. diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index de1ba90456..4164e009e4 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -251,6 +251,12 @@ jest .useFakeTimers() .useRealTimers(); +// https://jestjs.io/docs/en/jest-object#jestrequireactualmodulename +jest.requireActual("./thisReturnsTheActualModule"); + +// https://jestjs.io/docs/en/jest-object#jestrequiremockmodulename +jest.requireMock("./thisAlwaysReturnsTheMock"); + /* Mocks and spies */ const mock1: jest.Mock = jest.fn(); diff --git a/types/johnny-five/index.d.ts b/types/johnny-five/index.d.ts index a770cd2126..53716f9b33 100644 --- a/types/johnny-five/index.d.ts +++ b/types/johnny-five/index.d.ts @@ -4,6 +4,7 @@ // Zoltan Ujvary // Simon Colmer // XtrimSystems +// Marcin Obiedziński // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -111,11 +112,10 @@ export declare class Board { io: any; id: string; - repl: any; + repl: Repl; isReady: boolean; pins: Array; port: string; - inject: Repl; on(event: string, cb: () => void): this; on(event: "ready", cb: () => void): this; diff --git a/types/js-combinatorics/index.d.ts b/types/js-combinatorics/index.d.ts index 702ef1f9a2..8023aeff73 100644 --- a/types/js-combinatorics/index.d.ts +++ b/types/js-combinatorics/index.d.ts @@ -8,7 +8,7 @@ declare namespace __Combinatorics { interface IGenerator { /** - * Returns the element or undefined if no more element is available. + * Returns the element or undefined if no more elements are available. */ next():T; @@ -18,24 +18,24 @@ declare namespace __Combinatorics { forEach(f:(item:T) => void):void; /** - * All elements at once with function applied to each element. + * Returns an array that is the output of calling the callback function separately on each element. */ map(f:(item:T) => TResult):TResult[]; /** - * Returns an array with elements that passes the filter function. + * Returns an array of elements that return `true` for the filter function. */ filter(predicate:(item:T) => boolean):T[]; /** - * All elements at once. + * Returns an array of all elements. */ toArray():T[]; /** - * Returns the number of elements to be generated which equals to generator.toArray().length - * but it is precalculated without actually generating elements. - * Handy when you prepare for large iteration. + * Returns the total number of elements to be generated. This equals the result of calling + * `generator.toArray().length` but it is precalculated without actually generating any elements. + * Handy when doing setup for a potentially long-running loop. */ length:number; @@ -44,7 +44,7 @@ declare namespace __Combinatorics { interface IPredictableGenerator extends IGenerator { /** - * Returns the nth element (starting 0). + * Returns the nth element (indexed from 0). */ nth(n:number):T; @@ -53,11 +53,10 @@ declare namespace __Combinatorics { interface ICartesianProductGenerator extends IPredictableGenerator { /** - * Arguments are coordinates in integer. - * Arguments can be out of bounds but it returns undefined in such cases. + * Arguments are integer coordinates. + * Arguments can be out of bounds but it returns `undefined` in such cases. */ get(...coordinates:number[]):T; - } /** @@ -76,46 +75,47 @@ declare namespace __Combinatorics { function factorial(n:number):number; /** - * Returns the factoradic representation of n in array, in least significant order. + * Returns the factoradic representation of `n` in an array, in + * least significant order. * See http://en.wikipedia.org/wiki/Factorial_number_system */ function factoradic(n:number):number[]; /** - * Generates the power set of array. + * Generates the power set of `a`. */ function power(a:T[]):IPredictableGenerator; /** - * Generates the combination of array with n elements. - * When n is ommited, the length of the array is used. + * Generates the combination of `a` with `n` elements. + * `n` defaults to the length of `a`. */ function combination(a:T[], n?:number):IGenerator; /** - * Generates the combination of array with n elements, which + * Generates the combination of `a` with `n` elements, which * also supports larger sets of elements. - * When n is ommited, the length of the array is used. - * Somewhat slower than combination() + * When `n` is ommited, the length of the array is used. + * Somewhat slower than `combination()` */ function bigCombination(a:T[], n?:number):IGenerator; /** - * Generates the permutation of array with n elements. - * When n is ommited, the length of the array is used. + * Generates the permutation of `a` with `n` elements. + * `n` defaults to the length of `a`. */ function permutation(a:T[], n?:number):IGenerator; /** - * Generates the permutation of the combination of n. - * Equivalent to permutation(combination(a)), but more efficient. + * Generates the permutation of the combination of `a`. + * Equivalent to `permutation(combination(a))`, but more efficient. */ function permutationCombination(a:T[]):IGenerator; /** - * Generates n-digit "numbers" where each digit is an element in array. + * Generates `n`-digit "numbers" where each digit is an element in array. * Note this "number" is in the least significant order. - * When n is ommited, the length of the array is used. + * `n` defaults to the length of `a`. */ function baseN(a:T[], n?:number):IPredictableGenerator; diff --git a/types/keyboardjs/index.d.ts b/types/keyboardjs/index.d.ts index 037bf7189b..c97cda0741 100644 --- a/types/keyboardjs/index.d.ts +++ b/types/keyboardjs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for KeyboardJS v2.4.1 +// Type definitions for KeyboardJS v2.4.2 // Project: https://github.com/RobertWHurst/KeyboardJS // Definitions by: Vincent Bortone , // David Asmuth , @@ -92,14 +92,16 @@ declare namespace keyboardjs { /** * Triggers a key press. Stays in pressed state until released. - * @param keyCombo String of keys to be pressed to execute 'pressed' callbacks. + * @param keyCombo String of keys or keyCode to be pressed to execute 'pressed' callbacks. + * @param event The KeyEvent, can be null. */ - export function pressKey(keyCombo: string): void + export function pressKey(keyCombo: string | number, event?: KeyEvent): void; /** * Triggers a key release. - * @param keyCombo String of keys to be released to execute 'released' callbacks. + * @param keyCombo String of keys or keyCode to be released to execute 'released' callbacks. + * @param event The KeyEvent, can be null. */ - export function releaseKey(keyCombo: string): void; + export function releaseKey(keyCombo: string | number, event?: KeyEvent): void; /** * Releases all keys. */ diff --git a/types/keyv__mysql/index.d.ts b/types/keyv__mysql/index.d.ts new file mode 100644 index 0000000000..4aef9d06e0 --- /dev/null +++ b/types/keyv__mysql/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for @keyv/mysql 1.1 +// Project: https://github.com/lukechilds/keyv-mysql +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Store } from 'keyv'; +import { EventEmitter } from 'events'; + +export = KeyvMysql; + +declare class KeyvMysql extends EventEmitter implements Store { + readonly ttlSupport: false; + namespace?: string; + + constructor(uri?: string); + constructor(options?: KeyvMysql.Options); // tslint:disable-line:unified-signatures + + get(key: string): Promise; + set(key: string, value: string | undefined): Promise; + delete(key: string): Promise; + clear(): Promise; +} + +declare namespace KeyvMysql { + interface Options { + uri?: string; + table?: string; + keySize?: number; + } +} diff --git a/types/keyv__mysql/keyv__mysql-tests.ts b/types/keyv__mysql/keyv__mysql-tests.ts new file mode 100644 index 0000000000..5a1947710d --- /dev/null +++ b/types/keyv__mysql/keyv__mysql-tests.ts @@ -0,0 +1,12 @@ +import Keyv = require('keyv'); +import KeyvMysql = require('@keyv/mysql'); + +new Keyv('mysql://user:pass@localhost:3306/dbname', { table: 'cache' }); + +new KeyvMysql('mysql://user:pass@localhost:3306/dbname'); +new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname' }); +new KeyvMysql({ table: 'cache' }); +new KeyvMysql({ keySize: 100 }); + +const mysql = new KeyvMysql({ uri: 'mysql://user:pass@localhost:3306/dbname' }); +new Keyv({ store: mysql }); diff --git a/types/keyv__mysql/tsconfig.json b/types/keyv__mysql/tsconfig.json new file mode 100644 index 0000000000..e50e632d7c --- /dev/null +++ b/types/keyv__mysql/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@keyv/mysql": [ + "keyv__mysql" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "keyv__mysql-tests.ts" + ] +} diff --git a/types/keyv__mysql/tslint.json b/types/keyv__mysql/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/keyv__mysql/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/knockout/index.d.ts b/types/knockout/index.d.ts index fa0e195788..8bf99b79db 100644 --- a/types/knockout/index.d.ts +++ b/types/knockout/index.d.ts @@ -140,7 +140,7 @@ interface KnockoutSubscribableStatic { interface KnockoutSubscription { /** - * Terminates a subscription + * Terminates a subscription */ dispose(): void; } @@ -213,9 +213,6 @@ interface KnockoutReadonlyComputed extends KnockoutReadonlyObservable { interface KnockoutComputed extends KnockoutReadonlyComputed, KnockoutObservable, KnockoutComputedFunctions { fn: KnockoutComputedFunctions; - // It's possible for 'a' to be undefined, since the equalityComparer is run on the initial - // computation with undefined as the first argument. This is user-relevant for deferred computeds. - equalityComparer(a: T | undefined, b: T): boolean; /** * Manually disposes the computed observable, clearing all subscriptions to dependencies. * This function is useful if you want to stop a computed observable from being updated or want to clean up memory for a diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index 8d8f35df6b..b2163d09d1 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -19,12 +19,6 @@ import * as Koa from "koa"; -declare module "koa" { - interface Context { - params: any; - } -} - declare namespace Router { export interface IRouterOptions { /** @@ -61,11 +55,11 @@ declare namespace Router { } export interface IMiddleware { - (ctx: Router.IRouterContext, next: () => Promise): any; + (ctx: Koa.ParameterizedContext<{}, IRouterContext>, next: () => Promise): any; } export interface IParamMiddleware { - (param: string, ctx: Router.IRouterContext, next: () => Promise): any; + (param: string, ctx: Koa.ParameterizedContext<{}, IRouterContext>, next: () => Promise): any; } export interface IRouterAllowedMethodsOptions { @@ -88,7 +82,7 @@ declare namespace Router { sensitive?: boolean; strict?: boolean; } - + export interface IUrlOptionsQuery { query: object | string; } @@ -190,19 +184,19 @@ declare class Router { */ put(name: string, path: string | RegExp, ...middleware: Array): Router; put(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; - + /** * HTTP link method */ link(name: string, path: string | RegExp, ...middleware: Array): Router; link(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; - + /** * HTTP unlink method */ unlink(name: string, path: string | RegExp, ...middleware: Array): Router; unlink(path: string | RegExp | (string | RegExp)[], ...middleware: Array): Router; - + /** * HTTP delete method @@ -283,21 +277,21 @@ declare class Router { /** * Generate URL for route. Takes either map of named `params` or series of * arguments (for regular expression routes) - * + * * router = new Router(); * router.get('user', "/users/:id", ... - * + * * router.url('user', { id: 3 }); * // => "/users/3" - * + * * Query can be generated from third argument: - * + * * router.url('user', { id: 3 }, { query: { limit: 1 } }); * // => "/users/3?limit=1" - * + * * router.url('user', { id: 3 }, { query: "limit=1" }); * // => "/users/3?limit=1" - * + * */ url(name: string, params: any, options?: Router.IUrlOptionsQuery): string; url(name: string, params: any, options?: Router.IUrlOptionsQuery): Error; diff --git a/types/koa-router/koa-router-tests.ts b/types/koa-router/koa-router-tests.ts index e1c90c636d..50e66509ea 100644 --- a/types/koa-router/koa-router-tests.ts +++ b/types/koa-router/koa-router-tests.ts @@ -1,7 +1,7 @@ import Koa = require("koa"); import Router = require("koa-router"); -const app = new Koa(); +const app = new Koa<{}, {}>(); const router = new Router({ prefix: "/users" @@ -49,6 +49,10 @@ const match = router.match('/users/:id', 'GET'); let layer: Router.Layer let layerOptions: Router.ILayerOptions +const mw: Router.IMiddleware = (ctx: Router.IRouterContext, next: () => Promise) => { + ctx.body = "Ok"; +}; + app.use(router.routes()); app.use(router.allowedMethods()); diff --git a/types/libsodium-wrappers-sumo/index.d.ts b/types/libsodium-wrappers-sumo/index.d.ts index ceeadd5980..5341cca299 100644 --- a/types/libsodium-wrappers-sumo/index.d.ts +++ b/types/libsodium-wrappers-sumo/index.d.ts @@ -7,10 +7,12 @@ export * from 'libsodium-wrappers'; import { - Uint8ArrayOutputFormat, - StringOutputFormat, + KeyPair, onetimeauth_state_address, state_address, + StringKeyPair, + StringOutputFormat, + Uint8ArrayOutputFormat, } from 'libsodium-wrappers'; export const crypto_auth_hmacsha256_BYTES: number; @@ -77,6 +79,12 @@ export const crypto_stream_xchacha20_KEYBYTES: number; export const crypto_stream_xchacha20_NONCEBYTES: number; +export const crypto_box_curve25519xchacha20poly1305_NONCEBYTES: number; + +export const crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES: number; + +export const crypto_box_curve25519xchacha20poly1305_SECRETKEYBYTES: number; + export function crypto_auth_hmacsha256( message: string | Uint8Array, key: Uint8Array, @@ -113,6 +121,18 @@ export function crypto_auth_hmacsha512_keygen(outputFormat?: StringOutputFormat export function crypto_auth_hmacsha512_verify(tag: Uint8Array, message: string | Uint8Array, key: Uint8Array): boolean; +export function crypto_box_curve25519xchacha20poly1305_keypair(publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): KeyPair; + +export function crypto_box_curve25519xchacha20poly1305_keypair(publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: StringOutputFormat | null): StringKeyPair; + +export function crypto_box_curve25519xchacha20poly1305_seal(message: Uint8Array, publicKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; + +export function crypto_box_curve25519xchacha20poly1305_seal(message: Uint8Array, publicKey: Uint8Array, outputFormat?: StringOutputFormat | null): string; + +export function crypto_box_curve25519xchacha20poly1305_seal_open(ciphertext: Uint8Array, publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; + +export function crypto_box_curve25519xchacha20poly1305_seal_open(ciphertext: Uint8Array, publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: StringOutputFormat | null): string; + export function crypto_hash_sha256( message: string | Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null, @@ -240,6 +260,10 @@ export function crypto_sign_ed25519_sk_to_seed( outputFormat?: StringOutputFormat | null, ): string; +export function crypto_stream_chacha20(outLength: number, key: Uint8Array, nonce: Uint8Array, outputFormat?: StringOutputFormat | null): string; + +export function crypto_stream_chacha20(outLength: number, key: Uint8Array, nonce: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; + export function crypto_stream_chacha20_ietf_xor( input_message: string | Uint8Array, nonce: Uint8Array, diff --git a/types/libsodium-wrappers/index.d.ts b/types/libsodium-wrappers/index.d.ts index e9213da782..864aa2369f 100644 --- a/types/libsodium-wrappers/index.d.ts +++ b/types/libsodium-wrappers/index.d.ts @@ -886,30 +886,30 @@ export function crypto_secretstream_xchacha20poly1305_keygen(outputFormat?: Uint export function crypto_secretstream_xchacha20poly1305_keygen(outputFormat?: StringOutputFormat | null): string; export function crypto_secretstream_xchacha20poly1305_pull( - state_address?: secretstream_xchacha20poly1305_state_address, - cipher?: string | Uint8Array, + state_address: secretstream_xchacha20poly1305_state_address, + cipher: string | Uint8Array, ad?: string | Uint8Array | null, outputFormat?: Uint8ArrayOutputFormat | null, ): { message: Uint8Array; tag: Uint8Array }; export function crypto_secretstream_xchacha20poly1305_pull( - state_address?: secretstream_xchacha20poly1305_state_address, - cipher?: string | Uint8Array, + state_address: secretstream_xchacha20poly1305_state_address, + cipher: string | Uint8Array, ad?: string | Uint8Array | null, outputFormat?: StringOutputFormat | null, ): { message: string; tag: Uint8Array }; export function crypto_secretstream_xchacha20poly1305_push( - state_address?: secretstream_xchacha20poly1305_state_address, - message_chunk?: string | Uint8Array, + state_address: secretstream_xchacha20poly1305_state_address, + message_chunk: string | Uint8Array, ad?: string | Uint8Array | null, tag?: number, outputFormat?: Uint8ArrayOutputFormat | null, ): Uint8Array; export function crypto_secretstream_xchacha20poly1305_push( - state_address?: secretstream_xchacha20poly1305_state_address, - message_chunk?: string | Uint8Array, + state_address: secretstream_xchacha20poly1305_state_address, + message_chunk: string | Uint8Array, ad?: string | Uint8Array | null, tag?: number, outputFormat?: StringOutputFormat | null, diff --git a/types/linkifyjs/index.d.ts b/types/linkifyjs/index.d.ts index 9c095a41f3..a036ab52c1 100644 --- a/types/linkifyjs/index.d.ts +++ b/types/linkifyjs/index.d.ts @@ -1,8 +1,11 @@ // Type definitions for linkifyjs 2.1 // Project: https://github.com/SoapBox/linkifyjs#readme // Definitions by: Sean Zhu +// Ovidiu Bute // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.8 + +import * as React from "react"; export type PossiblyFuncOfHrefAndType = | T @@ -26,9 +29,9 @@ export interface LinkifyOptions { * Also accepts a function that takes the unformatted href, the link type * (e.g., 'url', 'email', etc.) and returns the object. */ - attributes?: PossiblyFuncOfHrefAndType<{ - [attrName: string]: string; - }> | null; + attributes?: PossiblyFuncOfHrefAndType< + React.AnchorHTMLAttributes + > | null; /** * className diff --git a/types/linkifyjs/linkifyjs-tests.ts b/types/linkifyjs/linkifyjs-tests.ts deleted file mode 100644 index 5688f9f99f..0000000000 --- a/types/linkifyjs/linkifyjs-tests.ts +++ /dev/null @@ -1,141 +0,0 @@ -import linkifyHtml from "linkifyjs/html"; - -// From the docs here: https://soapbox.github.io/linkifyjs/docs/options.html - -/* attributes */ - -linkifyHtml("github.com", { - attributes: { - rel: "nofollow" - } -}); - -/* className */ - -linkifyHtml("github.com", { - className: "new-link--url" -}); - -linkifyHtml("github.com", { - className(href, type) { - return "new-link--" + type; - } -}); - -linkifyHtml("github.com", { - className: { - url: "new-link--url", - email(href: string) { - return "new-link--email"; - } - } -}); - -/* events */ - -linkifyHtml("", { - events: { - click(e) { - alert("Link clicked!"); - }, - mouseover(e) { - alert("Link hovered!"); - } - } -}); - -/* defaultProtocol */ - -/* format */ - -linkifyHtml("", { - format(value, type) { - if (type === "url" && value.length > 50) { - value = value.slice(0, 50) + "…"; - } - return value; - } -}); - -linkifyHtml("", { - format: { - url(value) { - return value.length > 50 ? value.slice(0, 50) + "…" : value; - } - } -}); - -/* formatHref */ - -linkifyHtml("This site is #rad", { - formatHref(href, type) { - if (type === "hashtag") { - href = "https://twitter.com/hashtag/" + href.substring(1); - } - return href; - } -}); - -linkifyHtml("Hey @dhh, check out issue #23", { - formatHref: { - mention(href) { - return "https://github.com" + href; - }, - ticket(href) { - return ( - "https://github.com/SoapBox/linkifyjs/issues/" + - href.substring(1) - ); - } - } -}); - -/* ignoreTags */ - -linkifyHtml( - // tslint:disable-next-line:prefer-template - 'Please ignore \n' + - "but do b.ca", - { - ignoreTags: ["script", "style"] - } -); - -/* nl2br */ - -/* tagName */ - -linkifyHtml("github.com", { - tagName: "span" -}); - -linkifyHtml("#swag", { - tagName: { - hashtag: "span" - } -}); - -/* target */ - -linkifyHtml("github.com", { - target: "_parent" -}); - -linkifyHtml("test-email@example.com", { - target: { - url: "_parent", - email: null - } -}); - -/* validate */ - -// Don't linkify links that don't begin in a protocol -// e.g., "http://google.com" will be linkified, but "google.com" will not. -linkifyHtml("www.google.com", { - validate: { - url(value) { - return /^(http|ftp)s?:\/\//.test(value); - } - } -}); diff --git a/types/linkifyjs/linkifyjs-tests.tsx b/types/linkifyjs/linkifyjs-tests.tsx new file mode 100644 index 0000000000..02d9d3b6d5 --- /dev/null +++ b/types/linkifyjs/linkifyjs-tests.tsx @@ -0,0 +1,227 @@ +import * as React from "react"; +import linkifyHtml from "linkifyjs/html"; +import Linkify from "linkifyjs/react"; + +declare function describe(desc: string, f: () => void): void; + +describe("linkifyjs/html", () => { + /** + * The following tests were taken directly from the documentation: + * https://soapbox.github.io/linkifyjs/docs/options.html + */ + + /* attributes */ + + linkifyHtml("github.com", { + attributes: { + rel: "nofollow" + } + }); + + /* className */ + + linkifyHtml("github.com", { + className: "new-link--url" + }); + + linkifyHtml("github.com", { + className(href, type) { + return "new-link--" + type; + } + }); + + linkifyHtml("github.com", { + className: { + url: "new-link--url", + email(href: string) { + return "new-link--email"; + } + } + }); + + /* events */ + + linkifyHtml("", { + events: { + click(e) { + alert("Link clicked!"); + }, + mouseover(e) { + alert("Link hovered!"); + } + } + }); + + /* defaultProtocol */ + + /* format */ + + linkifyHtml("", { + format(value, type) { + if (type === "url" && value.length > 50) { + value = value.slice(0, 50) + "…"; + } + return value; + } + }); + + linkifyHtml("", { + format: { + url(value) { + return value.length > 50 ? value.slice(0, 50) + "…" : value; + } + } + }); + + /* formatHref */ + + linkifyHtml("This site is #rad", { + formatHref(href, type) { + if (type === "hashtag") { + href = "https://twitter.com/hashtag/" + href.substring(1); + } + return href; + } + }); + + linkifyHtml("Hey @dhh, check out issue #23", { + formatHref: { + mention(href) { + return "https://github.com" + href; + }, + ticket(href) { + return ( + "https://github.com/SoapBox/linkifyjs/issues/" + + href.substring(1) + ); + } + } + }); + + /* ignoreTags */ + + linkifyHtml( + // tslint:disable-next-line:prefer-template + 'Please ignore \n' + + "but do b.ca", + { + ignoreTags: ["script", "style"] + } + ); + + /* nl2br */ + + /* tagName */ + + linkifyHtml("github.com", { + tagName: "span" + }); + + linkifyHtml("#swag", { + tagName: { + hashtag: "span" + } + }); + + /* target */ + + linkifyHtml("github.com", { + target: "_parent" + }); + + linkifyHtml("test-email@example.com", { + target: { + url: "_parent", + email: null + } + }); + + /* validate */ + + // Don't linkify links that don't begin in a protocol + // e.g., "http://google.com" will be linkified, but "google.com" will not. + linkifyHtml("www.google.com", { + validate: { + url(value) { + return /^(http|ftp)s?:\/\//.test(value); + } + } + }); +}); + +describe("linkifyjs/react", () => { + /** + * The following tests were taken directly from the documentation: + * https://soapbox.github.io/linkifyjs/docs/linkify-react.html + */ + + /* Usage */ + + { + // render() + const options = { + /* … */ + }; + const content = + "For help with GitHub.com, please email support@github.com"; + + {content} + ; + } + + /* Events */ + + { + const content = + "For help with GitHub.com, please email support@github.com"; + const linkProps = { + onClick: (event: any) => { + if (!confirm("Are you sure you want to leave this page?")) { + event.preventDefault(); + } + } + }; + {content}; + } + + /** + * The following tests were made specifically for DefinitelyTyped. + */ + + /* Default values for all props */ + { + const content = + "For help with GitHub.com, please email support@github.com"; + + {content} + ; + } + + /* Custom class name */ + + { + const content = + "For help with GitHub.com, please email support@github.com"; + + {content} + ; + } + + /* Custom tag name */ + + { + const content = + "For help with GitHub.com, please email support@github.com"; + + {content} + ; + } +}); diff --git a/types/linkifyjs/react.d.ts b/types/linkifyjs/react.d.ts new file mode 100644 index 0000000000..0631b6c460 --- /dev/null +++ b/types/linkifyjs/react.d.ts @@ -0,0 +1,11 @@ +import * as React from "react"; +import { LinkifyOptions } from "./index"; + +export interface LinkifyProps { + options?: LinkifyOptions; + tagName?: string; +} + +declare class Linkify extends React.Component {} + +export default Linkify; diff --git a/types/linkifyjs/tsconfig.json b/types/linkifyjs/tsconfig.json index 52b1940fcd..16becbcf0a 100644 --- a/types/linkifyjs/tsconfig.json +++ b/types/linkifyjs/tsconfig.json @@ -1,25 +1,17 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6", - "dom" - ], + "lib": ["es6", "dom"], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" }, - "files": [ - "index.d.ts", - "html.d.ts", - "linkifyjs-tests.ts" - ] + "files": ["index.d.ts", "html.d.ts", "react.d.ts", "linkifyjs-tests.tsx"] } diff --git a/types/loadable__component/index.d.ts b/types/loadable__component/index.d.ts new file mode 100644 index 0000000000..c4877bd8a9 --- /dev/null +++ b/types/loadable__component/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for @loadable/component 5.2 +// Project: https://github.com/smooth-code/loadable-components +// Definitions by: Martynas Kadiša +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export interface DefaultImportedComponent

{ + default: React.ComponentType

; +} + +export type DefaultComponent

= React.ComponentType

| DefaultImportedComponent

; + +export interface Options { + fallback?: JSX.Element; +} + +export type LoadableComponent = React.ComponentType; +export type LoadableLibrary = React.ComponentType<{ + fallback?: JSX.Element; + children?: (module: TModule) => React.ReactNode; + ref?: React.Ref; +}> & + TModule; + +declare function lib( + loadFn: (props: object) => Promise, + options?: Options +): LoadableLibrary; + +declare function loadableFunc( + loadFn: (props: T) => Promise>, + options?: Options +): LoadableComponent; + +declare const loadable: typeof loadableFunc & { lib: typeof lib }; + +export default loadable; + +export namespace lazy { + function lib(loadFn: (props: object) => Promise): LoadableLibrary; +} + +export function lazy(loadFn: (props: T) => Promise>): LoadableComponent; + +export function loadableReady(done?: () => any): Promise; diff --git a/types/loadable__component/loadable__component-tests.tsx b/types/loadable__component/loadable__component-tests.tsx new file mode 100644 index 0000000000..d286711be1 --- /dev/null +++ b/types/loadable__component/loadable__component-tests.tsx @@ -0,0 +1,117 @@ +import * as React from 'react'; +import loadable, { lazy, loadableReady } from '@loadable/component'; + +const TestComponent: React.SFC<{ foo: string }> = () => <>test; + +function defaultImportComponentLoader() { + return new Promise<{ default: typeof TestComponent }>(resolve => resolve({ default: TestComponent })); +} + +function importComponentLoader() { + return new Promise(resolve => resolve(TestComponent)); +} + +const lib = { + getTestObj: () => ({ bar: 'bar', foo: 'foo' }) +}; + +function defaultImportLibLoader() { + return new Promise<{ default: typeof lib }>(resolve => resolve(({ default: lib }))); +} + +function importLibLoader() { + return new Promise(resolve => resolve(lib)); +} + +// loadable +{ + // Should infer props from imported component with default export + const LoadableDefaultComponent = loadable(defaultImportComponentLoader); + ; + + // Should infer props from imported component without default export + const LoadableComponent = loadable(importComponentLoader); + ; + + // Should allow passing JSX element to fallback in options + loadable(defaultImportComponentLoader, { fallback:

loading...
}); + + // Should allow passing `fallback` prop to loadable component + loading...} />; +} + +// lazy +{ + // Should infer props from imported component with default export + const LazyDefaultComponent = lazy(defaultImportComponentLoader); + ; + + // Should infer props from imported component without default export + const LazyComponent = lazy(importComponentLoader); + ; + + // Should allow passing fallback prop + loading...} />; +} + +// loadable.lib +{ + // Should infer types from module with default export and reflect them in children render prop + const LoadableDefaultLibrary = loadable.lib(defaultImportLibLoader); + + {({ default: { getTestObj } }) => getTestObj().foo} + ; + + // Should infer types from module without default export and reflect them in children render prop + const LoadableLibrary = loadable.lib(importLibLoader); + + {({ getTestObj }) => getTestObj().foo} + ; + + // Should allow passing fallback JSX element + loadable.lib(importLibLoader, { fallback:
loading lib...
}); + + // Should allow passing fallback prop + Loading library...}> + {({ getTestObj }) => getTestObj().foo} + ; + + // Should reflect inferred types from module in ref + const ref = React.createRef(); + ; + ref.current!.getTestObj().foo; +} + +// lazy.lib +{ + // Should infer types from module with default export and reflect them in children render prop + const LazyDefaultLibrary = lazy.lib(defaultImportLibLoader); + + {({ default: { getTestObj } }) => getTestObj().foo} + ; + + // Should infer types from module without default export and reflect them in children render prop + const LazyLibrary = lazy.lib(importLibLoader); + + {({ getTestObj }) => getTestObj().foo} + ; + + // Should allow passing fallback prop + Loading library...}> + {({ getTestObj }) => getTestObj().foo} + ; + + // Should reflect inferred types from module in ref + const ref = React.createRef(); + ; + ref.current!.getTestObj().foo; +} + +// loadableReady +{ + // Should allow passing callback argument + loadableReady(() => {}); + + // Should return a promise + loadableReady().then(() => {}); +} diff --git a/types/loadable__component/tsconfig.json b/types/loadable__component/tsconfig.json new file mode 100644 index 0000000000..440535e42b --- /dev/null +++ b/types/loadable__component/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@loadable/component": [ + "loadable__component" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "loadable__component-tests.tsx" + ] +} diff --git a/types/loadable__component/tslint.json b/types/loadable__component/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/loadable__component/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/loadable__server/index.d.ts b/types/loadable__server/index.d.ts new file mode 100644 index 0000000000..eafbd7eec7 --- /dev/null +++ b/types/loadable__server/index.d.ts @@ -0,0 +1,86 @@ +// Type definitions for @loadable/server 5.2 +// Project: https://github.com/smooth-code/loadable-components +// Definitions by: Martynas Kadiša +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { ComponentType, ReactElement, Component } from 'react'; + +export type ChunkExtractorOptions = { + /** + * Webpack entrypoints to load (default to `["main"]`) + */ + entrypoints?: string | string[]; + /** + * Optional output path (only for `requireEntrypoint`) + */ + outputPath?: string; +} & ({ + /** + * Stats file path generated using `@loadable/webpack-plugin` + */ + statsFile: string; + } | { + /** + * Stats generated using `@loadable/webpack-plugin`. + */ + stats: object; + }); + +/** + * Used to collect chunks server-side and get them as script tags or script elements + */ +export class ChunkExtractor { + constructor(options: ChunkExtractorOptions); + + /** + * Wrap your application in a `ChunkExtractorManager` + */ + collectChunks( + /** + * JSX element that will be wrapped in `ChunkExtractorManager` + */ + element: JSX.Element + ): JSX.Element; + + /** + * Require the entrypoint of your application as a commonjs module. + */ + requireEntrypoint(name?: string): { default: ComponentType }; + + /** + * Get scripts as a string of `