| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | const {promisify} = require('util'); |
| 3 | const path = require('path'); |
| 4 | const fs = require('graceful-fs'); |
| 5 | const fileType = require('file-type'); |
| 6 | const globby = require('globby'); |
| 7 | const makeDir = require('make-dir'); |
| 8 | const pPipe = require('p-pipe'); |
| 9 | const replaceExt = require('replace-ext'); |
| 10 | const junk = require('junk'); |
| 11 | |
| 12 | const readFile = promisify(fs.readFile); |
| 13 | const writeFile = promisify(fs.writeFile); |
| 14 | |
| 15 | const handleFile = async (sourcePath, {destination, plugins = []}) => { |
| 16 | if (plugins && !Array.isArray(plugins)) { |
| 17 | throw new TypeError('The `plugins` option should be an `Array`'); |
| 18 | } |
| 19 | |
| 20 | let data = await readFile(sourcePath); |
| 21 | data = await (plugins.length > 0 ? pPipe(...plugins)(data) : data); |
| 22 | |
| 23 | let destinationPath = destination ? path.join(destination, path.basename(sourcePath)) : undefined; |
| 24 | destinationPath = (fileType(data) && fileType(data).ext === 'webp') ? replaceExt(destinationPath, '.webp') : destinationPath; |
| 25 | |
| 26 | const returnValue = { |
| 27 | data, |
| 28 | sourcePath, |
| 29 | destinationPath |
| 30 | }; |
| 31 | |
| 32 | if (!destinationPath) { |
| 33 | return returnValue; |
| 34 | } |
| 35 | |
| 36 | await makeDir(path.dirname(returnValue.destinationPath)); |
| 37 | await writeFile(returnValue.destinationPath, returnValue.data); |
| 38 | |
| 39 | return returnValue; |
| 40 | }; |
| 41 | |
| 42 | module.exports = async (input, {glob = true, ...options} = {}) => { |
| 43 | if (!Array.isArray(input)) { |
| 44 | throw new TypeError(`Expected an \`Array\`, got \`${typeof input}\``); |
| 45 | } |
| 46 | |
| 47 | const filePaths = glob ? await globby(input, {onlyFiles: true}) : input; |
| 48 | |
| 49 | return Promise.all( |
| 50 | filePaths |
| 51 | .filter(filePath => junk.not(path.basename(filePath))) |
| 52 | .map(async filePath => { |
| 53 | try { |
| 54 | return await handleFile(filePath, options); |
| 55 | } catch (error) { |
| 56 | error.message = `Error occurred when handling file: ${input}\n\n${error.stack}`; |
| 57 | throw error; |
| 58 | } |
| 59 | }) |
| 60 | ); |
| 61 | }; |
| 62 | |
| 63 | module.exports.buffer = async (input, {plugins = []} = {}) => { |
| 64 | if (!Buffer.isBuffer(input)) { |
| 65 | throw new TypeError(`Expected a \`Buffer\`, got \`${typeof input}\``); |
| 66 | } |
| 67 | |
| 68 | if (plugins.length === 0) { |
| 69 | return input; |
| 70 | } |
| 71 | |
| 72 | return pPipe(...plugins)(input); |
| 73 | }; |