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 625baba356..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", 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/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/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/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 4cfbddc2a2..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): { @@ -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 2ee7da83d5..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) { @@ -198,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/hibp/tsconfig.json b/types/is-valid-path/tsconfig.json similarity index 93% rename from types/hibp/tsconfig.json rename to types/is-valid-path/tsconfig.json index 58ecb92a11..da95d11317 100644 --- a/types/hibp/tsconfig.json +++ b/types/is-valid-path/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "hibp-tests.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/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/koa-router/index.d.ts b/types/koa-router/index.d.ts index 81b0f697e6..b2163d09d1 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -43,7 +43,7 @@ declare namespace Router { strict?: boolean; } - export interface IRouterContext { + export interface IRouterContext extends Koa.Context { /** * url params */ diff --git a/types/koa-router/koa-router-tests.ts b/types/koa-router/koa-router-tests.ts index 51e95fb8a5..50e66509ea 100644 --- a/types/koa-router/koa-router-tests.ts +++ b/types/koa-router/koa-router-tests.ts @@ -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/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 `