diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index ab933d6019..43267255d1 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3663,7 +3663,7 @@ /types/onionoo/ @BendingBender /types/onoff/ @marcel-ernst @Kallu609 /types/ontime/ @Hirse -/types/open/ @Bartvds +/types/open/ @shinnn @SomaticIT @tlent @ffflorian /types/open-editor/ @BendingBender /types/open-graph/ @ffflorian /types/openapi-factory/ @runebaas @@ -3681,7 +3681,6 @@ /types/openstack-wrapper/ @sanjaymadane /types/opentok/ @westy92 @CatGuardian @pronebird /types/opentype.js/ @danmarshall @edzis -/types/opn/ @shinnn @SomaticIT @tlent /types/opossum/ @quinnlangille @merufm @lance @mastermatt /types/optics-agent/ @crevil /types/optimist/ @soywiz @chbrown diff --git a/README.es.md b/README.es.md index df675cbe41..4ba1be28fc 100644 --- a/README.es.md +++ b/README.es.md @@ -332,5 +332,3 @@ Es más apropiado importar este módulo utilizando la sintaxis `import foo = req Este proyecto es licenciado bajo la licencia MIT. Los derechos de autor de cada archivo de definición son respectivos de cada contribuidor listado al comienzo de cada archivo de definición. - -[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) diff --git a/README.ko.md b/README.ko.md index 224967a9dc..4314ccdc71 100644 --- a/README.ko.md +++ b/README.ko.md @@ -334,5 +334,3 @@ NPM 패키지의 경우, `node -p 'require("foo")'` 가 원하는 값이라면 ` 이 프로젝트는 MIT license 가 적용되어 있습니다. 각 자료형 정의(Type definition) 파일들의 저작권은 각 기여자들에게 있으며, 기여자들은 해당 자료형 정의(Type definition) 파일들의 맨 위에 나열되어 있습니다. - -[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) diff --git a/README.md b/README.md index b50272dbf4..7faea9035b 100644 --- a/README.md +++ b/README.md @@ -452,5 +452,3 @@ GitHub doesn't [support](http://stackoverflow.com/questions/5646174/how-to-make- This project is licensed under the MIT license. Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file. - -[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) diff --git a/README.ru.md b/README.ru.md index 9186c2ddd5..fc2eb49c47 100644 --- a/README.ru.md +++ b/README.ru.md @@ -346,8 +346,6 @@ GitHub не [поддерживает](http://stackoverflow.com/questions/564617 Авторские права на файлы определений принадлежат каждому участнику, указанному в начале каждого файла определения. -[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) - [![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) В среднем пакеты публикуются на npm менее чем за 10000 секунд? [![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Был ли typescript-bot активным на DefinitelyTyped в последние два часа? diff --git a/notNeededPackages.json b/notNeededPackages.json index 33ac19b762..3286978309 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -1416,6 +1416,12 @@ "sourceRepoURL": "http://onsen.io", "asOfVersion": "2.0.0" }, + { + "libraryName": "opn", + "typingsPackageName": "opn", + "sourceRepoURL": "https://github.com/sindresorhus/opn", + "asOfVersion": "5.5.0" + }, { "libraryName": "ora", "typingsPackageName": "ora", @@ -2130,6 +2136,12 @@ "sourceRepoURL": "https://servicestack.net/", "asOfVersion": "0.1.5" }, + { + "libraryName": "@storybook/addon-notes", + "typingsPackageName": "storybook__addon-notes", + "sourceRepoURL": "https://github.com/storybooks/storybook", + "asOfVersion": "5.0.0" + }, { "libraryName": "striptags", "typingsPackageName": "striptags", diff --git a/types/activestorage/index.d.ts b/types/activestorage/index.d.ts index e8214d2d8e..544c9bca60 100644 --- a/types/activestorage/index.d.ts +++ b/types/activestorage/index.d.ts @@ -13,7 +13,7 @@ export class DirectUpload { file: File; url: string; - constructor(file: File, url: string, delegate: DirectUploadDelegate) + constructor(file: File, url: string, delegate?: DirectUploadDelegate) create(callback: (error: Error, blob: Blob) => void): void; } diff --git a/types/airbnb-prop-types/airbnb-prop-types-tests.ts b/types/airbnb-prop-types/airbnb-prop-types-tests.ts index 7b79086848..9272fe6ddc 100644 --- a/types/airbnb-prop-types/airbnb-prop-types-tests.ts +++ b/types/airbnb-prop-types/airbnb-prop-types-tests.ts @@ -104,12 +104,13 @@ AirbnbPropTypes.forbidExtraProps({ // $ExpectType Requireable AirbnbPropTypes.integer(); -// $ExpectType Requireable<{}> -AirbnbPropTypes.keysOf(PropTypes.number); -// $ExpectType Requireable<{}> -AirbnbPropTypes.keysOf(PropTypes.number, 'foo'); -// $ExpectType Requireable<{}> -AirbnbPropTypes.keysOf(PropTypes.oneOf(['foo', 'bar'])); +const top = ((x?: T): T => x!)(); +type Top = typeof top; +declare function validateRequireableTop(x: React.Requireable): void; + +validateRequireableTop(AirbnbPropTypes.keysOf(PropTypes.number)); +validateRequireableTop(AirbnbPropTypes.keysOf(PropTypes.number, 'foo')); +validateRequireableTop(AirbnbPropTypes.keysOf(PropTypes.oneOf(['foo', 'bar']))); // $ExpectType Requireable AirbnbPropTypes.mutuallyExclusiveProps(PropTypes.number); @@ -137,8 +138,8 @@ AirbnbPropTypes.nonNegativeNumber(); // $ExpectType Requireable AirbnbPropTypes.numericString(); -// $ExpectType Requireable<{}> -AirbnbPropTypes.object(); +// $ExpectType Requireable +const props: PropTypes.Requireable = AirbnbPropTypes.object(); // $ExpectType Requireable<{ foo: string; }> AirbnbPropTypes.object<{ foo: string }>(); @@ -156,23 +157,17 @@ AirbnbPropTypes.requiredBy('foo', PropTypes.string); // $ExpectType Validator AirbnbPropTypes.requiredBy('bar', PropTypes.number, 42).isRequired; -// $ExpectType Requireable<{}> -AirbnbPropTypes.restrictedProp(); -// $ExpectType Requireable<{}> -AirbnbPropTypes.restrictedProp(() => 'Error'); -// $ExpectType Requireable<{}> -AirbnbPropTypes.restrictedProp(() => new Error('Error')); +validateRequireableTop(AirbnbPropTypes.restrictedProp()); +validateRequireableTop(AirbnbPropTypes.restrictedProp(() => 'Error')); +validateRequireableTop(AirbnbPropTypes.restrictedProp(() => new Error('Error'))); -// $ExpectType Requireable<{}> -AirbnbPropTypes.sequenceOf({ validator: PropTypes.number }); -// $ExpectType Requireable<{}> -AirbnbPropTypes.sequenceOf({ validator: PropTypes.number }, { validator: PropTypes.string }); -// $ExpectType Requireable<{}> -AirbnbPropTypes.sequenceOf( +validateRequireableTop(AirbnbPropTypes.sequenceOf({ validator: PropTypes.number })); +validateRequireableTop(AirbnbPropTypes.sequenceOf({ validator: PropTypes.number }, { validator: PropTypes.string })); +validateRequireableTop(AirbnbPropTypes.sequenceOf( { validator: PropTypes.number, min: 0, max: 10 }, { validator: PropTypes.string }, { validator: PropTypes.bool }, -); +)); interface ShapeShape { foo: string; diff --git a/types/arcgis-js-api/v3/index.d.ts b/types/arcgis-js-api/v3/index.d.ts index e38c5c0356..e595cdb9cc 100644 --- a/types/arcgis-js-api/v3/index.d.ts +++ b/types/arcgis-js-api/v3/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ArcGIS API for JavaScript 3.27 +// Type definitions for ArcGIS API for JavaScript 3.28 // Project: https://developers.arcgis.com/javascript/3/ // Definitions by: Esri // Bjorn Svensson @@ -3477,19 +3477,19 @@ declare module "esri/basemaps" { var basemaps: { /** The Light Gray Canvas basemap is designed to be used as a neutral background map for overlaying and emphasizing other map layers. */ gray: any; - /** The World Imagery map is a detailed imagery map layer and labels that is designed to be used as a basemap for various maps and applications. */ + /** The World Imagery with Labels map is a detailed imagery map layer and labels that is designed to be used as a basemap for various maps and applications: https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer */ hybrid: any; /** The Ocean Basemap is designed to be used as a basemap by marine GIS professionals and as a reference map by anyone interested in ocean data. */ oceans: any; /** The OpenStreetMap is a community map layer that is designed to be used as a basemap for various maps and applications. */ osm: any; - /** The World Imagery map is a detailed imagery map layer that is designed to be used as a basemap for various maps and applications. */ + /** The World Imagery map is a detailed imagery map layer that is designed to be used as a basemap for various maps and applications: https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer. */ satellite: any; - /** The Streets basemap presents a multiscale street map for the world. */ + /** The Streets basemap presents a multiscale street map for the world: https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer. */ streets: any; /** The Terrain with Labels basemap is designed to be used to overlay and emphasize other thematic map layers. */ terrain: any; - /** The Topographic map includes boundaries, cities, water features, physiographic features, parks, landmarks, transportation, and buildings. */ + /** The Topographic map includes boundaries, cities, water features, physiographic features, parks, landmarks, transportation, and buildings: https://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer */ topo: any; }; export = basemaps; @@ -9228,8 +9228,9 @@ declare module "esri/lang" { * @param data The data object used in the substitution. * @param template The template used for the substitution. * @param first When true, returns only the first property found in the data object. + * @param format The format object used in the substitution. */ - substitute(data: any, template?: string, first?: boolean): string; + substitute(data: any, template?: string, first?: boolean, format?: any): string; /** * Iterates through the argument array and searches for the identifier to which the argument value matches. * @param array The argument array for testing. @@ -10000,6 +10001,8 @@ declare module "esri/layers/FeatureLayer" { displayField: string; /** Indicates the field names for the editor fields. */ editFieldsInfo: any; + /** Applicable to ArcGIS Online hosted feature services. */ + editingInfo: any; /** The array of fields in the layer. */ fields: Field[]; /** The full extent of the layer. */ @@ -10054,6 +10057,8 @@ declare module "esri/layers/FeatureLayer" { supportsAttachmentsByUploadId: boolean; /** When true, the layer supports the Calculate REST operation when updating features. */ supportsCalculate: boolean; + /** If true, the layer supports a user-defined field description. */ + supportsFieldDescription: boolean; /** When true, the layer supports statistical functions in query operations. */ supportsStatistics: boolean; /** When true, the layer is suspended. */ @@ -10468,6 +10473,8 @@ declare module "esri/layers/Field" { class Field { /** The alias name for the field. */ alias: string; + /** A string that describes the default value set for a field. */ + defaultValue: string; /** Domain associated with the field. */ domain: Domain; /** Indicates whether the field is editable. */ diff --git a/types/better-sqlite3/better-sqlite3-tests.ts b/types/better-sqlite3/better-sqlite3-tests.ts index f5a6c0e070..ac72affc05 100644 --- a/types/better-sqlite3/better-sqlite3-tests.ts +++ b/types/better-sqlite3/better-sqlite3-tests.ts @@ -11,7 +11,7 @@ const registrationOptions: Sqlite.RegistrationOptions = { }; let db: Sqlite.Database = Sqlite('.'); -db = new Sqlite('.', { memory: true }); +db = new Sqlite('.', { memory: true, verbose: () => {} }); db.exec('CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL);'); db.exec('INSERT INTO test(name) VALUES("name");'); db.pragma('data_version', { simple: true }); diff --git a/types/better-sqlite3/index.d.ts b/types/better-sqlite3/index.d.ts index 32a71d96af..57a17e897f 100644 --- a/types/better-sqlite3/index.d.ts +++ b/types/better-sqlite3/index.d.ts @@ -5,6 +5,7 @@ // Santiago Aguilar // Alessandro Vergani // Andrew Kaiser +// Mark Stewart // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 @@ -97,6 +98,7 @@ declare namespace Database { readonly?: boolean; fileMustExist?: boolean; timeout?: number; + verbose?: (message?: any, ...additionalArgs: any[]) => void; } interface PragmaOptions { diff --git a/types/btoa/btoa-tests.ts b/types/btoa/btoa-tests.ts index 7ce230fcf7..d159bd5b7e 100644 --- a/types/btoa/btoa-tests.ts +++ b/types/btoa/btoa-tests.ts @@ -1,3 +1,5 @@ import btoa = require('btoa'); btoa('foo'); + +btoa(Buffer.from('foo')); diff --git a/types/btoa/index.d.ts b/types/btoa/index.d.ts index 4f16b77328..b4c06cf328 100644 --- a/types/btoa/index.d.ts +++ b/types/btoa/index.d.ts @@ -5,6 +5,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -declare function btoa(str: string): string; +/// + +declare function btoa(str: string | Buffer): string; export = btoa; diff --git a/types/changelog-parser/changelog-parser-tests.ts b/types/changelog-parser/changelog-parser-tests.ts index 1195d8077f..69a5ffdab3 100644 --- a/types/changelog-parser/changelog-parser-tests.ts +++ b/types/changelog-parser/changelog-parser-tests.ts @@ -5,12 +5,20 @@ const options = { removeMarkdown: false }; -parseChangelog({filePath: 'path/to/CHANGELOG.md'}, (result, error) => {}); +const fn = (obj: object): void => {}; -parseChangelog(options, (result, error) => {}); +parseChangelog({filePath: 'path/to/CHANGELOG.md'}, (error, result) => { + if (error) { + throw error; + } -parseChangelog({filePath: 'path/to/CHANGELOG.md'}, (result) => {}); + fn(result); +}); -parseChangelog(options); +parseChangelog(options, (error, result) => {}); -parseChangelog('path/to/CHANGELOG.md'); +parseChangelog({filePath: 'path/to/CHANGELOG.md'}, (error) => {}); + +parseChangelog(options).then((result) => {}); + +parseChangelog('path/to/CHANGELOG.md').then((result) => {}); diff --git a/types/changelog-parser/index.d.ts b/types/changelog-parser/index.d.ts index 7c03ff3ecd..a1799454c8 100644 --- a/types/changelog-parser/index.d.ts +++ b/types/changelog-parser/index.d.ts @@ -19,6 +19,7 @@ interface Options { /** * Change log parser for node. */ -declare function parseChangelog(options: Partial|string, callback?: (result: object, error: string|null) => void): Promise; +declare function parseChangelog(options: Partial|string, + callback?: (error: string|null, result: object) => void): Promise; export = parseChangelog; diff --git a/types/countries-and-timezones/index.d.ts b/types/countries-and-timezones/index.d.ts index 1012133d8e..3a84ea3b76 100644 --- a/types/countries-and-timezones/index.d.ts +++ b/types/countries-and-timezones/index.d.ts @@ -16,9 +16,9 @@ export interface Timezone { countries: string[]; } -export function getAllCountries(): Country[]; +export function getAllCountries(): {[key: string]: Country}; -export function getAllTimezones(): Timezone[]; +export function getAllTimezones(): {[key: string]: Timezone}; export function getCountriesForTimezone(timezoneId: string): Country[]; diff --git a/types/debug/debug-tests.ts b/types/debug/debug-tests.ts index 92d6f5eb8e..42c3399aff 100644 --- a/types/debug/debug-tests.ts +++ b/types/debug/debug-tests.ts @@ -29,3 +29,7 @@ extendedLog("Testing this is also an IDebugger."); const extendedWithCustomDelimiter: debug1.Debugger = log.extend('with-delim', '.'); extendedWithCustomDelimiter("Testing this is an IDebugger, too."); + +debug2.log = console.log.bind(console); +const anotherLogger = debug2("DefinitelyTyped:error"); +anotherLogger("This should be printed to stdout"); diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index 715e7c145e..f4f5866af8 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -5,9 +5,10 @@ // John McLaughlin // Brasten Sager // Nicolas Penin +// Kristian Brünn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var debug: debug.Debug & {debug: debug.Debug, default: debug.Debug}; +declare var debug: debug.Debug & { debug: debug.Debug; default: debug.Debug }; export = debug; export as namespace debug; @@ -19,6 +20,7 @@ declare namespace debug { disable: () => string; enable: (namespaces: string) => void; enabled: (namespaces: string) => boolean; + log: (...args: any[]) => any; names: RegExp[]; skips: RegExp[]; diff --git a/types/dotenv/dotenv-tests.ts b/types/dotenv/dotenv-tests.ts index 2776e6d202..9e57d1546f 100644 --- a/types/dotenv/dotenv-tests.ts +++ b/types/dotenv/dotenv-tests.ts @@ -3,7 +3,7 @@ import dotenv = require("dotenv"); const env = dotenv.config(); const dbUrl: string | null = env.error || !env.parsed ? null : env.parsed["BASIC"]; -dotenv.load({ +dotenv.config({ path: ".env-example", encoding: "utf8", debug: true diff --git a/types/dotenv/index.d.ts b/types/dotenv/index.d.ts index f8675ec22e..30b346b0bd 100644 --- a/types/dotenv/index.d.ts +++ b/types/dotenv/index.d.ts @@ -62,4 +62,5 @@ export interface DotenvConfigOutput { * */ export function config(options?: DotenvConfigOptions): DotenvConfigOutput; +/** @deprecated since v7.0.0 Use config instead. */ export const load: typeof config; diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 1a3eb0e39a..dd44093c52 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -10,6 +10,7 @@ // Ulf Schwekendiek // Pablo Varela // Claudio Procida +// Kevin Hawkinson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -211,6 +212,8 @@ declare namespace Draft { static isOptionKeyCommand(e: SyntheticKeyboardEvent): boolean; static hasCommandModifier(e: SyntheticKeyboardEvent): boolean; + + static isSoftNewlineEvent(e: SyntheticKeyboardEvent): boolean; } /** diff --git a/types/dwt/Dynamsoft.d.ts b/types/dwt/Dynamsoft.d.ts index 65569f61b3..38ddc3ef49 100644 --- a/types/dwt/Dynamsoft.d.ts +++ b/types/dwt/Dynamsoft.d.ts @@ -27,6 +27,7 @@ interface dwtEnv { DynamicContainers: string[]; DynamicDWTMap: {}; GetWebTwain(cid: string): WebTwain; + IfInstallDWTModuleWithZIP: boolean; IfUpdateService: boolean; IfUseActiveXForIE10Plus: boolean; JSVersion: string; diff --git a/types/dwt/index.d.ts b/types/dwt/index.d.ts index 04f600367d..3650529393 100644 --- a/types/dwt/index.d.ts +++ b/types/dwt/index.d.ts @@ -4,6 +4,7 @@ // Josh Hall // Lincoln Hu // Tom Kent +// Dave Sueltenfuss // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 diff --git a/types/elliptic/index.d.ts b/types/elliptic/index.d.ts index 7b1e885d6f..a6775225eb 100644 --- a/types/elliptic/index.d.ts +++ b/types/elliptic/index.d.ts @@ -4,7 +4,7 @@ // Gaylor Bosson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import BN = require('bn.js'); +import BN = require("bn.js"); // incomplete typings export const utils: any; @@ -29,10 +29,10 @@ export namespace curve { g: base.BasePoint; redN: BN; - constructor(type: string, conf: base.BaseCurveOptions) + constructor(type: string, conf: base.BaseCurveOptions); validate(point: base.BasePoint): boolean; - decodePoint(bytes: Buffer | string, enc?: 'hex'): base.BasePoint; + decodePoint(bytes: Buffer | string, enc?: "hex"): base.BasePoint; } namespace base { @@ -83,7 +83,12 @@ export namespace curve { constructor(conf: edwards.EdwardsConf); - point(x: BNInput, y: BNInput, z?: BNInput, t?: BNInput): edwards.EdwardsPoint; + point( + x: BNInput, + y: BNInput, + z?: BNInput, + t?: BNInput + ): edwards.EdwardsPoint; pointFromX(x: BNInput, odd?: boolean): edwards.EdwardsPoint; pointFromY(y: BNInput, odd?: boolean): edwards.EdwardsPoint; pointFromJSON(obj: BNInput[]): edwards.EdwardsPoint; @@ -144,7 +149,7 @@ export namespace curves { n: BN | undefined | null; hash: any; // ? - constructor(options: PresetCurve.Options) + constructor(options: PresetCurve.Options); } namespace PresetCurve { @@ -172,17 +177,47 @@ export class ec { g: any; hash: any; - constructor(options: string | curves.PresetCurve) + constructor(options: string | curves.PresetCurve); keyPair(options: ec.KeyPairOptions): ec.KeyPair; - keyFromPrivate(priv: Buffer | string | ec.KeyPair, enc?: string): ec.KeyPair; - keyFromPublic(pub: Buffer | string | {x: string, y: string} | ec.KeyPair, enc?: string): ec.KeyPair; + keyFromPrivate( + priv: Buffer | string | ec.KeyPair, + enc?: string + ): ec.KeyPair; + keyFromPublic( + pub: Buffer | string | { x: string; y: string } | ec.KeyPair, + enc?: string + ): ec.KeyPair; genKeyPair(options?: ec.GenKeyPairOptions): ec.KeyPair; - sign(msg: BNInput, key: Buffer | ec.KeyPair, enc: string, options?: ec.SignOptions): ec.Signature; - sign(msg: BNInput, key: Buffer | ec.KeyPair, options?: ec.SignOptions): ec.Signature; - verify(msg: BNInput, signature: ec.Signature | ec.SignatureOptions, key: Buffer | ec.KeyPair, enc?: string): boolean; - recoverPubKey(msg: BNInput, signature: ec.Signature | ec.SignatureOptions, j: number, enc?: string): any; - getKeyRecoveryParam(e: Error | undefined, signature: ec.Signature | ec.SignatureOptions, Q: BN, enc?: string): number; + sign( + msg: BNInput, + key: Buffer | ec.KeyPair, + enc: string, + options?: ec.SignOptions + ): ec.Signature; + sign( + msg: BNInput, + key: Buffer | ec.KeyPair, + options?: ec.SignOptions + ): ec.Signature; + verify( + msg: BNInput, + signature: ec.Signature | ec.SignatureOptions, + key: Buffer | ec.KeyPair, + enc?: string + ): boolean; + recoverPubKey( + msg: BNInput, + signature: ec.Signature | ec.SignatureOptions, + j: number, + enc?: string + ): any; + getKeyRecoveryParam( + e: Error | undefined, + signature: ec.Signature | ec.SignatureOptions, + Q: BN, + enc?: string + ): number; } export namespace ec { @@ -201,21 +236,32 @@ export namespace ec { } class KeyPair { - static fromPublic(ec: ec, pub: Buffer | string | {x: string, y: string} | KeyPair, enc?: string): KeyPair; - static fromPrivate(ec: ec, priv: Buffer | string | KeyPair, enc?: string): KeyPair; + static fromPublic( + ec: ec, + pub: Buffer | string | { x: string; y: string } | KeyPair, + enc?: string + ): KeyPair; + static fromPrivate( + ec: ec, + priv: Buffer | string | KeyPair, + enc?: string + ): KeyPair; ec: ec; - constructor(ec: ec, options: KeyPairOptions) + constructor(ec: ec, options: KeyPairOptions); - validate(): { readonly result: boolean, readonly reason: string }; + validate(): { readonly result: boolean; readonly reason: string }; getPublic(compact: boolean, enc?: string): any; // ? getPublic(enc?: string): any; // ? - getPrivate(enc?: 'hex'): Buffer | BN | string; + getPrivate(enc?: "hex"): Buffer | BN | string; derive(pub: any): any; // ? sign(msg: BNInput, enc: string, options?: SignOptions): Signature; sign(msg: BNInput, options?: SignOptions): Signature; - verify(msg: BNInput, signature: Signature | SignatureOptions): boolean; + verify( + msg: BNInput, + signature: Signature | SignatureOptions | string + ): boolean; inspect(): string; } @@ -224,7 +270,7 @@ export namespace ec { s: BN; recoveryParam: number | null; - constructor(options: SignatureOptions | Signature, enc?: string) + constructor(options: SignatureOptions | Signature, enc?: string); toDER(enc?: string | null): any; // ? } @@ -246,10 +292,14 @@ export namespace ec { export class eddsa { curve: curve.edwards; - constructor(name: 'ed25519'); + constructor(name: "ed25519"); sign(message: eddsa.Bytes, secret: eddsa.Bytes): eddsa.Signature; - verify(message: eddsa.Bytes, sig: eddsa.Bytes | eddsa.Signature, pub: eddsa.Bytes | eddsa.Point | eddsa.KeyPair): boolean; + verify( + message: eddsa.Bytes, + sig: eddsa.Bytes | eddsa.Signature, + pub: eddsa.Bytes | eddsa.Point | eddsa.KeyPair + ): boolean; hashInt(): BN; keyFromPublic(pub: eddsa.Bytes): eddsa.KeyPair; keyFromSecret(secret: eddsa.Bytes): eddsa.KeyPair; @@ -281,9 +331,9 @@ export namespace eddsa { secret(): Buffer; sign(message: Bytes): Signature; verify(message: Bytes, sig: Signature | Bytes): boolean; - getSecret(enc: 'hex'): string; + getSecret(enc: "hex"): string; getSecret(): Buffer; - getPublic(enc: 'hex'): string; + getPublic(enc: "hex"): string; getPublic(): Buffer; } diff --git a/types/ember-data/index.d.ts b/types/ember-data/index.d.ts index f5ff0c5d57..a98082a60e 100644 --- a/types/ember-data/index.d.ts +++ b/types/ember-data/index.d.ts @@ -16,8 +16,14 @@ import ModelRegistry from 'ember-data/types/registries/model'; import SerializerRegistry from 'ember-data/types/registries/serializer'; import AdapterRegistry from 'ember-data/types/registries/adapter'; -type AttributesFor = keyof Model; // TODO: filter to attr properties only (TS 2.8) -type RelationshipsFor = keyof Model; // TODO: filter to hasMany/belongsTo properties only (TS 2.8) +/** + The keys from the actual Model class, removing all the keys which come from + the base class. + */ +type ModelKeys = Exclude; + +type AttributesFor = ModelKeys; // TODO: filter to attr properties only (TS 2.8) +type RelationshipsFor = ModelKeys; // TODO: filter to hasMany/belongsTo properties only (TS 2.8) export interface ChangedAttributes { [key: string]: [any, any] | undefined; @@ -49,9 +55,9 @@ export namespace DS { */ function errorsArrayToHash(errors: any[]): {}; - interface RelationshipOptions { + interface RelationshipOptions { async?: boolean; - inverse?: RelationshipsFor | null; + inverse?: RelationshipsFor | null; polymorphic?: boolean; } @@ -457,12 +463,12 @@ export namespace DS { * Create a JSON representation of the record, using the serialization * strategy of the store's adapter. */ - serialize(options?: { includeId?: boolean }): {}; + serialize(options?: { includeId?: boolean }): object; /** * Use [DS.JSONSerializer](DS.JSONSerializer.html) to * get the JSON representation of a record. */ - toJSON(options: {}): {}; + toJSON(options?: { includeId?: boolean }): object; /** * Fired when the record is ready to be interacted with, * that is either loaded from the server or created locally. @@ -502,15 +508,15 @@ export namespace DS { * method if you want to allow the user to still `rollbackAttributes()` * after a delete was made. */ - deleteRecord(): any; + deleteRecord(): void; /** * Same as `deleteRecord`, but saves the record immediately. */ - destroyRecord(options?: {}): RSVP.Promise; + destroyRecord(options?: { adapterOptions?: object }): RSVP.Promise; /** * Unloads the record from the store. This will cause the record to be destroyed and freed up for garbage collection. */ - unloadRecord(): any; + unloadRecord(): void; /** * Returns an object, whose keys are changed properties, and value is * an [oldProp, newProp] array. @@ -520,16 +526,16 @@ export namespace DS { * If the model `hasDirtyAttributes` this function will discard any unsaved * changes. If the model `isNew` it will be removed from the store. */ - rollbackAttributes(): any; + rollbackAttributes(): void; /** * Save the record and persist any changes to the record to an * external source via the adapter. */ - save(options?: {}): RSVP.Promise; + save(options?: { adapterOptions?: object }): RSVP.Promise; /** * Reload the record from the adapter. */ - reload(): RSVP.Promise; + reload(options?: { adapterOptions?: object }): RSVP.Promise; /** * Get the reference for the specified belongsTo relationship. */ @@ -547,7 +553,7 @@ export namespace DS { this: T, callback: (name: string, details: RelationshipMeta) => void, binding?: any - ): any; + ): void; /** * Represents the model's class name as a string. This can be used to look up the model's class name through * `DS.Store`'s modelFor method. @@ -605,14 +611,14 @@ export namespace DS { static eachRelationship( callback: (name: string, details: RelationshipMeta) => void, binding?: any - ): any; + ): void; /** * Given a callback, iterates over each of the types related to a model, * invoking the callback with the related type's class. Each type will be * returned just once, regardless of how many different relationships it has * with a model. */ - static eachRelatedType(callback: Function, binding: any): any; + static eachRelatedType(callback: (name: string) => void, binding?: any): void; /** * A map whose keys are the attributes of the model (properties * described by DS.attr) and whose values are the meta object for the @@ -630,26 +636,27 @@ export namespace DS { * Iterates through the attributes of the model, calling the passed function on each * attribute. */ - static eachAttribute(callback: Function, binding: {}): any; + static eachAttribute>( + this: Class, + callback: ( + name: ModelKeys, + meta: AttributeMeta + ) => void, + binding?: any + ): void; /** * Iterates through the transformedAttributes of the model, calling * the passed function on each attribute. Note the callback will not be * called for any attributes that do not have an transformation type. */ - static eachTransformedAttribute(callback: Function, binding: {}): any; - /** - * Discards any unsaved changes to the given attribute. This feature is not enabled by default. You must enable `ds-rollback-attribute` and be running a canary build. - */ - rollbackAttribute(): any; - /** - * This Ember.js hook allows an object to be notified when a property - * is defined. - */ - didDefineProperty( - proto: {}, - key: string, - value: Ember.ComputedProperty - ): any; + static eachTransformedAttribute( + this: Class, + callback: ( + name: ModelKeys>, + type: keyof TransformRegistry + ) => void, + binding?: any + ): void; } /** * ### State @@ -700,7 +707,7 @@ export namespace DS { * Used to get the latest version of all of the records in this array * from the adapter. */ - update(): any; + update(): PromiseArray; /** * Saves all of the records in the `RecordArray`. */ @@ -782,7 +789,7 @@ export namespace DS { /** * `ids()` returns an array of the record ids in this relationship. */ - ids(): any[]; + ids(): string[]; /** * The meta data for the has-many relationship. */ @@ -948,7 +955,7 @@ export namespace DS { /** * Get snapshots of the underlying record array */ - snapshots(): any[]; + snapshots(): Snapshot[]; } class Snapshot { /** @@ -994,14 +1001,19 @@ export namespace DS { belongsTo>( keyName: L, options?: {} - ): Snapshot['record'][L] | string | null | undefined; + ): Snapshot | null | undefined; + belongsTo>( + keyName: L, + options: { id: true } + ): string | null | undefined; + /** * Returns the current value of a hasMany relationship. */ hasMany>( keyName: L, options?: { ids: false } - ): Array['record'][L]> | undefined; + ): Snapshot[] | undefined; hasMany>( keyName: L, options: { ids: true } @@ -1011,21 +1023,21 @@ export namespace DS { * function on each attribute. */ eachAttribute( - callback: (key: keyof M, meta: AttributeMeta) => void, + callback: (key: ModelKeys, meta: AttributeMeta) => void, binding?: {} - ): any; + ): void; /** * Iterates through all the relationships of the model, calling the passed * function on each relationship. */ eachRelationship( - callback: (key: keyof M, meta: RelationshipMeta) => void, + callback: (key: ModelKeys, meta: RelationshipMeta) => void, binding?: {} - ): any; + ): void; /** * Serializes the snapshot using the serializer for the model. */ - serialize(options: {}): {}; + serialize(options: O): object; } /** @@ -1095,7 +1107,8 @@ export namespace DS { */ query( modelName: K, - query: any + query: object, + options?: { adapterOptions?: object } ): AdapterPopulatedRecordArray & PromiseArray; /** @@ -1105,7 +1118,8 @@ export namespace DS { */ queryRecord( modelName: K, - query: any + query: object, + options?: { adapterOptions?: object } ): RSVP.Promise; /** * `findAll` asks the adapter's `findAll` method to find the records for the diff --git a/types/ember-data/test/model.ts b/types/ember-data/test/model.ts index 2085daf90a..356c607748 100644 --- a/types/ember-data/test/model.ts +++ b/types/ember-data/test/model.ts @@ -1,6 +1,7 @@ import Ember from 'ember'; import DS, { ChangedAttributes } from 'ember-data'; import { assertType } from "./lib/assert"; +import RSVP from 'rsvp'; const Person = DS.Model.extend({ firstName: DS.attr(), @@ -33,5 +34,26 @@ user.serialize(); user.serialize({ includeId: true }); user.serialize({ includeId: true }); -const attributes = user.changedAttributes(); -assertType(attributes); +const attributes: ChangedAttributes = user.changedAttributes(); + +user.rollbackAttributes(); // $ExpectType void + +let destroyResult: RSVP.Promise; +destroyResult = user.destroyRecord(); +destroyResult = user.destroyRecord({}); +destroyResult = user.destroyRecord({ adapterOptions: {}}); +destroyResult = user.destroyRecord({ adapterOptions: { waffles: 'are yummy' }}); + +user.deleteRecord(); // $ExpectType void + +user.unloadRecord(); // $ExpectType void + +let jsonified: object; +jsonified = user.toJSON(); +jsonified = user.toJSON({ includeId: true }); + +let reloaded: RSVP.Promise; +reloaded = user.reload(); +reloaded = user.reload({}); +reloaded = user.reload({ adapterOptions: {} }); +reloaded = user.reload({ adapterOptions: { fastAsCanBe: 'yessirree' } }); diff --git a/types/ember-data/test/relationships.ts b/types/ember-data/test/relationships.ts index 13a526ba6a..04aae75f0e 100644 --- a/types/ember-data/test/relationships.ts +++ b/types/ember-data/test/relationships.ts @@ -1,5 +1,7 @@ import Ember from 'ember'; import DS from 'ember-data'; +import TransformRegistry from 'ember-data/types/registries/transform'; +import { assertType } from './lib/assert'; declare const store: DS.Store; @@ -8,24 +10,65 @@ const Person = DS.Model.extend({ parent: DS.belongsTo('folder', { inverse: 'children' }) }); +// $ExpectType void +Person.eachAttribute(() => {}); +// $ExpectType void +Person.eachAttribute(() => {}, {}); +// $ExpectType void +Person.eachAttribute((name, meta) => { + assertType<'children' | 'parent'>(name); + assertType<{ + type: keyof TransformRegistry; + options: object; + name: 'children' | 'parent'; + parentType: DS.Model; + isAttribute: true; + }>(meta); +}); + +// $ExpectType void +Person.eachTransformedAttribute(() => {}); +// $ExpectType void +Person.eachTransformedAttribute(() => {}, {}); +// $ExpectType void +Person.eachTransformedAttribute((name, type) => { + assertType<'children' | 'parent'>(name); + let t: keyof TransformRegistry = type; +}); + const Polymorphic = DS.Model.extend({ paymentMethods: DS.hasMany('payment-method', { polymorphic: true }) }); +// $ExpectType void Polymorphic.eachRelationship(() => ''); +// $ExpectType void Polymorphic.eachRelationship(() => '', {}); +// $ExpectType void Polymorphic.eachRelationship((n, meta) => { let s: string = n; let m: 'belongsTo' | 'hasMany' = meta.kind; }); let p = Polymorphic.create(); +// $ExpectType void p.eachRelationship(() => ''); +// $ExpectType void p.eachRelationship(() => '', {}); +// $ExpectType void p.eachRelationship((n, meta) => { let s: string = n; let m: 'belongsTo' | 'hasMany' = meta.kind; }); +// $ExpectType void +Polymorphic.eachRelatedType(() => ''); +// $ExpectType void +Polymorphic.eachRelatedType(() => '', {}); +// $ExpectType void +Polymorphic.eachRelatedType((name) => { + let s: string = name; +}); + export class Comment extends DS.Model { author = DS.attr('string'); } diff --git a/types/ember-data/test/serializer.ts b/types/ember-data/test/serializer.ts index d38ced647a..490dc77493 100644 --- a/types/ember-data/test/serializer.ts +++ b/types/ember-data/test/serializer.ts @@ -1,6 +1,10 @@ import Ember from 'ember'; import DS from 'ember-data'; +interface Dict { + [key: string]: T | null | undefined; +} + const JsonApi = DS.JSONAPISerializer.extend({}); const Customized = DS.JSONAPISerializer.extend({ @@ -74,14 +78,16 @@ const SerializerUsingSnapshots = DS.RESTSerializer.extend({ DS.Serializer.extend({ serialize(snapshot: DS.Snapshot<'message-for-serializer'>, options: {}) { - let json: any = { + let json: Dict = { id: snapshot.id }; + // $ExpectType void snapshot.eachAttribute((key, attribute) => { json[key] = snapshot.attr(key); }); + // $ExpectType void snapshot.eachRelationship((key, relationship) => { if (relationship.kind === 'belongsTo') { json[key] = snapshot.belongsTo(key, { id: true }); diff --git a/types/ember-data/test/store.ts b/types/ember-data/test/store.ts index b6bb25993c..f692a668d9 100644 --- a/types/ember-data/test/store.ts +++ b/types/ember-data/test/store.ts @@ -24,6 +24,7 @@ let post = store.createRecord('post', { }); post.save(); // => POST to '/posts' +post.save({ adapterOptions: { makeItSo: 'number one ' } }); post.save().then(saved => { assertType(saved); }); diff --git a/types/ember/test/ember-module-tests.ts b/types/ember/test/ember-module-tests.ts index 5935578d3e..b37882a6cc 100644 --- a/types/ember/test/ember-module-tests.ts +++ b/types/ember/test/ember-module-tests.ts @@ -2,8 +2,12 @@ import Ember from 'ember'; // $ Ember.$; // $ExpectType JQueryStatic + +const top = ((x?: T): T => x!)(); +type Top = typeof top; +declare function expectTypeNativeArrayTop(x: Ember.NativeArray): void; // A -Ember.A(); // $ExpectType NativeArray<{}> +expectTypeNativeArrayTop(Ember.A()); Ember.A([1, 2]); // $ExpectType NativeArray // addListener Ember.addListener({ a: 'foo' }, 'a', {}, () => {}); diff --git a/types/ember__routing/-private/route-info.d.ts b/types/ember__routing/-private/route-info.d.ts new file mode 100644 index 0000000000..6cc971bd9c --- /dev/null +++ b/types/ember__routing/-private/route-info.d.ts @@ -0,0 +1,49 @@ +// https://api.emberjs.com/ember/3.6/classes/RouteInfo +/** + * A `RouteInfo` is an object that contains metadata about a specific route within a `Transition`. + * It is read-only and internally immutable. + * It is also not observable, because a `Transition` instance is never changed after creation. + */ +export default interface RouteInfo { + /** + * A reference to the childe route's `RouteInfo`. + * This can be used to traverse downward to the leafmost `RouteInfo`. + */ + readonly child: RouteInfo | null; + /** + * The final segment of the fully-qualified name of the route, like "index". + */ + readonly localName: string; + /** + * The dot-separated, fully-qualified name of the route, like "people.index". + */ + readonly name: string; + /** + * The ordered list of the names of the params required for this route. + * It will contain the same strings as `Object.keys(params)`, but here the order is significant. + * This allows users to correctly pass params into routes programmatically. + */ + readonly paramNames: string[]; + /** + * The values of the route's parameters. + * These are the same params that are received as arguments to the route's `model` hook. + * Contains only the parameters valid for this route, if any (params for parent or child routes are not merged). + */ + readonly params: { [key: string]: string | undefined }; + /** + * A reference to the parent route's `RouteInfo`. + * This can be used to traverse upward to the topmost `RouteInfo`. + */ + readonly parent: RouteInfo | null; + /** + * The values of any query params on this route. + */ + readonly queryParams: { [key: string]: string | undefined }; + /** + * Allows you to traverse through the linked list of `RouteInfo`s from the topmost to leafmost. + * Returns the first `RouteInfo` in the linked list for which the callback returns true. + * + * @param callback the callback to execute. + */ + find(callback: (item: RouteInfo) => boolean): RouteInfo | undefined; +} diff --git a/types/ember__routing/-private/transition.d.ts b/types/ember__routing/-private/transition.d.ts index 53d06f80e8..027e913aca 100644 --- a/types/ember__routing/-private/transition.d.ts +++ b/types/ember__routing/-private/transition.d.ts @@ -1,4 +1,17 @@ +import RouteInfo from './route-info'; + export default interface Transition { + /** + * This property is a `RouteInfo` object that represents where transition originated from. + * It's important to note that a `RouteInfo` is a linked list and this property is simply the head node of the list. + * In the case of an initial render, `from` will be set to `null`. + */ + readonly from: RouteInfo | null; + /** + * This property is a `RouteInfo` object that represents where the router is transitioning to. + * It's important to note that a `RouteInfo` is a linked list and this property is simply the leafmost route. + */ + readonly to: RouteInfo; /** * Aborts the Transition. Note you can also implicitly abort a transition * by initiating another transition while a previous one is underway. diff --git a/types/ember__routing/router-service.d.ts b/types/ember__routing/router-service.d.ts index decc36af34..07349dc765 100644 --- a/types/ember__routing/router-service.d.ts +++ b/types/ember__routing/router-service.d.ts @@ -1,3 +1,4 @@ +import RouteInfo from '@ember/routing/-private/route-info'; import Transition from '@ember/routing/-private/transition'; import Service from '@ember/service'; @@ -10,6 +11,12 @@ type RouteModel = object | string | number; */ export default class RouterService extends Service { // + /** + * A `RouteInfo` that represents the current leaf route. + * It is guaranteed to change whenever a route transition happens + * (even when that transition only changes parameters and doesn't change the active route) + */ + readonly currentRoute: RouteInfo; /** * Name of the current route. * This property represent the logical name of the route, @@ -212,4 +219,23 @@ export default class RouterService extends Service { modelsD: RouteModel, options?: { queryParams: object } ): string; + + // https://api.emberjs.com/ember/3.6/classes/RouterService/events/routeDidChange?anchor=routeDidChange + /** + * Register a callback for an event. + * + * The `routeWillChange` event is fired at the beginning of any attempted transition with a `Transition` object as the sole argument. + * This action can be used for aborting, redirecting, or decorating the transition from the currently active routes. + * + * The `routeDidChange` event only fires once a transition has settled. + * This includes aborts and error substates. + * Like the `routeWillChange` event it recieves a `Transition` as the sole argument. + * + * @param name the name of the event + * @param callback the callback to execute + */ + on( + name: 'routeDidChange' | 'routeWillChange', + callback: (transition: Transition) => void + ): RouterService; } diff --git a/types/ember__routing/test/router.ts b/types/ember__routing/test/router.ts index be1c16d821..cbba58c65d 100755 --- a/types/ember__routing/test/router.ts +++ b/types/ember__routing/test/router.ts @@ -1,4 +1,3 @@ -import { assertType } from './lib/assert'; import Router from '@ember/routing/router'; import Service, { inject as service } from '@ember/service'; import EmberObject, { get } from '@ember/object'; @@ -52,5 +51,33 @@ const RouterServiceConsumer = Service.extend({ const model = EmberObject.create(); get(this, 'router') .transitionTo('index', model, { queryParams: { search: 'ember' }}); - } + }, + onAndRouteInfo() { + const router = get(this, 'router'); + router + .on('routeWillChange', transition => { + const to = transition.to; + to.child; // $ExpectType RouteInfo | null + to.localName; // $ExpectType string + to.name; // $ExpectType string + to.paramNames; // $ExpectType string[] + to.params.foo; // $ExpectType string | undefined + to.parent; // $ExpectType RouteInfo | null + to.queryParams.foo; // $ExpectType string | undefined + to.find(info => info.name === 'foo'); // $ExpectType RouteInfo | undefined + }) + .on('routeDidChange', transition => { + const from = transition.from; + if (from) { + from.child; // $ExpectType RouteInfo | null + from.localName; // $ExpectType string + from.name; // $ExpectType string + from.paramNames; // $ExpectType string[] + from.params.foo; // $ExpectType string | undefined + from.parent; // $ExpectType RouteInfo | null + from.queryParams.foo; // $ExpectType string | undefined + from.find(info => info.name === 'foo'); // $ExpectType RouteInfo | undefined + } + }); + }, }); diff --git a/types/ember__routing/tsconfig.json b/types/ember__routing/tsconfig.json index c5bd434549..e7c16536f6 100644 --- a/types/ember__routing/tsconfig.json +++ b/types/ember__routing/tsconfig.json @@ -44,6 +44,7 @@ "router.d.ts", "types.d.ts", "-private/router-dsl.d.ts", + "-private/route-info.d.ts", "-private/transition.d.ts", "test/lib/assert.ts", "test/route.ts", diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index cd52bd54e5..d800fe01bc 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -143,7 +143,7 @@ interface IDataURLOptions { interface IEvent { e: Event; target?: Object; - transform?: { corner: string }; + transform?: { corner: string, original: Object, width: number }; } interface IFillOptions { diff --git a/types/get-value/get-value-tests.ts b/types/get-value/get-value-tests.ts index 9e7534e000..c6cf6c7de4 100644 --- a/types/get-value/get-value-tests.ts +++ b/types/get-value/get-value-tests.ts @@ -6,6 +6,9 @@ get(obj, "a"); get(obj, "a.b"); get(obj, "a.b.c"); get(obj, "a.b.c.d"); +get(obj, ['a']); +get(obj, ['a', 'b', 'c']); +get(obj, ['a', 'b', 'c', 'd']); { const isEnumerable = Object.prototype.propertyIsEnumerable; diff --git a/types/get-value/index.d.ts b/types/get-value/index.d.ts index 70cf0286e7..04dabe5101 100644 --- a/types/get-value/index.d.ts +++ b/types/get-value/index.d.ts @@ -1,13 +1,14 @@ // Type definitions for get-value 3.0 // Project: https://github.com/jonschlinkert/get-value // Definitions by: Daniel Rosenwasser +// Mathew Allen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 export = get; declare function get(obj: T): T; -declare function get(obj: object, key: string, options?: get.Options): any; +declare function get(obj: object, key: string | string[], options?: get.Options): any; declare namespace get { interface Options { diff --git a/types/glob-parent/index.d.ts b/types/glob-parent/index.d.ts index 052bbcd1db..b41cc48c31 100644 --- a/types/glob-parent/index.d.ts +++ b/types/glob-parent/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for glob-parent 3.1 -// Project: https://github.com/es128/glob-parent +// Project: https://github.com/gulpjs/glob-parent // Definitions by: mrmlnc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/graphql/execution/execute.d.ts b/types/graphql/execution/execute.d.ts index fc6ad898d1..1791ed9222 100644 --- a/types/graphql/execution/execute.d.ts +++ b/types/graphql/execution/execute.d.ts @@ -17,7 +17,7 @@ import { InlineFragmentNode, FragmentDefinitionNode, } from "../language/ast"; -import { MaybePromise } from "../jsutils/MaybePromise"; +import { PromiseOrValue } from "../jsutils/PromiseOrValue"; /** * Data that must be available at all points during query execution. @@ -37,7 +37,7 @@ export interface ExecutionContext { } export interface ExecutionResultDataDefault { - [key: string]: any + [key: string]: any; } /** @@ -73,7 +73,9 @@ export type ExecutionArgs = { * * Accepts either an object with named arguments, or individual arguments. */ -export function execute(args: ExecutionArgs): MaybePromise>; +export function execute( + args: ExecutionArgs +): PromiseOrValue>; export function execute( schema: GraphQLSchema, document: DocumentNode, @@ -82,7 +84,7 @@ export function execute( variableValues?: Maybe<{ [key: string]: any }>, operationName?: Maybe, fieldResolver?: Maybe> -): MaybePromise>; +): PromiseOrValue>; /** * Given a ResponsePath (found in the `path` entry in the information provided diff --git a/types/graphql/graphql-tests.ts b/types/graphql/graphql-tests.ts index e75fecb329..77787aa436 100644 --- a/types/graphql/graphql-tests.ts +++ b/types/graphql/graphql-tests.ts @@ -1,4 +1,4 @@ -import { assertInputType, isInputType, isOutputType } from 'graphql'; +import { assertInputType, isInputType, isOutputType } from "graphql"; /////////////////////////// // graphql // diff --git a/types/graphql/index.d.ts b/types/graphql/index.d.ts index 0206859643..d152dba8c5 100644 --- a/types/graphql/index.d.ts +++ b/types/graphql/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for graphql 14.0 +// Type definitions for graphql 14.2 // Project: https://github.com/graphql/graphql-js // Definitions by: TonyYang // Caleb Meredith @@ -18,6 +18,7 @@ // Jonathan Cardoso // Pavel Lang // Mark Caudill +// Martijn Walraven // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 diff --git a/types/graphql/jsutils/MaybePromise.d.ts b/types/graphql/jsutils/MaybePromise.d.ts deleted file mode 100644 index 5eb85a3f92..0000000000 --- a/types/graphql/jsutils/MaybePromise.d.ts +++ /dev/null @@ -1 +0,0 @@ -export type MaybePromise = Promise | T; diff --git a/types/graphql/jsutils/PromiseOrValue.d.ts b/types/graphql/jsutils/PromiseOrValue.d.ts new file mode 100644 index 0000000000..6b2517ee62 --- /dev/null +++ b/types/graphql/jsutils/PromiseOrValue.d.ts @@ -0,0 +1 @@ +export type PromiseOrValue = Promise | T; diff --git a/types/graphql/language/blockStringValue.d.ts b/types/graphql/language/blockString.d.ts similarity index 78% rename from types/graphql/language/blockStringValue.d.ts rename to types/graphql/language/blockString.d.ts index 64fb87dafd..a6bf5f6f0c 100644 --- a/types/graphql/language/blockStringValue.d.ts +++ b/types/graphql/language/blockString.d.ts @@ -4,4 +4,4 @@ * * This implements the GraphQL spec's BlockStringValue() static algorithm. */ -export default function blockStringValue(rawString: string): string; +export function dedentBlockStringValue(rawString: string): string; diff --git a/types/graphql/language/printer.d.ts b/types/graphql/language/printer.d.ts index de823b5b3e..6b5635a06a 100644 --- a/types/graphql/language/printer.d.ts +++ b/types/graphql/language/printer.d.ts @@ -1,5 +1,7 @@ +import { ASTNode } from "./ast"; + /** * Converts an AST into a string, using one set of reasonable * formatting rules. */ -export function print(ast: any): string; +export function print(ast: ASTNode): string; diff --git a/types/graphql/tsutils/Maybe.d.ts b/types/graphql/tsutils/Maybe.d.ts index 7ad0bc85a4..6a3391138f 100644 --- a/types/graphql/tsutils/Maybe.d.ts +++ b/types/graphql/tsutils/Maybe.d.ts @@ -1,4 +1,4 @@ // Conveniently represents flow's "Maybe" type https://flow.org/en/docs/types/maybe/ -type Maybe = null | undefined | T +type Maybe = null | undefined | T; -export default Maybe +export default Maybe; diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index f491919a13..b36c75539c 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -1,5 +1,5 @@ import Maybe from "../tsutils/Maybe"; -import { MaybePromise } from "../jsutils/MaybePromise"; +import { PromiseOrValue } from "../jsutils/PromiseOrValue"; import { ScalarTypeDefinitionNode, ObjectTypeDefinitionNode, @@ -161,7 +161,6 @@ interface GraphQLList { inspect(): string; } - interface _GraphQLList { (type: T): GraphQLList; new (type: T): GraphQLList; @@ -280,6 +279,12 @@ export class GraphQLScalarType { extensionASTNodes: Maybe>; constructor(config: GraphQLScalarTypeConfig); + toConfig(): GraphQLScalarTypeConfig & { + parseValue: GraphQLScalarValueParser; + parseLiteral: GraphQLScalarLiteralParser; + extensionASTNodes: ReadonlyArray; + }; + toString(): string; toJSON(): string; inspect(): string; @@ -342,11 +347,7 @@ export interface GraphQLScalarTypeConfig { * }); * */ -export class GraphQLObjectType< - TSource = any, - TContext = any, - TArgs = { [key: string]: any } -> { +export class GraphQLObjectType { name: string; description: Maybe; astNode: Maybe; @@ -356,16 +357,19 @@ export class GraphQLObjectType< constructor(config: GraphQLObjectTypeConfig); getFields(): GraphQLFieldMap; getInterfaces(): GraphQLInterfaceType[]; + + toConfig(): GraphQLObjectTypeConfig & { + interfaces: GraphQLInterfaceType[]; + fields: GraphQLFieldConfigMap; + extensionASTNodes: ReadonlyArray; + }; + toString(): string; toJSON(): string; inspect(): string; } -export interface GraphQLObjectTypeConfig< - TSource, - TContext, - TArgs = { [key: string]: any } -> { +export interface GraphQLObjectTypeConfig { name: string; interfaces?: Thunk>; fields: Thunk>; @@ -375,21 +379,17 @@ export interface GraphQLObjectTypeConfig< extensionASTNodes?: Maybe>; } -export type GraphQLTypeResolver< - TSource, - TContext, - TArgs = { [key: string]: any } -> = ( +export type GraphQLTypeResolver = ( value: TSource, context: TContext, info: GraphQLResolveInfo -) => MaybePromise | string>>; +) => PromiseOrValue | string>>; export type GraphQLIsTypeOfFn = ( source: TSource, context: TContext, info: GraphQLResolveInfo -) => MaybePromise; +) => PromiseOrValue; export type GraphQLFieldResolver = ( source: TSource, @@ -461,11 +461,7 @@ export interface GraphQLArgument { export function isRequiredArgument(arg: GraphQLArgument): boolean; -export type GraphQLFieldMap< - TSource, - TContext, - TArgs = { [key: string]: any } -> = { +export type GraphQLFieldMap = { [key: string]: GraphQLField; }; @@ -498,16 +494,17 @@ export class GraphQLInterfaceType { getFields(): GraphQLFieldMap; + toConfig(): GraphQLInterfaceTypeConfig & { + fields: GraphQLFieldConfigMap; + extensionASTNodes: ReadonlyArray; + }; + toString(): string; toJSON(): string; inspect(): string; } -export interface GraphQLInterfaceTypeConfig< - TSource, - TContext, - TArgs = { [key: string]: any } -> { +export interface GraphQLInterfaceTypeConfig { name: string; fields: Thunk>; /** @@ -555,6 +552,11 @@ export class GraphQLUnionType { getTypes(): GraphQLObjectType[]; + toConfig(): GraphQLUnionTypeConfig & { + types: GraphQLObjectType[]; + extensionASTNodes: ReadonlyArray; + }; + toString(): string; toJSON(): string; inspect(): string; @@ -607,6 +609,11 @@ export class GraphQLEnumType { serialize(value: any): Maybe; parseValue(value: any): Maybe; parseLiteral(valueNode: ValueNode, _variables: Maybe<{ [key: string]: any }>): Maybe; + + toConfig(): GraphQLEnumTypeConfig & { + extensionASTNodes: ReadonlyArray; + }; + toString(): string; toJSON(): string; inspect(): string; @@ -665,6 +672,12 @@ export class GraphQLInputObjectType { extensionASTNodes: Maybe>; constructor(config: GraphQLInputObjectTypeConfig); getFields(): GraphQLInputFieldMap; + + toConfig(): GraphQLInputObjectTypeConfig & { + fields: GraphQLInputFieldConfigMap; + extensionASTNodes: ReadonlyArray; + }; + toString(): string; toJSON(): string; inspect(): string; diff --git a/types/graphql/type/directives.d.ts b/types/graphql/type/directives.d.ts index ca9e947640..b3995704a7 100644 --- a/types/graphql/type/directives.d.ts +++ b/types/graphql/type/directives.d.ts @@ -20,6 +20,10 @@ export class GraphQLDirective { astNode: Maybe; constructor(config: GraphQLDirectiveConfig); + + toConfig(): GraphQLDirectiveConfig & { + args: GraphQLFieldConfigArgumentMap; + }; } export interface GraphQLDirectiveConfig { diff --git a/types/graphql/type/schema.d.ts b/types/graphql/type/schema.d.ts index 7ccb390dbe..a1722844e4 100644 --- a/types/graphql/type/schema.d.ts +++ b/types/graphql/type/schema.d.ts @@ -52,6 +52,12 @@ export class GraphQLSchema { getDirectives(): ReadonlyArray; getDirective(name: string): Maybe; + + toConfig(): GraphQLSchemaConfig & { + types: GraphQLNamedType[]; + directives: GraphQLDirective[]; + extensionASTNodes: ReadonlyArray; + }; } type TypeMap = { [key: string]: GraphQLNamedType }; diff --git a/types/graphql/utilities/buildASTSchema.d.ts b/types/graphql/utilities/buildASTSchema.d.ts index 1390601f65..8b7a725ec8 100644 --- a/types/graphql/utilities/buildASTSchema.d.ts +++ b/types/graphql/utilities/buildASTSchema.d.ts @@ -15,7 +15,7 @@ import { GraphQLDirective } from "../type/directives"; import { Source } from "../language/source"; import { GraphQLSchema, GraphQLSchemaValidationOptions } from "../type/schema"; import { ParseOptions } from "../language/parser"; -import blockStringValue from "../language/blockStringValue"; +import { dedentBlockStringValue } from "../language/blockString"; interface BuildSchemaOptions extends GraphQLSchemaValidationOptions { /** diff --git a/types/graphql/validation/validate.d.ts b/types/graphql/validation/validate.d.ts index 6c0e644ea3..aee901bbb5 100644 --- a/types/graphql/validation/validate.d.ts +++ b/types/graphql/validation/validate.d.ts @@ -2,7 +2,7 @@ import { GraphQLError } from "../error"; import { DocumentNode } from "../language/ast"; import { GraphQLSchema } from "../type/schema"; import { TypeInfo } from "../utilities/TypeInfo"; -import { ValidationRule } from "./ValidationContext"; +import { ValidationRule, SDLValidationRule } from "./ValidationContext"; /** * Implements the "Validation" section of the spec. @@ -27,6 +27,13 @@ export function validate( typeInfo?: TypeInfo ): ReadonlyArray; +// @internal +export function validateSDL( + documentAST: DocumentNode, + schemaToExtend?: GraphQLSchema | null, + rules?: ReadonlyArray +): GraphQLError[]; + /** * Utility function which asserts a SDL document is valid by throwing an error * if it is invalid. diff --git a/types/gtag.js/gtag.js-tests.ts b/types/gtag.js/gtag.js-tests.ts new file mode 100644 index 0000000000..c25db26c5f --- /dev/null +++ b/types/gtag.js/gtag.js-tests.ts @@ -0,0 +1,12 @@ +gtag('config', 'GA-TRACKING_ID'); +gtag('config', 'GA-TRACKING_ID', {send_page_view: false}); + +gtag('event', 'login', { + method: 'Google' +}); + +gtag('set', {currency: 'USD'}); +gtag('set', { + country: 'US', + currency: 'USD' +}); diff --git a/types/gtag.js/index.d.ts b/types/gtag.js/index.d.ts new file mode 100644 index 0000000000..6f7715b1b1 --- /dev/null +++ b/types/gtag.js/index.d.ts @@ -0,0 +1,93 @@ +// Type definitions for Google gtag.js API +// Project: https://developers.google.com/gtagjs +// Definitions by: Junyoung Choi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var gtag: Gtag.Gtag; +declare namespace Gtag { + interface Gtag { + (command: 'config', targetId: string, config?: ControlParams | EventParams | CustomParams): void; + (command: 'set', config: CustomParams): void; + (command: 'event', eventName: EventNames | string, eventParams?: ControlParams | EventParams | CustomParams): void; + } + + interface CustomParams { + [key: string]: any; + } + + interface ControlParams { + groups?: string | string[]; + send_to?: string | string[]; + event_callback?: () => void; + event_timeout?: number; + } + + type EventNames = 'add_payment_info' + | 'add_payment_info' + | 'add_to_cart' + | 'add_to_wishlist' + | 'begin_checkout' + | 'checkout_progress' + | 'exception' + | 'generate_lead' + | 'login' + | 'page_view' + | 'purchase' + | 'refund' + | 'remove_from_cart' + | 'screen_view' + | 'search' + | 'select_content' + | 'set_checkout_option' + | 'share' + | 'sign_up' + | 'timing_complete' + | 'view_item' + | 'view_item_list' + | 'view_promotion' + | 'view_search_results'; + + interface EventParams { + checkout_option?: string; + checkout_step?: number; + content_id?: string; + content_type?: string; + coupon?: string; + currency?: string; + description?: string; + fatal?: boolean; + items?: Item[]; + method?: string; + number?: string; + promotions?: Promotion[]; + screen_name?: string; + search_term?: string; + shipping?: Currency; + tax?: Currency; + transaction_id?: string; + value?: number; + event_label?: string; + event_category: string; + } + + type Currency = string | number; + + interface Item { + brand?: string; + category?: string; + creative_name?: string; + creative_slot?: string; + id?: string; + location_id?: string; + name?: string; + price?: Currency; + quantity?: number; + } + + interface Promotion { + creative_name?: string; + creative_slot?: string; + id?: string; + name?: string; + } +} diff --git a/types/gtag.js/tsconfig.json b/types/gtag.js/tsconfig.json new file mode 100644 index 0000000000..4e8cd26f3f --- /dev/null +++ b/types/gtag.js/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gtag.js-tests.ts" + ] +} \ No newline at end of file diff --git a/types/gtag.js/tslint.json b/types/gtag.js/tslint.json new file mode 100644 index 0000000000..035c359a3d --- /dev/null +++ b/types/gtag.js/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "dt-header": false + } +} diff --git a/types/gulp-intercept/gulp-intercept-tests.ts b/types/gulp-intercept/gulp-intercept-tests.ts new file mode 100644 index 0000000000..36952e438f --- /dev/null +++ b/types/gulp-intercept/gulp-intercept-tests.ts @@ -0,0 +1,14 @@ +import gulpIntercept = require('gulp-intercept'); +import gulp = require('gulp'); +import Vinyl = require('vinyl'); + +gulp.task('testTask', () => { + return gulp.src(['src/*.html']) + + .pipe(gulpIntercept((sourceFile: Vinyl) => { + console.log(sourceFile.path); + return sourceFile; + })) + + .pipe(gulp.dest('dist/')); +}); diff --git a/types/gulp-intercept/index.d.ts b/types/gulp-intercept/index.d.ts new file mode 100644 index 0000000000..1a73d899ae --- /dev/null +++ b/types/gulp-intercept/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for gulp-intercept 0.1 +// Project: https://github.com/khilnani/gulp-intercept +// Definitions by: Takesi Tokugawa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import Vinyl = require('vinyl'); + +declare namespace intercept { + interface Intercept { + (interceptFunction: InterceptFunction): NodeJS.ReadWriteStream; + } + + interface InterceptFunction { + (file: Vinyl): Vinyl; + } +} + +declare var intercept: intercept.Intercept; + +export = intercept; diff --git a/types/gulp-intercept/tsconfig.json b/types/gulp-intercept/tsconfig.json new file mode 100644 index 0000000000..07acf8c416 --- /dev/null +++ b/types/gulp-intercept/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-intercept-tests.ts" + ] +} diff --git a/types/opn/tslint.json b/types/gulp-intercept/tslint.json similarity index 100% rename from types/opn/tslint.json rename to types/gulp-intercept/tslint.json diff --git a/types/html5-to-pdf/html5-to-pdf-tests.ts b/types/html5-to-pdf/html5-to-pdf-tests.ts new file mode 100644 index 0000000000..1081f5fa12 --- /dev/null +++ b/types/html5-to-pdf/html5-to-pdf-tests.ts @@ -0,0 +1,9 @@ +import * as HTML5ToPDF from "html5-to-pdf"; + +const options = { inputBody: "Hello World" }; +const converter = new HTML5ToPDF(options); +converter.parseOptions(options); // $ExpectType ParsedOptions +converter.build(); // $ExpectType Promise +converter.includeAssets(); // $ExpectType Promise +converter.start(); // $ExpectType Promise +converter.close(); // $ExpectType Promise diff --git a/types/html5-to-pdf/index.d.ts b/types/html5-to-pdf/index.d.ts new file mode 100644 index 0000000000..a4967ed199 --- /dev/null +++ b/types/html5-to-pdf/index.d.ts @@ -0,0 +1,118 @@ +// Type definitions for html5-to-pdf 3.1 +// Project: https://github.com/peterdemartini/html5-to-pdf +// Definitions by: Sam Alexander +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { LaunchOptions, PDFOptions, Page } from "puppeteer"; + +declare class HTML5ToPDF { + constructor(options: HTML5ToPDF.Options); + + build(): Promise; + + close(): Promise; + + includeAssets(): Promise; + + parseOptions(options: HTML5ToPDF.Options): HTML5ToPDF.ParsedOptions; + + start(): Promise; +} + +declare namespace HTML5ToPDF { + interface FileDef { + /** + * File type + */ + type: "css" | "js"; + /** + * File path + */ + filePath: string; + } + + interface ParsedOptions { + body: string | Buffer; + pdf: PDFOptions; + templatePath: string; + templateUrl: string; + launchOptions: LaunchOptions; + include: FileDef[]; + renderDelay: number; + } + + interface LegacyOptions { + /** + * [COMPATIBLE]\ + * Page size + */ + pageSize?: "A3" | "A4" | "Legal" | "Tabloid"; + /** + * [COMPATIBLE]\ + * True for landscape, false for portrait. + */ + landscape?: boolean; + /** + * [NOT COMPATIBLE]\ + * 0 - default\ + * 1 - none\ + * 2 - minimum + */ + marginsType?: number; + /** + * [COMPATIBLE]\ + * Whether to print CSS backgrounds. + */ + printBackground?: boolean; + } + + interface Options { + /** + * Path to the input HTML. + */ + inputPath?: string; + /** + * Path to the input html as a String, or Buffer. If specified this will override inputPath. + */ + inputBody?: string | Buffer; + /** + * Path to the output pdf file. + */ + outputPath?: string; + /** + * Delay in milliseconds before rendering the PDF (give HTML and CSS a chance to load). + */ + rendererDelay?: number; + /** + * A list of CSS or JS assets to include. + */ + include?: Array; + /** + * The template to use when rendering the html. + */ + template?: string; + /** + * The template to use for rendering the html. If this is set, it will use this instead of the template path. + */ + templateUrl?: string; + /** + * This object will be passed directly to `puppeteer`. + */ + pdf?: PDFOptions; + /** + * This object will be passed directly to `puppeteer`. + */ + launchOptions?: LaunchOptions; + /** + * @deprecated Legacy Options. + * See `options.pdf` for pdf options. Since some of these options are converted over to work with `puppeteer`, + * this is automatically done if `options.pdf` is left empty. + */ + options?: LegacyOptions; + } +} + +export = HTML5ToPDF; + +export as namespace HTML5ToPDF; diff --git a/types/html5-to-pdf/tsconfig.json b/types/html5-to-pdf/tsconfig.json new file mode 100644 index 0000000000..a2ee9070de --- /dev/null +++ b/types/html5-to-pdf/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom", + "es2017" + ], + "target": "es2017", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "html5-to-pdf-tests.ts" + ] +} diff --git a/types/storybook__addon-notes/tslint.json b/types/html5-to-pdf/tslint.json similarity index 100% rename from types/storybook__addon-notes/tslint.json rename to types/html5-to-pdf/tslint.json diff --git a/types/identicon.js/identicon.js-tests.ts b/types/identicon.js/identicon.js-tests.ts new file mode 100644 index 0000000000..4c233912c7 --- /dev/null +++ b/types/identicon.js/identicon.js-tests.ts @@ -0,0 +1,16 @@ +import Identicon, { Svg } from "identicon.js"; + +// create an identicon with only a hash and a size +new Identicon("d3b07384d113edec49eaa6238ad5ff00", 420).toString(); + +// create an identicon with a hash and other options and get the svg +const svg = new Identicon("d3b07384d113edec49eaa6238ad5ff00", { + background: [255, 255, 255, 255], + foreground: [0, 0, 0, 0], + margin: 0.05, + size: 64, + format: "svg", +}).image() as Svg; +svg.getDump(); +// or get the base64 encoded svg +svg.getBase64(); diff --git a/types/identicon.js/index.d.ts b/types/identicon.js/index.d.ts new file mode 100644 index 0000000000..499a1f1f5c --- /dev/null +++ b/types/identicon.js/index.d.ts @@ -0,0 +1,129 @@ +// Type definitions for identicon.js 2.3 +// Project: https://github.com/stewartlord/identicon.js +// Definitions by: D0miH +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Color = [number, number, number, number]; + +export interface IdenticonOptions { + background?: Color; + foreground?: Color; + margin?: number; + size?: number; + format?: "svg" | "png"; +} + +export interface PNGlib { + width: number; + height: number; + depth: number; + + /** + * Returns the index of a given pixel in the image data array. + * @param x The given x coordinate of the pixel. + * @param y The given y coordinate of the pixel. + */ + index(x: number, y: number): number; + + /** + * Returns the image as a base64 encoded string. + */ + getBase64(): string; + + /** + * Returns the png as a string. + */ + getDump(): string; +} + +export interface Svg { + size: number; + foreground: Color; + background: Color; + rectangles: [ + { + x: number; + y: number; + width: number; + height: number; + color: Color; + } + ]; + + /** + * Returns a string with the structure 'rgb(r, g, b, a)'. + * @param red + * @param green + * @param blue + * @param alpha + */ + color(red: number, green: number, blue: number, alpha: number): string; + + /** + * Returns the Svg as string. + */ + getDump(): string; + + /** + * Returns the Svg as a base64 encoded string. + */ + getBase64(): string; +} + +export default class Identicon { + hash: string; + foreground: Color; + background: Color; + size: number; + format: "svg" | "png"; + margin: number; + + constructor(hash: string, size?: number); + constructor(hash: string, options: IdenticonOptions); + + /** + * Returns a new blank image as Svg or PNGlib. + */ + image(): Svg | PNGlib; + + /** + * Returns a new image as Svg or PNGlib with the identicon applied. + */ + render(): Svg | PNGlib; + + /** + * Places a rectangle at the given position with the given width, height and color in the image. + * @param x The x coordinate. + * @param y The y coordinate + * @param w The width. + * @param h The height. + * @param color The color. + * @param image The image. + */ + rectangle( + x: number, + y: number, + w: number, + h: number, + color: Color, + image: Svg | PNGlib + ): void; + + /** + * Converts from hsl to rgb. + * @param h hue + * @param s saturation + * @param b brightness + */ + hsl2rgb(h: number, s: number, b: number): [number, number, number]; + + /** + * Returns the image data as a string. + */ + toString(): string; + + /** + * Returns true if the identicon is a Svg. + */ + isSvg(): boolean; +} diff --git a/types/identicon.js/tsconfig.json b/types/identicon.js/tsconfig.json new file mode 100644 index 0000000000..c679002ee1 --- /dev/null +++ b/types/identicon.js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "identicon.js-tests.ts" + ] +} diff --git a/types/identicon.js/tslint.json b/types/identicon.js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/identicon.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ink-select-input/index.d.ts b/types/ink-select-input/index.d.ts index 2654084e25..6f511e304b 100644 --- a/types/ink-select-input/index.d.ts +++ b/types/ink-select-input/index.d.ts @@ -1,25 +1,28 @@ -// Type definitions for ink-select-input 2.0 +// Type definitions for ink-select-input 3.0 // Project: https://github.com/vadimdemedes/ink-select-input#readme // Definitions by: Łukasz Ostrowski +// Jakub Satnik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import { Component, InkComponent } from 'ink'; +import { Component } from 'react'; -interface ItemOfSelectInput { +export interface ItemOfSelectInput { label: string; value: any; + key?: string | number; } -interface SelectInputProps { +export interface SelectInputProps { focus?: boolean; - indicatorComponent?: InkComponent; - itemComponent?: InkComponent; + indicatorComponent?: Component; + itemComponent?: Component; items?: ReadonlyArray; limit?: number; + initialIndex?: number; onSelect?: (item: T) => void; } declare class SelectInput extends Component { } -export = SelectInput; +export default SelectInput; diff --git a/types/ink-select-input/ink-select-input-tests.tsx b/types/ink-select-input/ink-select-input-tests.tsx index da29f9918e..fd80d43394 100644 --- a/types/ink-select-input/ink-select-input-tests.tsx +++ b/types/ink-select-input/ink-select-input-tests.tsx @@ -1,32 +1,31 @@ -/** @jsx h */ -import { h, InkComponent } from 'ink'; -import SelectInput from 'ink-select-input'; +import * as React from 'react'; + +// tslint:disable-next-line:import-name +import SelectInput, { ItemOfSelectInput } from 'ink-select-input'; // NOTE: `import SelectInput = require('ink-select-input');` will work as well. // If importing using ES6 default import as above, // `allowSyntheticDefaultImports` flag in compiler options needs to be set to `true` -interface DemoItem { - label: string; - value: string; +const items: ReadonlyArray = [ + { + label: 'First', + value: 'first', + key: 0, + }, + { + label: 'Second', + value: 'second', + }, + { + label: 'Third', + value: 'third', + }, +]; + +class Demo extends React.PureComponent { + handleSelect = (item: ItemOfSelectInput) => {}; + + render() { + return ; + } } - -const items: ReadonlyArray = [{ - label: 'First', - value: 'first' -}, -{ - label: 'Second', - value: 'second' -}, -{ - label: 'Third', - value: 'third' -}]; - -const Demo: InkComponent = () => { - const handleSelect = (item: DemoItem) => { - console.log(item); - }; - - return ; -}; diff --git a/types/is-glob/index.d.ts b/types/is-glob/index.d.ts index 3c478c084b..f9bf69d00b 100644 --- a/types/is-glob/index.d.ts +++ b/types/is-glob/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for is-glob 4.0 -// Project: https://github.com/jonschlinkert/is-glob +// Project: https://github.com/micromatch/is-glob // Definitions by: mrmlnc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/js-cookie/index.d.ts b/types/js-cookie/index.d.ts index 7b90b4ecd5..71fd7c793d 100644 --- a/types/js-cookie/index.d.ts +++ b/types/js-cookie/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Theodore Brown // BendingBender // Antoine Lépée +// Yuto Doi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -88,7 +89,7 @@ declare namespace Cookies { * will run the converter first for each cookie. The returned * string will be used as the cookie value. */ - withConverter(converter: CookieReadConverter | { write: CookieWriteConverter; read: CookieReadConverter; }): CookiesStatic; + withConverter(converter: CookieReadConverter | { write?: CookieWriteConverter; read?: CookieReadConverter; }): CookiesStatic; } type CookieWriteConverter = (value: string | T, name: string) => string; diff --git a/types/js-cookie/js-cookie-tests.ts b/types/js-cookie/js-cookie-tests.ts index df30d90975..5e263ca266 100644 --- a/types/js-cookie/js-cookie-tests.ts +++ b/types/js-cookie/js-cookie-tests.ts @@ -53,3 +53,15 @@ const PHPCookies = Cookies.withConverter({ .replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent); } }); + +const BlankConverterCookies = Cookies.withConverter({ + read(value, name) { + if (name === 'hoge') { + return value.replace('hoge', 'fuga'); + } + return value; + } +}); + +document.cookie = 'hoge=hogehoge'; +BlankConverterCookies.get('hoge'); diff --git a/types/license-checker-webpack-plugin/index.d.ts b/types/license-checker-webpack-plugin/index.d.ts index ff131df767..3c512a00eb 100644 --- a/types/license-checker-webpack-plugin/index.d.ts +++ b/types/license-checker-webpack-plugin/index.d.ts @@ -7,7 +7,7 @@ import { Plugin } from 'webpack'; declare class LicenseCheckerWebpackPlugin extends Plugin { - constructor(options: LicenseCheckerWebpackPlugin.Options); + constructor(options?: Partial); } declare namespace LicenseCheckerWebpackPlugin { @@ -23,14 +23,14 @@ declare namespace LicenseCheckerWebpackPlugin { /** * Regular expression that matches the file paths of dependencies to check. */ - filter?: RegExp; + filter: RegExp; /** * SPDX expression with allowed licenses. * * Default: `"(Apache-2.0 OR BSD-2-Clause OR BSD-3-Clause OR MIT)"` */ - allow?: string; + allow: string; /** * Array of dependencies to ignore, in the format `["@"]`. @@ -38,7 +38,7 @@ declare namespace LicenseCheckerWebpackPlugin { * * Default: `[]` */ - ignore?: string[]; + ignore: string[]; /** * Object of dependencies to override, in the format `{"@": { ... }}`. @@ -46,27 +46,27 @@ declare namespace LicenseCheckerWebpackPlugin { * * Default: `{}` */ - override?: Record>; + override: Record>; /** * Whether to emit errors instead of warnings. * * Default: `false` */ - emitError?: boolean; + emitError: boolean; /** * Path to a `.ejs` template, or function that will generate the contents * of the third-party notices file. */ - outputWriter?: string | ((dependencies: Dependency[]) => string); + outputWriter: string | ((dependencies: Dependency[]) => string); /** * Name of the third-party notices file with all licensing information. * * Default: `"ThirdPartyNotices.txt"` */ - outputFilename?: string; + outputFilename: string; } } diff --git a/types/license-checker-webpack-plugin/license-checker-webpack-plugin-tests.ts b/types/license-checker-webpack-plugin/license-checker-webpack-plugin-tests.ts index f476b515f5..de766de7b3 100644 --- a/types/license-checker-webpack-plugin/license-checker-webpack-plugin-tests.ts +++ b/types/license-checker-webpack-plugin/license-checker-webpack-plugin-tests.ts @@ -22,3 +22,6 @@ new LicenseCheckerWebpackPlugin({ return dependencies.map(d => `${d.name} ${d.licenseName}`).join('\n'); }, }); + +// $ExpectType LicenseCheckerWebpackPlugin +new LicenseCheckerWebpackPlugin(); diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index 3dcb7bbeea..95c0d509cf 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -4989,7 +4989,7 @@ fp.now(); // $ExpectType number _.create(prototype, properties); // $ExpectType { a: number; } & { b: string; } _(prototype).create(properties); // $ExpectType LoDashImplicitWrapper<{ a: number; } & { b: string; }> _.chain(prototype).create(properties); // $ExpectType LoDashExplicitWrapper<{ a: number; } & { b: string; }> - fp.create(prototype); // $ExpectType { a: number; } + const combined: { a: number } & object = fp.create(prototype); } // _.defaultsDeep diff --git a/types/naver-whale/index.d.ts b/types/naver-whale/index.d.ts new file mode 100644 index 0000000000..de1ce94bc8 --- /dev/null +++ b/types/naver-whale/index.d.ts @@ -0,0 +1,636 @@ +// Type definitions for Naver Whale extension development +// Project: https://developers.whale.naver.com/getting_started/ +// Definitions by: tbvjaos510 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +/// + +declare interface Window { + whale: typeof whale; +} +declare namespace chrome.downloads { + export interface StateType { + readonly COMPLETE: string; + readonly IN_PROGRESS: string; + readonly INTERRUPTED: string; + } + export const State: StateType; +} + +declare namespace whale { + /** + * 지정한 주기 혹은 시간에 코드가 실행되도록 예약합니다 + * 권한: "alarms" + * @since Chrome 22. + */ + export import alarms = chrome.alarms; + + /** + * 북마크의 생성, 삭제, 수정 및 폴더 변경 등 북마크에 관한 기능을 제공합니다. 이 API를 이용해 북마크 관리자를 만들 수 있습니다. + * 권한: "bookmarks" + * @since Chrome 5. + */ + export import bookmarks = chrome.bookmarks; + + /** + * 주소창 오른쪽 툴바 영역에 나타나는 버튼을 제어 할 수 있습니다. 아이콘을 변경하거나 뱃지를 표시할 수도 있고, 팝업이 나타나게 할 수도 있습니다. + * Manifest: "browser_action": {...} + * @since Chrome 5. + */ + export import browserAction = chrome.browserAction; + + /** + * 인터넷 사용 기록을 삭제할 수 있습니다. 설정 > 개인정보 보호 > 인터넷 사용 기록 삭제 영역의 각 항목별 삭제를 수행할 수 있습니다. + * 권한: "browsingData" + * @since Chrome 19. + */ + export import browsingData = chrome.browsingData; + + /** + * 확장앱에 단축키를 부여할 수 있습니다. + * Manifest: "commands": {...} + * @since Chrome 16. + */ + export import commands = chrome.commands; + + /** + * 쿠키, 자바스크립트, 마이크 등 웹 사이트에서 요청한 정보를 제공할 것인지 설정할 수 있습니다. 설정 > 개인정보 보호 > 콘텐츠 설정에서 확인할 수 있는 항목을 제어할 수 있습니다. + * 권한: "contentSettings" + * @since Chrome 16. + */ + export import contentSettings = chrome.contentSettings; + + /** + * 마우스 오른쪽 버튼을 클릭하면 나타나는 콘텍스트 메뉴를 만들 수 있습니다. 페이지, 링크, 이미지 등 클릭한 위치에 따라 서로 다른 메뉴를 표시할 수 있습니다 + * 권한: "contextMenus" + * @since Chrome 6. + */ + export import contextMenus = chrome.contextMenus; + + /** + * 쿠키를 제어하거나 변경시 이벤트를 수신할 수 있습니다 + * 권한: "cookies", host 권한 + * @since Chrome 6. + */ + export import cookies = chrome.cookies; + + /** + * 특정 탭의 네트워크 통신, JavaScript 디버깅, DOM · CSS 변형 등 디버그를 위한 [원격 디버깅 프로토콜](https://chromedevtools.github.io/devtools-protocol/tot/Network)을 사용할 수 있습니다. + * `sendCommand()` 메소드와 `onEvent` 핸들러 함수를 이용해 개발자도구에서 제공하는 개별 기능을 명령 단위로 수행할 수 있습니다. + * 권한: "debugger" + * @since Chrome 18. + */ + const _debugger: typeof chrome.debugger; + export { _debugger as debugger }; + + /** + * 웹 페이지에 대한 접근 권한 요청없이 특정 페이지의 콘텐트 혹은 상태에 의존적인 동작을 수행할 수 있습니다. + * 권한: "declarativeContent" + * @since Chrome 33. + */ + export import declarativeContent = chrome.declarativeContent; + + /** + * 화면, 윈도우 또는 탭의 콘텐츠를 캡쳐할 수 있습니다. + * 권한: "desktopCapture" + * @since Chrome 34. + */ + export import desktopCapture = chrome.desktopCapture; + + export namespace devtools { + /** + * 개발자도구를 이용한 검사(Inspect)가 진행중인 윈도우에서 코드를 실행하거나 페이지를 새로고침 하는 등의 작업을 수행할 수 있습니다. + * @since Chrome 18. + */ + + export import inspectedWindow = chrome.devtools.inspectedWindow; + + /** + * 개발자도구 > 네트워크 패널에서 수신하는 정보들을 수신할 수 있습니다. + * @since Chrome 18. + */ + export import network = chrome.devtools.network; + + /** + * 개발자도구에 새로운 패널을 추가하거나 기존의 패널에 접근할 수 있습니다. + * @since Chrome 18. + */ + export import panels = chrome.devtools.panels; + } + + /** + * 지정한 URL의 파일 다운로드, 진행중인 다운로드의 제어 및 검색 등 파일 다운로드에 관련된 기능을 사용할 수 있습니다. + * 권한: "downloads" + * @since Chrome 31 + */ + export import downloads = chrome.downloads; + + /** + * 웨일 브라우저 API에서 사용되는 공통 이벤트 자료형을 포함하는 네임스페이스입니다. + * @since Chrome 21. + */ + export import events = chrome.events; + + /** + * 서로 다른 확장앱 사이에 메시지를 교환하거나, 현재 확장앱에 관한 정보를 얻을 수 있습니다. + * @since Chrome 5. + */ + export import extension = chrome.extension; + + /** + * 글꼴 관련 설정을 제어할 수 있습니다. + * 권한: "fontSettings" + * @since Chrome 22. + */ + export import fontSettings = chrome.fontSettings; + + /** + * Google Cloud Messaging 서비스와 메시지를 주고받습니다. + * 권한: "gcm" + * @since Chrome 35. + */ + export import gcm = chrome.gcm; + + /** + * 방문 기록의 생성, 삭제 및 검색 등 방문 기록에 관한 기능을 제공합니다. 이 API를 이용해 방문 기록 페이지를 만들 수 있습니다. + * 권한: "history" + * @since Chrome 5. + */ + export import history = chrome.history; + + /** + * 다국어 지원을 위한 기능을 제공합니다. + * @since Chrome 5. + */ + export import i18n = chrome.i18n; + + /** + * 시스템의 유휴 상태(Idle) 여부를 확인하거나 변화를 감지할 수 있습니다. + * 권한: "idle" + * @since Chrome 6. + */ + export import idle = chrome.idle; + + /** + * 설치되어 있는 확장앱 정보를 얻어 제어할 수 있습니다. + * 권한: "management" + * @since Chrome 8. + */ + export import management = chrome.management; + + /** + * 시스템 트레이에 알림창을 표시할 수 있습니다. + * 권한: "notifications" + * @since Chrome 28. + */ + export import notifications = chrome.notifications; + + /** + * 주소창에서 특정 키워드를 입력하면 확장앱이 주소창 영역에 관여하게 할 수 있습니다. + * Manifest: "omnibox": {...} + * @since Chrome 9. + */ + export import omnibox = chrome.omnibox; + + /** + * 주소창 오른쪽 툴바 영역에 나타나는 버튼을 제어 할 수 있습니다. + * `browserAction`과 거의 동일하지만 현재 페이지에 대해서만 기능을 수행하기 위해 제공된다는 점이 다릅니다. 비활성 상태에서는 버튼이 회색으로 표시됩니다. + * Manifest: "page_action": {...} + * @since Chrome 5. + */ + export import pageAction = chrome.pageAction; + + /** + * 지정한 탭의 웹 페이지를 MHTML 형식으로 저장할 수 있습니다. + * 권한: "pageCapture" + * @since Chrome 18. + */ + export import pageCapture = chrome.pageCapture; + + /** + * 매니페스트에 optional_permissions로 정의한 추가 권한을 사용자에게 요청할 수 있습니다 + * @since Chrome 16. + */ + export import permissions = chrome.permissions; + + /** + * 전원 관리 기능을 제어할 수 있습니다. + * 권한: "power" + */ + export import power = chrome.power; + + /** + * The chrome.printerProvider API exposes events used by print manager to query printers controlled by extensions, to query their capabilities and to submit print jobs to these printers. + * 권한: "printerProvider" + */ + export import printerProvider = chrome.printerProvider; + + /** + * 개인정보 보호 관련 설정을 제어할 수 있습니다. + * 권한: "privacy" + */ + export import privacy = chrome.privacy; + + /** + * 프록시 관련 설정을 제어할 수 있습니다. + * 권한: "proxy" + */ + export import proxy = chrome.proxy; + + /** + * 백그라운드 페이지 검색, 매니페스트 확인 및 확장앱 수명주기에 관한 이벤트 수신, 메시지 교환 등의 기능을 제공합니다. + */ + export import runtime = chrome.runtime; + + /** + * 웨일 사이드바 API. + * Manifest: "sidebar_action": {...} + * @since whale + */ + export namespace sidebarAction { + export interface SidebarShowDetail { + /** Optional. 사이드바 영역에 표시할 페이지 URL. 지정하지 않으면 매니페스트에 정의한 default_page. */ + url?: string; + /** + * Optional. url 인자와 현재 URL이 같을 때에도 페이지를 새로고침 할 것인지 여부. + * @default false + */ + reload?: boolean; + } + + export interface SidebarTitleDetail { + title: string; + } + + export interface SidebarIconDetail { + /** + * 아이콘 이미지 데이터입니다. @see https://developer.chrome.com/extensions/pageAction#type-ImageDataType + * */ + icon: ImageData; + } + + export interface SidebarPageDetail { + /** html 파일의 리소스 경로. 빈 문자열(‘’)로 설정하면 사이드바에 빈화면이 보입니다. */ + page: string; + } + + export interface SidebarBadgeDetail { + /** 설정할 badge 문자열 */ + text: string; + } + + export interface SidebarDockDetail { + /** 부모 윈도우의 ID. 지정하지 않으면 마지막 사용된 윈도우에 도킹합니다. */ + targetWindowId?: number; + } + + export interface BadgeBackgroundColorDetails { + /** 색상값 배열([255, 0, 0, 255]) 혹은 HEX 색상 표현 문자열(#FF0000). */ + color: string | ColorArray; + } + export type ColorArray = [number, number, number, number]; + + export interface BrowserClickedEvent + extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> {} + + /** + * 지정한 윈도우에 사이드바 영역을 열고 포커스를 주는 메소드입니다. 이미 사이드바가 열려있다면 포커스만 옮겨줍니다. + * + * @param windowId Optional. 대상 윈도우의 ID. + * @param details Optional. url 설정 + * @param callback Optional. 콜백 함수. 인자값으로 windowId가 넘어감 + */ + export function show( + windowId: number, + details?: SidebarShowDetail, + callback?: (windowId: number) => void + ): void; + + /** + * 현재 윈도우에 사이드바 영역을 열고 포커스를 주는 메소드입니다. 이미 사이드바가 열려있다면 포커스만 옮겨줍니다. + * + * @param details Optional. url 설정 + * @param callback Optional. 콜백 함수. 인자값으로 windowId가 넘어감 + */ + export function show( + details: SidebarShowDetail, + callback?: (windowId: number) => void + ): void; + + /** + * 현재 윈도우에 사이드바 영역을 열고 포커스를 주는 메소드입니다. 이미 사이드바가 열려있다면 포커스만 옮겨줍니다. + * + * @param callback Optional. 콜백 함수. 인자값으로 windowId가 넘어감 + */ + export function show(callback: (windowId: number) => void): void; + + /** + * 현재 윈도우에 사이드바 영역을 열고 포커스를 주는 메소드입니다. 이미 사이드바가 열려있다면 포커스만 옮겨줍니다. + * + */ + export function show(): void; + + /** + * 지정된 윈도우의 사이드바를 닫습니다. 현재 확장앱에 포커스가 있는 상황에만 동작합니다. + * @param windowId Optional. 대상 윈도우의 ID. 지정하지 않으면 현재 윈도우. + * @param callback Optional. 콜백 함수. 인자값으로 windowId가 넘어감 + */ + export function hide( + windowId: number, + callback?: (windowId: number) => void + ): void; + + /** + * 현재 윈도우의 사이드바를 닫습니다. 현재 확장앱에 포커스가 있는 상황에만 동작합니다. + * @param callback Optional. 콜백 함수. 인자값으로 windowId가 넘어감 + */ + export function hide(callback: (windowId: number) => void): void; + + /** + * 현재 윈도우의 사이드바를 닫습니다. 현재 확장앱에 포커스가 있는 상황에만 동작합니다. + */ + export function hide(): void; + + /** + * 확장앱 아이콘에 마우스를 올렸을 때 나타나는 툴팁 문자열을 변경합니다. + * sidebar_action 에서 default_title 속성으로 지정하는 영역입니다. + * 열려 있는 모든 윈도우에 동시 적용됩니다. + * @param details 설정 할 데이터 + */ + export function setTitle(details: SidebarTitleDetail): void; + + /** + * 확장앱 아이콘에 마우스를 올렸을 때 나타나는 툴팁 문자열을 반환합니다. + * sidebar_action 에서 default_title 속성으로 지정한 영역입니다. + * @param callback title을 담은 결과를 인자값으로 넣은 콜백 함수 + */ + export function getTitle(callback: (result: string) => void): void; + + /** + * 확장앱 아이콘을 동적으로 변경합니다. 열려 있는 모든 윈도우에 동시 적용됩니다. + * @param details 아이콘 데이터 + */ + export function setIcon(details: SidebarIconDetail): void; + + /** + * 확장앱 아이콘이 클릭되었을 때, 로딩되는 페이지 리소스의 경로를 변경합니다. + * @param details 페이지 상세 정보 + */ + export function setPage(details: SidebarPageDetail): void; + + /** + * 사이드바 확장앱 아이콘이 클릭되었을 때, 로딩되는 페이지 리소스의 경로를 반환합니다. + * @param callback 현재 page 경로를 인자값으로 넣은 콜백 함수 + */ + export function getPage(callback: (result: string) => void): void; + + /** + * 확장앱 아이콘 위에 표시되는 뱃지의 문자열을 변경합니다. 열려 있는 모든 윈도우에 동시 적용됩니다. + * @param details badge 정보 + */ + export function setBadgeText(details: SidebarBadgeDetail): void; + + /** + * 사이드바 확장앱 아이콘 위에 표시되는 뱃지의 문자열을 반환합니다. + * @param callback 현재 뱃지 텍스트를 인자값으로 넣은 콜백 함수. + */ + export function getBadgeText(callback: (result: string) => void): void; + + /** + * 확장앱 아이콘 위에 표시되는 뱃지의 배경 색상을 변경합니다. 열려 있는 모든 윈도우에 동시 적용됩니다. + * @param details 뱃지 배경 색상을 담은 객체 + */ + export function setBadgeBackgroundColor( + details: BadgeBackgroundColorDetails + ): void; + + /** + * 확장앱 아이콘 위에 표시되는 뱃지의 배경색상을 반환합니다. + * @param callback 뱃지 배경 색상. RGBA 색상값 배열 [R, G, B, A]를 담은 인자값으로 넣은 콜백 함수. + */ + export function getBadgeBackgroundColor( + callback: (color: ColorArray) => void + ): void; + + /** + * 팝업 윈도우를 사이드바에 도킹합니다. details를 통해 도킹하고자 하는 부모 윈도우를 지정할 수 있습니다. + * 도킹 후에는 팝업 윈도우의 ID는 더 이상 유효하지 않습니다. + * @param popupWindowId 팝업 윈도우의 ID. + * @param details Optional. 부모 윈도우의 ID를 담은 객체 + * @param callback 도킹 된 windowId를 인자값으로 넣은 콜백 함수. + */ + export function dock( + popupWindowId: number, + details: SidebarDockDetail, + callback: (windowId: number) => void + ): void; + + /** + * 팝업 윈도우를 사이드바에 도킹합니다. details를 통해 도킹하고자 하는 부모 윈도우를 지정할 수 있습니다. + * 도킹 후에는 팝업 윈도우의 ID는 더 이상 유효하지 않습니다. + * @param popupWindowId 팝업 윈도우의 ID. + * @param callback 도킹 된 windowId를 인자값으로 넣은 콜백 함수. + */ + export function dock( + popupWindowId: number, + callback: (windowId: number) => void + ): void; + + /** + * 도킹된 윈도우를 부모 윈도우에서 떼어냅니다. + * @param popupWindowId 부모 윈도우의 ID + * @param callback 새로 부여된 윈도우 Id를 인자값으로 넣은 콜백 함수. + * 여기서 windowId는 `whale.sidebarAction.dock()`으로 붙일 때 사용했던 윈도우 ID와는 다르다. + */ + export function undock( + popupWindowId: number, + callback: (windowId: number) => void + ): void; + + /** + * 사이드바 확장앱 아이콘이 클릭될 때 발생하는 이벤트 핸들러 + */ + export var onClicked: BrowserClickedEvent; + } + + /** + * 데이터 저장소 기능을 제공합니다. 데이터 변경시 이벤트를 수신할 수 있습니다. 이 API를 이용해 저장한 데이터는 쿠키, 웹 스토리지 등 인터넷 사용 기록과는 별도로 관리됩니다. + * 권한: "storage" + * @since Chrome 20. + */ + export import storage = chrome.storage; + + export namespace system { + /** + * 시스템 CPU 관련 정보를 얻을 수 있습니다. + * 권한: "system.cpu" + * @since Chrome 32. + */ + export import cpu = chrome.system.cpu; + + /** + * 시스템 메모리 관련 정보를 얻을 수 있습니다. + * 권한: "system.memory" + * @since Chrome 32. + */ + export import memory = chrome.system.memory; + + /** + * 시스템 연결된 이동식 저장매체에 대한 정보를 얻을 수 있습니다. 새로운 이동식 저장매체가 연결되거나, 이미 연결되어 있던 매체가 연결 해제되는 경우 이벤트를 수신할 수 있습니다. + * Permissions: "system.storage" + * @since Chrome 30. + */ + export import storage = chrome.system.storage; + } + + /** + * 지정한 탭의 미디어 스트림을 캡쳐할 수 있습니다 + * 권한: "tabCapture" + * @since Chrome 31. + */ + export import tabCapture = chrome.tabCapture; + + /** + * 새로운 탭을 생성하거나 이미 생성된 탭을 제어할 수 있습니다. + * @since Chrome 5. + */ + export import tabs = chrome.tabs; + + /** + * 새 탭 페이지의 "자주 가는 사이트" 목록을 얻거나 수정, 검색 할 수 있습니다. + * Whale에서 더 많은 기능을 지원합니다. + * 권한: "topSites" + * @since Chrome 19. + * + */ + export namespace topSites { + /** 많이 방문한 URL을 저장하는 Object입니다. get에서 사용됩니다. */ + export interface MostVisitedURL { + /** 많이 방문한 url. */ + url: string; + /** 페이지 제목 */ + title: string; + /** + * 방문기록에서 판단한 여부입니다. + * api로 추가한 경우에는 false입니다. + */ + from_history: boolean; + } + + /** 많이 방문한 URL을 저장하는 Object입니다. search에서 사용됩니다. */ + export interface MostVisitedURL2 { + /** 많이 방문한 url. */ + url: string; + /** 페이지 제목 */ + title: string; + } + + /** + * 자주 가는 사이트를 전부 리스트로 담아옵니다. + * @param callback 결과를 콜백함수의 인자값으로 보냅니다. + */ + export function get(callback: (data: MostVisitedURL[]) => void): void; + + /** + * 자주 가는 사이트에 url과 title을 추가합니다. + * @param url 추가할 url + * @param title 제목 + * @param callback 상태를 콜백 함수의 인자값으로 보냅니다. 성공시 true, 실패시 false + */ + export function add( + url: string, + title: string, + callback?: (status: boolean) => void + ): void; + + /** + * 자주 가는 사이트에서 해당 url을 삭제합니다. + * @param url 삭제할 url + */ + var _delete: (url: string) => void; + export { _delete as delete }; + + /** + * 자주 가는 사이트에서 해당 url을 숨깁니다. + * @param url block할 url + */ + export function block(url: string): void; + + /** + * 자주 가는 사이트에서 숨겨진 url을 보이게 합니다. + * @param url block을 풀 url + */ + export function unblock(url: string): void; + + /** + * 자주 가는 사이트에 block당한 여부를 확인합니다. + * @param url 확인할 uri + * @param callback block 여부를 콜백함수의 인자값으로 보냅니다. + */ + export function isBlocked( + url: string, + callback: (status: boolean) => void + ): void; + + /** + * 방문기록에서 자주 가는 사이트 순으로 검색을 합니다. + * @param term 검색할 키워드 + * @param count 검색할 개수. + * @param callback 결과 리스트를 함수의 인자값으로 보냅니다. + */ + export function search( + term: string, + count: number, + callback?: (result: MostVisitedURL2[]) => void + ): void; + + /** + * 자주 가는 사이트에 해당 배열을 추가합니다. + * 만약 다시 update를 실행하면 기존에 update에 존재하는 배열은 삭제됩니다. + * @param urls url, title로 구성된 Object Array + */ + export function update(urls: MostVisitedURL2[]); + } + + /** + * text-to-speech를 사용할 수 있는 api입니다. + * 권한: "tts" + * @since Chrome 14. + */ + export import tts = chrome.tts; + + /** + * text-to-speech를 사용할 수 있는 api입니다. + * 권한: "tts" + * @since Chrome 14. + */ + export import ttsEngine = chrome.ttsEngine; + + /** + * Whale API의 type 정보를 얻을 수 있습니다. + * @since Chrome 13. + */ + export import types = chrome.types; + + /** + * 웹 탐색 요청을 수신하여 제어할 수 있습니다. + * 권한: "webNavigation" + * @since Chrome 16. + */ + export import webNavigation = chrome.webNavigation; + + /** + * 웹 요청을 감지하여 차단, 수정 및 간섭할 수 있습니다. + * 권한: "webRequest", host 권한 + * @since Chrome 17. + */ + export import webRequest = chrome.webRequest; + + /** + * 새로운 창을 생성하거나 이미 생성된 창을 제어할 수 있습니다. + * 아무런 권한이 없어도 되지만, Tab권한이 있어야 favocon, uri, title의 정보를 불러올 수 있다. + * @since Chrome 5. + */ + export import windows = chrome.windows; +} diff --git a/types/naver-whale/test/index.ts b/types/naver-whale/test/index.ts new file mode 100644 index 0000000000..8219faf18f --- /dev/null +++ b/types/naver-whale/test/index.ts @@ -0,0 +1,258 @@ +// https://developers.whale.naver.com/tutorials/browserAction/ +function ToolBarExample() { + whale.browserAction.onClicked.addListener(() => { + whale.tabs.create({ + url: `http://news.naver.com/` + }); + }); +} + +// https://developers.whale.naver.com/tutorials/messagePassing/ +function MessageExample() { + // background + whale.runtime.onMessage.addListener((message, sender, sendResponse) => { + if (message === `How are you?`) { + sendResponse(`I'm fine thank you and you?`); + } + }); + + // contentScript + for (let i = 0; i < 100; i++) { + console.log(`How are you?`); + whale.runtime.sendMessage(`How are you?`, response => { + console.log(response); // = I'm fine thank you and you? + }); + } + + // connect + const port = whale.runtime.connect({ name: `greetings` }); + + port.onMessage.addListener(message => { + console.log(message); + }); + + for (let i = 0; i < 100; i++) { + console.log(`How are you?`); + port.postMessage(`How are you?`); + } + + whale.runtime.onConnect.addListener(port => { + if (port.name === `greetings`) { + port.onMessage.addListener(message => { + if (message === `How are you?`) { + port.postMessage(`I'm fine thank you and you?`); + } + }); + } + }); + whale.sidebarAction.show(() => { + whale.runtime.sendMessage(`Hello Sidebar!`); + }); + + window.addEventListener(`DOMContentLoaded`, () => { + // 이 구문이 실행되기 전 이미 contentScript.js 의 sendMessage() 가 끝난 상태. + // 그러므로 sidebarAction.show() 의 콜백에서 보내는 메시지는 이곳에 도달하지 않습니다. + whale.runtime.onMessage.addListener(message => { + console.log(message); + }); + }); +} + +function StorageExample() { + window.addEventListener(`DOMContentLoaded`, () => { + // 처음 로딩 될 때: 메시지가 있는지 확인하고 삭제 + whale.storage.local.get(`message`, storage => { + console.log(storage.message); // = Hello + whale.storage.local.remove(`message`); + }); + + // 로딩 이후의 변화 대응 + whale.storage.onChanged.addListener((changes, areaName) => { + if (areaName === `local` && changes.message) { + console.log(changes.message.newValue); + } + }); + }); +} + +// https://developers.whale.naver.com/tutorials/sidebarAction/ +function SidebarExample() { + whale.sidebarAction.onClicked.addListener(result => { + // result.opened: 사이드바가 열렸는지 닫혔는지를 알려주는 boolean 값. 열렸으면 true. + }); + + whale.sidebarAction.setTitle({ + title: `새 제목` + }); + + whale.sidebarAction.setBadgeText({ + text: `5` + }); + + whale.sidebarAction.setBadgeBackgroundColor({ + color: `#ff0000` // RGBA 색상값 배열([255, 0, 0, 255]) 혹은 HEX 색상 표현 문자열(#FF0000). + }); +} + +// https://developers.whale.naver.com/tutorials/sidebarAdvance/ +function SidebarExample2() { + whale.sidebarAction.show({ url: `http://MYWEBSITE.com` }); + whale.sidebarAction.show({ + url: whale.runtime.getURL(`index.html`) + }); +} + +// https://developers.whale.naver.com/tutorials/downloads/ +function DownloadExample() { + whale.downloads.download({ + url: `http://example.org/example.zip` + }); + + whale.downloads.download( + { + url: `http://example.org/example.zip`, + filename: `download.zip`, + saveAs: true + }, + downloadId => { + // 만약 'downloadId' 가 undefined 라면 오류가 발생했다는 뜻입니다. + // 그러므로 이후의 과정을 진행하기 전에 오류 여부를 확인해야 합니다. + if (typeof downloadId !== `undefined`) { + console.log(`다운로드가 시작되었습니다. (ID: ${downloadId})`); + } + } + ); + + whale.downloads.search( + { + orderBy: ["-startTime"], + limit: 5 + }, + downloadedItems => { + downloadedItems.forEach(item => { + console.log(` + id: ${item.id} + filename: ${item.filename} + startedAt: ${new Date(item.startTime).toLocaleString()} + `); + }); + } + ); + + whale.downloads.onCreated.addListener(evt => { + console.log(` + 다운로드가 시작되었습니다. + - ID: ${evt.id} + - URL: ${evt.url} + - fileSize: ${evt.fileSize} + `); + }); + + whale.downloads.onChanged.addListener(({ id, state }) => { + if (typeof state === `undefined`) { + return; + } + + switch (state.current) { + case whale.downloads.State.COMPLETE: + console.log(`다운로드가 완료되었습니다. (ID: ${id})`); + break; + + case whale.downloads.State.INTERRUPTED: + console.log(`다운로드가 중단되었습니다. (ID: ${id})`); + break; + } + }); +} + +// https://developers.whale.naver.com/tutorials/bookmarks/ +function BookmarkExample() { + whale.bookmarks.getTree(function(bmTree) { + bmTree.forEach(function(node) {}); + }); +} +whale.browserAction.onClicked.addListener(function() { + whale.bookmarks.create( + { + title: `네이버 웨일`, + parentId: `1` + }, + function(newEntry) { + whale.bookmarks.create({ + title: "웨일 홈", + url: "http://whale.naver.com/", + parentId: newEntry.id + }); + + whale.bookmarks.create({ + title: "웨일 연구소", + url: "http://lab.whale.naver.com", + parentId: newEntry.id + }); + + console.log("New Entry Added"); + } + ); +}); + +// https://developers.whale.naver.com/tutorials/commands/ +whale.commands.onCommand.addListener(function(command) { + if (command === `test`) { + alert("컨트롤 쉬프트 제이를 누르셨군요!"); + } +}); + +whale.commands.onCommand.addListener(function(command) { + if (command === `open-popup`) { + whale.browserAction.setPopup({ + popup: whale.runtime.getManifest().browser_action!.default_popup! + }); + } +}); + +// https://developers.whale.naver.com/tutorials/history/ +var count = 0; + +whale.browserAction.onClicked.addListener(function(tab) { + whale.history.getVisits( + { + url: tab.url! + }, + function(visitItem) { + count = visitItem.length; + + whale.browserAction.setBadgeBackgroundColor({ + color: `#ff0000` + }); + + whale.browserAction.setBadgeText({ + text: `${count}` + }); + + console.log(`The user has visited ${tab.url} ${count} times`); + } + ); +}); + +whale.browserAction.onClicked.addListener(function(tab) { + whale.history.deleteUrl({ + url: tab.url! + }); +}); + +// https://developers.whale.naver.com/tutorials/contextMenu/ +whale.contextMenus.create({ + title: `%s 검색하기`, + contexts: [`selection`], + onclick: () => {} +}); + +function searchText(info) { + const myQuery = encodeURI( + `https://search.naver.com/search.naver?query=${info.selectionText}` + ); + + whale.tabs.create({ + url: myQuery + }); +} diff --git a/types/naver-whale/tsconfig.json b/types/naver-whale/tsconfig.json new file mode 100644 index 0000000000..7efc1e4818 --- /dev/null +++ b/types/naver-whale/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": false, + "noImplicitThis": false, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "test/index.ts"] +} diff --git a/types/naver-whale/tslint.json b/types/naver-whale/tslint.json new file mode 100644 index 0000000000..6c7fd03ccd --- /dev/null +++ b/types/naver-whale/tslint.json @@ -0,0 +1,81 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "npm-naming": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-angle-bracket-type-assertion": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} diff --git a/types/node-downloader-helper/index.d.ts b/types/node-downloader-helper/index.d.ts new file mode 100644 index 0000000000..767575cd72 --- /dev/null +++ b/types/node-downloader-helper/index.d.ts @@ -0,0 +1,54 @@ +// Type definitions for node-downloader-helper 1.0 +// Project: https://github.com/hgouveia/node-downloader-helper +// Definitions by: Rémy Jeancolas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +import { EventEmitter } from 'events'; +import { RequestOptions as HttpRequestOptions, OutgoingHttpHeaders } from 'http'; +import { RequestOptions as HttpsRequestOptions } from 'https'; + +export interface Options { + method?: string; // Request Method Verb + headers?: OutgoingHttpHeaders; // Custom HTTP Header ex: Authorization, User-Agent + fileName?: string; // Custom filename when saved + forceResume?: boolean; // If the server does not return the "accept-ranges" header, can be force if it does support it + override?: boolean; // if true it will override the file, otherwise will append '(number)' to the end of file + httpRequestOptions?: HttpRequestOptions; // Override the http request options + httpsRequestOptions?: HttpsRequestOptions; // Override the https request options, ex: to add SSL Certs +} + +export interface Stats { + total: number; // total size that needs to be downloaded in bytes + downloaded: number; // downloaded size in bytes + progress: number; // progress porcentage 0-100% + speed: number; // download speed in bytes +} + +export enum DH_STATES { + IDLE = 'IDLE', + STARTED = 'STARTED', + DOWNLOADING = 'DOWNLOADING', + PAUSED = 'PAUSED', + RESUMED = 'RESUMED', + STOPPED = 'STOPPED', + FINISHED = 'FINISHED', + FAILED = 'FAILED' +} + +export interface DownloaderHelper { + on(event: 'start' | 'download' | 'end' | 'pause' | 'resume' | 'stop' | string, callback: () => void): this; + on(event: 'progress', callback: (stats: Stats) => void): this; + on(event: 'error', callback: (error: Error) => void): this; + on(event: 'stateChanged', callback: (state: DH_STATES) => void): this; +} + +export class DownloaderHelper extends EventEmitter { + constructor(url: string, destFolder: string, options?: Options); + start(): Promise; + pause(): Promise; + resume(): Promise; + stop(): Promise; +} diff --git a/types/node-downloader-helper/node-downloader-helper-tests.ts b/types/node-downloader-helper/node-downloader-helper-tests.ts new file mode 100644 index 0000000000..6a9e5bebd9 --- /dev/null +++ b/types/node-downloader-helper/node-downloader-helper-tests.ts @@ -0,0 +1,41 @@ +import { DownloaderHelper } from 'node-downloader-helper'; + +let paused = false; +const dl = new DownloaderHelper('http://example.com', __dirname); + +dl.on('start', () => { + console.log('Download started'); + + if (!paused) { + paused = true; + dl.pause(); + } +}); +dl.on('download', () => { + console.log('Downloading'); +}); +dl.on('progress', (stats) => { + console.log(`${stats.progress}% downloaded`); +}); +dl.on('end', () => { + console.log('Download finished'); +}); +dl.on('error', (err) => { + console.error(err); +}); +dl.on('pause', () => { + console.log('Download paused'); + dl.resume(); +}); +dl.on('resume', () => { + console.log('Download resumed'); + dl.stop(); +}); +dl.on('stop', () => { + console.log('Download stopped'); +}); +dl.on('stateChanged', (state) => { + console.log(`State changed: ${state}`); +}); + +dl.start().catch(e => console.error(e)); diff --git a/types/node-downloader-helper/tsconfig.json b/types/node-downloader-helper/tsconfig.json new file mode 100644 index 0000000000..841909c25c --- /dev/null +++ b/types/node-downloader-helper/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", + "node-downloader-helper-tests.ts" + ] +} diff --git a/types/node-downloader-helper/tslint.json b/types/node-downloader-helper/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/node-downloader-helper/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/node/child_process.d.ts b/types/node/child_process.d.ts index d1e14df580..53ea5fc9e4 100644 --- a/types/node/child_process.d.ts +++ b/types/node/child_process.d.ts @@ -19,9 +19,9 @@ declare module "child_process" { readonly pid: number; readonly connected: boolean; kill(signal?: string): void; - send(message: any, callback?: (error: Error) => void): boolean; - send(message: any, sendHandle?: net.Socket | net.Server, callback?: (error: Error) => void): boolean; - send(message: any, sendHandle?: net.Socket | net.Server, options?: MessageOptions, callback?: (error: Error) => void): boolean; + send(message: any, callback?: (error: Error | null) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, callback?: (error: Error | null) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, options?: MessageOptions, callback?: (error: Error | null) => void): boolean; disconnect(): void; unref(): void; ref(): void; diff --git a/types/node/cluster.d.ts b/types/node/cluster.d.ts index fae80659d8..43340ff800 100644 --- a/types/node/cluster.d.ts +++ b/types/node/cluster.d.ts @@ -24,7 +24,7 @@ declare module "cluster" { class Worker extends events.EventEmitter { id: number; process: child.ChildProcess; - send(message: any, sendHandle?: any, callback?: (error: Error) => void): boolean; + send(message: any, sendHandle?: any, callback?: (error: Error | null) => void): boolean; kill(signal?: string): void; destroy(signal?: string): void; disconnect(): void; diff --git a/types/node/globals.d.ts b/types/node/globals.d.ts index 6209f9b83e..15007121a1 100644 --- a/types/node/globals.d.ts +++ b/types/node/globals.d.ts @@ -603,8 +603,7 @@ declare namespace NodeJS { isPaused(): boolean; pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: WritableStream): this; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; + unshift(chunk: string | Buffer | Uint8Array): void; wrap(oldStream: ReadableStream): this; [Symbol.asyncIterator](): AsyncIterableIterator; } @@ -892,7 +891,7 @@ declare namespace NodeJS { domain: Domain; // Worker - send?(message: any, sendHandle?: any): void; + send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean}, callback?: (error: Error | null) => void): boolean; disconnect(): void; connected: boolean; diff --git a/types/node/http2.d.ts b/types/node/http2.d.ts index 9b3fd295aa..5ebe11a5e4 100644 --- a/types/node/http2.d.ts +++ b/types/node/http2.d.ts @@ -6,7 +6,7 @@ declare module "http2" { import * as tls from "tls"; import * as url from "url"; - import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders } from "http"; + import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders, IncomingMessage, ServerResponse } from "http"; export { OutgoingHttpHeaders } from "http"; export interface IncomingHttpStatusHeader { @@ -32,8 +32,8 @@ declare module "http2" { export interface StreamState { localWindowSize?: number; state?: number; - streamLocalClose?: number; - streamRemoteClose?: number; + localClose?: number; + remoteClose?: number; sumDependencyWeight?: number; weight?: number; } @@ -50,7 +50,7 @@ declare module "http2" { export interface ServerStreamFileResponseOptions { statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean; - getTrailers?: (trailers: OutgoingHttpHeaders) => void; + waitForTrailers?: boolean; offset?: number; length?: number; } @@ -59,10 +59,18 @@ declare module "http2" { onError?: (err: NodeJS.ErrnoException) => void; } - export interface Http2Stream extends stream.Duplex { + export class Http2Stream extends stream.Duplex { + protected constructor(); + readonly aborted: boolean; + readonly bufferSize: number; readonly closed: boolean; readonly destroyed: boolean; + /** + * Set the true if the END_STREAM flag was set in the request or response HEADERS frame received, + * indicating that no additional data should be received and the readable side of the Http2Stream will be closed. + */ + readonly endAfterHeaders: boolean; readonly pending: boolean; readonly rstCode: number; readonly sentHeaders: OutgoingHttpHeaders; @@ -70,16 +78,12 @@ declare module "http2" { readonly sentTrailers?: OutgoingHttpHeaders; readonly session: Http2Session; readonly state: StreamState; - /** - * Set the true if the END_STREAM flag was set in the request or response HEADERS frame received, - * indicating that no additional data should be received and the readable side of the Http2Stream will be closed. - */ - readonly endAfterHeaders: boolean; + close(code?: number, callback?: () => void): void; priority(options: StreamPriorityOptions): void; setTimeout(msecs: number, callback?: () => void): void; + sendTrailers(headers: OutgoingHttpHeaders): void; - addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "aborted", listener: () => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "data", listener: (chunk: Buffer | string) => void): this; @@ -94,8 +98,8 @@ declare module "http2" { addListener(event: "timeout", listener: () => void): this; addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; emit(event: "aborted"): boolean; emit(event: "close"): boolean; emit(event: "data", chunk: Buffer | string): boolean; @@ -110,8 +114,8 @@ declare module "http2" { emit(event: "timeout"): boolean; emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; - on(event: string, listener: (...args: any[]) => void): this; on(event: "aborted", listener: () => void): this; on(event: "close", listener: () => void): this; on(event: "data", listener: (chunk: Buffer | string) => void): this; @@ -126,8 +130,8 @@ declare module "http2" { on(event: "timeout", listener: () => void): this; on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; once(event: "aborted", listener: () => void): this; once(event: "close", listener: () => void): this; once(event: "data", listener: (chunk: Buffer | string) => void): this; @@ -142,8 +146,8 @@ declare module "http2" { once(event: "timeout", listener: () => void): this; once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "aborted", listener: () => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; @@ -158,8 +162,8 @@ declare module "http2" { prependListener(event: "timeout", listener: () => void): this; prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "aborted", listener: () => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; @@ -174,43 +178,52 @@ declare module "http2" { prependOnceListener(event: "timeout", listener: () => void): this; prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; prependOnceListener(event: "wantTrailers", listener: () => void): this; - - sendTrailers(headers: OutgoingHttpHeaders): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } - export interface ClientHttp2Stream extends Http2Stream { - addListener(event: string, listener: (...args: any[]) => void): this; + export class ClientHttp2Stream extends Http2Stream { + private constructor(); + + addListener(event: "continue", listener: () => {}): this; addListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; addListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "continue"): boolean; emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; - on(event: string, listener: (...args: any[]) => void): this; + on(event: "continue", listener: () => {}): this; on(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; on(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; + once(event: "continue", listener: () => {}): this; once(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; once(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "continue", listener: () => {}): this; prependListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; prependListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "continue", listener: () => {}): this; prependOnceListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; prependOnceListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } - export interface ServerHttp2Stream extends Http2Stream { + export class ServerHttp2Stream extends Http2Stream { + private constructor(); + additionalHeaders(headers: OutgoingHttpHeaders): void; readonly headersSent: boolean; readonly pushAllowed: boolean; @@ -230,6 +243,7 @@ declare module "http2" { maxFrameSize?: number; maxConcurrentStreams?: number; maxHeaderListSize?: number; + enableConnectProtocol?: boolean; } export interface ClientSessionRequestOptions { @@ -237,7 +251,7 @@ declare module "http2" { exclusive?: boolean; parent?: number; weight?: number; - getTrailers?: (trailers: OutgoingHttpHeaders, flags: number) => void; + waitForTrailers?: boolean; } export interface SessionState { @@ -252,7 +266,9 @@ declare module "http2" { inflateDynamicTableSize?: number; } - export interface Http2Session extends events.EventEmitter { + export class Http2Session extends events.EventEmitter { + protected constructor(); + readonly alpnProtocol?: string; close(callback?: () => void): void; readonly closed: boolean; @@ -268,148 +284,159 @@ declare module "http2" { ping(payload: Buffer | DataView | NodeJS.TypedArray , callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; ref(): void; readonly remoteSettings: Settings; - rstStream(stream: Http2Stream, code?: number): void; setTimeout(msecs: number, callback?: () => void): void; readonly socket: net.Socket | tls.TLSSocket; readonly state: SessionState; - priority(stream: Http2Stream, options: StreamPriorityOptions): void; settings(settings: Settings): void; readonly type: number; unref(): void; - addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; addListener(event: "timeout", listener: () => void): this; - addListener(event: "ping", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; emit(event: "close"): boolean; emit(event: "error", err: Error): boolean; emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; emit(event: "remoteSettings", settings: Settings): boolean; emit(event: "timeout"): boolean; - emit(event: "ping"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; - on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; on(event: "remoteSettings", listener: (settings: Settings) => void): this; on(event: "timeout", listener: () => void): this; - on(event: "ping", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; once(event: "remoteSettings", listener: (settings: Settings) => void): this; once(event: "timeout", listener: () => void): this; - once(event: "ping", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; prependListener(event: "timeout", listener: () => void): this; - prependListener(event: "ping", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } - export interface ClientHttp2Session extends Http2Session { + export class ClientHttp2Session extends Http2Session { + private constructor(); + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; - addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: string[]): boolean; emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; - on(event: string, listener: (...args: any[]) => void): this; on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } export interface AlternativeServiceOptions { origin: number | string | url.URL; } - export interface ServerHttp2Session extends Http2Session { + export class ServerHttp2Session extends Http2Session { + private constructor(); + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + origin(...args: Array): void; readonly server: Http2Server | Http2SecureServer; - addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; - on(event: string, listener: (...args: any[]) => void): this; on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; once(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } // Http2Server export interface SessionOptions { maxDeflateDynamicTableSize?: number; - maxReservedRemoteStreams?: number; + maxSessionMemory?: number; + maxHeaderListPairs?: number; + maxOutstandingPings?: number; maxSendHeaderBlockLength?: number; paddingStrategy?: number; peerMaxConcurrentStreams?: number; @@ -418,8 +445,17 @@ declare module "http2" { createConnection?: (authority: url.URL, option: SessionOptions) => stream.Duplex; } - export type ClientSessionOptions = SessionOptions; - export type ServerSessionOptions = SessionOptions; + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number; + createConnection?: (authority: url.URL, option: SessionOptions) => stream.Duplex; + } + + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage; + Http1ServerResponse?: typeof ServerResponse; + Http2ServerRequest?: typeof Http2ServerRequest; + Http2ServerResponse?: typeof Http2ServerResponse; + } export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { } export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { } @@ -428,141 +464,199 @@ declare module "http2" { export interface SecureServerOptions extends SecureServerSessionOptions { allowHTTP1?: boolean; + origins?: string[]; } - export interface Http2Server extends net.Server { - addListener(event: string, listener: (...args: any[]) => void): this; + export class Http2Server extends net.Server { + private constructor(); + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; addListener(event: "sessionError", listener: (err: Error) => void): this; addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; emit(event: "sessionError", err: Error): boolean; emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; - on(event: string, listener: (...args: any[]) => void): this; on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; on(event: "sessionError", listener: (err: Error) => void): this; on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; once(event: "sessionError", listener: (err: Error) => void): this; once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; prependListener(event: "sessionError", listener: (err: Error) => void): this; prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + setTimeout(msec?: number, callback?: () => void): this; } - export interface Http2SecureServer extends tls.Server { - addListener(event: string, listener: (...args: any[]) => void): this; + export class Http2SecureServer extends tls.Server { + private constructor(); + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; addListener(event: "sessionError", listener: (err: Error) => void): this; addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; addListener(event: "timeout", listener: () => void): this; addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; emit(event: "sessionError", err: Error): boolean; emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; emit(event: "timeout"): boolean; emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; - on(event: string, listener: (...args: any[]) => void): this; on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; on(event: "sessionError", listener: (err: Error) => void): this; on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; on(event: "timeout", listener: () => void): this; on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; once(event: "sessionError", listener: (err: Error) => void): this; once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; once(event: "timeout", listener: () => void): this; once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; prependListener(event: "sessionError", listener: (err: Error) => void): this; prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; prependListener(event: "timeout", listener: () => void): this; prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; prependOnceListener(event: "timeout", listener: () => void): this; prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + setTimeout(msec?: number, callback?: () => void): this; } export class Http2ServerRequest extends stream.Readable { private constructor(); - headers: IncomingHttpHeaders; - httpVersion: string; - method: string; - rawHeaders: string[]; - rawTrailers: string[]; + + readonly aborted: boolean; + readonly authority: string; + readonly headers: IncomingHttpHeaders; + readonly httpVersion: string; + readonly method: string; + readonly rawHeaders: string[]; + readonly rawTrailers: string[]; + readonly scheme: string; setTimeout(msecs: number, callback?: () => void): void; - socket: net.Socket | tls.TLSSocket; - stream: ServerHttp2Stream; - trailers: IncomingHttpHeaders; - url: string; + readonly socket: net.Socket | tls.TLSSocket; + readonly stream: ServerHttp2Stream; + readonly trailers: IncomingHttpHeaders; + readonly url: string; + + read(size?: number): Buffer | string | null; - addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; - on(event: string, listener: (...args: any[]) => void): this; on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } export class Http2ServerResponse extends stream.Stream { private constructor(); + addTrailers(trailers: OutgoingHttpHeaders): void; - connection: net.Socket | tls.TLSSocket; + readonly connection: net.Socket | tls.TLSSocket; end(callback?: () => void): void; - end(data?: string | Buffer, callback?: () => void): void; - end(data?: string | Buffer, encoding?: string, callback?: () => void): void; + end(data: string | Buffer | Uint8Array, callback?: () => void): void; + end(data: string | Buffer | Uint8Array, encoding: string, callback?: () => void): void; readonly finished: boolean; getHeader(name: string): string; getHeaderNames(): string[]; @@ -573,58 +667,64 @@ declare module "http2" { sendDate: boolean; setHeader(name: string, value: number | string | string[]): void; setTimeout(msecs: number, callback?: () => void): void; - socket: net.Socket | tls.TLSSocket; + readonly socket: net.Socket | tls.TLSSocket; statusCode: number; statusMessage: ''; - stream: ServerHttp2Stream; - write(chunk: string | Buffer, callback?: (err: Error) => void): boolean; - write(chunk: string | Buffer, encoding?: string, callback?: (err: Error) => void): boolean; + readonly stream: ServerHttp2Stream; + write(chunk: string | Buffer | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Buffer | Uint8Array, encoding: string, callback?: (err: Error) => void): boolean; writeContinue(): void; writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; - writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "drain", listener: () => void): this; addListener(event: "error", listener: (error: Error) => void): this; addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "aborted", hadError: boolean, code: number): boolean; emit(event: "close"): boolean; emit(event: "drain"): boolean; emit(event: "error", error: Error): boolean; emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; - on(event: string, listener: (...args: any[]) => void): this; - on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; on(event: "close", listener: () => void): this; on(event: "drain", listener: () => void): this; on(event: "error", listener: (error: Error) => void): this; on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; - once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; once(event: "close", listener: () => void): this; once(event: "drain", listener: () => void): this; once(event: "error", listener: (error: Error) => void): this; once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "drain", listener: () => void): this; prependListener(event: "error", listener: (error: Error) => void): this; prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "drain", listener: () => void): this; prependOnceListener(event: "error", listener: (error: Error) => void): this; prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } // Public API @@ -841,7 +941,7 @@ declare module "http2" { } export function getDefaultSettings(): Settings; - export function getPackedSettings(settings: Settings): Settings; + export function getPackedSettings(settings: Settings): Buffer; export function getUnpackedSettings(buf: Buffer | Uint8Array): Settings; export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; diff --git a/types/node/stream.d.ts b/types/node/stream.d.ts index a43d668092..d94d26022f 100644 --- a/types/node/stream.d.ts +++ b/types/node/stream.d.ts @@ -119,11 +119,11 @@ declare module "stream" { _destroy(error: Error | null, callback: (error?: Error | null) => void): void; _final(callback: (error?: Error | null) => void): void; write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; - write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: string, cb?: (error: Error | null | undefined) => void): boolean; setDefaultEncoding(encoding: string): this; end(cb?: () => void): void; end(chunk: any, cb?: () => void): void; - end(chunk: any, encoding?: string, cb?: () => void): void; + end(chunk: any, encoding: string, cb?: () => void): void; cork(): void; uncork(): void; destroy(error?: Error): void; diff --git a/types/node/test/child_process.ts b/types/node/test/child_process.ts index cf5b3e4656..ee42d55b92 100644 --- a/types/node/test/child_process.ts +++ b/types/node/test/child_process.ts @@ -69,15 +69,15 @@ async function testPromisify() { }); _boolean = cp.send(1, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send('one', (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send({ type: 'test' }, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send(1, _socket); @@ -87,15 +87,15 @@ async function testPromisify() { }, _socket); _boolean = cp.send(1, _socket, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send('one', _socket, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send({ type: 'test' }, _socket, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send(1, _socket, { @@ -113,19 +113,19 @@ async function testPromisify() { _boolean = cp.send(1, _socket, { keepOpen: true }, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send('one', _socket, { keepOpen: true }, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send({ type: 'test' }, _socket, { keepOpen: true }, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send(1, _server); @@ -135,15 +135,15 @@ async function testPromisify() { }, _server); _boolean = cp.send(1, _server, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send('one', _server, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send({ type: 'test' }, _server, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send(1, _server, { @@ -161,19 +161,19 @@ async function testPromisify() { _boolean = cp.send(1, _server, { keepOpen: true }, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send('one', _server, { keepOpen: true }, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); _boolean = cp.send({ type: 'test' }, _server, { keepOpen: true }, (error) => { - const _err: Error = error; + const _err: Error | null = error; }); const stdin: Writable | null = cp.stdio[0]; diff --git a/types/node/test/http2.ts b/types/node/test/http2.ts index c87b66a3f0..3b47929d92 100644 --- a/types/node/test/http2.ts +++ b/types/node/test/http2.ts @@ -95,16 +95,13 @@ import { URL } from 'url'; exclusive: true, parent: 0, weight: 0, - getTrailers: (trailers: OutgoingHttpHeaders) => {} + waitForTrailers: true }; (http2Session as ClientHttp2Session).request(); (http2Session as ClientHttp2Session).request(headers); (http2Session as ClientHttp2Session).request(headers, options); const stream: Http2Stream = {} as any; - http2Session.rstStream(stream); - http2Session.rstStream(stream, 0); - http2Session.setTimeout(100, () => {}); http2Session.close(() => {}); @@ -122,13 +119,6 @@ import { URL } from 'url'; inflateDynamicTableSize: 0 }; - http2Session.priority(stream, { - exclusive: true, - parent: 0, - weight: 0, - silent: true - }); - http2Session.settings(settings); http2Session.ping((err: Error | null, duration: number, payload: Buffer) => {}); @@ -150,6 +140,7 @@ import { URL } from 'url'; http2Stream.on('wantTrailers', () => {}); const aborted: boolean = http2Stream.aborted; + const bufferSize: number = http2Stream.bufferSize; const closed: boolean = http2Stream.closed; const destroyed: boolean = http2Stream.destroyed; const pending: boolean = http2Stream.pending; @@ -164,13 +155,15 @@ import { URL } from 'url'; const sesh: Http2Session = http2Stream.session; http2Stream.setTimeout(100, () => {}); + const trailers: OutgoingHttpHeaders = {}; + http2Stream.sendTrailers(trailers); let state: StreamState = http2Stream.state; state = { localWindowSize: 0, state: 0, - streamLocalClose: 0, - streamRemoteClose: 0, + localClose: 0, + remoteClose: 0, sumDependencyWeight: 0, weight: 0 }; @@ -207,7 +200,7 @@ import { URL } from 'url'; const options2: ServerStreamFileResponseOptions = { statCheck: (stats: Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => {}, - getTrailers: (trailers: OutgoingHttpHeaders) => {}, + waitForTrailers: true, offset: 0, length: 0 }; @@ -218,7 +211,7 @@ import { URL } from 'url'; const options3: ServerStreamFileResponseOptionsWithError = { onError: (err: NodeJS.ErrnoException) => {}, statCheck: (stats: Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => {}, - getTrailers: (trailers: OutgoingHttpHeaders) => {}, + waitForTrailers: true, offset: 0, length: 0 }; @@ -236,10 +229,12 @@ import { URL } from 'url'; const s2: Server = http2SecureServer; [http2Server, http2SecureServer].forEach((server) => { server.on('sessionError', (err: Error) => {}); + server.on('session', (session: ServerHttp2Session) => {}); server.on('checkContinue', (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => {}); server.on('stream', (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => {}); server.on('request', (request: Http2ServerRequest, response: Http2ServerResponse) => {}); server.on('timeout', () => {}); + server.setTimeout().setTimeout(5).setTimeout(5, () => {}); }); http2SecureServer.on('unknownProtocol', (socket: TLSSocket) => {}); @@ -251,7 +246,6 @@ import { URL } from 'url'; }; const serverOptions: ServerOptions = { maxDeflateDynamicTableSize: 0, - maxReservedRemoteStreams: 0, maxSendHeaderBlockLength: 0, paddingStrategy: 0, peerMaxConcurrentStreams: 0, @@ -265,12 +259,15 @@ import { URL } from 'url'; // Http2ServerRequest const readable: Readable = request; + const aborted: boolean = request.aborted; + const authority: string = request.authority; let incomingHeaders: IncomingHttpHeaders = request.headers; incomingHeaders = request.trailers; const httpVersion: string = request.httpVersion; let method: string = request.method; let rawHeaders: string[] = request.rawHeaders; rawHeaders = request.rawTrailers; + const scheme: string = request.scheme; let socket: Socket | TLSSocket = request.socket; let stream: ServerHttp2Stream = request.stream; const url: string = request.url; @@ -368,6 +365,7 @@ import { URL } from 'url'; serverHttp2Session.altsvc('', { origin: '' }); serverHttp2Session.altsvc('', { origin: 0 }); serverHttp2Session.altsvc('', { origin: new URL('') }); + serverHttp2Session.origin('https://example.com', new URL(''), { origin: 'https://foo.com' }); let clientHttp2Session: ClientHttp2Session; @@ -380,7 +378,7 @@ import { URL } from 'url'; clientHttp2Session.on('altsvc', (alt: string, origin: string, number: number) => {}); settings = getDefaultSettings(); - settings = getPackedSettings(settings); + const packet: Buffer = getPackedSettings(settings); settings = getUnpackedSettings(Buffer.from([])); settings = getUnpackedSettings(Uint8Array.from([])); } diff --git a/types/node/test/process.ts b/types/node/test/process.ts index 0c6865a9ad..c011ac0eeb 100644 --- a/types/node/test/process.ts +++ b/types/node/test/process.ts @@ -56,3 +56,11 @@ import { EventEmitter } from "events"; dest = report.writeReport('asdasd'); dest = report.writeReport(new Error()); } +{ + if (process.send) { + let r: boolean = process.send('aMessage'); + r = process.send({ msg: "foo"}, {}); + r = process.send({ msg: "foo"}, {}, { swallowErrors: true }); + r = process.send({ msg: "foo"}, {}, { swallowErrors: true }, (err: Error | null) => {}); + } +} diff --git a/types/nodegit/blob.d.ts b/types/nodegit/blob.d.ts index 9d7320c935..cece48a54d 100644 --- a/types/nodegit/blob.d.ts +++ b/types/nodegit/blob.d.ts @@ -10,21 +10,20 @@ export class Blob { * @param len - length of the data * @returns - return the id of the written blob */ - static createFromBuffer(repo: Repository, buffer: Buffer, len: number): Oid; + static createFromBuffer(repo: Repository, buffer: Buffer, len: number): Promise; /** - * @param id - return the id of the written blob * @param repo - repository where the blob will be written. this repository can be bare or not * @param path - file from which the blob will be created */ - static createFromDisk(id: Oid, repo: Repository, path: string): number; + static createFromDisk(repo: Repository, path: string): Promise; static createFromStream(repo: Repository, hintPath: string): Promise; /** - * @param id - return the id of the written blob * @param repo - repository where the blob will be written. this repository cannot be bare * @param relativePath - file from which the blob will be created, relative to the repository's working dir * @returns - 0 or an error code */ - static createFromWorkdir(id: Oid, repo: Repository, relativePath: string): number; + static createFromWorkdir(repo: Repository, relativePath: string): Promise; + static filteredContent(blob: Blob, as_path: string, check_for_binary_data: number): Promise; static lookup(repo: Repository, id: string | Oid | Blob): Promise; static lookupPrefix(repo: Repository, id: Oid, len: number): Promise; diff --git a/types/nodegit/tree-builder.d.ts b/types/nodegit/tree-builder.d.ts index f5a6715492..5d489beefb 100644 --- a/types/nodegit/tree-builder.d.ts +++ b/types/nodegit/tree-builder.d.ts @@ -11,5 +11,5 @@ export class Treebuilder { get(filename: string): TreeEntry; insert(filename: string, id: Oid, filemode: number): Promise; remove(filename: string): number; - write(): Oid; + write(): Promise; } diff --git a/types/nodejs-license-file/index.d.ts b/types/nodejs-license-file/index.d.ts new file mode 100644 index 0000000000..9f890e08a8 --- /dev/null +++ b/types/nodejs-license-file/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for nodejs-license-file 4.0 +// Project: https://github.com/bushev/nodejs-license-file +// Definitions by: Troy McKinnon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function parse(options: ParseOptions): License; +export function generate(options: GenerateOptions): string; +export interface License { + valid: boolean; + serial: string; + data: any; +} +export interface ParseOptions { + publicKeyPath?: string; + publicKey?: string; + licenseFilePath?: string; + licenseFile?: string; + template: string; +} +export interface GenerateOptions { + privateKeyPath?: string; + privateKey?: string; + template: string; + data: any; +} diff --git a/types/nodejs-license-file/nodejs-license-file-tests.ts b/types/nodejs-license-file/nodejs-license-file-tests.ts new file mode 100644 index 0000000000..c806d5e69b --- /dev/null +++ b/types/nodejs-license-file/nodejs-license-file-tests.ts @@ -0,0 +1,32 @@ +import * as LicenseFile from "nodejs-license-file"; + +const template: string = [ + "====BEGIN LICENSE====", + "{{&name}}", + "{{&id}}", + "{{&serial}}", + "=====END LICENSE=====", +].join("\n"); + +const generateOpts: LicenseFile.GenerateOptions = { + privateKeyPath: "private_key.pem", + template, + data: { + name: "John Doe", + id: "123456789", + }, +}; + +/** License data you can write to file. */ +const licenseString: string = LicenseFile.generate(generateOpts); + +const parseOpts: LicenseFile.ParseOptions = { + publicKeyPath: "public_key.pem", + licenseFilePath: "license", + template, +}; +/** Parsed license obj */ +const license: LicenseFile.License = LicenseFile.parse(parseOpts); + +// Access license data (e.g., "name"): +license.data.name; diff --git a/types/nodejs-license-file/tsconfig.json b/types/nodejs-license-file/tsconfig.json new file mode 100644 index 0000000000..ac1a20d729 --- /dev/null +++ b/types/nodejs-license-file/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", + "nodejs-license-file-tests.ts" + ] +} diff --git a/types/nodejs-license-file/tslint.json b/types/nodejs-license-file/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/nodejs-license-file/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/omit-empty/index.d.ts b/types/omit-empty/index.d.ts new file mode 100644 index 0000000000..bc2907726d --- /dev/null +++ b/types/omit-empty/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for omit-empty 1.0 +// Project: https://github.com/jonschlinkert/omit-empty +// Definitions by: Shubham Kanodia +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +interface OmitOptions { + omitZero?: boolean; +} + +declare function omitEmpty(obj: object, options?: OmitOptions): object; +export default omitEmpty; diff --git a/types/omit-empty/omit-empty-tests.ts b/types/omit-empty/omit-empty-tests.ts new file mode 100644 index 0000000000..5c8909604f --- /dev/null +++ b/types/omit-empty/omit-empty-tests.ts @@ -0,0 +1,4 @@ +import omitEmpty from 'omit-empty'; + +omitEmpty({ a: 1 }); // $ExpectType object +omitEmpty({ a: 0}, { omitZero: true }); // $ExpectType object diff --git a/types/omit-empty/tsconfig.json b/types/omit-empty/tsconfig.json new file mode 100644 index 0000000000..f8d525a620 --- /dev/null +++ b/types/omit-empty/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", + "omit-empty-tests.ts" + ] +} diff --git a/types/omit-empty/tslint.json b/types/omit-empty/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/omit-empty/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/open/index.d.ts b/types/open/index.d.ts index 9822824a98..7a5ba02b59 100644 --- a/types/open/index.d.ts +++ b/types/open/index.d.ts @@ -1,8 +1,50 @@ -// Type definitions for open 0.0.3 -// Project: https://github.com/jjrdn/node-open -// Definitions by: Bart van der Schoor +// Type definitions for open 6.0 +// Project: https://github.com/sindresorhus/open +// Definitions by: Shinnosuke Watanabe , +// Maxime LUCE , +// Tommy Lent , +// Florian Keller // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// -declare function open(target: string, app?: string): void; +import { ChildProcess } from 'child_process'; + +/* Note that ES6 modules cannot directly export callable functions. + * This file should be imported using the CommonJS-style: + * import x = require('open'); + */ export = open; + +/** + * Uses the command `open` on OS X, `start` on Windows and `xdg-open` on other platforms. + * + * Returns a promise for the spawned child process. You would normally not need to use this for + * anything, but it can be useful if you'd like to attach custom event listeners or perform + * other operations directly on the spawned process. + * + * @param target The thing you want to open. Can be a URL, file, or executable. + * Opens in the default app for the file type. For example, URLs open in your default + * browser. + * @param options Options to be passed to opn. + */ +declare function open(target: string, options?: Open.Options): Promise; + +declare namespace Open { + interface Options { + /** + * Wait for the opened app to exit before fulfilling the promise. + * If `false` it's fulfilled immediately when opening the app. + * On Windows you have to explicitly specify an app for it to be able to wait. + * Defaults to `false`. + */ + wait?: boolean; + + /** + * Specify the app to open the `target` with, or an array with the app and app arguments. + * The app name is platform dependent. Don't hard code it in reusable modules. + * Eg. Chrome is `google chrome` on OS X, `google-chrome` on Linux and `chrome` on Windows. + */ + app?: string | ReadonlyArray; + } +} diff --git a/types/open/open-tests.ts b/types/open/open-tests.ts index fa7701553e..c23846c10e 100644 --- a/types/open/open-tests.ts +++ b/types/open/open-tests.ts @@ -1,5 +1,8 @@ - import open = require('open'); -open('foo'); -open('foo', 'bar'); +open('foo'); // $ExpectType Promise + +open('foo', { app: 'bar' }); // $ExpectType Promise +open('foo', { app: ['bar', '--arg'] }); // $ExpectType Promise +open('foo', { app: 'bar', wait: false }); // $ExpectType Promise +open('foo', { app: ['bar', '--arg'], wait: false }); // $ExpectType Promise diff --git a/types/open/tsconfig.json b/types/open/tsconfig.json index 1395893dcb..7302e9f627 100644 --- a/types/open/tsconfig.json +++ b/types/open/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "open-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/open/tslint.json b/types/open/tslint.json index 3d59f55fda..f93cf8562a 100644 --- a/types/open/tslint.json +++ b/types/open/tslint.json @@ -1,80 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "npm-naming": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/opn/index.d.ts b/types/opn/index.d.ts deleted file mode 100644 index 2a7c5afe25..0000000000 --- a/types/opn/index.d.ts +++ /dev/null @@ -1,52 +0,0 @@ -// Type definitions for opn 5.1 -// Project: https://github.com/sindresorhus/opn -// Definitions by: Shinnosuke Watanabe , -// Maxime LUCE , -// Tommy Lent -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -import * as cp from 'child_process'; - -/* Note that ES6 modules cannot directly export callable functions. - * This file should be imported using the CommonJS-style: - * import x = require('opn'); - */ -export = opn; - -/** - * Uses the command `open` on OS X, `start` on Windows and `xdg-open` on other platforms. - * - * Returns a promise for the spawned child process. You would normally not need to use this for - * anything, but it can be useful if you'd like to attach custom event listeners or perform - * other operations directly on the spawned process. - * - * @param target The thing you want to open. Can be a URL, file, or executable. - * Opens in the default app for the file type. For example, URLs open in your default - * browser. - * @param options Options to be passed to opn. - */ -declare function opn( - target: string, - options?: Opn.Options -): Promise; - -declare namespace Opn { - interface Options { - /** - * Wait for the opened app to exit before fulfilling the promise. - * If `false` it's fulfilled immediately when opening the app. - * On Windows you have to explicitly specify an app for it to be able to wait. - * Defaults to `true`. - */ - wait?: boolean; - - /** - * Specify the app to open the `target` with, or an array with the app and app arguments. - * The app name is platform dependent. Don't hard code it in reusable modules. - * Eg. Chrome is `google chrome` on OS X, `google-chrome` on Linux and `chrome` on Windows. - */ - app?: string | ReadonlyArray; - } -} diff --git a/types/opn/opn-tests.ts b/types/opn/opn-tests.ts deleted file mode 100644 index c2956f2546..0000000000 --- a/types/opn/opn-tests.ts +++ /dev/null @@ -1,8 +0,0 @@ -import opn = require('opn'); - -opn('foo'); // $ExpectType Promise - -opn('foo', { app: 'bar' }); // $ExpectType Promise -opn('foo', { app: ['bar', '--arg'] }); // $ExpectType Promise -opn('foo', { app: 'bar', wait: false }); // $ExpectType Promise -opn('foo', { app: ['bar', '--arg'], wait: false }); // $ExpectType Promise diff --git a/types/parcel-bundler/index.d.ts b/types/parcel-bundler/index.d.ts index 230d928db1..d6db014c9d 100644 --- a/types/parcel-bundler/index.d.ts +++ b/types/parcel-bundler/index.d.ts @@ -1,12 +1,30 @@ -// Type definitions for parcel-bundler 1.10 +// Type definitions for parcel-bundler 1.12 // Project: https://github.com/parcel-bundler/parcel#readme // Definitions by: pinage404 +// Nick Woodward // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 +import * as http from 'http'; +import * as https from 'https'; import * as express from "express-serve-static-core"; declare namespace ParcelBundler { + interface HttpsOptions { + /** + * Path to custom certificate + * + * @default "./ssl/c.crt" + */ + cert?: string; + /** + * Path to custom key + * + * @default "./ssl/k.key" + */ + key?: string; + } + interface ParcelOptions { /** * The out directory to put the build files in @@ -74,20 +92,7 @@ declare namespace ParcelBundler { https?: | true | false - | { - /** - * Path to custom certificate - * - * @default "./ssl/c.crt" - */ - cert?: string; - /** - * Path to custom key - * - * @default "./ssl/k.key" - */ - key?: string; - }; + | HttpsOptions; /** * 3 = log everything, 2 = log warnings & errors, 1 = log errors * @@ -124,6 +129,27 @@ declare namespace ParcelBundler { * @default false */ detailedReport?: boolean; + + /** + * Expose modules as UMD under this name, disabled by default + */ + global?: string; + + /** + * By default, package.json dependencies are not included when using 'node' or 'electron' with the 'target' option. + * + * Set to true to add them to the bundle. + * + * @default false + */ + bundleNodeModules?: true | false; + + /** + * Enable or disable HMR while watching + * + * @default false + */ + hmr?: true | false; } type ParcelAsset = any; @@ -161,6 +187,11 @@ declare namespace ParcelBundler { * A Map of all the locations of the assets inside the bundle, used to generate accurate source maps */ offsets: Map; + + /** + * A Set of all child bundles + */ + childBundles: Set; } } @@ -177,6 +208,15 @@ declare class ParcelBundler { bundle(): Promise; middleware(): (req: express.Request, res: express.Response, next: express.NextFunction) => any; + + serve(port?: number, https?: true | false | ParcelBundler.HttpsOptions, host?: string): Promise; + + on(name: 'buildEnd', cb: () => void): void; + on(name: 'bundled', cb: (bundle: ParcelBundler.ParcelBundle) => void): void; + on(name: 'buildStart', cb: (entryPoints: string[]) => void): void; + on(name: 'buildError', cb: (error: Error) => void): void; + + off(name: 'buildEnd'| 'bundled'| 'buildStart'| 'buildError', cb: (...any: any[]) => void): void; } export = ParcelBundler; diff --git a/types/parcel-bundler/parcel-bundler-tests.ts b/types/parcel-bundler/parcel-bundler-tests.ts index 0623056c89..dbe0ecdfbb 100644 --- a/types/parcel-bundler/parcel-bundler-tests.ts +++ b/types/parcel-bundler/parcel-bundler-tests.ts @@ -6,6 +6,20 @@ const files = ["./index.d.ts"]; const bundler = new ParcelBundler(files, parcelOption); +bundler.on('buildStart', (entryPoints) => { + console.log(entryPoints); +}); + +bundler.on('bundled', (bundle) => { + console.log(bundle); +}); + +bundler.on('buildEnd', () => console.log('Parcel bundler finished!')); + +const cb = () => {}; +bundler.on('buildEnd', cb); +bundler.off('buildEnd', cb); + bundler.addAssetType('md', 'markdown-asset'); bundler.addPackager('md', 'markdown-packager'); @@ -13,3 +27,11 @@ bundler.addPackager('md', 'markdown-packager'); bundler.middleware(); bundler.bundle().then(bundle => bundle.name); + +bundler.serve(1234, false, 'localhost').then((server) => server.close()); + +const otherBundler = new ParcelBundler(['./missing.d.ts'], parcelOption); + +otherBundler.on('buildError', (error) => console.log(error)); + +otherBundler.bundle(); diff --git a/types/postman-collection/index.d.ts b/types/postman-collection/index.d.ts index 0b32209b4f..4b1b5f9af5 100644 --- a/types/postman-collection/index.d.ts +++ b/types/postman-collection/index.d.ts @@ -9,7 +9,7 @@ export interface PropertyBaseDefinition { description?: string | DescriptionDefinition; } -export class PropertyBase implements PropertyBaseDefinition { +export class PropertyBase implements PropertyBaseDefinition { description?: string | DescriptionDefinition; constructor(definition?: PropertyBaseDefinition | {info: PropertyBaseDefinition} | string); @@ -42,7 +42,7 @@ export interface PropertyDefinition extends PropertyBaseDefinition { disabled?: boolean; } -export class Property extends PropertyBase implements PropertyDefinition { +export class Property extends PropertyBase implements PropertyDefinition { disabled: boolean; id: string; name: string; diff --git a/types/prettyjson/index.d.ts b/types/prettyjson/index.d.ts index 71df6ea359..705bc6257f 100644 --- a/types/prettyjson/index.d.ts +++ b/types/prettyjson/index.d.ts @@ -3,9 +3,6 @@ // Definitions by: Wael BEN ZID EL GUEBSI // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - - /** * Defines prettyjson version */ @@ -19,7 +16,7 @@ export declare var version: string; * @param indentation {number} Indentation size. * * @return {string} pretty serialized json data ready to display. - */ + */ export declare function render(data: any, options?: RendererOptions, indentation?: number): string; /** @@ -30,16 +27,16 @@ export declare function render(data: any, options?: RendererOptions, indentation * @param indentation {number} Indentation size. * * @return {string} pretty serialized json data ready to display. - */ + */ export declare function renderString(data: string, options?: RendererOptions, indentation?: number): string; export interface RendererOptions { - /** * Define behavior for Array objects */ emptyArrayMsg?: string; // default: (empty) inlineArrays?: boolean; + noAlign?: boolean; /** * Color definition diff --git a/types/prismic-dom/index.d.ts b/types/prismic-dom/index.d.ts index 56536895f2..955ba79d04 100644 --- a/types/prismic-dom/index.d.ts +++ b/types/prismic-dom/index.d.ts @@ -1,12 +1,50 @@ -// Type definitions for prismic-dom 2.0 +// Type definitions for prismic-dom 2.1 // Project: https://github.com/prismicio/prismic-dom#readme // Definitions by: Nick Whyte // Siggy Bilstein +// Douglas Nomizo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +type ElementType = + | "heading1" + | "heading2" + | "heading3" + | "heading4" + | "heading5" + | "heading6" + | "paragraph" + | "preformatted" + | "strong" + | "em" + | "list-item" + | "o-list-item" + | "group-list-item" + | "group-o-list-item" + | "image" + | "embed" + | "hyperlink" + | "label" + | "span"; + +type Elements = {[key in ElementType]: string}; + +type HTMLSerializer = ( + type: ElementType, + element: any, + text: string | null, + children: T[], + index: number, +) => T; interface RichText { - asHtml(richText: any, linkResolver?: (doc: any) => string): string; - asText(richText: any, joinString?: string): string; + asHtml( + richText: any, + linkResolver?: (doc: any) => string, + serializer?: HTMLSerializer, + ): string; + asText(richText: any, joinString?: string): string; + Elements: Elements; } interface Link { @@ -15,6 +53,11 @@ interface Link { export const RichText: RichText; export const Link: Link; +export const HTMLSerializer: HTMLSerializer; + +declare const _default: { + RichText: RichText; + Link: Link +}; -declare const _default: { RichText: RichText, Link: Link }; export default _default; diff --git a/types/prismic-dom/prismic-dom-tests.ts b/types/prismic-dom/prismic-dom-tests.ts index 598573cced..3975113e20 100644 --- a/types/prismic-dom/prismic-dom-tests.ts +++ b/types/prismic-dom/prismic-dom-tests.ts @@ -1,3 +1,5 @@ import prismicDom = require("prismic-dom"); -const rendered: string = prismicDom.RichText.asHtml({}); +const string = ''; +const rendered: string = prismicDom.RichText.asHtml({}, () => string, () => string); +const link: string = prismicDom.Link.url({}, ({}) => string); diff --git a/types/promise-timeout/promise-timeout-tests.ts b/types/promise-timeout/promise-timeout-tests.ts index 60c4597a15..2cae7e384b 100644 --- a/types/promise-timeout/promise-timeout-tests.ts +++ b/types/promise-timeout/promise-timeout-tests.ts @@ -7,4 +7,8 @@ acceptError(new TimeoutError()); timeout(); // $ExpectError timeout(new Promise(() => { })); // $ExpectError -timeout(new Promise(() => { }), 1000); // $ExpectType Promise<{}> +const top = ((x?: T): T => x!)(); +type Top = typeof top; +declare function expectPromiseTop(x: Promise): void; + +expectPromiseTop(timeout(new Promise(() => { }), 1000)); diff --git a/types/protractor-browser-logs/package.json b/types/protractor-browser-logs/package.json index 6e5104b930..2317a4c4ea 100644 --- a/types/protractor-browser-logs/package.json +++ b/types/protractor-browser-logs/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "protractor": "latest" + "protractor": "5.4.2" } } diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 4a8b497506..b63149544a 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -116,7 +116,7 @@ declare class Pubnub { ): any; decrypt( - data: object, + data: string | object, customCipherKey?: string, options?: Pubnub.CryptoParameters ): any; diff --git a/types/pubnub/pubnub-tests.ts b/types/pubnub/pubnub-tests.ts index 8750919e59..eac4d49d24 100644 --- a/types/pubnub/pubnub-tests.ts +++ b/types/pubnub/pubnub-tests.ts @@ -113,4 +113,5 @@ const mySecret = { message: 'Hi!', }; pubnub.decrypt(mySecret, undefined, cryptoOptions); +pubnub.decrypt('mySecretString', undefined, cryptoOptions); pubnub.encrypt('egrah5rwgrehwqh5eh3hwfwef', undefined, cryptoOptions); diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 8887c52c57..12152ecb4b 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1975,9 +1975,9 @@ class Rectangle { }; () => { - const a: boolean = R.pathSatisfies(x => x > 0, ["x"], {x: 1, y: 2}); // => true - const b: boolean = R.pathSatisfies(x => x > 0, ["x"])({x: 1, y: 2}); // => true - const c: boolean = R.pathSatisfies(x => x > 0)(["x"])({x: 1, y: 2}); // => true + const a: boolean = R.pathSatisfies((x: number) => x > 0, ["x"], {x: 1, y: 2}); // => true + const b: boolean = R.pathSatisfies((x: number) => x > 0, ["x"])({x: 1, y: 2}); // => true + const c: boolean = R.pathSatisfies((x: number) => x > 0)(["x"])({x: 1, y: 2}); // => true }; () => { @@ -2091,9 +2091,9 @@ class Rectangle { }; () => { - const a: boolean = R.propSatisfies(x => x > 0, "x", {x: 1, y: 2}); // => true - const b: boolean = R.propSatisfies(x => x > 0, "x")({x: 1, y: 2}); // => true - const c: boolean = R.propSatisfies(x => x > 0)("x")({x: 1, y: 2}); // => true + const a: boolean = R.propSatisfies((x: number) => x > 0, "x", {x: 1, y: 2}); // => true + const b: boolean = R.propSatisfies((x: number) => x > 0, "x")({x: 1, y: 2}); // => true + const c: boolean = R.propSatisfies((x: number) => x > 0)("x")({x: 1, y: 2}); // => true }; () => { diff --git a/types/rasha/index.d.ts b/types/rasha/index.d.ts new file mode 100644 index 0000000000..eeb0dadb5e --- /dev/null +++ b/types/rasha/index.d.ts @@ -0,0 +1,57 @@ +// Type definitions for rasha 1.2 +// Project: https://git.coolaj86.com/coolaj86/rasha.js +// Definitions by: Justin Baroux +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export as namespace Rasha; + +export interface Jwk { + kty: string; + n: string; + e: string; + d: string; + p: string; + q: string; + dp: string; + dq: string; + qi: string; +} + +export interface GenerateOptions { + format: string; + encoding?: string; + modulusLength?: number; + publicExponent?: number; +} + +export interface ImportOptions { + pem: string; + public: boolean; +} + +export interface ExportOptions { + jwk: Jwk; + format: string; + public: boolean; +} + +export interface RsaKeys { + private: string; + public: string; +} + +// Generate RSA KEY +export function generate(opts: GenerateOptions): Promise; + +// PEM-to-JWK +declare function Import(opts: ImportOptions): Promise; +export { Import as import }; + +// JWK-to-PEM +declare function Export(opts: ExportOptions): Promise; +export { Export as export }; + +// JWK Thumbprint +export function thumbprint(jwk: Jwk): Promise; diff --git a/types/rasha/rasha-tests.ts b/types/rasha/rasha-tests.ts new file mode 100644 index 0000000000..fade7c165b --- /dev/null +++ b/types/rasha/rasha-tests.ts @@ -0,0 +1,10 @@ +import * as rasha from 'rasha'; + +const gOptions: Rasha.GenerateOptions = { format: 'jwk' }; + +rasha.generate(gOptions).then((keypair: Rasha.RsaKeys) => { + console.log(keypair.private); + console.log(keypair.public); +}); + +// const rsa: RsaKeys = Rasha.generate(gOptions); diff --git a/types/rasha/tsconfig.json b/types/rasha/tsconfig.json new file mode 100644 index 0000000000..838de830c9 --- /dev/null +++ b/types/rasha/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "rasha-tests.ts" + ] +} \ No newline at end of file diff --git a/types/rasha/tslint.json b/types/rasha/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rasha/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-autocomplete/index.d.ts b/types/react-autocomplete/index.d.ts index fd0bdc8b8a..a377a71813 100644 --- a/types/react-autocomplete/index.d.ts +++ b/types/react-autocomplete/index.d.ts @@ -76,7 +76,7 @@ declare namespace Autocomplete { * and the width of the dropdown menu. */ renderMenu?: ( - items: any[], + items: ReactNode[], value: string, styles: CSSProperties, ) => ReactNode; diff --git a/types/react-autocomplete/react-autocomplete-tests.tsx b/types/react-autocomplete/react-autocomplete-tests.tsx index 36834b46d1..0132023dd1 100644 --- a/types/react-autocomplete/react-autocomplete-tests.tsx +++ b/types/react-autocomplete/react-autocomplete-tests.tsx @@ -16,3 +16,8 @@ render( />, container, ); + +// $ExpectError +const renderMenu: React.ComponentProps['renderMenu'] = ( + (item: string[]) =>
+); diff --git a/types/react-broadcast/react-broadcast-tests.tsx b/types/react-broadcast/react-broadcast-tests.tsx index 6f3466e729..2e5e097434 100644 --- a/types/react-broadcast/react-broadcast-tests.tsx +++ b/types/react-broadcast/react-broadcast-tests.tsx @@ -8,7 +8,7 @@ class ExampleOfUsingReactBroadcast extends React.Component {
- {state =>
{state}
} + {(state: React.ReactNode) =>
{state}
}
diff --git a/types/react-dev-utils/openBrowser.d.ts b/types/react-dev-utils/openBrowser.d.ts index 1c87eee617..a8c797dd41 100644 --- a/types/react-dev-utils/openBrowser.d.ts +++ b/types/react-dev-utils/openBrowser.d.ts @@ -3,7 +3,7 @@ * * On Mac OS X, attempts to reuse an existing Chrome tab via AppleScript. * - * Otherwise, falls back to [opn](https://github.com/sindresorhus/opn) behavior. + * Otherwise, falls back to [open](https://github.com/sindresorhus/open) behavior. */ declare function openBrowser(url: string): boolean; export = openBrowser; diff --git a/types/react-jsonschema-form/index.d.ts b/types/react-jsonschema-form/index.d.ts index fc4da16e0b..2f5681a39f 100644 --- a/types/react-jsonschema-form/index.d.ts +++ b/types/react-jsonschema-form/index.d.ts @@ -7,13 +7,19 @@ // Sylvain Thénault // Sebastian Busch // Mehdi Lahlou +// Saad Tazi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 + declare module "react-jsonschema-form" { import * as React from "react"; import { JSONSchema6 } from "json-schema"; + type ErrorSchema = { + [k: string]: ErrorSchema + }; + export interface FormProps { schema: JSONSchema6; disabled?: boolean; @@ -27,7 +33,7 @@ declare module "react-jsonschema-form" { showErrorList?: boolean; ErrorList?: React.StatelessComponent; validate?: (formData: T, errors: FormValidation) => FormValidation; - onChange?: (e: IChangeEvent) => any; + onChange?: (e: IChangeEvent, es?: ErrorSchema) => any; onError?: (e: any) => any; onSubmit?: (e: ISubmitEvent) => any; liveValidate?: boolean; @@ -95,13 +101,13 @@ declare module "react-jsonschema-form" { | React.StatelessComponent | React.ComponentClass; - export interface FieldProps extends React.HTMLAttributes { + export interface FieldProps extends React.HTMLAttributes { schema: JSONSchema6; uiSchema: UiSchema; idSchema: IdSchema; - formData: any; - errorSchema: object; - onChange: (value: any) => void; + formData: T; + errorSchema: ErrorSchema; + onChange: (e: IChangeEvent | any, es?: ErrorSchema) => any; registry: { fields: { [name: string]: Field }; widgets: { [name: string]: Widget }; @@ -241,7 +247,8 @@ declare module "react-jsonschema-form" { } declare module "react-jsonschema-form/lib/utils" { - import { JSONSchema6 } from "json-schema"; + import { JSONSchema6, JSONSchema6Definition } from "json-schema"; + import { FieldProps } from "react-jsonschema-form"; export interface IRangeSpec { min?: number; @@ -250,4 +257,20 @@ declare module "react-jsonschema-form/lib/utils" { } export function rangeSpec(schema: JSONSchema6): IRangeSpec; + + export function resolveSchema( + schema: JSONSchema6Definition, + definitions: FieldProps["registry"]["definitions"], + formData: object + ): JSONSchema6; +} + +declare module "react-jsonschema-form/lib/validate" { + import { JSONSchema6Definition } from "json-schema"; + import { AjvError } from "react-jsonschema-form"; + + export default function validateFormData( + formData: T, + schema: JSONSchema6Definition + ): AjvError[]; } diff --git a/types/react-jsonschema-form/react-jsonschema-form-tests.tsx b/types/react-jsonschema-form/react-jsonschema-form-tests.tsx index 419b21cce5..c3a92d6d26 100644 --- a/types/react-jsonschema-form/react-jsonschema-form-tests.tsx +++ b/types/react-jsonschema-form/react-jsonschema-form-tests.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Form, { UiSchema, ErrorListProps, WidgetProps } from "react-jsonschema-form"; +import Form, { UiSchema, ErrorListProps, WidgetProps, ErrorSchema } from "react-jsonschema-form"; import { JSONSchema6 } from "json-schema"; // example taken from the react-jsonschema-form playground: @@ -109,6 +109,31 @@ export class Example extends React.Component { } } +interface FuncExampleProps { + formData: object; + onError: (e: ErrorSchema) => void; + onChange: (e: any) => void; +} + +export const FuncExample = (props: FuncExampleProps) => { + const { formData, onChange, onError } = props; + return ( +
{ + onChange(formData); + onError(errorSchema) + }} + /> + ); +}; + export const BooleanCustomWidget: React.SFC = (props) => props.onFocus('id', true)} diff --git a/types/react-native-view-pdf/index.d.ts b/types/react-native-view-pdf/index.d.ts new file mode 100644 index 0000000000..cb9b242e77 --- /dev/null +++ b/types/react-native-view-pdf/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for react-native-view-pdf 0.8 +// Project: https://github.com/rumax/react-native-PDFView#readme +// Definitions by: Sérgio Miguel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.1 + +import * as React from 'react'; + +type HTTPMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + +interface URLProps { + method?: HTTPMethod; + headers?: { [key: string]: string }; + body?: string; +} + +export interface PDFViewProps { + onError?: (error: Error) => void; + onLoad?: () => void; + onPageChanged?: (page: number, pageCount: number) => void; + onScrolled?: (offset: number) => void; + resource: string; + resourceType?: 'url' | 'base64' | 'file'; + fileFrom?: 'bundle' | 'documentsDirectory'; + urlProps?: URLProps; + textEncoding?: 'utf-8' | 'utf-16'; + fadeInDuration?: number; + [key: string]: any; +} + +declare class PDFView extends React.Component {} + +export default PDFView; diff --git a/types/react-native-view-pdf/react-native-view-pdf-tests.tsx b/types/react-native-view-pdf/react-native-view-pdf-tests.tsx new file mode 100644 index 0000000000..aee3b4855c --- /dev/null +++ b/types/react-native-view-pdf/react-native-view-pdf-tests.tsx @@ -0,0 +1,13 @@ +import * as React from 'react'; +import PDFView from 'react-native-view-pdf'; + +export default class extends React.Component { + render(): JSX.Element { + return ( + + ); + } +} diff --git a/types/react-native-view-pdf/tsconfig.json b/types/react-native-view-pdf/tsconfig.json new file mode 100644 index 0000000000..e8e47f55c7 --- /dev/null +++ b/types/react-native-view-pdf/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "jsx": "react-native", + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-native-view-pdf-tests.tsx" + ] +} diff --git a/types/react-native-view-pdf/tslint.json b/types/react-native-view-pdf/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-view-pdf/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 1c6d6437d9..99998e9241 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -18,6 +18,7 @@ // Souvik Ghosh // Cheng Gibson // Saransh Kataria +// Francesco Moro // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -7292,6 +7293,36 @@ export interface CameraRollStatic { getPhotos(params: GetPhotosParamType): Promise; } +// https://facebook.github.io/react-native/docs/checkbox.html +export interface CheckBoxProps extends ViewProps { + /** + * If true the user won't be able to toggle the checkbox. Default value is false. + */ + disabled?: boolean; + + /** + * Used in case the props change removes the component. + */ + onChange?: (value: boolean) => void; + + /** + * Invoked with the new value when the value changes. + */ + onValueChange?: (value: boolean) => void; + + /** + * Used to locate this view in end-to-end tests. + */ + testID?: string; + + /** + * The value of the checkbox. If true the checkbox will be turned on. Default value is false. + */ + value?: boolean; +} + +export class CheckBox extends React.Component {} + /** Clipboard gives you an interface for setting and getting content from Clipboard on both iOS and Android */ export interface ClipboardStatic { getString(): Promise; diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 49e1bab1ac..7de9b96374 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -21,6 +21,7 @@ import { BackAndroid, BackHandler, Button, + CheckBox, ColorPropType, DataSourceAssetCallback, DeviceEventEmitterStatic, @@ -534,6 +535,16 @@ class MaskedViewTest extends React.Component { } } +const CheckboxTest = () => ( + { console.log(value); }} + onValueChange={value => { console.log(value); }} + value={true} + /> +); + class InputAccessoryViewTest extends React.Component { render() { const uniqueID = "foobar"; diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index 9b2aee84e2..0c56d71914 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -662,7 +662,7 @@ export interface NavigationScreenProp { getParam(param: T): P[T]; setParams: (newParams: Partial

) => boolean; addListener: ( - eventName: 'willBlur' | 'willFocus' | 'didFocus' | 'didBlur', + eventName: EventType, callback: NavigationEventCallback ) => NavigationEventSubscription; push: ( diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index f97fd11b9d..66b1d7afa5 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -87,7 +87,7 @@ export type Matching = { */ export type Shared< InjectedProps, - DecorationTargetProps extends Shared + DecorationTargetProps > = { [P in Extract]?: InjectedProps[P] extends DecorationTargetProps[P] ? DecorationTargetProps[P] : never; }; diff --git a/types/react-redux/v6/index.d.ts b/types/react-redux/v6/index.d.ts index bcbcced0bd..0d23b6c036 100644 --- a/types/react-redux/v6/index.d.ts +++ b/types/react-redux/v6/index.d.ts @@ -84,7 +84,7 @@ export type Matching = { */ export type Shared< InjectedProps, - DecorationTargetProps extends Shared + DecorationTargetProps > = { [P in Extract]?: InjectedProps[P] extends DecorationTargetProps[P] ? DecorationTargetProps[P] : never; }; diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index ec51291e30..e0c511f6af 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -95,7 +95,7 @@ export interface QueryRendererProps): React.ReactElement | undefined | null; + render(readyState: ReadyState): React.ReactNode; variables: T["variables"]; rerunParamExperimental?: RelayRuntimeTypes.RerunParam; } @@ -191,3 +191,11 @@ export function createRefetchContainer

( fragmentSpec: RelayRuntimeTypes.GraphQLTaggedNode | GeneratedNodeMap, taggedNode: RelayRuntimeTypes.GraphQLTaggedNode ): RelayContainer

; + +// ~~~~~~~~~~~~~~~~~~~~~ +// Context +// ~~~~~~~~~~~~~~~~~~~~~ + +export const ReactRelayContext: React.Context< + RelayRuntimeTypes.CRelayContext +>; diff --git a/types/react-relay/test/react-relay-tests.tsx b/types/react-relay/test/react-relay-tests.tsx index 14461ab9e5..ac2b33148f 100644 --- a/types/react-relay/test/react-relay-tests.tsx +++ b/types/react-relay/test/react-relay-tests.tsx @@ -11,6 +11,7 @@ import { createRefetchContainer, requestSubscription, QueryRenderer, + ReactRelayContext, RelayRefetchProp, RelayPaginationProp, RelayProp, @@ -501,3 +502,10 @@ requestSubscription( }, } ); + +// ~~~~~~~~~~~~~~~~~~~~~ +// Context +// ~~~~~~~~~~~~~~~~~~~~~ + +ReactRelayContext.Consumer.prototype; +ReactRelayContext.Provider.prototype; diff --git a/types/react-spinner/index.d.ts b/types/react-spinner/index.d.ts new file mode 100644 index 0000000000..a00f1a061f --- /dev/null +++ b/types/react-spinner/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for react-spinner 0.2 +// Project: https://github.com/chenglou/react-spinner/ +// Definitions by: Jake Boone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export default class Spinner extends React.Component {} diff --git a/types/react-spinner/react-spinner-tests.tsx b/types/react-spinner/react-spinner-tests.tsx new file mode 100644 index 0000000000..2681a397eb --- /dev/null +++ b/types/react-spinner/react-spinner-tests.tsx @@ -0,0 +1,4 @@ +import * as React from 'react'; +import Spinner from 'react-spinner'; + +const spinner: JSX.Element = ; diff --git a/types/react-spinner/tsconfig.json b/types/react-spinner/tsconfig.json new file mode 100644 index 0000000000..37a83c0edd --- /dev/null +++ b/types/react-spinner/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-spinner-tests.tsx" + ] +} diff --git a/types/react-spinner/tslint.json b/types/react-spinner/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/react-spinner/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-virtualized-auto-sizer/index.d.ts b/types/react-virtualized-auto-sizer/index.d.ts new file mode 100644 index 0000000000..29d2ff7da4 --- /dev/null +++ b/types/react-virtualized-auto-sizer/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for react-virtualized-auto-sizer 1.0 +// Project: https://github.com/bvaughn/react-virtualized-auto-sizer/ +// Definitions by: Hidemi Yukita +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +export interface Size { + height: number; + width: number; +} + +export interface AutoSizerProps { + /** Function responsible for rendering children. */ + children: (size: Size) => React.ReactNode; + + /** Optional custom CSS class name to attach to root AutoSizer element. */ + className?: string; + + /** Default height to use for initial render; useful for SSR */ + defaultHeight?: number; + + /** Default width to use for initial render; useful for SSR */ + defaultWidth?: number; + + /** Disable dynamic :height property */ + disableHeight?: boolean; + + /** Disable dynamic :width property */ + disableWidth?: boolean; + + /** Nonce of the inlined stylesheet for Content Security Policy */ + nonce?: string; + + /** Callback to be invoked on-resize */ + onResize?: (size: Size) => void; + + /** Optional inline style */ + style?: React.CSSProperties; +} + +export default class extends React.Component {} diff --git a/types/react-virtualized-auto-sizer/react-virtualized-auto-sizer-tests.tsx b/types/react-virtualized-auto-sizer/react-virtualized-auto-sizer-tests.tsx new file mode 100644 index 0000000000..b194611356 --- /dev/null +++ b/types/react-virtualized-auto-sizer/react-virtualized-auto-sizer-tests.tsx @@ -0,0 +1,51 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import AutoSizer, { Size } from 'react-virtualized-auto-sizer'; + +class TestAutoSizer extends AutoSizer {} + +class TestApp extends React.Component { + onResize = (size: Size) => { + console.log(`width: ${size.width}`); + console.log(`height: ${size.height}`); + } + + render() { + return ( + <> + + {({ width, height }) => { + const _width: number = width; + const _height: number = height; + console.log(`width: ${_width}`); + console.log(`height: ${_height}`); + return null; + }} + + + {({ width, height }) => { + const _width: number = width; + const _height: number = height; + console.log(`width: ${_width}`); + console.log(`height: ${_height}`); + return null; + }} + + + ); + } +} + + ReactDOM.render( + , + document.getElementById("test-app"), +); diff --git a/types/react-virtualized-auto-sizer/tsconfig.json b/types/react-virtualized-auto-sizer/tsconfig.json new file mode 100644 index 0000000000..0d65a828c5 --- /dev/null +++ b/types/react-virtualized-auto-sizer/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "react-virtualized-auto-sizer-tests.tsx" + ] +} diff --git a/types/react-virtualized-auto-sizer/tslint.json b/types/react-virtualized-auto-sizer/tslint.json new file mode 100644 index 0000000000..4f44991c3c --- /dev/null +++ b/types/react-virtualized-auto-sizer/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-empty-interface": false + } +} diff --git a/types/react/global.d.ts b/types/react/global.d.ts index 2ea2b7ca91..da8de1e6b0 100644 --- a/types/react/global.d.ts +++ b/types/react/global.d.ts @@ -97,6 +97,7 @@ interface SVGFEConvolveMatrixElement extends SVGElement { } interface SVGFEDiffuseLightingElement extends SVGElement { } interface SVGFEDisplacementMapElement extends SVGElement { } interface SVGFEDistantLightElement extends SVGElement { } +interface SVGFEDropShadowElement extends SVGElement { } interface SVGFEFloodElement extends SVGElement { } interface SVGFEFuncAElement extends SVGElement { } interface SVGFEFuncBElement extends SVGElement { } diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 8f9645df3c..d7fcb51d61 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -2922,6 +2922,7 @@ declare global { feDiffuseLighting: React.SVGProps; feDisplacementMap: React.SVGProps; feDistantLight: React.SVGProps; + feDropShadow: React.SVGProps; feFlood: React.SVGProps; feFuncA: React.SVGProps; feFuncB: React.SVGProps; diff --git a/types/react/test/tsx.tsx b/types/react/test/tsx.tsx index 12b885dac4..f88db9ae7a 100644 --- a/types/react/test/tsx.tsx +++ b/types/react/test/tsx.tsx @@ -229,9 +229,7 @@ const Memoized5 = React.memo<{ test: boolean }>( ; -// for some reason the ExpectType doesn't work if the type is namespaced -// $ExpectType NamedExoticComponent<{}> -const Memoized6 = React.memo(props => null); +const Memoized6: React.NamedExoticComponent = React.memo(props => null); ; // $ExpectError ; diff --git a/types/remotedev-serialize/index.d.ts b/types/remotedev-serialize/index.d.ts new file mode 100644 index 0000000000..86a5e206f9 --- /dev/null +++ b/types/remotedev-serialize/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for remotedev-serialize 1.0 +// Project: https://github.com/zalmoxisus/remotedev-serialize/ +// Definitions by: Julian Hundeloh +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.1 + +import * as Immutable from 'immutable'; + +export type Options = Record; + +export type Refs = Record; + +export type DefaultReplacer = (key: string, value: any) => any; + +export type Replacer = ( + key: string, + value: any, + replacer: DefaultReplacer +) => any; + +export type DefaultReviver = (key: string, value: any) => any; + +export type Reviver = (key: string, value: any, reviver: DefaultReviver) => any; + +export function immutable( + immutable: typeof Immutable, + refs?: Refs, + customReplacer?: Replacer, + customReviver?: Reviver +): { + stringify: (input: any) => string; + parse: (input: string) => any; + serialize: ( + immutable: typeof Immutable, + refs?: Refs, + customReplacer?: Replacer, + customReviver?: Reviver + ) => { + replacer: Replacer; + reviver: Reviver; + options: Options; + }; +}; diff --git a/types/remotedev-serialize/package.json b/types/remotedev-serialize/package.json new file mode 100644 index 0000000000..9b1e26b353 --- /dev/null +++ b/types/remotedev-serialize/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "immutable": "^3.8.1" + } +} \ No newline at end of file diff --git a/types/remotedev-serialize/remotedev-serialize-tests.ts b/types/remotedev-serialize/remotedev-serialize-tests.ts new file mode 100644 index 0000000000..bca43ccd33 --- /dev/null +++ b/types/remotedev-serialize/remotedev-serialize-tests.ts @@ -0,0 +1,8 @@ +import * as Immutable from 'immutable'; +import * as Serialize from 'remotedev-serialize'; + +const { stringify, parse } = Serialize.immutable(Immutable); + +const data = Immutable.fromJS({foo: 'bar', baz: {qux: 42}}); +const serialized = stringify(data); +const parsed = parse(serialized); diff --git a/types/remotedev-serialize/tsconfig.json b/types/remotedev-serialize/tsconfig.json new file mode 100644 index 0000000000..ff53419fed --- /dev/null +++ b/types/remotedev-serialize/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", + "remotedev-serialize-tests.ts" + ] +} diff --git a/types/remotedev-serialize/tslint.json b/types/remotedev-serialize/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/remotedev-serialize/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sarif/index.d.ts b/types/sarif/index.d.ts index 56bcf3e8da..98572933fa 100644 --- a/types/sarif/index.d.ts +++ b/types/sarif/index.d.ts @@ -5,7 +5,7 @@ // TypeScript Version: 2.4 /** - * Static Analysis Results Format (SARIF) Version 2.0.0-csd.2.beta-2019-01-24 JSON Schema: a standard format for the + * Static Analysis Results Format (SARIF) Version 2.0.0-csd.2.beta-2019-02-20 JSON Schema: a standard format for the * output of static analysis tools. */ export interface Log { @@ -24,6 +24,11 @@ export interface Log { */ runs: Run[]; + /** + * References to external property files that share data between runs. + */ + inlineExternalPropertyFiles?: ExternalPropertyFile[]; + /** * Key/value pairs that provide additional information about the log file. */ @@ -32,7 +37,43 @@ export interface Log { export namespace Log { type version = - "2.0.0-csd.2.beta.2019-01-24"; + "2.0.0-csd.2.beta.2019-02-20"; +} + +/** + * The effective address of a reported issue. + */ +export interface Address { + /** + * A base address rendered as a hexadecimal string. + */ + baseAddress?: number; + + /** + * An index into run.addresses used to retrieve a cached instance to represent the address. + */ + index?: number; + + /** + * An open-ended string that identifies the address kind. 'section' and 'segment' are well-known values. + */ + kind?: string; + + /** + * A name that is associated with the address, e.g., '.text'. + */ + name?: string; + + /** + * an offset from the base address, if present, rendered as a hexadecimal string. + */ + offset?: number; + + /** + * An index into run.addresses to retrieve a parent address. The parent can provide a base address (from which the + * current offset value is relevant) and other details. + */ + parentIndex?: number; } /** @@ -172,7 +213,7 @@ export interface ArtifactLocation { /** * A string containing a valid relative or absolute URI. */ - uri: string; + uri?: string; /** * A string which indirectly specifies the absolute URI with respect to which a relative URI in the "uri" property @@ -187,7 +228,7 @@ export interface ArtifactLocation { } /** - * An artifact relevant to a tool invocation or to a result. + * An artifact relevant to a result. */ export interface Attachment { /** @@ -341,7 +382,7 @@ export interface Exception { /** * A message that describes the exception. */ - message?: Message; + message?: string; /** * The sequence of function calls leading to the exception. @@ -358,21 +399,21 @@ export interface Exception { * TBD */ export interface ExternalPropertyFile { - /** - * The location of the external property file. - */ - artifactLocation?: ArtifactLocation; - /** * A stable, unique identifer for the external property file in the form of a GUID. */ - instanceGuid?: string; + guid?: string; /** * A non-negative integer specifying the number of items contained in the external property file. */ itemCount?: number; + /** + * The location of the external property file. + */ + location?: ArtifactLocation; + /** * Key/value pairs that provide additional information about the external property file. */ @@ -383,6 +424,11 @@ export interface ExternalPropertyFile { * References to external property files that should be inlined with the content of a root log file. */ export interface ExternalPropertyFiles { + /** + * An array of external property files containing run.addresses arrays to be merged with the root log file. + */ + addresses?: ExternalPropertyFile[]; + /** * An array of external property files containing run.artifacts arrays to be merged with the root log file. */ @@ -418,10 +464,26 @@ export interface ExternalPropertyFiles { */ results?: ExternalPropertyFile[]; + /** + * An array of external property files containing run.taxonomies arrays to be merged with the root log file. + */ + taxonomies?: ExternalPropertyFile[]; + + /** + * An array of external property files containing run.threadFlowLocations arrays to be merged with the root log + * file. + */ + threadFlowLocations?: ExternalPropertyFile[]; + /** * An external property file containing a run.tool object to be merged with the root log file. */ tool?: ExternalPropertyFile; + + /** + * Key/value pairs that provide additional information about the external property files. + */ + properties?: PropertyBag; } /** @@ -521,21 +583,11 @@ export interface Invocation { */ arguments?: string[]; - /** - * A set of artifacts relevant to the invocation of the tool. - */ - attachments?: Attachment[]; - /** * The command line used to invoke the tool. */ commandLine?: string; - /** - * A list of conditions detected by the tool that are relevant to the tool's configuration. - */ - configurationNotifications?: Notification[]; - /** * The Coordinated Universal Time (UTC) date and time at which the run ended. See "Date/time properties" in the * SARIF spec for the required format. @@ -624,14 +676,19 @@ export interface Invocation { stdoutStderr?: ArtifactLocation; /** - * A value indicating whether the tool's execution completed successfully. + * A list of conditions detected by the tool that are relevant to the tool's configuration. */ - toolExecutionSuccessful?: boolean; + toolConfigurationNotifications?: Notification[]; /** * A list of runtime conditions detected by the tool during the analysis. */ - toolNotifications?: Notification[]; + toolExecutionNotifications?: Notification[]; + + /** + * A value indicating whether the tool's execution completed successfully. + */ + toolExecutionSuccessful?: boolean; /** * The working directory for the analysis tool run. @@ -648,6 +705,11 @@ export interface Invocation { * A location within a programming artifact. */ export interface Location { + /** + * The address of the location. + */ + address?: Address; + /** * A set of regions relevant to the location. */ @@ -698,8 +760,9 @@ export interface LogicalLocation { /** * The type of construct this logical location component refers to. Should be one of 'function', 'member', - * 'module', 'namespace', 'parameter', 'resource', 'returnType', 'type', or 'variable', if any of those accurately - * describe the construct. + * 'module', 'namespace', 'parameter', 'resource', 'returnType', 'type', 'variable', 'object', 'array', 'property', + * 'value', 'element', 'text', 'attribute', 'comment', 'declaration', 'dtd' or 'processingInstruction', if any of + * those accurately describe the construct. */ kind?: string; @@ -736,7 +799,7 @@ export interface Message { markdown?: string; /** - * The resource id for a plain text or Markdown message string. + * The message identifier for this message. */ messageId?: string; @@ -1123,7 +1186,12 @@ export interface ReportingDescriptor { * A description of the report. Should, as far as possible, provide details sufficient to enable resolution of any * problem indicated by the result. */ - fullDescription?: Message; + fullDescription?: MultiformatMessageString; + + /** + * A unique identifer for the reporting descriptor in the form of a GUID. + */ + guid?: string; /** * Provides the primary documentation for the report, useful when there is no online documentation. @@ -1150,13 +1218,25 @@ export interface ReportingDescriptor { /** * A report identifier that is understandable to an end user. */ - name?: Message; + name?: string; + + /** + * An array of references used to locate an optional set of taxonomy reporting descriptors that may be applied to a + * result. + */ + optionalTaxonomyReferences?: ReportingDescriptorReference[]; /** * A concise description of the report. Should be a single sentence that is understandable when visible space is * limited to a single line of text. */ - shortDescription?: Message; + shortDescription?: MultiformatMessageString; + + /** + * An array of references used to locate a set of taxonomy reporting descriptors that are always applicable to a + * result. + */ + taxonomyReferences?: ReportingDescriptorReference[]; /** * Key/value pairs that provide additional information about the report. @@ -1164,6 +1244,67 @@ export interface ReportingDescriptor { properties?: PropertyBag; } +/** + * Information about how to locate a relevant reporting descriptor. + */ +export interface ReportingDescriptorReference { + /** + * A notification identifier. + */ + id?: string; + + /** + * A JSON pointer used to retrieve a reporting descriptor from an array within a tool component. + */ + pointer?: string; + + /** + * Key/value pairs that provide additional information about the reporting descriptor reference. + */ + properties?: PropertyBag; +} + +/** + * Provides localized message strings for a reporting descriptor in a single language. + */ +export interface ReportingDescriptorTranslation { + /** + * A description of the report. Should, as far as possible, provide details sufficient to enable resolution of any + * problem indicated by the result. + */ + fullDescription?: MultiformatMessageString; + + /** + * The unique identifier in the form of a GUID of the reporting descriptor to which this translation belongs, + * matching reportingDescriptor.guid. + */ + guid?: string; + + /** + * The stable, opaque identifier of the reporting descriptor to which this translation belongs, matching + * reportingDescriptor.id. + */ + id?: string; + + /** + * A set of name/value pairs with arbitrary names. Each value is a multiformatMessageString object, which holds + * message strings in plain text and (optionally) Markdown format. The property names are a subset of the property + * names in the messageStrings property of the reportingDescriptor object to which this translation belongs. + */ + messageStrings?: { [key: string]: MultiformatMessageString }; + + /** + * A concise description of the report. Should be a single sentence that is understandable when visible space is + * limited to a single line of text. + */ + shortDescription?: MultiformatMessageString; + + /** + * Key/value pairs that provide additional information about reportingDescriptorTranslation. + */ + properties?: PropertyBag; +} + /** * A result produced by an analysis tool. */ @@ -1299,6 +1440,11 @@ export interface Result { */ suppressionStates?: Result.suppressionStates[]; + /** + * An array of references to taxonomy reporting descriptors that are applicable to the result. + */ + taxonomyReferences?: ReportingDescriptorReference[]; + /** * The URIs of the work items associated with this result. */ @@ -1312,7 +1458,6 @@ export interface Result { export namespace Result { type kind = - "none" | "notApplicable" | "pass" | "fail" | @@ -1385,6 +1530,11 @@ export interface ResultProvenance { * Describes a single run of an analysis tool, and contains the reported output of that run. */ export interface Run { + /** + * Addresses associated with this run instance, if any. + */ + addresses?: Address[]; + /** * Automation details that describe the aggregate of runs to which this run belongs. */ @@ -1475,6 +1625,16 @@ export interface Run { */ results?: Result[]; + /** + * An array of reportingDescriptor objects relevant to a taxonomy in which results are categorized. + */ + taxonomies?: ReportingDescriptor[]; + + /** + * An array of threadFlowLocation objects cached at run level. + */ + threadFlowLocations?: ThreadFlowLocation[]; + /** * Information about the tool or tool pipeline that generated the results in this run. A run can only contain * results produced by a single tool or tool pipeline. A run can aggregate results from multiple log files, as long @@ -1482,6 +1642,11 @@ export interface Run { */ tool: Tool; + /** + * The set of available translations of the localized data provided by the tool. + */ + translations?: Translation[]; + /** * Specifies the revision in version control of the artifacts that were scanned. */ @@ -1559,7 +1724,7 @@ export interface StackFrame { /** * The address of the method or function that is executing. */ - address?: number; + address?: Address; /** * The location to which this stack frame refers. @@ -1571,11 +1736,6 @@ export interface StackFrame { */ module?: string; - /** - * The offset from the method or function that is executing. - */ - offset?: number; - /** * The parameters of the call that is executing. */ @@ -1638,6 +1798,11 @@ export interface ThreadFlowLocation { */ importance?: ThreadFlowLocation.importance; + /** + * The index within the run threadFlowLocations array. + */ + index?: number; + /** * A set of distinct strings that categorize the thread flow location. Well-known kinds include acquire, release, * enter, exit, call, return, branch, implicit, false, true, caution, danger, unknown, unreachable, taint, @@ -1699,12 +1864,6 @@ export interface Tool { */ extensions?: ToolComponent[]; - /** - * The tool language (expressed as an ISO 649 two-letter lowercase culture code) and region (expressed as an ISO - * 3166 two-letter uppercase subculture code associated with a country or region). - */ - language?: string; - /** * Key/value pairs that provide additional information about the tool. */ @@ -1712,27 +1871,32 @@ export interface Tool { } /** - * A component, such as a plug-in or the default driver, of the analysis tool that was run. + * A component, such as a plug-in or the driver, of the analysis tool that was run. */ export interface ToolComponent { /** - * The index within the run artifacts array of the artifact object associated with the component. + * The indices within the run artifacts array of the artifact objects associated with the tool component. */ - artifactIndex?: number; + artifactIndices?: number[]; /** - * The binary version of the component's primary executable file expressed as four non-negative integers separated - * by a period (for operating systems that express file versions in this way). + * The binary version of the tool component's primary executable file expressed as four non-negative integers + * separated by a period (for operating systems that express file versions in this way). */ dottedQuadFileVersion?: string; /** - * The absolute URI from which the component can be downloaded. + * The absolute URI from which the tool component can be downloaded. */ downloadUri?: string; /** - * The name of the component along with its version and any other useful identifying information, such as its + * A comprehensive description of the tool component. + */ + fullDescription?: MultiformatMessageString; + + /** + * The name of the tool component along with its version and any other useful identifying information, such as its * locale. */ fullName?: string; @@ -1746,33 +1910,122 @@ export interface ToolComponent { globalMessageStrings?: { [key: string]: MultiformatMessageString }; /** - * The name of the component. + * A unique identifer for the tool component in the form of a GUID. + */ + guid?: string; + + /** + * The name of the tool component. */ name: string; /** * An array of reportDescriptor objects relevant to the notifications related to the configuration and runtime - * execution of the component. + * execution of the tool component. */ notificationDescriptors?: ReportingDescriptor[]; /** - * An array of reportDescriptor objects relevant to the analysis performed by the component. + * The organization or company that produced the tool component. + */ + organization?: string; + + /** + * A product suite to which the tool component belongs. + */ + product?: string; + + /** + * An array of reportDescriptor objects relevant to the analysis performed by the tool component. */ ruleDescriptors?: ReportingDescriptor[]; /** - * The component version in the format specified by Semantic Versioning 2.0. + * The tool component version in the format specified by Semantic Versioning 2.0. */ semanticVersion?: string; /** - * The component version, in whatever format the component natively provides. + * A brief description of the tool component. + */ + shortDescription?: MultiformatMessageString; + + /** + * The tool component version, in whatever format the component natively provides. */ version?: string; /** - * Key/value pairs that provide additional information about the component. + * Key/value pairs that provide additional information about the tool component. + */ + properties?: PropertyBag; +} + +/** + * Provides localized message strings for a tool component in a single language. + */ +export interface ToolComponentTranslation { + /** + * A dictionary, each of whose keys is a message identifier and each of whose values is a multiformatMessageString + * object, which holds message strings in plain text and (optionally) Markdown format. The strings can include + * placeholders, which can be used to construct a message in combination with an arbitrary number of additional + * string arguments. The property names are a subset of the property names in the globalMessageStrings property of + * the toolComponent object to which this translation belongs. + */ + globalMessageStrings?: { [key: string]: MultiformatMessageString }; + + /** + * The location of the translation. + */ + location?: ArtifactLocation; + + /** + * Provides an array of translations for a notification descriptor in a available languages. + */ + notificationDescriptors?: ReportingDescriptorTranslation[]; + + /** + * True if this object contains a subset of the strings defined by the tool component. + */ + partialTranslation?: boolean; + + /** + * Provides an array of translations for a reporting descriptor in a available languages. + */ + reportingDescriptors?: ReportingDescriptorTranslation[]; + + /** + * The semantic version of the tool component for which the translation was made. + */ + semanticVersion?: string; + + /** + * The unique identifier for the tool component in the form of a GUID, matching toolComponent.guid. + */ + toolComponentGuid?: string; + + /** + * Key/value pairs that provide additional information about the translationComponentTranslation. + */ + properties?: PropertyBag; +} + +/** + * Provides localized strings for the current run in a single language. + */ +export interface Translation { + /** + * The translation language in ISO 639 format, e.g., 'en-US'. + */ + language?: string; + + /** + * Provides localized message strings for a single tool component in a single language. + */ + toolComponentTranslations?: ToolComponentTranslation[]; + + /** + * Key/value pairs that provide additional information about the translation. */ properties?: PropertyBag; } diff --git a/types/saywhen/saywhen-tests.ts b/types/saywhen/saywhen-tests.ts index 3eb72825fe..6bbb0c1aaf 100644 --- a/types/saywhen/saywhen-tests.ts +++ b/types/saywhen/saywhen-tests.ts @@ -13,6 +13,10 @@ const spy: JasmineSpy = jasmine.createSpy('test'); when(spy); // $ExpectType CallHandler when(spy).isCalled; // $ExpectType Proxy -when.captor(); // $ExpectType MatcherProxy<{}> +const top = ((x?: T): T => x!)(); +type Top = typeof top; +declare function expectMatcherProxyTop(x: (arg: Top) => boolean): void; + +expectMatcherProxyTop(when.captor()); when.captor(jasmine.any(Number)); // $ExpectType MatcherProxy when.noConflict(); // $ExpectType void diff --git a/types/seedrandom/index.d.ts b/types/seedrandom/index.d.ts index 4db50058bc..26f0a537ba 100644 --- a/types/seedrandom/index.d.ts +++ b/types/seedrandom/index.d.ts @@ -1,11 +1,11 @@ // Type definitions for seedrandom 2.4.2 // Project: https://github.com/davidbau/seedrandom -// Definitions by: Kern Handa +// Definitions by: Kern Handa , Eugene Zaretskiy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace seedrandom { - export type seedrandomStateType = boolean | (() => prng); + export type State = {}; interface prng { new (seed?: string, options?: seedRandomOptions, callback?: any): prng; @@ -13,28 +13,28 @@ declare namespace seedrandom { quick(): number; int32(): number; double(): number; - state(): () => prng; + state(): State; } interface seedrandom_prng { - (seed?: string, options?: seedRandomOptions, callback?: any): prng; - alea: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; - xor128: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; - tychei: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; - xorwow: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; - xor4096: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; - xorshift7: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; - quick: (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback) => prng; + (seed?: string, options?: seedRandomOptions, callback?: seedrandomCallback): prng; + alea: (seed?: string, options?: seedRandomOptions) => prng; + xor128: (seed?: string, options?: seedRandomOptions) => prng; + tychei: (seed?: string, options?: seedRandomOptions) => prng; + xorwow: (seed?: string, options?: seedRandomOptions) => prng; + xor4096: (seed?: string, options?: seedRandomOptions) => prng; + xorshift7: (seed?: string, options?: seedRandomOptions) => prng; + quick: (seed?: string, options?: seedRandomOptions) => prng; } interface seedrandomCallback { - (prng?: prng, shortseed?: string, global?: boolean, state?: seedrandomStateType): prng; + (prng?: prng, shortseed?: string, global?: boolean, state?: State): prng; } interface seedRandomOptions { entropy?: boolean; 'global'?: boolean; - state?: seedrandomStateType; + state?: boolean | State; pass?: seedrandomCallback; } } diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index c00d6274fd..12fe90a34c 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -3487,7 +3487,7 @@ declare namespace sequelize { /** * Options for Model.findOrInitialize method */ - interface FindOrInitializeOptions extends AnyFindOptions { + interface FindOrInitializeOptions extends FindOptions { /** * Default values to use if building a new instance @@ -4380,7 +4380,7 @@ declare namespace sequelize { /** * Inserts multiple records at once */ - bulkInsert(tableName: string, records: Object[], options?: QueryOptions, + bulkInsert(tableName: string | { tableName: string, schema: string }, records: Object[], options?: QueryOptions, attributes?: string[] | string): Promise; /** diff --git a/types/sequelize/sequelize-tests.ts b/types/sequelize/sequelize-tests.ts index e598111225..01b8bc27fd 100644 --- a/types/sequelize/sequelize-tests.ts +++ b/types/sequelize/sequelize-tests.ts @@ -1217,6 +1217,7 @@ queryInterface.createTable( { tableName : 'y', schema : 'a' }, queryInterface.changeColumn( { tableName : 'a', schema : 'b' }, 'c', { type : Sequelize.FLOAT }, { logging : () => s } ); queryInterface.createTable( 'users', { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); +queryInterface.bulkInsert({tableName:'users', schema:'test'}, [{}, {}, {}]); queryInterface.createTable( 'level', { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); queryInterface.addColumn( 'users', 'someEnum', Sequelize.ENUM( 'value1', 'value2', 'value3' ) ); queryInterface.addColumn( 'users', 'so', { type : Sequelize.ENUM, values : ['value1', 'value2', 'value3'] } ); diff --git a/types/sharp/index.d.ts b/types/sharp/index.d.ts index a8d51f4257..3f8acea600 100644 --- a/types/sharp/index.d.ts +++ b/types/sharp/index.d.ts @@ -424,7 +424,15 @@ declare namespace sharp { * @throws {Error} Invalid parameters * @returns A sharp instance that can be used to chain operations */ - linear(a?: number, b?: number): Sharp; + linear(a?: number | null, b?: number): Sharp; + + /** + * Recomb the image with the specified matrix. + * @param inputMatrix 3x3 Recombination matrix + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + recomb(inputMatrix: Matrix3x3): Sharp; //#endregion @@ -1028,6 +1036,12 @@ declare namespace sharp { files: { current: number; max: number; }; items: { current: number; max: number; }; } + + type Matrix3x3 = [ + [number, number, number], + [number, number, number], + [number, number, number] + ]; } export = sharp; diff --git a/types/sharp/sharp-tests.ts b/types/sharp/sharp-tests.ts index 84e1d33f4b..b313ea69c3 100644 --- a/types/sharp/sharp-tests.ts +++ b/types/sharp/sharp-tests.ts @@ -233,3 +233,15 @@ const vipsVersion: string = sharp.versions.vips; if (sharp.versions.cairo) { const cairoVersion: string = sharp.versions.cairo; } + +sharp('input.gif') + .linear(1) + .linear(1, 0) + .linear(null, 0) + + .recomb([ + [0.3588, 0.7044, 0.1368], + [0.2990, 0.5870, 0.1140], + [0.2392, 0.4696, 0.0912], + ]) +; diff --git a/types/sinon/ts3.1/index.d.ts b/types/sinon/ts3.1/index.d.ts index 444ed86f22..cab3c80b67 100644 --- a/types/sinon/ts3.1/index.d.ts +++ b/types/sinon/ts3.1/index.d.ts @@ -238,22 +238,22 @@ declare namespace Sinon { * Returns true if the spy was called before @param anotherSpy * @param anotherSpy */ - calledBefore(anotherSpy: SinonSpy): boolean; + calledBefore(anotherSpy: SinonInspectable): boolean; /** * Returns true if the spy was called after @param anotherSpy * @param anotherSpy */ - calledAfter(anotherSpy: SinonSpy): boolean; + calledAfter(anotherSpy: SinonInspectable): boolean; /** * Returns true if spy was called before @param anotherSpy, and no spy calls occurred between spy and @param anotherSpy. * @param anotherSpy */ - calledImmediatelyBefore(anotherSpy: SinonSpy): boolean; + calledImmediatelyBefore(anotherSpy: SinonInspectable): boolean; /** * Returns true if spy was called after @param anotherSpy, and no spy calls occurred between @param anotherSpy and spy. * @param anotherSpy */ - calledImmediatelyAfter(anotherSpy: SinonSpy): boolean; + calledImmediatelyAfter(anotherSpy: SinonInspectable): boolean; /** * Returns true if the spy was always called with @param obj as this. * @param obj diff --git a/types/sinon/ts3.1/sinon-tests.ts b/types/sinon/ts3.1/sinon-tests.ts index 6251692c2d..05b582b9db 100644 --- a/types/sinon/ts3.1/sinon-tests.ts +++ b/types/sinon/ts3.1/sinon-tests.ts @@ -379,6 +379,7 @@ function testSpy() { let fn = (arg: string, arg2: number): boolean => true; const obj = class { foo() { } + foobar(p1?: string) { return p1; } set bar(val: number) { } get bar() { return 0; } }; @@ -387,8 +388,19 @@ function testSpy() { const spy = sinon.spy(); // $ExpectType SinonSpy const spyTwo = sinon.spy().named('spyTwo'); - const methodSpy = sinon.spy(instance, 'foo'); - const methodSpy2 = sinon.spy(instance, 'bar', ['set', 'get']); + const methodSpy = sinon.spy(instance, 'foo'); // $ExpectType SinonSpy<[], void> + const methodSpy2 = sinon.spy(instance, 'bar', ['set', 'get']); // $ExpectType SinonSpy + const methodSpy3 = sinon.spy(instance, 'foobar'); // $ExpectType SinonSpy<[(string | undefined)?], string | undefined> + + methodSpy.calledBefore(methodSpy2); + methodSpy.calledAfter(methodSpy2); + methodSpy.calledImmediatelyBefore(methodSpy2); + methodSpy.calledImmediatelyAfter(methodSpy2); + + methodSpy.calledBefore(methodSpy3); + methodSpy.calledAfter(methodSpy3); + methodSpy.calledImmediatelyBefore(methodSpy3); + methodSpy.calledImmediatelyAfter(methodSpy3); let count = 0; count = spy.callCount; diff --git a/types/storybook__addon-notes/index.d.ts b/types/storybook__addon-notes/index.d.ts deleted file mode 100644 index d858e11e9e..0000000000 --- a/types/storybook__addon-notes/index.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Type definitions for @storybook/addon-notes 4.0 -// Project: https://github.com/storybooks/storybook, https://github.com/storybooks/storybook/tree/master/addons/notes -// Definitions by: Joscha Feth -// A.MacLeay -// Michael Loughry -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 - -import * as React from 'react'; -import { RenderFunction, StoryDecorator } from '@storybook/react'; -import { MarkedOptions } from 'marked'; - -export type WithNotesOptions = string | { - text: string; -} | { - markdown: string; - markdownOptions?: MarkedOptions; -}; - -// It would be preferable to infer the argument types, but that requires TS v 3.1 -// export function withNotes(...args: StoryDecorator extends (...a: infer A) => any ? A : never): ReturnType; -export function withNotes(story: RenderFunction, context: { kind: string, story: string }): ReturnType; -// Less-preferred but still supported: -export function withNotes(options?: WithNotesOptions): StoryDecorator; -export function withMarkdownNotes(markdown: string, options?: MarkedOptions): StoryDecorator; diff --git a/types/storybook__addon-notes/storybook__addon-notes-tests.tsx b/types/storybook__addon-notes/storybook__addon-notes-tests.tsx deleted file mode 100644 index edfe0daf14..0000000000 --- a/types/storybook__addon-notes/storybook__addon-notes-tests.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import * as React from 'react'; - -import { addDecorator, storiesOf } from '@storybook/react'; -import { withNotes, withMarkdownNotes, } from '@storybook/addon-notes'; - -// New, preferred global registration: -addDecorator(withNotes); - -const SIMPLE_MARKDOWN = ` -## Markdown for component - -A very simple component with markdown notes -`; - -storiesOf('Component', module) - .addDecorator(withNotes()) - .add('with withNotes', - () => (
my component
) - ); - -storiesOf('Component', module) - .addDecorator(withNotes('Some text')) - .add('with withNotes', - () => (
my component
) - ); - -storiesOf('Component', module) - .addDecorator(withNotes({ text: 'Some text' })) - .add('with withNotes', - () => (
my component
) - ); - -storiesOf('Component', module) - .addDecorator(withNotes({ markdown: 'Some text' })) - .add('with withNotes', - () => (
my component
) - ); - -storiesOf('Component', module) - .addDecorator(withNotes({ markdown: 'Some text', markdownOptions: { sanitize: true } })) - .add('with withNotes', - () => (
my component
) - ); diff --git a/types/storybook__preact/index.d.ts b/types/storybook__preact/index.d.ts new file mode 100644 index 0000000000..0917f2cd21 --- /dev/null +++ b/types/storybook__preact/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for @storybook/preact 5.0 +// Project: https://github.com/storybooks/storybook, https://github.com/storybooks/storybook/tree/master/app/preact +// Definitions by: Keisuke Kan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.3 +// Created with the help of storybook__react types + +/// + +import * as Preact from 'preact'; + +export type Renderable = Preact.AnyComponent | JSX.Element; +export type RenderFunction = () => Renderable | Renderable[]; + +export interface DecoratorParameters { + [key: string]: any; +} +export type StoryDecorator = (story: RenderFunction, context: { kind: string, story: string }) => Renderable | null; + +export interface Story { + readonly kind: string; + add(storyName: string, callback: RenderFunction, parameters?: DecoratorParameters): this; + addDecorator(decorator: StoryDecorator): this; + addParameters(parameters: DecoratorParameters): this; +} + +export function addDecorator(decorator: StoryDecorator): void; +export function addParameters(parameters: DecoratorParameters): void; +export function clearDecorators(): void; +export function configure(fn: () => void, module: NodeModule): void; +export function setAddon(addon: object): void; +export function storiesOf(name: string, module: NodeModule): Story; +export function storiesOf(name: string, module: NodeModule): Story & T; +export function forceReRender(): void; + +export interface StoryObject { + name: string; + render: RenderFunction; +} + +export interface StoryBucket { + kind: string; + stories: StoryObject[]; +} + +export function getStorybook(): StoryBucket[]; diff --git a/types/storybook__preact/package.json b/types/storybook__preact/package.json new file mode 100644 index 0000000000..b74d0d14dc --- /dev/null +++ b/types/storybook__preact/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "preact": "^8.4.2" + } +} diff --git a/types/storybook__preact/storybook__preact-tests.tsx b/types/storybook__preact/storybook__preact-tests.tsx new file mode 100644 index 0000000000..72651611c5 --- /dev/null +++ b/types/storybook__preact/storybook__preact-tests.tsx @@ -0,0 +1,45 @@ +/** @jsx h */ +import { h } from 'preact'; +import { storiesOf, setAddon, addDecorator, addParameters, configure, getStorybook, RenderFunction, Story, forceReRender, DecoratorParameters, clearDecorators } from '@storybook/preact'; + +const Decorator = (story: RenderFunction) =>
{story()}
; +const parameters: DecoratorParameters = { parameter: 'foo' }; + +forceReRender(); + +storiesOf('Welcome', module) + // local addDecorator + .addDecorator(Decorator) + .add('to Storybook', () =>
) + .add('to Storybook as Array', () => [
,
]) + .add('and a story with additional parameters', () =>
, parameters); + +// global addDecorator +addDecorator(Decorator); +addParameters(parameters); +clearDecorators(); + +// setAddon +interface AnyAddon { + addWithSideEffect(this: Story & T, storyName: string, storyFn: RenderFunction): Story & T; +} +const AnyAddon: AnyAddon = { + addWithSideEffect(this: Story & T, storyName: string, storyFn: RenderFunction): Story & T { + console.log(this.kind === 'withAnyAddon'); + return this.add(storyName, storyFn); + } +}; +setAddon(AnyAddon); +storiesOf('withAnyAddon', module) + .addWithSideEffect('custom story', () =>
) + .addWithSideEffect('more', () =>
) + .add('another story', () =>
) + .add('to Storybook as Array', () => [
,
]) + .add('and a story with additional parameters', () =>
, parameters) + .addWithSideEffect('even more', () =>
); + +// configure +configure(() => undefined, module); + +// getStorybook +getStorybook().forEach(({ kind, stories }) => stories.forEach(({ name, render }) => render())); diff --git a/types/storybook__addon-notes/tsconfig.json b/types/storybook__preact/tsconfig.json similarity index 69% rename from types/storybook__addon-notes/tsconfig.json rename to types/storybook__preact/tsconfig.json index 2bc7d76ea8..3ded473006 100644 --- a/types/storybook__addon-notes/tsconfig.json +++ b/types/storybook__preact/tsconfig.json @@ -10,16 +10,13 @@ "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "jsx": "react", + "jsx": "preserve", "typeRoots": [ "../" ], "paths": { - "@storybook/addon-notes": [ - "storybook__addon-notes" - ], - "@storybook/react": [ - "storybook__react" + "@storybook/preact": [ + "storybook__preact" ] }, "types": [], @@ -28,6 +25,6 @@ }, "files": [ "index.d.ts", - "storybook__addon-notes-tests.tsx" + "storybook__preact-tests.tsx" ] -} \ No newline at end of file +} diff --git a/types/storybook__preact/tslint.json b/types/storybook__preact/tslint.json new file mode 100644 index 0000000000..71ee04c4e1 --- /dev/null +++ b/types/storybook__preact/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index 2a93740f3f..840b1ee62d 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -1982,9 +1982,9 @@ declare namespace Stripe { billing: "charge_automatically" | "send_invoice"; /** - * Indicates the reason why the invoice was created. subscription_cycle indicates an invoice created by a subscription advancing into a new period. subscription_update indicates an invoice created due to creating or updating a subscription. subscription is set for all old invoices to indicate either a change to a subscription or a period advancement. manual is set for all invoices unrelated to a subscription (for example: created via the invoice editor). The upcoming value is reserved for simulated invoices per the upcoming invoice endpoint. + * Indicates the reason why the invoice was created. subscription_cycle indicates an invoice created by a subscription advancing into a new period. subscription_create indicates an invoice created due to creating a subscription. subscription_update indicates an invoice created due to creating or updating a subscription. subscription is set for all old invoices to indicate either a change to a subscription or a period advancement. manual is set for all invoices unrelated to a subscription (for example: created via the invoice editor). The upcoming value is reserved for simulated invoices per the upcoming invoice endpoint. subscription_threshold indicates an invoice created due to a billing threshold being reached. */ - billing_reason: "subscription_cycle" | "subscription_update" | "subscription" | "manual" | "upcoming"; + billing_reason: "subscription_cycle" | "subscription_create" | "subscription_update" | "subscription" | "manual" | "upcoming" | "subscription_threshold"; /** * ID of the latest charge generated for this invoice, if any. [Expandable] diff --git a/types/strophejs-plugin-roster/index.d.ts b/types/strophejs-plugin-roster/index.d.ts new file mode 100644 index 0000000000..d6188a5fc2 --- /dev/null +++ b/types/strophejs-plugin-roster/index.d.ts @@ -0,0 +1,58 @@ +// Type definitions for strophejs-plugin-roster 1.1 +// Project: https://github.com/strophe/strophejs-plugin-roster#readme +// Definitions by: LeartS +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import { Strophe } from 'strophe.js'; + +export {}; + +export type IqCallback = (stanza: Element) => any; +export type IqID = string; +export type RosterSubscriptionState = 'none' | 'to' | 'from' | 'both' | 'remove'; +export type PresenceSubscriptionType = 'subscribe' | 'unsubscribe' | 'subscribed' | 'unsubscribed'; + +export interface RosterResource { + priority: string; + show: string; + status: string; +} + +export interface RosterItem { + name: string; + jid: string; + subscription: RosterSubscriptionState; + ask: string; + groups: string[]; + resources: {[resourceId: string]: RosterResource}; +} + +export type RosterUpdateCallback = +(items: RosterItem[], item: RosterItem, previousItem: RosterItem) => any; +export type PresenceRequestCallback = (from: string) => any; + +interface StropheRosterPlugin { + supportVersioning(): boolean; + get(userCallback: IqCallback, ver?: string, items?: string[]): IqID; + registerCallback(callback: RosterUpdateCallback): void; + registerRequestCallback(callback: PresenceRequestCallback): void; + findItem(jid: string): RosterItem | false; + removeItem(jid: string): boolean; + subscribe(jid: string, message?: string, nick?: string): void; + unsubscribe(jid: string, message?: string): void; + authorize(jid: string, message?: string): void; + unauthorize(jid: string, message?: string): void; + add(jid: string, name: string, groups: string[], call_back?: IqCallback): IqID; + update(jid: string, name?: string, groups?: string[], call_back?: IqCallback): IqID; + remove(jid: string, call_back?: IqCallback): void; +} + +/*~ Here, declare the same module as the one you imported above */ +declare module 'strophe.js' { + namespace Strophe { + interface Connection { + roster: StropheRosterPlugin; + } + } +} diff --git a/types/strophejs-plugin-roster/strophejs-plugin-roster-tests.ts b/types/strophejs-plugin-roster/strophejs-plugin-roster-tests.ts new file mode 100644 index 0000000000..10f005826b --- /dev/null +++ b/types/strophejs-plugin-roster/strophejs-plugin-roster-tests.ts @@ -0,0 +1,43 @@ +import { RosterItem } from 'strophejs-plugin-roster'; + +// Test that RosterItem interface is correctly exported +// Pretty common for users to extend it in their own custom types +interface AugmentedRosterItem extends RosterItem { + customField: string; +} + +function onSubscribeRequest(from: string) { + // Automatically accept and also send "inverse" subscribe request so that + // both users will be in each other rosters with subscription="both" + connection.roster.authorize(from); + connection.roster.subscribe(from); + connection.roster.unsubscribe(from); + connection.roster.unauthorize(from); + return true; +} + +function onRosterUpdate(items: RosterItem[], updatedItem?: RosterItem): void { + if (updatedItem && updatedItem.subscription === 'remove') { + // This is the case where we (or another of our resources) + // deleted a roster item using a roster set + // and this is the server's resulting roster push. + console.log(`Successfully removed ${updatedItem.jid} from roster`); + } +} + +const connection = new Strophe.Connection('someservice'); + +function onRosterAdd(stanza: Element) { + console.log(stanza.tagName); +} + +// Initial roster ask in order to become "interested resource" +connection.roster.get(() => console.log('Sent initial roster request')); +connection.roster.registerRequestCallback(onSubscribeRequest); +connection.roster.registerCallback(onRosterUpdate); + +connection.roster.add('node@domain/resource', 'Contact One', ['group1'], onRosterAdd); +connection.roster.update('node@domain/resource', undefined, ['group1', 'group2']); +const contactOne: RosterItem = (connection.roster.findItem('node@domain/resource') || undefined)!; +contactOne.groups.length === 2; +connection.roster.remove(contactOne.jid); diff --git a/types/strophejs-plugin-roster/tsconfig.json b/types/strophejs-plugin-roster/tsconfig.json new file mode 100644 index 0000000000..07a6d097a2 --- /dev/null +++ b/types/strophejs-plugin-roster/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "strophejs-plugin-roster-tests.ts" + ] +} diff --git a/types/strophejs-plugin-roster/tslint.json b/types/strophejs-plugin-roster/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/strophejs-plugin-roster/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/stylelint-webpack-plugin/index.d.ts b/types/stylelint-webpack-plugin/index.d.ts index 21405d739d..35a8a21f7f 100644 --- a/types/stylelint-webpack-plugin/index.d.ts +++ b/types/stylelint-webpack-plugin/index.d.ts @@ -33,5 +33,6 @@ declare namespace StylelintWebpackPlugin { lintDirtyModulesOnly?: boolean; syntax?: string; quiet?: boolean; + fix?: boolean; } } diff --git a/types/svg4everybody/index.d.ts b/types/svg4everybody/index.d.ts index 376d10befb..3fd79523db 100644 --- a/types/svg4everybody/index.d.ts +++ b/types/svg4everybody/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for svg4everybody 2.1 // Project: https://github.com/jonathantneal/svg4everybody#readme -// Definitions by: BendingBender +// Definitions by: BendingBender , bryceosterhaus // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace svg4everybody; @@ -11,6 +11,7 @@ declare function svg4everybody(options?: svg4everybody.Svg4everybodyOpts): void; declare namespace svg4everybody { interface Svg4everybodyOpts { + attributeName?: string; fallback?(src: string, svg: SVGElement, use: SVGUseElement): string; validate?(src: string, svg: SVGElement, use: SVGUseElement): boolean; nosvg?: boolean; diff --git a/types/svg4everybody/svg4everybody-tests.ts b/types/svg4everybody/svg4everybody-tests.ts index 2a62a71a24..2f1d214b55 100644 --- a/types/svg4everybody/svg4everybody-tests.ts +++ b/types/svg4everybody/svg4everybody-tests.ts @@ -13,6 +13,7 @@ svg4everybody({ }); svg4everybody({ + attributeName: 'data-href', nosvg: true, polyfill: true }); diff --git a/types/tern/lib/tern/index.d.ts b/types/tern/lib/tern/index.d.ts index 22001ed075..dce523d7eb 100644 --- a/types/tern/lib/tern/index.d.ts +++ b/types/tern/lib/tern/index.d.ts @@ -6,7 +6,7 @@ export { }; // #### Programming interface #### export type ConstructorOptions = CtorOptions & (SyncConstructorOptions | ASyncConstructorOptions); -interface CtorOptions { +export interface CtorOptions { /** The definition objects to load into the server’s environment. */ defs?: Def[]; /** The ECMAScript version to parse. Should be either 5 or 6. Default is 6. */ @@ -17,7 +17,7 @@ interface CtorOptions { plugins?: { [key: string]: object }; } -interface SyncConstructorOptions { +export interface SyncConstructorOptions { /** Indicates whether `getFile` is asynchronous. Default is `false`. */ async?: false; /** @@ -29,7 +29,7 @@ interface SyncConstructorOptions { getFile?(filename: string): string; } -interface ASyncConstructorOptions { +export interface ASyncConstructorOptions { /** Indicates whether `getFile` is asynchronous. Default is `false`. */ async: true; /** diff --git a/types/three/index.d.ts b/types/three/index.d.ts index ac754b4575..85e169f0ca 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -43,6 +43,7 @@ export * from './three-FirstPersonControls'; export * from './three-gltfexporter'; export * from './three-gltfloader'; export * from './three-lensflare'; +export * from './three-lut'; export * from './three-mapcontrols'; export * from './three-maskpass'; export * from './three-mtlloader'; diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index d018d3241d..bbd5c6bc26 100755 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -1477,7 +1477,7 @@ export namespace GeometryUtils { * @see src/core/InstancedBufferAttribute.js */ export class InstancedBufferAttribute extends BufferAttribute { - constructor(data: ArrayLike, itemSize: number, meshPerAttribute?: number); + constructor(array: ArrayLike, itemSize: number, normalized?: boolean, meshPerAttribute?: number); meshPerAttribute: number; } diff --git a/types/three/three-lut.d.ts b/types/three/three-lut.d.ts new file mode 100644 index 0000000000..93c05ed742 --- /dev/null +++ b/types/three/three-lut.d.ts @@ -0,0 +1,31 @@ +// https://github.com/mrdoob/three.js/blob/master/examples/js/math/Lut.js + +import { Color, Mesh, Vector3 } from './three-core'; + +export type ColorMapKeyword = 'rainbow'|'cooltowarm'|'blackbody'|'grayscale'; + +export class Lut { + constructor(colormap: ColorMapKeyword, numberofcolors: number); + + addColorMap(colormapName: string, arrayOfColors: Array<[number, string]>) : void; + + changeColorMap(colormap: ColorMapKeyword): Lut; + + changeNumberOfColors(numberofcolors: number): Lut; + + copy(lut: Lut): void; + + getColor(alpha: number): Color; + + setLegendLayout(layout: 'horizontal'|'vertical'): void; + + setLegendOff(): void; + + setLegendOn(): Mesh; + + setLegendPosition(position: Vector3): void; + + setMax(max: number): void; + + setMin(min: number): void; +} diff --git a/types/trusted-types/index.d.ts b/types/trusted-types/index.d.ts index e6e410dfed..78949ba997 100644 --- a/types/trusted-types/index.d.ts +++ b/types/trusted-types/index.d.ts @@ -1,42 +1,54 @@ // Type definitions for trusted-types 1.0 // Project: https://github.com/WICG/trusted-types -// Definitions by: Jakub Vrana +// Definitions by: Jakub Vrana , +// Damien Engels // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 declare class TrustedHTML { - private readonly _TrustedHTMLBrand: true; // To prevent structural typing. + private readonly _brand: true; // To prevent structural typing. } declare class TrustedScript { - private readonly _TrustedScriptBrand: true; // To prevent structural typing. + private readonly _brand: true; // To prevent structural typing. } declare class TrustedScriptURL { - private readonly _TrustedScriptURLBrand: true; // To prevent structural typing. + private readonly _brand: true; // To prevent structural typing. } declare class TrustedURL { - private readonly _TrustedURLBrand: true; // To prevent structural typing. + private readonly _brand: true; // To prevent structural typing. } declare class TrustedTypePolicy { - createHTML(s: string): TrustedHTML; - createScript(s: string): TrustedScript; - createScriptURL(s: string): TrustedScriptURL; - createURL(s: string): TrustedURL; + readonly name: string; + createHTML(input: string): TrustedHTML; + createScript(input: string): TrustedScript; + createScriptURL(input: string): TrustedScriptURL; + createURL(input: string): TrustedURL; } -interface TrustedTypeInnerPolicy { - createHTML(s: string): string; - createScript(s: string): string; - createScriptURL(s: string): string; - createURL(s: string): string; +interface TrustedTypePolicyOptions { + createHTML?: (input: string) => string; + createScript?: (input: string) => string; + createScriptURL?: (input: string) => string; + createURL?: (input: string) => string; } declare class TrustedTypePolicyFactory { - createPolicy(name: string, policy: TrustedTypeInnerPolicy, expose?: boolean): TrustedTypePolicy; - getExposedPolicy(name: string): TrustedTypePolicy; - getPolicyNames(): string[]; + createPolicy( + name: string, + policyOptions: Pick, + expose?: boolean, + ): Pick; + getExposedPolicy(name: string): TrustedTypePolicy|null; + getPolicyNames(): string[]; + + isHTML(value: any): value is TrustedHTML; + isScript(value: any): value is TrustedScript; + isScriptURL(value: any): value is TrustedScriptURL; + isURL(value: any): value is TrustedURL; } declare const TrustedTypes: TrustedTypePolicyFactory; diff --git a/types/trusted-types/trusted-types-tests.ts b/types/trusted-types/trusted-types-tests.ts index 79f79db4b7..e1f754288b 100644 --- a/types/trusted-types/trusted-types-tests.ts +++ b/types/trusted-types/trusted-types-tests.ts @@ -1,17 +1,47 @@ const policy = { - createHTML: (s: string) => s, - createScript: (s: string) => s, - createScriptURL: (s: string) => s, - createURL: (s: string) => s, + createHTML: (s: string) => s, + createScript: (s: string) => s, + createScriptURL: (s: string) => s, + createURL: (s: string) => s, }; +// $ExpectType string[] TrustedTypes.getPolicyNames(); TrustedTypes.createPolicy('default', policy, true); +// $ExpectType TrustedTypePolicy | null TrustedTypes.getExposedPolicy('default'); const trustedTypes = TrustedTypes.createPolicy('test', policy); -trustedTypes.createHTML('') instanceof TrustedHTML; -trustedTypes.createScript('') instanceof TrustedScript; -trustedTypes.createScriptURL('') instanceof TrustedScriptURL; -trustedTypes.createURL('') instanceof TrustedURL; +// $ExpectType string +const policyName = trustedTypes.name; +// $ExpectType TrustedHTML +trustedTypes.createHTML(''); +// $ExpectType TrustedScript +trustedTypes.createScript(''); +// $ExpectType TrustedScriptURL +trustedTypes.createScriptURL(''); +// $ExpectType TrustedURL +trustedTypes.createURL(''); + +const htmlOnlyPolicy = TrustedTypes.createPolicy('htmlOnly', { + createHTML: (html: string) => { + return html; + }, +}); + +// $ExpectType string +const htmlOnlyName = htmlOnlyPolicy.name; +// $ExpectType TrustedHTML +const html = htmlOnlyPolicy.createHTML(''); +// $ExpectError +const script = htmlOnlyPolicy.createScript(''); + +// $ExpectType boolean +TrustedTypes.isHTML(html); +// $ExpectType boolean +TrustedTypes.isScript(html); +// $ExpectType boolean +TrustedTypes.isScriptURL(html); +// $ExpectType boolean +TrustedTypes.isURL(html); diff --git a/types/twilio-video/index.d.ts b/types/twilio-video/index.d.ts index 9b1d483987..2a63736a4a 100644 --- a/types/twilio-video/index.d.ts +++ b/types/twilio-video/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for twilio-video 2.0 // Project: https://twilio.com/video, https://twilio.com -// Definitions by: MindDoc , Darío Blanco +// Definitions by: MindDoc +// Darío Blanco +// katashin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -469,6 +471,7 @@ export type AudioTrackPublication = LocalAudioTrackPublication | RemoteAudioTrac export interface ConnectOptions { abortOnIceServersTimeout?: boolean; audio?: boolean | CreateLocalTrackOptions; + dominantSpeaker?: boolean; iceServers?: RTCIceServer[]; iceServersTimeout?: number; iceTransportPolicy?: RTCIceTransportPolicy; @@ -476,6 +479,7 @@ export interface ConnectOptions { maxAudioBitRate?: number | null; maxVideoBitRate?: number | null; name?: string | null; + networkQuality?: boolean; preferredAudioCodecs?: AudioCodec[]; preferredVideoCodecs?: VideoCodec[] | VideoCodecSettings[]; logLevel?: LogLevel | LogLevels; diff --git a/types/twilio-video/twilio-video-tests.ts b/types/twilio-video/twilio-video-tests.ts index 12291e9555..9407bed52b 100644 --- a/types/twilio-video/twilio-video-tests.ts +++ b/types/twilio-video/twilio-video-tests.ts @@ -8,7 +8,13 @@ let localAudioTrack: Video.LocalAudioTrack | null = null; async function initRoom() { // Connect to Twilio without creating audio and video track - room = await Video.connect('$TOKEN', { name: 'room-name', video: false, audio: false }); + room = await Video.connect('$TOKEN', { + name: 'room-name', + video: false, + audio: false, + dominantSpeaker: true, + networkQuality: true + }); // Create local video track from default input localVideoTrack = await Video.createLocalVideoTrack({ name: 'camera' }); // Create local audio track from default input diff --git a/types/tz-offset/index.d.ts b/types/tz-offset/index.d.ts new file mode 100644 index 0000000000..74bce60780 --- /dev/null +++ b/types/tz-offset/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for tz-offset 0.0 +// Project: https://github.com/node-cron/tz-offset, https://github.com/merencia/tz-offset +// Definitions by: Richard Honor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Timezone = 'Etc/GMT+12' | 'Pacific/Pago_Pago' | 'Pacific/Midway' | 'Pacific/Honolulu' | 'America/Juneau' | 'America/Los_Angeles' | 'America/Tijuana' | 'America/Phoenix' | + 'America/Chihuahua' | 'America/Mazatlan' | 'America/Denver' | 'America/Guatemala' | 'America/Chicago' | 'America/Mexico_City' | 'America/Monterrey' | 'America/Regina' | + 'America/Bogota' | 'America/New_York' | 'America/Indiana/Indianapolis' | 'America/Lima' | 'America/Halifax' | 'America/Caracas' | 'America/Guyana' | 'America/La_Paz' | + 'America/Puerto_Rico' | 'America/Santiago' | 'America/St_Johns' | 'America/Sao_Paulo' | 'America/Argentina/Buenos_Aires' | 'America/Godthab' | 'America/Montevideo' | + 'Atlantic/South_Georgia' | 'Atlantic/Azores' | 'Atlantic/Cape_Verde' | 'Africa/Casablanca' | 'Europe/London' | 'Europe/Lisbon' | 'Africa/Monrovia' | 'Etc/UTC' | + 'Europe/Amsterdam' | 'Europe/Belgrade' | 'Europe/Berlin' | 'Europe/Zurich' | 'Europe/Bratislava' | 'Europe/Brussels' | 'Europe/Budapest' | 'Europe/Copenhagen' | + 'Europe/Dublin' | 'Europe/Ljubljana' | 'Europe/Madrid' | 'Europe/Paris' | 'Europe/Prague' | 'Europe/Rome' | 'Europe/Sarajevo' | 'Europe/Skopje' | 'Europe/Stockholm' | + 'Europe/Vienna' | 'Europe/Warsaw' | 'Africa/Algiers' | 'Europe/Zagreb' | 'Europe/Athens' | 'Europe/Bucharest' | 'Africa/Cairo' | 'Africa/Harare' | 'Europe/Helsinki' | + 'Asia/Jerusalem' | 'Europe/Kaliningrad' | 'Europe/Kiev' | 'Africa/Johannesburg' | 'Europe/Riga' | 'Europe/Sofia' | 'Europe/Tallinn' | 'Europe/Vilnius' | 'Asia/Baghdad' | + 'Europe/Istanbul' | 'Asia/Kuwait' | 'Europe/Minsk' | 'Europe/Moscow' | 'Africa/Nairobi' | 'Asia/Riyadh' | 'Europe/Volgograd' | 'Asia/Tehran' | 'Asia/Muscat' | 'Asia/Baku' | + 'Europe/Samara' | 'Asia/Tbilisi' | 'Asia/Yerevan' | 'Asia/Kabul' | 'Asia/Yekaterinburg' | 'Asia/Karachi' | 'Asia/Tashkent' | 'Asia/Kolkata' | 'Asia/Colombo' | + 'Asia/Kathmandu' | 'Asia/Almaty' | 'Asia/Dhaka' | 'Asia/Urumqi' | 'Asia/Rangoon' | 'Asia/Bangkok' | 'Asia/Jakarta' | 'Asia/Krasnoyarsk' | 'Asia/Novosibirsk' | 'Asia/Shanghai' | + 'Asia/Chongqing' | 'Asia/Hong_Kong' | 'Asia/Irkutsk' | 'Asia/Kuala_Lumpur' | 'Australia/Perth' | 'Asia/Singapore' | 'Asia/Taipei' | 'Asia/Ulaanbaatar' | 'Asia/Tokyo' | + 'Asia/Seoul' | 'Asia/Yakutsk' | 'Australia/Adelaide' | 'Australia/Darwin' | 'Australia/Brisbane' | 'Australia/Melbourne' | 'Pacific/Guam' | 'Australia/Hobart' | + 'Pacific/Port_Moresby' | 'Australia/Sydney' | 'Asia/Vladivostok' | 'Asia/Magadan' | 'Pacific/Noumea' | 'Pacific/Guadalcanal' | 'Asia/Srednekolymsk' | 'Pacific/Auckland' | + 'Pacific/Fiji' | 'Asia/Kamchatka' | 'Pacific/Majuro' | 'Pacific/Chatham' | 'Pacific/Tongatapu' | 'Pacific/Apia' | 'Pacific/Fakaofo'; + +export function offsetOf(timezone: Timezone): number; + +export function removeOffset(date: Date): number; + +export function timeAt(date: Date, timezone: Timezone): Date; diff --git a/types/tz-offset/tsconfig.json b/types/tz-offset/tsconfig.json new file mode 100644 index 0000000000..b4743b31f7 --- /dev/null +++ b/types/tz-offset/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "dom", + "es6" + ], + "noImplicitAny": true, + "strictNullChecks": true, + "noImplicitThis": true, + "noUnusedLocals": true, + "strictFunctionTypes": true, + "noUnusedParameters": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "tz-offset-tests.ts" + ] +} diff --git a/types/tz-offset/tslint.json b/types/tz-offset/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/tz-offset/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/tz-offset/tz-offset-tests.ts b/types/tz-offset/tz-offset-tests.ts new file mode 100644 index 0000000000..d0e1ae9e81 --- /dev/null +++ b/types/tz-offset/tz-offset-tests.ts @@ -0,0 +1,26 @@ +import tzOffset = require('tz-offset'); + +// $ExpectType number +tzOffset.offsetOf('Etc/GMT+12'); +// $ExpectError +tzOffset.offsetOf('invalid TZ'); + +// $ExpectType number +tzOffset.removeOffset(new Date()); +// $ExpectError +tzOffset.removeOffset('invalid date'); + +// $ExpectType Date +tzOffset.timeAt(new Date(), 'America/Lima'); +// $ExpectError +tzOffset.timeAt(new Date(), 'invalid TZ'); +// $ExpectError +tzOffset.timeAt('invalid date', 'Pacific/Pago_Pago'); +// $ExpectError +tzOffset.timeAt('invalid date', 'invalid TZ'); + +const timezone: tzOffset.Timezone = 'Europe/Brussels'; +console.log(timezone); +// $ExpectError +const notTimezone: tzOffset.Timezone = 'invalid TS'; +console.log(notTimezone); diff --git a/types/unique-push-id/index.d.ts b/types/unique-push-id/index.d.ts new file mode 100644 index 0000000000..0c7b6a2874 --- /dev/null +++ b/types/unique-push-id/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for unique-push-id 1.0 +// Project: https://github.com/limit-zero/unique-push-id +// Definitions by: Nathan Amick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +/** + * Fancy ID generator that creates 20-character string identifiers with the following properties: + * + * 1. They're based on timestamp so that they sort *after* any existing ids. + * 2. They contain 72-bits of random data after the timestamp so that IDs won't collide with other clients' IDs. + * 3. They sort *lexicographically* (so the timestamp is converted to characters that will sort properly). + * 4. They're monotonically increasing. Even if you generate more than one in the same timestamp, the + * latter ones will sort after the former ones. We do this by using the previous random bits + * but "incrementing" them by 1 (only in the case of a timestamp collision). + * + * @returns A unique, chronological, lexicographical 20-character string identifier. + */ +declare function pushId(): string; + +export = pushId; diff --git a/types/unique-push-id/tsconfig.json b/types/unique-push-id/tsconfig.json new file mode 100644 index 0000000000..115ecafc67 --- /dev/null +++ b/types/unique-push-id/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "unique-push-id-tests.ts" + ] +} diff --git a/types/unique-push-id/tslint.json b/types/unique-push-id/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/unique-push-id/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/unique-push-id/unique-push-id-tests.ts b/types/unique-push-id/unique-push-id-tests.ts new file mode 100644 index 0000000000..3db6422d8f --- /dev/null +++ b/types/unique-push-id/unique-push-id-tests.ts @@ -0,0 +1,3 @@ +import pushId from "unique-push-id"; + +pushId(); // $ExpectType string diff --git a/types/uslug/index.d.ts b/types/uslug/index.d.ts new file mode 100644 index 0000000000..c248562dc1 --- /dev/null +++ b/types/uslug/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for uslug 1.0 +// Project: https://github.com/jeremys/uslug +// Definitions by: Junyoung Choi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Generate a slug for the string passed. + * @param value The string you want to slugify + * @param options An optional object that can contain: + * - allowedChars: a String of chars that you want to be whitelisted. Default: '-_~'. + * - lower: a Boolean to force to lower case the slug. Default: true. + * - spaces: a Boolean to allow spaces. Default: false. + */ +declare function uslug(value: string, options?: uslug.UslugOptions): string; + +declare namespace uslug { + interface UslugOptions { + allowedChars?: string; + lower?: boolean; + spaces?: boolean; + } +} + +export = uslug; diff --git a/types/uslug/tsconfig.json b/types/uslug/tsconfig.json new file mode 100644 index 0000000000..b7ed02eddf --- /dev/null +++ b/types/uslug/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "uslug-tests.ts" + ] +} \ No newline at end of file diff --git a/types/uslug/tslint.json b/types/uslug/tslint.json new file mode 100644 index 0000000000..30a1bdde2e --- /dev/null +++ b/types/uslug/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/uslug/uslug-tests.ts b/types/uslug/uslug-tests.ts new file mode 100644 index 0000000000..48a108ca44 --- /dev/null +++ b/types/uslug/uslug-tests.ts @@ -0,0 +1,8 @@ +import uslug = require("uslug"); + +uslug('Быстрее и лучше!'); // 'быстрее-и-лучше' +uslug('汉语/漢語'); // '汉语漢語' + +uslug('Y U NO', { lower: false }); // 'Y-U-NO' +uslug('Y U NO', { spaces: true }); // 'y u no' +uslug('Y-U|NO', { allowedChars: '|' }); // 'yu|no' diff --git a/types/utm/index.d.ts b/types/utm/index.d.ts new file mode 100644 index 0000000000..e52f6e01db --- /dev/null +++ b/types/utm/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for utm 1.1 +// Project: https://github.com/timothygu/utm#readme +// Definitions by: Hyeonsoo David Lee +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function fromLatLon( + latitude: number, + longitude: number, + forceZoneNum?: number, +): { + easting: number + northing: number + zoneNum: number + zoneLetter: string +}; + +export function toLatLon( + easting: number, + northing: number, + zoneNum: number, + zoneLetter: string, + northern: boolean, + strict?: boolean, +): { + latitude: number + longitude: number +}; diff --git a/types/opn/tsconfig.json b/types/utm/tsconfig.json similarity index 94% rename from types/opn/tsconfig.json rename to types/utm/tsconfig.json index 7551867ee1..581d9d392d 100644 --- a/types/opn/tsconfig.json +++ b/types/utm/tsconfig.json @@ -6,8 +6,8 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": true, "strictFunctionTypes": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "opn-tests.ts" + "utm-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/utm/tslint.json b/types/utm/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/utm/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/utm/utm-tests.ts b/types/utm/utm-tests.ts new file mode 100644 index 0000000000..10b3a984f6 --- /dev/null +++ b/types/utm/utm-tests.ts @@ -0,0 +1,23 @@ +import { fromLatLon, toLatLon } from 'utm'; + +const latLon1 = { + lat: 37.240778, + lon: 131.869556, +}; + +const utmCoord1 = fromLatLon(latLon1.lat, latLon1.lon); + +const latLon2 = toLatLon( + utmCoord1.easting, + utmCoord1.northing, + utmCoord1.zoneNum, + utmCoord1.zoneLetter, + true, +); + +const utmCoord2 = fromLatLon(latLon2.latitude, latLon2.longitude); + +utmCoord1.easting === utmCoord2.easting; +utmCoord1.northing === utmCoord2.northing; +utmCoord1.zoneNum === utmCoord2.zoneNum; +utmCoord1.zoneLetter === utmCoord2.zoneLetter; diff --git a/types/validator/index.d.ts b/types/validator/index.d.ts index 01ac19882f..9e07dee1bd 100644 --- a/types/validator/index.d.ts +++ b/types/validator/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for validator.js v10.9.0 +// Type definitions for validator.js v10.11.0 // Project: https://github.com/chriso/validator.js // Definitions by: tgfjt // Ilya Mochalov @@ -8,6 +8,7 @@ // Bonggyun Lee // Naoto Yokoyama // Philipp Katz +// Jace Warren // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace ValidatorJS { @@ -140,6 +141,9 @@ declare namespace ValidatorJS { // check if the string is valid JSON (note: uses JSON.parse). isJSON(str: string): boolean; + // check if the string is valid JWT token. + isJWT(str: string): boolean; + // check if the string is a valid latitude-longitude coordinate in the format lat,long or lat, long. isLatLong(str: string): boolean; @@ -589,6 +593,11 @@ declare module "validator/lib/isJSON" { export = isJSON; } +declare module "validator/lib/isJWT" { + const isJWT: typeof validator.isJWT; + export = isJWT; +} + declare module "validator/lib/isLatLong" { const isLatLong: typeof validator.isLatLong; export = isLatLong; diff --git a/types/validator/validator-tests.ts b/types/validator/validator-tests.ts index 09a9a7ba17..a9f27fce4a 100644 --- a/types/validator/validator-tests.ts +++ b/types/validator/validator-tests.ts @@ -41,6 +41,7 @@ import isISRCFunc = require('validator/lib/isISRC'); import isInFunc = require('validator/lib/isIn'); import isIntFunc = require('validator/lib/isInt'); import isJSONFunc = require('validator/lib/isJSON'); +import isJWTFunc = require('validator/lib/isJWT'); import isLatLongFunc = require('validator/lib/isLatLong'); import isLengthFunc = require('validator/lib/isLength'); import isLowercaseFunc = require('validator/lib/isLowercase'); @@ -181,6 +182,9 @@ import whitelistFunc = require('validator/lib/whitelist'); let _isJSON = validator.isJSON; _isJSON = isJSONFunc; + let _isJWT = validator.isJWT; + _isJWT = isJWTFunc; + let _isLatLong = validator.isLatLong; _isLatLong = isLatLongFunc; diff --git a/types/vis/index.d.ts b/types/vis/index.d.ts index 827c71b260..813a149baf 100644 --- a/types/vis/index.d.ts +++ b/types/vis/index.d.ts @@ -1828,6 +1828,13 @@ export interface NodeOptions { level?: number; + margin?: { + top?: number; + right?: number; + bottom?: number; + left?: number; + }; + mass?: number; physics?: boolean; @@ -1839,11 +1846,11 @@ export interface NodeOptions { shape?: string; shapeProperties?: { - borderDashes: boolean | number[], // only for borders - borderRadius: number, // only for box shape - interpolation: boolean, // only for image and circularImage shapes - useImageSize: boolean, // only for image and circularImage shapes - useBorderWithImage: boolean // only for image shape + borderDashes?: boolean | number[], // only for borders + borderRadius?: number, // only for box shape + interpolation?: boolean, // only for image and circularImage shapes + useImageSize?: boolean, // only for image and circularImage shapes + useBorderWithImage?: boolean // only for image shape }; size?: number; diff --git a/types/workbox-webpack-plugin/index.d.ts b/types/workbox-webpack-plugin/index.d.ts index b08aa72c98..8fa7d95db6 100644 --- a/types/workbox-webpack-plugin/index.d.ts +++ b/types/workbox-webpack-plugin/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for workbox-webpack-plugin 3.6 +// Type definitions for workbox-webpack-plugin 4.1 // Project: https://github.com/GoogleChrome/workbox/blob/master/packages/workbox-webpack-plugin, https://github.com/googlechrome/workbox // Definitions by: Kevin Groat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export type ChacheStrategy = 'cacheFirst' | 'cacheOnly' | 'networkFirst' | 'networkOnly' | 'staleWhileRevalidate'; +export type ChacheStrategy = 'CacheFirst' | 'CacheOnly' | 'NetworkFirst' | 'NetworkOnly' | 'StaleWhileRevalidate'; export interface ManifestEntry { revision: string; diff --git a/types/workbox-webpack-plugin/v3/index.d.ts b/types/workbox-webpack-plugin/v3/index.d.ts new file mode 100644 index 0000000000..b08aa72c98 --- /dev/null +++ b/types/workbox-webpack-plugin/v3/index.d.ts @@ -0,0 +1,461 @@ +// Type definitions for workbox-webpack-plugin 3.6 +// Project: https://github.com/GoogleChrome/workbox/blob/master/packages/workbox-webpack-plugin, https://github.com/googlechrome/workbox +// Definitions by: Kevin Groat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type ChacheStrategy = 'cacheFirst' | 'cacheOnly' | 'networkFirst' | 'networkOnly' | 'staleWhileRevalidate'; + +export interface ManifestEntry { + revision: string; + url: string; +} + +export interface RuntimeCacheOptions { + /** + * Fall back to the cache after X seconds. + */ + networkTimeoutSeconds?: number; + + /** + * A custom cache name for this route. + */ + cacheName?: string; + + /** + * Custom cache expiration. + */ + expiration?: { + /** + * Cache will only hold X entries. + */ + maxEntries?: number; + /** + * Cache will only hold entries for X seconds. + */ + maxAgeSeconds?: number; + }; + + /** + * Configure background sync. + */ + backgroundSync?: { + name: string; + options?: { + maxRetentionTime: number; + }; + }; + + /** + * Configure which responses are considered cacheable. + */ + cacheableResponse?: { + /** + * Only cache responses with HTTP code(s) listed. + */ + statuses?: number[]; + /** + * Only cache responses with headers which match this map. + */ + headers?: { [header: string]: string }; + }; + + /** + * Configure the broadcast cache update plugin. + */ + broadcastUpdate?: { + channelName?: string; + }; + + /** + * Add in any additional plugin logic you need. + */ + plugins?: any[]; + + /** + * Used to configure the handler. + */ + fetchOptions?: any; + + /** + * Used to configure the handler. + */ + matchOptions?: any; +} + +export interface RuntimeCacheRule { + /** + * Cache any same-origin request that matches the pattern. + */ + urlPattern?: string | RegExp; + + /** + * The `handler` values are strings, corresponding to names of the strategies supported by + * [`workbox.strategies`](https://developers.google.com/web/tools/workbox/reference-docs/latest/workbox.strategies#methods). + */ + handler?: ChacheStrategy; + + /** + * The `options` properties can be used to configure instances of the cache expiration, cacheable response, and broadcast cache update plugins to apply to a given route. + */ + options?: RuntimeCacheOptions; +} + +export interface CommonOptions { + /** + * The path and filename of the service worker file that will be created by the build process, relative to the webpack output directory. + * + * @default 'service-worker.js' + * @example swDest: 'custom-sw-name.js' + */ + swDest?: string; + + /** + * Valid values are `'cdn'`, `'local'`, and `'disabled'`. + * + * - `'cdn'`, the default, will use a URL for the Workbox runtime libraries hosted on a highly-available Google Cloud Storage instance. + * + * - `'local'` will copy all of the Workbox runtime libraries into a versioned directory alongside your generated service worker, and configure the service worker to use those local copies. + * This option is provided for developers who would prefer to host everything themselves and not rely on the Google Cloud Storage CDN. + * + * - `'disabled'` will opt-out automatic behavior. It's up to you to host a local copy of the Workbox libraries at your preferred URL, and to pass in the correct path to `workbox-sw.js` + * via the `importScripts` configuration option. + * + * - Note: In webpack, passing in a string corresponding to the webpack chunk name containing a custom Workbox runtime library bundle is also supported. + * + * @default 'cdn' + * @example importWorkboxFrom: 'local' + */ + importWorkboxFrom?: 'cdn' | 'local' | 'disabled'; + + /** + * By default, Workbox will precache assets regardless of which chunk the asset is part of. + * + * If you would like to override this behavior via a whitelist, specify one or more chunk names. Only assets belonging to those chunks will be precached; + * any assets belonging to another chunk or without a chunk association will be skipped. + * + * @default [] + * @example chunks: ['chunk-name-1', 'chunk-name-2'] + */ + chunks?: string[]; + + /** + * By default, Workbox will precache all assets generated by the webpack compilation, regardless of which chunk the asset is part of. + * + * If you would like to override this behavior via a blacklist, specify one or more chunk names. Any assets belonging to those chunks will be skipped. + * + * @default [] + * @example excludeChunks: ['chunk-name-1', 'chunk-name-2'] + */ + excludeChunks?: string[]; + + /** + * This allows you to only include assets matching any of the provided criteria when creating the precache manifest. It provides a filename-based approach to filtering. + * + * This filtering takes place after any chunk-based filtering is applied. + * + * In keeping with [webpack convention](https://webpack.js.org/configuration/module/#condition), the option `test` can be used as an alias/alternative to `include`. + * + * @default [] + * @example include: [/\.html$/, /\.js$/] + * @alias test + */ + include?: Array; + test?: Array; + + /** + * This allows you to specifically omit assets matching any of the provided criteria from being included in the precache manifest. It provides a filename-based approach to filtering. + * + * This filtering takes place after any chunk-based filtering is applied. + * + * @default [/\.map$/, /^manifest.*\.js(?:on)?$/] + * @example exclude: [/\.jpg$/, /\.png$/] + */ + exclude?: Array; + + /** + * Workbox creates assets as part of your webpack build process: a precache manifest file, and potentially a local copy of the Workbox libraries (if `importWorkboxFrom` is set to `'local'`). + * + * These assets will, by default, be created at the root of your webpack build directory, i.e. `output.path`. You can set the `importsDirectory` option if you want these assets to be created in + * a subdirectory of `output.path` instead of at the top-level. + * + * Note: This option does not effect where the main service worker JavaScript file is created. That is determined by the `swDest` option. + * + * @default '' + * @example importsDirectory: 'wb-assets' + */ + importsDirectory?: string; + + /** + * Workbox automatically creates a JavaScript file that contains information about URLs that need to be precached. By default, this file is called `precache-manifest.[manifestHash].js`, + * where `[manifestHash]` is automatically replaced by a unique value that identifies the contents of the file. + * + * `precacheManifestFilename` can be used to override this default filename. You must include the string `[manifestHash]` somewhere as part of the filename. + * + * If you'd like to change the output directory to which the precache manifest is written, you can configure the `importsDirectory` option. + * + * @default 'precache-manifest.[manifestHash].js' + * @example precacheManifestFilename: 'wb-manifest.[manifestHash].js' + */ + precacheManifestFilename?: string; + + /** + * The base directory you wish to match `globPatterns` against, relative to the current working directory. + * + * If you do set this, make sure to also configure `globPatterns`. + * + * @default undefined + * @example globDirectory: '.' + */ + globDirectory?: string; + + /** + * Determines whether or not symlinks are followed when generating the precache manifest. + * + * For more information, see the definition of `follow` in the `glob` [documentation](https://github.com/isaacs/node-glob#options). + * + * @default true + * @example globFollow: false + */ + globFollow?: boolean; + + /** + * A set of patterns matching files to always exclude when generating the precache manifest. + * + * For more information, see the definition of `ignore` in the `glob` [documentation](https://github.com/isaacs/node-glob#options). + * + * @default ['node_modules/**\/*'] + * @example globIgnores: ['**\/ignored.html'] + */ + globIgnores?: string[]; + + /** + * Files matching against any of these patterns will be included in the precache manifest. + * + * For more information, see the [glob primer](https://github.com/isaacs/node-glob#glob-primer). + * + * Note: Setting `globPatterns` is often unnecessary when using the `workbox-webpack-plugin`, which will automatically precache files that are part of the webpack build pipeline by default. + * When using the webpack plugin, only set it when you need to cache + * [non-webpack assets](https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin#cache_additional_non-webpack_assets). + * + * @default [] + * @example globPatterns: ['dist/*.{js,png,html,css}'] + */ + globPatterns?: string[]; + + /** + * If `true`, an error reading a directory when generating a precache manifest will cause the build to fail. If `false`, the problematic directory will be skipped. + * + * For more information, see the definition of `strict` in the `glob` [documentation](https://github.com/isaacs/node-glob#options). + * + * @default true + * @example globStrict: false + */ + globStrict?: boolean; + + /** + * If a URL is rendered generated based on some server-side logic, its contents may depend on multiple files or on some other unique string value. + * + * If used with an array of strings, they will be interpreted as glob patterns, and the contents of any files matching the patterns will be used to uniquely version the URL. + * + * If used with a single string, it will be interpreted as unique versioning information that you've generated out of band for a given URL. + * + * @default null + */ + templatedUrls?: { [url: string]: string | (string[]) } | null; + + /** + * This value can be used to determine the maximum size of files that will be precached. This prevents you from inadvertantly precaching very large files that might have + * accidentally matched one of your patterns. + * + * @default 2097152 + * @example maximumFileSizeToCacheInBytes: 4 * 1024 * 1024 + */ + maximumFileSizeToCacheInBytes?: number; + + /** + * Assets that match this regex will be assumed to be uniquely versioned via their URL, and exempted from the normal HTTP cache-busting that's done when populating the precache. + * + * While not required, it's recommended that if your existing build process already inserts a `[hash]` value into each filename, you provide a RegExp that will detect those values, + * as it will reduce the amount of bandwidth consumed when precaching. + * + * @default null + * @example dontCacheBustUrlsMatching: /\.\w{8}\./ + */ + dontCacheBustUrlsMatching?: RegExp | null; + + /** + * A mapping of prefixes that, if present in an entry in the precache manifest, will be replaced with the corresponding value. + * + * This can be used to, for example, remove or add a path prefix from a manifest entry if your web hosting setup doesn't match your local filesystem setup. + * + * As an alternative with more flexibility, you can use the `manifestTransforms` option and provide a function that modifies the entries in the manifest using whatever logic you provide. + * + * @default null + * @example modifyUrlPrefix: { '/dist': '' } + */ + modifyUrlPrefix?: { [url: string]: string } | null; + + /** + * One or more [`ManifestTransform`](https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build#.ManifestTransform) + * functions, which will be applied sequentially against the generated manifest. + * + * If `modifyUrlPrefix` or `dontCacheBustUrlsMatching` are also specified, their corresponding transformations will be applied first. + */ + manifestTransforms?: Array<(originalManifest: ReadonlyArray) => { manifest: ManifestEntry[], warnings?: string[] }> | null; +} + +export interface GenerateSWOptions extends CommonOptions { + /** + * Whether or not the service worker should skip over the waiting lifecycle stage. Normally this is used with `clientsClaim: true`. + * + * @default false + * @example skipWaiting: true + */ + skipWaiting?: boolean; + + /** + * Whether or not the service worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim) + * any existing clients as soon as it activates. + * + * @default false + * @example clientsClaim: true + */ + clientsClaim?: boolean; + + /** + * Passing in an array of objects containing `urlPatterns`, `handlers`, and potentially `options` will add the appropriate code to the generated service worker to handle runtime caching. + * + * Requests for precached URLs that are picked up via `globPatterns` are handled by default, and don't need to be accommodated in `runtimeCaching`. + * + * @default [] + */ + runtimeCaching?: RuntimeCacheRule[]; + + /** + * This will be used to create a [`NavigationRoute`](https://developers.google.com/web/tools/workbox/reference-docs/latest/workbox.routing.NavigationRoute) + * that will respond to [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests) + * for URLs that that aren't precached. + * + * This is meant to be used in a [Single Page App](https://en.wikipedia.org/wiki/Single-page_application) scenario, in which you want all navigations to use common App Shell HTML. + * + * It's not intended for use as a fallback that's displayed when the browser is offline. + * + * @default undefined + * @example navigateFallback: '/app-shell' + */ + navigateFallback?: string; + + /** + * An optional array of regular expressions that restricts which URLs the configured navigateFallback behavior applies to. + * + * This is useful if only a subset of your site's URLs should be treated as being part of a Single Page App. + * + * If both navigateFallbackBlacklist and navigateFallbackWhitelist are configured, the blacklist takes precedent. + * + * @default [] + * @example navigateFallbackBlacklist: [/^\/_/, /admin/] + */ + navigateFallbackBlacklist?: RegExp[]; + + /** + * An optional array of regular expressions that restricts which URLs the configured navigateFallback behavior applies to. + * + * This is useful if only a subset of your site's URLs should be treated as being part of a Single Page App. + * + * If both navigateFallbackBlacklist and navigateFallbackWhitelist are configured, the blacklist takes precedent. + * + * @default [] + * @example navigateFallbackWhitelist: [/^\/pages/] + */ + navigateFallbackWhitelist?: RegExp[]; + + /** + * An required list of JavaScript files that should be passed to + * [`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts) inside the generated service worker file. + * + * If one of the imported files sets the `self.__precacheManifest` variable to an array of + * [`ManifestEntrys`](https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build#.ManifestEntry), + * those entries will be automatically precached in the generated service worker. + * + * This is also useful when you want to let Workbox create your top-level service worker file, but want to include some additional code, such as a `push` event listener. + * + * @default [] + * @example importScripts: ['push-notifications.abcd1234.js'] + */ + importScripts?: string[]; + + /** + * Any search parameter names that match against one of the regex's in this array will be removed before looking for a precache match. + * + * This is useful if your users might request URLs that contain, for example, URL parameters used to track the source of the traffic. + * Those URL parameters would normally cause the cache lookup to fail, since the URL strings used as cache keys would not be expected to include them. + * + * @default [/^utm_/] + * @example ignoreUrlParametersMatching: [/./] + */ + ignoreUrlParametersMatching?: RegExp[]; + + /** + * If a [navigation request](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests) + * for a URL ending in `/` fails to match a precached URL, this value will be appended to the URL and that will be checked for a precache match. + * + * This should be configured to whatever your web server is using, if anything, for its [directory index](https://httpd.apache.org/docs/2.0/mod/mod_dir.html). + * + * @default 'index.html' + * @example directoryIndex: 'index.html' + */ + directoryIndex?: string; + + /** + * An optional ID to be prepended to cache names used by Workbox. + * + * This is primarily useful for local development where multiple sites may be served from the same `http://localhost:port` origin. + * + * @default null + * @example cacheId: 'my-app' + */ + cacheId?: string | null; + + /** + * Controls whether or not to include support for [offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics). + * + * When `true`, `workbox.googleAnalytics.initialize()` will be added to your new service worker file. + * + * @default false + * @example offlineGoogleAnalytics: true + */ + offlineGoogleAnalytics?: boolean; +} + +export interface InjectManifestOptions extends CommonOptions { + /** + * The path to the source service worker file that can contain your own customized code, in addition to containing a match for `injectionPointRegexp`. + * + * Your service worker file should reference the `self.__precacheManifest` variable to obtain a list of + * [`ManifestEntrys`](https://developers.google.com/web/tools/workbox/reference-docs/latest/module-workbox-build#.ManifestEntry) obtained as part of the compilation: + * `workbox.precaching.precacheAndRoute(self.__precacheManifest)`. + * + * @example swSrc: path.join('src', 'sw.js') + */ + swSrc: string; +} + +/** + * The `GenerateSW` plugin will create a service worker file for you and add it to the webpack asset pipeline. + * + * @see https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin + */ +export class GenerateSW { + constructor(opts?: GenerateSWOptions); + apply(...args: any[]): void; +} + +/** + * The `InjectManifest` plugin will generate a list of URLs to precache and add that precache manifest to an existing service worker file. It will otherwise leave the file as-is. + * + * @see https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin + */ +export class InjectManifest { + constructor(opts?: InjectManifestOptions); + apply(...args: any[]): void; +} diff --git a/types/workbox-webpack-plugin/v3/tsconfig.json b/types/workbox-webpack-plugin/v3/tsconfig.json new file mode 100644 index 0000000000..a671748a3c --- /dev/null +++ b/types/workbox-webpack-plugin/v3/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "workbox-webpack-plugin": [ + "workbox-webpack-plugin/v3" + ], + "workbox-webpack-plugin/*": [ + "workbox-webpack-plugin/v3/*" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} diff --git a/types/workbox-webpack-plugin/v3/tslint.json b/types/workbox-webpack-plugin/v3/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/workbox-webpack-plugin/v3/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/workbox-webpack-plugin/workbox-webpack-plugin-tests.ts b/types/workbox-webpack-plugin/workbox-webpack-plugin-tests.ts index dd3e109b4a..8d48b34630 100644 --- a/types/workbox-webpack-plugin/workbox-webpack-plugin-tests.ts +++ b/types/workbox-webpack-plugin/workbox-webpack-plugin-tests.ts @@ -32,7 +32,7 @@ import { GenerateSW, InjectManifest } from 'workbox-webpack-plugin'; // Match any same-origin request that contains 'api'. urlPattern: /api/, // Apply a network-first strategy. - handler: 'networkFirst', + handler: 'NetworkFirst', options: { // Fall back to the cache after 10 seconds. networkTimeoutSeconds: 10, @@ -75,7 +75,7 @@ import { GenerateSW, InjectManifest } from 'workbox-webpack-plugin'; // To match cross-origin requests, use a RegExp that matches // the start of the origin: urlPattern: new RegExp('^https://cors\.example\.com/'), - handler: 'staleWhileRevalidate', + handler: 'StaleWhileRevalidate', options: { cacheableResponse: { statuses: [0, 200] diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index 152fdd25e4..ff45c00a92 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -383,7 +383,9 @@ arrSchema.min(5, "min"); arrSchema.min(5, () => "min"); arrSchema.compact((value, index, array) => value === array[index]); -yup.array(); // $ExpectType ArraySchema<{}> +const arr = yup.array(); +const top = ((x?: T): T => x!)(); +const validArr: yup.ArraySchema = arr; yup.array(yup.string()); // $ExpectType ArraySchema yup.array().of(yup.string()); // $ExpectType ArraySchema