diff options
author | Minteck <nekostarfan@gmail.com> | 2021-08-24 14:41:48 +0200 |
---|---|---|
committer | Minteck <nekostarfan@gmail.com> | 2021-08-24 14:41:48 +0200 |
commit | d25e11bee6ca5ca523884da132d18e1400e077b9 (patch) | |
tree | 8af39fde19f7ed640a60fb397c7edd647dff1c4c /node_modules/pify | |
download | kartik-iridium-d25e11bee6ca5ca523884da132d18e1400e077b9.tar.gz kartik-iridium-d25e11bee6ca5ca523884da132d18e1400e077b9.tar.bz2 kartik-iridium-d25e11bee6ca5ca523884da132d18e1400e077b9.zip |
Initial commit
Diffstat (limited to 'node_modules/pify')
-rw-r--r-- | node_modules/pify/index.js | 113 | ||||
-rw-r--r-- | node_modules/pify/license | 9 | ||||
-rw-r--r-- | node_modules/pify/package.json | 49 | ||||
-rw-r--r-- | node_modules/pify/readme.md | 146 |
4 files changed, 317 insertions, 0 deletions
diff --git a/node_modules/pify/index.js b/node_modules/pify/index.js new file mode 100644 index 0000000..a3877e1 --- /dev/null +++ b/node_modules/pify/index.js @@ -0,0 +1,113 @@ +'use strict'; + +const processFn = (fn, options, proxy, unwrapped) => function (...arguments_) { + const P = options.promiseModule; + + return new P((resolve, reject) => { + if (options.multiArgs) { + arguments_.push((...result) => { + if (options.errorFirst) { + if (result[0]) { + reject(result); + } else { + result.shift(); + resolve(result); + } + } else { + resolve(result); + } + }); + } else if (options.errorFirst) { + arguments_.push((error, result) => { + if (error) { + reject(error); + } else { + resolve(result); + } + }); + } else { + arguments_.push(resolve); + } + + const self = this === proxy ? unwrapped : this; + Reflect.apply(fn, self, arguments_); + }); +}; + +const filterCache = new WeakMap(); + +module.exports = (input, options) => { + options = { + exclude: [/.+(?:Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise, + ...options + }; + + const objectType = typeof input; + if (!(input !== null && (objectType === 'object' || objectType === 'function'))) { + throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${input === null ? 'null' : objectType}\``); + } + + const filter = (target, key) => { + let cached = filterCache.get(target); + + if (!cached) { + cached = {}; + filterCache.set(target, cached); + } + + if (key in cached) { + return cached[key]; + } + + const match = pattern => (typeof pattern === 'string' || typeof key === 'symbol') ? key === pattern : pattern.test(key); + const desc = Reflect.getOwnPropertyDescriptor(target, key); + const writableOrConfigurableOwn = (desc === undefined || desc.writable || desc.configurable); + const included = options.include ? options.include.some(match) : !options.exclude.some(match); + const shouldFilter = included && writableOrConfigurableOwn; + cached[key] = shouldFilter; + return shouldFilter; + }; + + const cache = new WeakMap(); + + const proxy = new Proxy(input, { + apply(target, thisArg, args) { + const cached = cache.get(target); + + if (cached) { + return Reflect.apply(cached, thisArg, args); + } + + const pified = options.excludeMain ? target : processFn(target, options, proxy, target); + cache.set(target, pified); + return Reflect.apply(pified, thisArg, args); + }, + + get(target, key) { + const property = target[key]; + + // eslint-disable-next-line no-use-extend-native/no-use-extend-native + if (!filter(target, key) || property === Function.prototype[key]) { + return property; + } + + const cached = cache.get(property); + + if (cached) { + return cached; + } + + if (typeof property === 'function') { + const pified = processFn(property, options, proxy, target); + cache.set(property, pified); + return pified; + } + + return property; + } + }); + + return proxy; +}; diff --git a/node_modules/pify/license b/node_modules/pify/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/pify/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/pify/package.json b/node_modules/pify/package.json new file mode 100644 index 0000000..ad75f0a --- /dev/null +++ b/node_modules/pify/package.json @@ -0,0 +1,49 @@ +{ + "name": "pify", + "version": "5.0.0", + "description": "Promisify a callback-style function", + "license": "MIT", + "repository": "sindresorhus/pify", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava", + "optimization-test": "node --allow-natives-syntax optimization-test.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "promisify", + "callback", + "promise", + "promises", + "denodify", + "denodeify", + "node", + "then", + "thenify", + "convert", + "transform", + "wrap", + "wrapper", + "bind", + "async", + "await", + "es2015", + "bluebird" + ], + "devDependencies": { + "ava": "^2.4.0", + "pinkie-promise": "^2.0.0", + "v8-natives": "^1.1.0", + "xo": "^0.26.1" + } +} diff --git a/node_modules/pify/readme.md b/node_modules/pify/readme.md new file mode 100644 index 0000000..9a190ce --- /dev/null +++ b/node_modules/pify/readme.md @@ -0,0 +1,146 @@ +# pify [![Build Status](https://travis-ci.org/sindresorhus/pify.svg?branch=master)](https://travis-ci.org/sindresorhus/pify) + +> Promisify a callback-style function + +## Install + +``` +$ npm install pify +``` + +## Usage + +```js +const fs = require('fs'); +const pify = require('pify'); + +(async () => { + // Promisify a single function. + const data = await pify(fs.readFile)('package.json', 'utf8'); + console.log(JSON.parse(data).name); + //=> 'pify' + + // Promisify all methods in a module. + const data2 = await pify(fs).readFile('package.json', 'utf8'); + console.log(JSON.parse(data2).name); + //=> 'pify' +})(); +``` + +## API + +### pify(input, options?) + +Returns a `Promise` wrapped version of the supplied function or module. + +#### input + +Type: `Function | object` + +Callback-style function or module whose methods you want to promisify. + +#### options + +Type: `object` + +##### multiArgs + +Type: `boolean`\ +Default: `false` + +By default, the promisified function will only return the second argument from the callback, which works fine for most APIs. This option can be useful for modules like `request` that return multiple arguments. Turning this on will make it return an array of all arguments from the callback, excluding the error argument, instead of just the second argument. This also applies to rejections, where it returns an array of all the callback arguments, including the error. + +```js +const request = require('request'); +const pify = require('pify'); + +const pRequest = pify(request, {multiArgs: true}); + +(async () => { + const [httpResponse, body] = await pRequest('https://sindresorhus.com'); +})(); +``` + +##### include + +Type: `Array<string | RegExp>` + +Methods in a module to promisify. Remaining methods will be left untouched. + +##### exclude + +Type: `Array<string | RegExp>`\ +Default: `[/.+(?:Sync|Stream)$/]` + +Methods in a module **not** to promisify. Methods with names ending with `'Sync'` are excluded by default. + +##### excludeMain + +Type: `boolean`\ +Default: `false` + +If the given module is a function itself, it will be promisified. Enable this option if you want to promisify only methods of the module. + +```js +const pify = require('pify'); + +function fn() { + return true; +} + +fn.method = (data, callback) => { + setImmediate(() => { + callback(null, data); + }); +}; + +(async () => { + // Promisify methods but not `fn()`. + const promiseFn = pify(fn, {excludeMain: true}); + + if (promiseFn()) { + console.log(await promiseFn.method('hi')); + } +})(); +``` + +##### errorFirst + +Type: `boolean`\ +Default: `true` + +Whether the callback has an error as the first argument. You'll want to set this to `false` if you're dealing with an API that doesn't have an error as the first argument, like `fs.exists()`, some browser APIs, Chrome Extension APIs, etc. + +##### promiseModule + +Type: `Function` + +Custom promise module to use instead of the native one. + +## FAQ + +#### How is this different from Node.js's [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)? + +- Pify existed long before `util.promisify`. +- Pify is [faster](https://github.com/sindresorhus/pify/issues/41#issuecomment-429988506). +- Pify supports wrapping a whole module/object, not just a specific method. +- Pify has useful options like the ability to handle multiple arguments (`multiArgs`). +- Pify does not have [magic behavior](https://nodejs.org/api/util.html#util_custom_promisified_functions) for certain Node.js methods and instead focuses on predictability. + +## Related + +- [p-event](https://github.com/sindresorhus/p-event) - Promisify an event by waiting for it to be emitted +- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently +- [Moreā¦](https://github.com/sindresorhus/promise-fun) + +--- + +<div align="center"> + <b> + <a href="https://tidelift.com/subscription/pkg/npm-pify?utm_source=npm-pify&utm_medium=referral&utm_campaign=readme">Get professional support for 'pify' with a Tidelift subscription</a> + </b> + <br> + <sub> + Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. + </sub> +</div> |