From c020e662a1b920edec2549e349b6e942f4a80dda Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Tue, 26 Feb 2019 23:24:30 +0100 Subject: [PATCH 1/3] Add TypeScript definition --- .gitignore | 1 + index.d.ts | 202 ++++++++++++++++++++++++++++++++++++++++++++++++ index.js | 5 +- index.test-d.ts | 126 ++++++++++++++++++++++++++++++ package.json | 7 +- 5 files changed, 338 insertions(+), 3 deletions(-) create mode 100644 index.d.ts create mode 100644 index.test-d.ts diff --git a/.gitignore b/.gitignore index 239ecff..7c4e91c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ node_modules yarn.lock +.prettierrc diff --git a/index.d.ts b/index.d.ts new file mode 100644 index 0000000..12564bd --- /dev/null +++ b/index.d.ts @@ -0,0 +1,202 @@ +/// + +export type AddRemoveListener = ( + event: string | symbol, + listener: ( + firstArgument: FirstArgumentType, + ...rest: RestArgumentsType[] + ) => void +) => void; + +export interface Emitter { + on?: AddRemoveListener; + addListener?: AddRemoveListener; + addEventListener?: AddRemoveListener; + off?: AddRemoveListener; + removeListener?: AddRemoveListener; + removeEventListener?: AddRemoveListener; +} + +export type FilterFunction = (element: ElementType) => boolean; + +export interface CancelablePromise extends Promise { + cancel(): void; +} + +/** + * Promisify an event by waiting for it to be emitted. + * + * @param emitter - Event emitter object. Should have either a `.on()`/`.addListener()`/`.addEventListener()` and `.off()`/`.removeListener()`/`.removeEventListener()` method, like the [Node.js `EventEmitter`](https://nodejs.org/api/events.html) and [DOM events](https://developer.mozilla.org/en-US/docs/Web/Events). + * @param event - Name of the event or events to listen to. If the same event is defined both here and in `rejectionEvents`, this one takes priority. **Note**: `event` is a string for a single event type, for example, `'data'`. To listen on multiple events, pass an array of strings, such as `['started', 'stopped']`. + * @returns A `Promise` that is fulfilled when emitter emits an event matching `event`, or rejects if emitter emits any of the events defined in the `rejectionEvents` option. The returned promise has a `.cancel()` method, which when called, removes the event listeners and causes the promise to never be settled. + */ +declare function pEvent( + emitter: Emitter, + event: string | symbol | (string | symbol)[], + options: MultiArgumentsOptions +): CancelablePromise<(EmittedType | EmittedTypeRest)[]>; +declare function pEvent( + emitter: Emitter, + event: string | symbol | (string | symbol)[], + filter: FilterFunction +): CancelablePromise; +declare function pEvent( + emitter: Emitter, + event: string | symbol | (string | symbol)[], + options?: Options +): CancelablePromise; + +export default pEvent; + +/** + * Wait for multiple event emissions. Returns an array. + */ +export function multiple( + emitter: Emitter, + event: string | symbol | (string | symbol)[], + options: MultipleMultiArgumentsOptions +): CancelablePromise<(EmittedType | EmittedTypeRest)[][]>; +export function multiple( + emitter: Emitter, + event: string | symbol | (string | symbol)[], + options: MultipleOptions +): CancelablePromise; + +/** + * @returns An [async iterator](http://2ality.com/2016/10/asynchronous-iteration.html) that lets you asynchronously iterate over events of `event` emitted from `emitter`. The iterator ends when `emitter` emits an event matching any of the events defined in `resolutionEvents`, or rejects if `emitter` emits any of the events defined in the `rejectionEvents` option. + */ +export function iterator( + emitter: Emitter, + event: string | symbol | (string | symbol)[], + options: IteratorMultiArgumentsOptions +): AsyncIterableIterator<(EmittedType | EmittedTypeRest)[]>; +export function iterator( + emitter: Emitter, + event: string | symbol | (string | symbol)[], + filter: FilterFunction +): AsyncIterableIterator; +export function iterator( + emitter: Emitter, + event: string | symbol | (string | symbol)[], + options?: IteratorOptions +): AsyncIterableIterator; + +export interface Options { + /** + * Events that will reject the promise. + * + * @default ['error'] + */ + rejectionEvents?: (string | symbol)[]; + + /** + * By default, the promisified function will only return the first argument from the event callback, which works fine for most APIs. This option can be useful for APIs that return multiple arguments in the callback. Turning this on will make it return an array of all arguments from the callback, instead of just the first argument. This also applies to rejections. + * + * @default false + * + * @example + * + * const pEvent = require('p-event'); + * const emitter = require('./some-event-emitter'); + * + * (async () => { + * const [foo, bar] = await pEvent(emitter, 'finish', {multiArgs: true}); + * })(); + */ + multiArgs?: boolean; + + /** + * Time in milliseconds before timing out. + * + * @default Infinity + */ + timeout?: number; + + /** + * Filter function for accepting an event. + * + * @example + * + * const pEvent = require('p-event'); + * const emitter = require('./some-event-emitter'); + * + * (async () => { + * const result = await pEvent(emitter, '🦄', value => value > 3); + * // Do something with first 🦄 event with a value greater than 3 + * })(); + */ + filter?: FilterFunction; +} + +export interface MultiArgumentsOptions + extends Options { + multiArgs: true; +} + +export interface MultipleOptions extends Options { + /** + * The number of times the event needs to be emitted before the promise resolves. + */ + count: number; + + /** + * Whether to resolve the promise immediately. Emitting one of the `rejectionEvents` won't throw an error. + * + * **Note**: The returned array will be mutated when an event is emitted. + * + * @example + * + * const emitter = new EventEmitter(); + * + * const promise = multiple(emitter, 'hello', { + * resolveImmediately: true, + * count: Infinity + * }); + * + * const result = await promise; + * console.log(result); + * //=> [] + * + * emitter.emit('hello', 'Jack'); + * console.log(result); + * //=> ['Jack'] + * + * emitter.emit('hello', 'Mark'); + * console.log(result); + * //=> ['Jack', 'Mark'] + * + * // Stops listening + * emitter.emit('error', new Error('😿')); + * + * emitter.emit('hello', 'John'); + * console.log(result); + * //=> ['Jack', 'Mark'] + */ + resolveImmediately?: boolean; +} + +export interface MultipleMultiArgumentsOptions + extends MultipleOptions { + multiArgs: true; +} + +export interface IteratorOptions extends Options { + /** + * Maximum number of events for the iterator before it ends. When the limit is reached, the iterator will be marked as `done`. This option is useful to paginate events, for example, fetching 10 events per page. + * + * @default Infinity + */ + limit?: number; + + /** + * Events that will end the iterator. + * + * @default [] + */ + resolutionEvents?: (string | symbol)[]; +} + +export interface IteratorMultiArgumentsOptions + extends IteratorOptions { + multiArgs: true; +} diff --git a/index.js b/index.js index b8ee9b5..31bda5f 100644 --- a/index.js +++ b/index.js @@ -93,7 +93,7 @@ const multiple = (emitter, event, options) => { return ret; }; -module.exports = (emitter, event, options) => { +const pEvent = (emitter, event, options) => { if (typeof options === 'function') { options = {filter: options}; } @@ -111,6 +111,9 @@ module.exports = (emitter, event, options) => { return promise; }; +module.exports = pEvent; +module.exports.default = pEvent; + module.exports.multiple = multiple; module.exports.iterator = (emitter, event, options) => { diff --git a/index.test-d.ts b/index.test-d.ts new file mode 100644 index 0000000..fe52391 --- /dev/null +++ b/index.test-d.ts @@ -0,0 +1,126 @@ +/// + +import {expectType} from 'tsd-check'; +import pEvent, {multiple, iterator, CancelablePromise} from '.'; +import {EventEmitter} from 'events'; +import * as fs from 'fs'; + +class NodeEmitter extends EventEmitter { + on(event: 'finish', listener: (number: number, string: string) => void) { + return this; + } + addListener( + event: 'finish', + listener: (number: number, string: string) => void + ) { + return this; + } + addEventListener( + event: 'finish', + listener: (number: number, string: string) => void + ) { + return this; + } + off(event: 'finish', listener: (number: number, string: string) => void) { + return this; + } + removeListener( + event: 'finish', + listener: (number: number, string: string) => void + ) { + return this; + } + removeEventListener( + event: 'finish', + listener: (number: number, string: string) => void + ) { + return this; + } +} + +class DomEmitter implements EventTarget { + addEventListener( + type: 'foo', + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void {} + + dispatchEvent(event: Event): boolean { + return false; + } + + removeEventListener( + type: 'foo', + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void {} +} + +expectType>(pEvent(new NodeEmitter(), 'finish')); +expectType>( + pEvent(new NodeEmitter(), '🦄', value => value > 3) +); +expectType>(pEvent(new DomEmitter(), 'finish')); +expectType>(pEvent(document, 'DOMContentLoaded')); + +expectType>( + pEvent(new NodeEmitter(), 'finish', {rejectionEvents: ['error']}) +); +expectType>( + pEvent(new NodeEmitter(), 'finish', {timeout: 1}) +); +expectType>( + pEvent(new NodeEmitter(), 'finish', {filter: value => value > 3}) +); +expectType>( + pEvent(new NodeEmitter(), 'finish', {multiArgs: true}) +); + +pEvent(new NodeEmitter(), 'finish').cancel(); + +expectType>( + multiple(new NodeEmitter(), 'hello', {count: Infinity}) +); +expectType>( + multiple(new NodeEmitter(), 'hello', { + resolveImmediately: true, + count: Infinity + }) +); +expectType>( + multiple(new NodeEmitter(), 'hello', { + count: Infinity, + multiArgs: true + }) +); + +expectType>( + iterator(new NodeEmitter(), 'finish') +); +expectType>( + iterator(new NodeEmitter(), '🦄', value => value > 3) +); + +expectType>( + iterator(new NodeEmitter(), 'finish', {limit: 1}) +); +expectType>( + iterator(new NodeEmitter(), 'finish', {resolutionEvents: ['finish']}) +); +expectType>( + iterator(new NodeEmitter(), 'finish', {multiArgs: true}) +); + +async function getOpenReadStream(file: string) { + const stream = fs.createReadStream(file); + await pEvent(stream, 'open'); + return stream; +} + +const stream = await getOpenReadStream('unicorn.txt'); +stream.pipe(process.stdout); + +const result = await pEvent(new NodeEmitter(), 'finish'); +if (result === 1) { + throw new Error('Emitter finished with an error'); +} diff --git a/package.json b/package.json index 2b844cc..3f3c7cf 100644 --- a/package.json +++ b/package.json @@ -13,10 +13,11 @@ "node": ">=8" }, "scripts": { - "test": "xo && ava" + "test": "xo && ava && tsd-check" }, "files": [ - "index.js" + "index.js", + "index.d.ts" ], "keywords": [ "promise", @@ -45,8 +46,10 @@ "p-timeout": "^2.0.1" }, "devDependencies": { + "@types/node": "^11.9.5", "ava": "^1.2.1", "delay": "^4.1.0", + "tsd-check": "^0.3.0", "xo": "^0.24.0" } } From 54ac2564bd1e8078602056f9cd9a48a4d4f55594 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Thu, 28 Feb 2019 17:13:38 +0100 Subject: [PATCH 2/3] remove .prettierrc from .gitignore --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index 7c4e91c..239ecff 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,2 @@ node_modules yarn.lock -.prettierrc From cfb073eab811d8cc40c784a9319f9cad0444f08c Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Thu, 28 Feb 2019 18:25:40 +0100 Subject: [PATCH 3/3] replace any with unknown --- index.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/index.d.ts b/index.d.ts index 12564bd..e0190cf 100644 --- a/index.d.ts +++ b/index.d.ts @@ -36,12 +36,12 @@ declare function pEvent( options: MultiArgumentsOptions ): CancelablePromise<(EmittedType | EmittedTypeRest)[]>; declare function pEvent( - emitter: Emitter, + emitter: Emitter, event: string | symbol | (string | symbol)[], filter: FilterFunction ): CancelablePromise; declare function pEvent( - emitter: Emitter, + emitter: Emitter, event: string | symbol | (string | symbol)[], options?: Options ): CancelablePromise; @@ -57,7 +57,7 @@ export function multiple( options: MultipleMultiArgumentsOptions ): CancelablePromise<(EmittedType | EmittedTypeRest)[][]>; export function multiple( - emitter: Emitter, + emitter: Emitter, event: string | symbol | (string | symbol)[], options: MultipleOptions ): CancelablePromise; @@ -71,12 +71,12 @@ export function iterator( options: IteratorMultiArgumentsOptions ): AsyncIterableIterator<(EmittedType | EmittedTypeRest)[]>; export function iterator( - emitter: Emitter, + emitter: Emitter, event: string | symbol | (string | symbol)[], filter: FilterFunction ): AsyncIterableIterator; export function iterator( - emitter: Emitter, + emitter: Emitter, event: string | symbol | (string | symbol)[], options?: IteratorOptions ): AsyncIterableIterator;