diff --git a/commands/DDSToPNG.js b/commands/DDSToPNG.js index 162b8a6a..5708a2d9 100644 --- a/commands/DDSToPNG.js +++ b/commands/DDSToPNG.js @@ -1,69 +1,36 @@ -// DDSToPNG.js +//https://github.com/mmomtchev/magickwand.js/blob/main/example/example.mjs const vscode = require('vscode'); -const path = require('path'); -const { exec } = require('child_process'); +const { Magick } = require('magickwand.js'); const DDSToPNGCommand = vscode.commands.registerCommand('bg3-mod-helper.DDSToPNG', async (uri) => { + if (!uri) { + vscode.window.showErrorMessage('No file selected.'); + return; + } + console.log('‾‾DDSToPNGCommand‾‾'); - const checkWandScriptPath = path.join(__dirname, '..', 'support_files', 'python_scripts', 'check_wand.py'); - const scriptPath = path.join(__dirname, '..', 'support_files', 'scripts', 'python', 'DDS_to_PNG.py'); const filePath = uri.fsPath; + const outputPath = filePath.replace(/\.[^/.]+$/, ".png"); - // Check if Wand is installed - exec(`python "${checkWandScriptPath}"`, (error, stdout, stderr) => { - if (error) { - console.error('Error:', error); - return; - } - if (stderr) { - console.error('Script error:', stderr); + try { + let image = new Magick.Image(); + await image.readAsync(filePath); + + const infoDDS = new Magick.CoderInfo('DDS'); + if (!infoDDS || !infoDDS.isReadable()) { + vscode.window.showErrorMessage("DDS format is not supported for reading."); return; } - if (stdout.trim() === "Wand not installed") { - vscode.window.showInformationMessage( - "Wand Python package is not installed. Open terminal to install wand? ENSURE PIP IS UPDATED, OTHERWISE RUN THIS MANUALLY IN TERMINAL: pip install wand", - "Yes", - "No" - ).then(selection => { - if (selection === "Yes") { - // Open a new terminal with the command typed but not executed - const terminal = vscode.window.createTerminal(`Wand Install`); - terminal.show(); - terminal.sendText("pip install wand", false); // false means don't execute - // Prompt user to press Enter in terminal - vscode.window.showInformationMessage("The terminal has opened with the pip install command. Please press Enter in the terminal to install Wand, then rerun this command."); - } - }); - } else if (stdout.trim() === "ImageMagick not installed") { - // Prompt user to download ImageMagick - vscode.window.showInformationMessage( - "ImageMagick is not installed, which is required by Wand. Would you like to download it (installed headers as well in options when downlaoding)?", - "Download ImageMagick" - ).then(selection => { - if (selection === "Download ImageMagick") { - vscode.env.openExternal(vscode.Uri.parse("https://imagemagick.org/script/download.php")); - } - }); - } else { - // Wand is installed, proceed with conversion - const convertCommand = `python "${scriptPath}" -f "${filePath}"`; - exec(convertCommand, (convertError, convertStdout, convertStderr) => { - if (convertError) { - console.error('Error:', convertError); - vscode.window.showErrorMessage(`Error converting file: ${convertError.message}`); - return; - } - if (convertStderr) { - console.error('Script error:', convertStderr); - } - if (convertStdout) { - console.log('Script output:', convertStdout); - } - vscode.window.showInformationMessage(`File converted successfully.`); - }); - } - }); + await image.magickAsync('PNG'); + await image.writeAsync(outputPath); + + vscode.window.showInformationMessage(`DDS file converted successfully and saved as ${outputPath}`); + } catch (error) { + console.error('Error:', error); + vscode.window.showErrorMessage('Failed to convert DDS to PNG: ' + error.message); + } + console.log('__DDSToPNGCommand__'); }); diff --git a/commands/PNGToDDS.js b/commands/PNGToDDS.js index f43a634f..248ca345 100644 --- a/commands/PNGToDDS.js +++ b/commands/PNGToDDS.js @@ -1,75 +1,33 @@ -// PNGToDDS.js +//https://github.com/mmomtchev/magickwand.js/blob/main/example/example.mjs const vscode = require('vscode'); -const path = require('path'); -const { exec } = require('child_process'); +const { Magick } = require('magickwand.js'); const PNGToDDSCommand = vscode.commands.registerCommand('bg3-mod-helper.PNGToDDS', async (uri) => { - console.log('‾‾PNGToDDSCommand‾‾'); - const checkWandScriptPath = path.join(__dirname, '..', 'support_files', 'python_scripts', 'check_wand.py'); - const scriptPath = path.join(__dirname, '..', 'support_files', 'scripts', 'python', 'PNG_to_DDS.py'); + if (!uri) { + vscode.window.showErrorMessage('No file selected.'); + return; + } + const filePath = uri.fsPath; + const normalizedFilePath = filePath.toLowerCase().replace(/\\/g, '/'); + + const ddsCompression = normalizedFilePath.includes('assets/textures/icons') ? 'DXT5' : 'DXT1'; + const outputExtension = normalizedFilePath.includes('assets/textures') ? '.dds' : '.DDS'; + const outputPath = filePath.replace(/\.[^/.]+$/, outputExtension); + + try { + let image = new Magick.Image(); + await image.readAsync(filePath); - // Normalize file path and determine output format - const normalizedFilePath = filePath.replace(/\\/g, '/').toLowerCase(); // Replace backslashes with forward slashes and convert to lower case - const outputFormat = normalizedFilePath.includes('assets/textures/icons') ? '.dds' : '.DDS'; - const ddsCompression = outputFormat === '.dds' ? 'dxt5' : 'dxt1'; + await image.magickAsync('DDS'); - // Check if Wand is installed - exec(`python "${checkWandScriptPath}"`, (error, stdout, stderr) => { - if (error) { - console.error('Error:', error); - return; - } - if (stderr) { - console.error('Script error:', stderr); - return; - } - if (stdout.trim() === "Wand not installed") { - vscode.window.showInformationMessage( - "Wand Python package is not installed. Open terminal to install wand? ENSURE PIP IS UPDATED, OTHERWISE RUN THIS MANUALLY IN TERMINAL: pip install wand", - "Yes", - "No" - ).then(selection => { - if (selection === "Yes") { - // Open a new terminal with the command typed but not executed - const terminal = vscode.window.createTerminal(`Wand Install`); - terminal.show(); - terminal.sendText("pip install wand", false); // false means don't execute + await image.writeAsync(outputPath); - // Prompt user to press Enter in terminal - vscode.window.showInformationMessage("The terminal has opened with the pip install command. Please press Enter in the terminal to install Wand, then rerun this command."); - } - }); - } else if (stdout.trim() === "ImageMagick not installed") { - // Prompt user to download ImageMagick - vscode.window.showInformationMessage( - "ImageMagick is not installed, which is required by Wand. Would you like to download it (installed headers as well in options when downlaoding)?", - "Download ImageMagick" - ).then(selection => { - if (selection === "Download ImageMagick") { - vscode.env.openExternal(vscode.Uri.parse("https://imagemagick.org/script/download.php")); - } - }); - } else { - // Wand is installed, proceed with conversion - const convertCommand = `python "${scriptPath}" -o "${outputFormat}" --ddscompression "${ddsCompression}" -f "${filePath}"`; - exec(convertCommand, (convertError, convertStdout, convertStderr) => { - if (convertError) { - console.error('Error:', convertError); - vscode.window.showErrorMessage(`Error converting file: ${convertError.message}`); - return; - } - if (convertStderr) { - console.error('Script error:', convertStderr); - } - if (convertStdout) { - console.log('Script output:', convertStdout); - } - vscode.window.showInformationMessage(`File converted successfully.`); - }); - } - }); - console.log('__PNGToDDSCommand__'); + vscode.window.showInformationMessage(`File converted successfully and saved as ${outputPath}`); + } catch (error) { + console.error('Error:', error); + vscode.window.showErrorMessage('Failed to convert image: ' + error.message); + } }); module.exports = PNGToDDSCommand; diff --git a/commands/addIconBackground.js b/commands/addIconBackground.js index 42331d2e..f281c310 100644 --- a/commands/addIconBackground.js +++ b/commands/addIconBackground.js @@ -1,7 +1,7 @@ const vscode = require('vscode'); -const sharp = require('sharp'); const path = require('path'); -const fs = require('fs').promises; // Use promises version of fs for async/await compatibility +const fs = require('fs').promises; +const { Magick, MagickCore } = require('magickwand.js'); async function addIconBackground(uri) { const inputPath = uri.fsPath; @@ -10,17 +10,14 @@ async function addIconBackground(uri) { try { const files = await fs.readdir(backgroundsDir); const pngFiles = files.filter(file => file.endsWith('.png')); - // Ensure each option has an isCustom property for consistent handling const backgroundOptions = pngFiles.map(file => ({ label: file, isCustom: false })); backgroundOptions.push({ label: 'Custom Background...', isCustom: true }); - // Prompt user for background selection const selectedBackground = await vscode.window.showQuickPick(backgroundOptions, { placeHolder: 'Select a background' }); if (!selectedBackground) return; let backgroundPath; if (selectedBackground.isCustom) { - // Handle custom background selection const customUri = await vscode.window.showOpenDialog({ openLabel: 'Use Background', canSelectMany: false, @@ -29,42 +26,53 @@ async function addIconBackground(uri) { if (customUri && customUri[0]) { backgroundPath = customUri[0].fsPath; } else { - return; // No file selected, exit the function + return; } } else { - // Use selected predefined background backgroundPath = path.join(backgroundsDir, selectedBackground.label); } const outputPath = inputPath.replace(/\.\w+$/, `_with_background.png`); - // Load both images to compare sizes - const iconImage = sharp(inputPath); - const background = sharp(backgroundPath); - const [iconMetadata, backgroundMetadata] = await Promise.all([iconImage.metadata(), background.metadata()]); + const iconImage = new Magick.Image; + await iconImage.readAsync(inputPath); + const background = new Magick.Image; + await background.readAsync(backgroundPath); + + const iconSize = await iconImage.sizeAsync(); + const backgroundSize = await background.sizeAsync(); + const iconWidth = iconSize.width(); + const iconHeight = iconSize.height(); + let backgroundWidth = backgroundSize.width(); + let backgroundHeight = backgroundSize.height(); - if (iconMetadata.width !== backgroundMetadata.width || iconMetadata.height !== backgroundMetadata.height) { + if (iconWidth !== backgroundWidth || iconHeight !== backgroundHeight) { const resizeBackground = await vscode.window.showInformationMessage( 'The background and icon sizes do not match. Resize the background to match the icon?', 'Yes', 'No' ); if (resizeBackground === 'Yes') { - await background.resize(iconMetadata.width, iconMetadata.height); + await background.resizeAsync(`${iconWidth}x${iconHeight}`); + const backgroundSizeResize = await background.sizeAsync(); + backgroundWidth = backgroundSizeResize.width(); + backgroundHeight = backgroundSizeResize.height(); } else { return; } } - // Composite the icon over the resized background - background - .composite([{ input: await iconImage.toBuffer(), gravity: 'centre' }]) - .toFile(outputPath) - .then(() => { - vscode.window.showInformationMessage(`Background added: ${outputPath}`); - }) - .catch(err => { - vscode.window.showErrorMessage(`Error adding background: ${err}`); - }); + const xOffset = Math.floor((backgroundWidth - iconWidth) / 2); + const yOffset = Math.floor((backgroundHeight - iconHeight) / 2); + + console.log(`Calculated xOffset: ${xOffset}, yOffset: ${yOffset}`); + + // Create a Geometry object for the composite operation + const geometry = new Magick.Geometry(iconWidth, iconHeight, xOffset, yOffset); + console.log('Attempting to composite with geometry:', geometry.toString()); + await background.compositeAsync(iconImage, geometry, MagickCore.OverCompositeOp); + + await background.writeAsync(outputPath); + vscode.window.showInformationMessage(`Background added: ${outputPath}`); } catch (err) { vscode.window.showErrorMessage(`Failed to read backgrounds directory or process images: ${err}`); } diff --git a/commands/resizeImage.js b/commands/resizeImage.js index 44fd286a..e319c5cb 100644 --- a/commands/resizeImage.js +++ b/commands/resizeImage.js @@ -1,5 +1,5 @@ -const sharp = require('sharp'); const vscode = require('vscode'); +const { Magick } = require('magickwand.js'); async function resizeImage(uri, width = null, height = null) { console.log('‾‾resizeImage‾‾'); @@ -24,15 +24,15 @@ async function resizeImage(uri, width = null, height = null) { const outputPath = inputPath.replace(/\.\w+$/, `_resized_${width}x${height}.png`); - sharp(inputPath) - .resize(width, height) - .toFile(outputPath) - .then(() => { - vscode.window.showInformationMessage(`Image resized to ${width}x${height}: ${outputPath}`); - }) - .catch(err => { - vscode.window.showErrorMessage(`Error resizing image: ${err}`); - }); + try { + let image = new Magick.Image(); + await image.readAsync(inputPath); + await image.scaleAsync(`${width}x${height}`); + await image.writeAsync(outputPath); + vscode.window.showInformationMessage(`Image resized to ${width}x${height}: ${outputPath}`); + } catch (err) { + vscode.window.showErrorMessage(`Error resizing image: ${err}`); + } console.log('__resizeImage__'); } @@ -40,6 +40,5 @@ module.exports = { resizeImageTooltip: (uri) => resizeImage(uri, 380, 380), resizeImageController: (uri) => resizeImage(uri, 144, 144), resizeImageHotbar: (uri) => resizeImage(uri, 64, 64), - resizeImageCustom: resizeImage // Using the same function for custom resizing - // ... other exports ... -}; \ No newline at end of file + resizeImageCustom: resizeImage +}; diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index 6f7b2c45..1ff67fe2 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -1,6 +1,6 @@ { "name": "bg3-mod-helper", - "version": "2.1.34", + "version": "2.1.50", "lockfileVersion": 3, "requires": true, "packages": { @@ -395,18 +395,6 @@ "node": ">=6" } }, - "node_modules/color": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", - "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", - "dependencies": { - "color-convert": "^2.0.1", - "color-string": "^1.9.0" - }, - "engines": { - "node": ">=12.5.0" - } - }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -423,15 +411,6 @@ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" }, - "node_modules/color-string": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", - "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", - "dependencies": { - "color-name": "^1.0.0", - "simple-swizzle": "^0.2.2" - } - }, "node_modules/color-support": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", @@ -823,11 +802,6 @@ "node": ">= 12" } }, - "node_modules/is-arrayish": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz", - "integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==" - }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -1489,45 +1463,6 @@ "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==" }, - "node_modules/sharp": { - "version": "0.33.3", - "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.3.tgz", - "integrity": "sha512-vHUeXJU1UvlO/BNwTpT0x/r53WkLUVxrmb5JTgW92fdFCFk0ispLMAeu/jPO2vjkXM1fYUi3K7/qcLF47pwM1A==", - "hasInstallScript": true, - "dependencies": { - "color": "^4.2.3", - "detect-libc": "^2.0.3", - "semver": "^7.6.0" - }, - "engines": { - "libvips": ">=8.15.2", - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-darwin-arm64": "0.33.3", - "@img/sharp-darwin-x64": "0.33.3", - "@img/sharp-libvips-darwin-arm64": "1.0.2", - "@img/sharp-libvips-darwin-x64": "1.0.2", - "@img/sharp-libvips-linux-arm": "1.0.2", - "@img/sharp-libvips-linux-arm64": "1.0.2", - "@img/sharp-libvips-linux-s390x": "1.0.2", - "@img/sharp-libvips-linux-x64": "1.0.2", - "@img/sharp-libvips-linuxmusl-arm64": "1.0.2", - "@img/sharp-libvips-linuxmusl-x64": "1.0.2", - "@img/sharp-linux-arm": "0.33.3", - "@img/sharp-linux-arm64": "0.33.3", - "@img/sharp-linux-s390x": "0.33.3", - "@img/sharp-linux-x64": "0.33.3", - "@img/sharp-linuxmusl-arm64": "0.33.3", - "@img/sharp-linuxmusl-x64": "0.33.3", - "@img/sharp-wasm32": "0.33.3", - "@img/sharp-win32-ia32": "0.33.3", - "@img/sharp-win32-x64": "0.33.3" - } - }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -1552,14 +1487,6 @@ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" }, - "node_modules/simple-swizzle": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz", - "integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==", - "dependencies": { - "is-arrayish": "^0.3.1" - } - }, "node_modules/smart-buffer": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", diff --git a/node_modules/color-string/LICENSE b/node_modules/color-string/LICENSE deleted file mode 100644 index a8b08d4f..00000000 --- a/node_modules/color-string/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2011 Heather Arthur - -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/color-string/README.md b/node_modules/color-string/README.md deleted file mode 100644 index e58670c6..00000000 --- a/node_modules/color-string/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# color-string - -> library for parsing and generating CSS color strings. - -## Install - -With [npm](http://npmjs.org/): - -```console -$ npm install color-string -``` - -## Usage - -### Parsing - -```js -colorString.get('#FFF') // {model: 'rgb', value: [255, 255, 255, 1]} -colorString.get('#FFFA') // {model: 'rgb', value: [255, 255, 255, 0.67]} -colorString.get('#FFFFFFAA') // {model: 'rgb', value: [255, 255, 255, 0.67]} -colorString.get('hsl(360, 100%, 50%)') // {model: 'hsl', value: [0, 100, 50, 1]} -colorString.get('hsl(360 100% 50%)') // {model: 'hsl', value: [0, 100, 50, 1]} -colorString.get('hwb(60, 3%, 60%)') // {model: 'hwb', value: [60, 3, 60, 1]} - -colorString.get.rgb('#FFF') // [255, 255, 255, 1] -colorString.get.rgb('blue') // [0, 0, 255, 1] -colorString.get.rgb('rgba(200, 60, 60, 0.3)') // [200, 60, 60, 0.3] -colorString.get.rgb('rgba(200 60 60 / 0.3)') // [200, 60, 60, 0.3] -colorString.get.rgb('rgba(200 60 60 / 30%)') // [200, 60, 60, 0.3] -colorString.get.rgb('rgb(200, 200, 200)') // [200, 200, 200, 1] -colorString.get.rgb('rgb(200 200 200)') // [200, 200, 200, 1] - -colorString.get.hsl('hsl(360, 100%, 50%)') // [0, 100, 50, 1] -colorString.get.hsl('hsl(360 100% 50%)') // [0, 100, 50, 1] -colorString.get.hsl('hsla(360, 60%, 50%, 0.4)') // [0, 60, 50, 0.4] -colorString.get.hsl('hsl(360 60% 50% / 0.4)') // [0, 60, 50, 0.4] - -colorString.get.hwb('hwb(60, 3%, 60%)') // [60, 3, 60, 1] -colorString.get.hwb('hwb(60, 3%, 60%, 0.6)') // [60, 3, 60, 0.6] - -colorString.get.rgb('invalid color string') // null -``` - -### Generation - -```js -colorString.to.hex([255, 255, 255]) // "#FFFFFF" -colorString.to.hex([0, 0, 255, 0.4]) // "#0000FF66" -colorString.to.hex([0, 0, 255], 0.4) // "#0000FF66" -colorString.to.rgb([255, 255, 255]) // "rgb(255, 255, 255)" -colorString.to.rgb([0, 0, 255, 0.4]) // "rgba(0, 0, 255, 0.4)" -colorString.to.rgb([0, 0, 255], 0.4) // "rgba(0, 0, 255, 0.4)" -colorString.to.rgb.percent([0, 0, 255]) // "rgb(0%, 0%, 100%)" -colorString.to.keyword([255, 255, 0]) // "yellow" -colorString.to.hsl([360, 100, 100]) // "hsl(360, 100%, 100%)" -colorString.to.hwb([50, 3, 15]) // "hwb(50, 3%, 15%)" - -// all functions also support swizzling -colorString.to.rgb(0, [0, 255], 0.4) // "rgba(0, 0, 255, 0.4)" -colorString.to.rgb([0, 0], [255], 0.4) // "rgba(0, 0, 255, 0.4)" -colorString.to.rgb([0], 0, [255, 0.4]) // "rgba(0, 0, 255, 0.4)" -``` diff --git a/node_modules/color-string/index.js b/node_modules/color-string/index.js deleted file mode 100644 index dd5d2b7b..00000000 --- a/node_modules/color-string/index.js +++ /dev/null @@ -1,242 +0,0 @@ -/* MIT license */ -var colorNames = require('color-name'); -var swizzle = require('simple-swizzle'); -var hasOwnProperty = Object.hasOwnProperty; - -var reverseNames = Object.create(null); - -// create a list of reverse color names -for (var name in colorNames) { - if (hasOwnProperty.call(colorNames, name)) { - reverseNames[colorNames[name]] = name; - } -} - -var cs = module.exports = { - to: {}, - get: {} -}; - -cs.get = function (string) { - var prefix = string.substring(0, 3).toLowerCase(); - var val; - var model; - switch (prefix) { - case 'hsl': - val = cs.get.hsl(string); - model = 'hsl'; - break; - case 'hwb': - val = cs.get.hwb(string); - model = 'hwb'; - break; - default: - val = cs.get.rgb(string); - model = 'rgb'; - break; - } - - if (!val) { - return null; - } - - return {model: model, value: val}; -}; - -cs.get.rgb = function (string) { - if (!string) { - return null; - } - - var abbr = /^#([a-f0-9]{3,4})$/i; - var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i; - var rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; - var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; - var keyword = /^(\w+)$/; - - var rgb = [0, 0, 0, 1]; - var match; - var i; - var hexAlpha; - - if (match = string.match(hex)) { - hexAlpha = match[2]; - match = match[1]; - - for (i = 0; i < 3; i++) { - // https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19 - var i2 = i * 2; - rgb[i] = parseInt(match.slice(i2, i2 + 2), 16); - } - - if (hexAlpha) { - rgb[3] = parseInt(hexAlpha, 16) / 255; - } - } else if (match = string.match(abbr)) { - match = match[1]; - hexAlpha = match[3]; - - for (i = 0; i < 3; i++) { - rgb[i] = parseInt(match[i] + match[i], 16); - } - - if (hexAlpha) { - rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255; - } - } else if (match = string.match(rgba)) { - for (i = 0; i < 3; i++) { - rgb[i] = parseInt(match[i + 1], 0); - } - - if (match[4]) { - if (match[5]) { - rgb[3] = parseFloat(match[4]) * 0.01; - } else { - rgb[3] = parseFloat(match[4]); - } - } - } else if (match = string.match(per)) { - for (i = 0; i < 3; i++) { - rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55); - } - - if (match[4]) { - if (match[5]) { - rgb[3] = parseFloat(match[4]) * 0.01; - } else { - rgb[3] = parseFloat(match[4]); - } - } - } else if (match = string.match(keyword)) { - if (match[1] === 'transparent') { - return [0, 0, 0, 0]; - } - - if (!hasOwnProperty.call(colorNames, match[1])) { - return null; - } - - rgb = colorNames[match[1]]; - rgb[3] = 1; - - return rgb; - } else { - return null; - } - - for (i = 0; i < 3; i++) { - rgb[i] = clamp(rgb[i], 0, 255); - } - rgb[3] = clamp(rgb[3], 0, 1); - - return rgb; -}; - -cs.get.hsl = function (string) { - if (!string) { - return null; - } - - var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; - var match = string.match(hsl); - - if (match) { - var alpha = parseFloat(match[4]); - var h = ((parseFloat(match[1]) % 360) + 360) % 360; - var s = clamp(parseFloat(match[2]), 0, 100); - var l = clamp(parseFloat(match[3]), 0, 100); - var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); - - return [h, s, l, a]; - } - - return null; -}; - -cs.get.hwb = function (string) { - if (!string) { - return null; - } - - var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; - var match = string.match(hwb); - - if (match) { - var alpha = parseFloat(match[4]); - var h = ((parseFloat(match[1]) % 360) + 360) % 360; - var w = clamp(parseFloat(match[2]), 0, 100); - var b = clamp(parseFloat(match[3]), 0, 100); - var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); - return [h, w, b, a]; - } - - return null; -}; - -cs.to.hex = function () { - var rgba = swizzle(arguments); - - return ( - '#' + - hexDouble(rgba[0]) + - hexDouble(rgba[1]) + - hexDouble(rgba[2]) + - (rgba[3] < 1 - ? (hexDouble(Math.round(rgba[3] * 255))) - : '') - ); -}; - -cs.to.rgb = function () { - var rgba = swizzle(arguments); - - return rgba.length < 4 || rgba[3] === 1 - ? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')' - : 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')'; -}; - -cs.to.rgb.percent = function () { - var rgba = swizzle(arguments); - - var r = Math.round(rgba[0] / 255 * 100); - var g = Math.round(rgba[1] / 255 * 100); - var b = Math.round(rgba[2] / 255 * 100); - - return rgba.length < 4 || rgba[3] === 1 - ? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)' - : 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')'; -}; - -cs.to.hsl = function () { - var hsla = swizzle(arguments); - return hsla.length < 4 || hsla[3] === 1 - ? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)' - : 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')'; -}; - -// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax -// (hwb have alpha optional & 1 is default value) -cs.to.hwb = function () { - var hwba = swizzle(arguments); - - var a = ''; - if (hwba.length >= 4 && hwba[3] !== 1) { - a = ', ' + hwba[3]; - } - - return 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')'; -}; - -cs.to.keyword = function (rgb) { - return reverseNames[rgb.slice(0, 3)]; -}; - -// helpers -function clamp(num, min, max) { - return Math.min(Math.max(min, num), max); -} - -function hexDouble(num) { - var str = Math.round(num).toString(16).toUpperCase(); - return (str.length < 2) ? '0' + str : str; -} diff --git a/node_modules/color-string/package.json b/node_modules/color-string/package.json deleted file mode 100644 index f34ee980..00000000 --- a/node_modules/color-string/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "color-string", - "description": "Parser and generator for CSS color strings", - "version": "1.9.1", - "author": "Heather Arthur ", - "contributors": [ - "Maxime Thirouin", - "Dyma Ywanov ", - "Josh Junon" - ], - "repository": "Qix-/color-string", - "scripts": { - "pretest": "xo", - "test": "node test/basic.js" - }, - "license": "MIT", - "files": [ - "index.js" - ], - "xo": { - "rules": { - "no-cond-assign": 0, - "operator-linebreak": 0 - } - }, - "dependencies": { - "color-name": "^1.0.0", - "simple-swizzle": "^0.2.2" - }, - "devDependencies": { - "xo": "^0.12.1" - }, - "keywords": [ - "color", - "colour", - "rgb", - "css" - ] -} diff --git a/node_modules/color/LICENSE b/node_modules/color/LICENSE deleted file mode 100644 index 68c864ee..00000000 --- a/node_modules/color/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2012 Heather Arthur - -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/color/README.md b/node_modules/color/README.md deleted file mode 100644 index 674a7318..00000000 --- a/node_modules/color/README.md +++ /dev/null @@ -1,123 +0,0 @@ -# color - -> JavaScript library for immutable color conversion and manipulation with support for CSS color strings. - -```js -const color = Color('#7743CE').alpha(0.5).lighten(0.5); -console.log(color.hsl().string()); // 'hsla(262, 59%, 81%, 0.5)' - -console.log(color.cmyk().round().array()); // [ 16, 25, 0, 8, 0.5 ] - -console.log(color.ansi256().object()); // { ansi256: 183, alpha: 0.5 } -``` - -## Install -```console -$ npm install color -``` - -## Usage -```js -const Color = require('color'); -``` - -### Constructors -```js -const color = Color('rgb(255, 255, 255)') -const color = Color({r: 255, g: 255, b: 255}) -const color = Color.rgb(255, 255, 255) -const color = Color.rgb([255, 255, 255]) -``` - -Set the values for individual channels with `alpha`, `red`, `green`, `blue`, `hue`, `saturationl` (hsl), `saturationv` (hsv), `lightness`, `whiteness`, `blackness`, `cyan`, `magenta`, `yellow`, `black` - -String constructors are handled by [color-string](https://www.npmjs.com/package/color-string) - -### Getters -```js -color.hsl(); -``` -Convert a color to a different space (`hsl()`, `cmyk()`, etc.). - -```js -color.object(); // {r: 255, g: 255, b: 255} -``` -Get a hash of the color value. Reflects the color's current model (see above). - -```js -color.rgb().array() // [255, 255, 255] -``` -Get an array of the values with `array()`. Reflects the color's current model (see above). - -```js -color.rgbNumber() // 16777215 (0xffffff) -``` -Get the rgb number value. - -```js -color.hex() // #ffffff -``` -Get the hex value. (**NOTE:** `.hex()` does not return alpha values; use `.hexa()` for an RGBA representation) - -```js -color.red() // 255 -``` -Get the value for an individual channel. - -### CSS Strings -```js -color.hsl().string() // 'hsl(320, 50%, 100%)' -``` - -Calling `.string()` with a number rounds the numbers to that decimal place. It defaults to 1. - -### Luminosity -```js -color.luminosity(); // 0.412 -``` -The [WCAG luminosity](http://www.w3.org/TR/WCAG20/#relativeluminancedef) of the color. 0 is black, 1 is white. - -```js -color.contrast(Color("blue")) // 12 -``` -The [WCAG contrast ratio](http://www.w3.org/TR/WCAG20/#contrast-ratiodef) to another color, from 1 (same color) to 21 (contrast b/w white and black). - -```js -color.isLight(); // true -color.isDark(); // false -``` -Get whether the color is "light" or "dark", useful for deciding text color. - -### Manipulation -```js -color.negate() // rgb(0, 100, 255) -> rgb(255, 155, 0) - -color.lighten(0.5) // hsl(100, 50%, 50%) -> hsl(100, 50%, 75%) -color.lighten(0.5) // hsl(100, 50%, 0) -> hsl(100, 50%, 0) -color.darken(0.5) // hsl(100, 50%, 50%) -> hsl(100, 50%, 25%) -color.darken(0.5) // hsl(100, 50%, 0) -> hsl(100, 50%, 0) - -color.lightness(50) // hsl(100, 50%, 10%) -> hsl(100, 50%, 50%) - -color.saturate(0.5) // hsl(100, 50%, 50%) -> hsl(100, 75%, 50%) -color.desaturate(0.5) // hsl(100, 50%, 50%) -> hsl(100, 25%, 50%) -color.grayscale() // #5CBF54 -> #969696 - -color.whiten(0.5) // hwb(100, 50%, 50%) -> hwb(100, 75%, 50%) -color.blacken(0.5) // hwb(100, 50%, 50%) -> hwb(100, 50%, 75%) - -color.fade(0.5) // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 0.4) -color.opaquer(0.5) // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 1.0) - -color.rotate(180) // hsl(60, 20%, 20%) -> hsl(240, 20%, 20%) -color.rotate(-90) // hsl(60, 20%, 20%) -> hsl(330, 20%, 20%) - -color.mix(Color("yellow")) // cyan -> rgb(128, 255, 128) -color.mix(Color("yellow"), 0.3) // cyan -> rgb(77, 255, 179) - -// chaining -color.green(100).grayscale().lighten(0.6) -``` - -## Propers -The API was inspired by [color-js](https://github.com/brehaut/color-js). Manipulation functions by CSS tools like Sass, LESS, and Stylus. diff --git a/node_modules/color/index.js b/node_modules/color/index.js deleted file mode 100644 index ddb0b5df..00000000 --- a/node_modules/color/index.js +++ /dev/null @@ -1,496 +0,0 @@ -const colorString = require('color-string'); -const convert = require('color-convert'); - -const skippedModels = [ - // To be honest, I don't really feel like keyword belongs in color convert, but eh. - 'keyword', - - // Gray conflicts with some method names, and has its own method defined. - 'gray', - - // Shouldn't really be in color-convert either... - 'hex', -]; - -const hashedModelKeys = {}; -for (const model of Object.keys(convert)) { - hashedModelKeys[[...convert[model].labels].sort().join('')] = model; -} - -const limiters = {}; - -function Color(object, model) { - if (!(this instanceof Color)) { - return new Color(object, model); - } - - if (model && model in skippedModels) { - model = null; - } - - if (model && !(model in convert)) { - throw new Error('Unknown model: ' + model); - } - - let i; - let channels; - - if (object == null) { // eslint-disable-line no-eq-null,eqeqeq - this.model = 'rgb'; - this.color = [0, 0, 0]; - this.valpha = 1; - } else if (object instanceof Color) { - this.model = object.model; - this.color = [...object.color]; - this.valpha = object.valpha; - } else if (typeof object === 'string') { - const result = colorString.get(object); - if (result === null) { - throw new Error('Unable to parse color from string: ' + object); - } - - this.model = result.model; - channels = convert[this.model].channels; - this.color = result.value.slice(0, channels); - this.valpha = typeof result.value[channels] === 'number' ? result.value[channels] : 1; - } else if (object.length > 0) { - this.model = model || 'rgb'; - channels = convert[this.model].channels; - const newArray = Array.prototype.slice.call(object, 0, channels); - this.color = zeroArray(newArray, channels); - this.valpha = typeof object[channels] === 'number' ? object[channels] : 1; - } else if (typeof object === 'number') { - // This is always RGB - can be converted later on. - this.model = 'rgb'; - this.color = [ - (object >> 16) & 0xFF, - (object >> 8) & 0xFF, - object & 0xFF, - ]; - this.valpha = 1; - } else { - this.valpha = 1; - - const keys = Object.keys(object); - if ('alpha' in object) { - keys.splice(keys.indexOf('alpha'), 1); - this.valpha = typeof object.alpha === 'number' ? object.alpha : 0; - } - - const hashedKeys = keys.sort().join(''); - if (!(hashedKeys in hashedModelKeys)) { - throw new Error('Unable to parse color from object: ' + JSON.stringify(object)); - } - - this.model = hashedModelKeys[hashedKeys]; - - const {labels} = convert[this.model]; - const color = []; - for (i = 0; i < labels.length; i++) { - color.push(object[labels[i]]); - } - - this.color = zeroArray(color); - } - - // Perform limitations (clamping, etc.) - if (limiters[this.model]) { - channels = convert[this.model].channels; - for (i = 0; i < channels; i++) { - const limit = limiters[this.model][i]; - if (limit) { - this.color[i] = limit(this.color[i]); - } - } - } - - this.valpha = Math.max(0, Math.min(1, this.valpha)); - - if (Object.freeze) { - Object.freeze(this); - } -} - -Color.prototype = { - toString() { - return this.string(); - }, - - toJSON() { - return this[this.model](); - }, - - string(places) { - let self = this.model in colorString.to ? this : this.rgb(); - self = self.round(typeof places === 'number' ? places : 1); - const args = self.valpha === 1 ? self.color : [...self.color, this.valpha]; - return colorString.to[self.model](args); - }, - - percentString(places) { - const self = this.rgb().round(typeof places === 'number' ? places : 1); - const args = self.valpha === 1 ? self.color : [...self.color, this.valpha]; - return colorString.to.rgb.percent(args); - }, - - array() { - return this.valpha === 1 ? [...this.color] : [...this.color, this.valpha]; - }, - - object() { - const result = {}; - const {channels} = convert[this.model]; - const {labels} = convert[this.model]; - - for (let i = 0; i < channels; i++) { - result[labels[i]] = this.color[i]; - } - - if (this.valpha !== 1) { - result.alpha = this.valpha; - } - - return result; - }, - - unitArray() { - const rgb = this.rgb().color; - rgb[0] /= 255; - rgb[1] /= 255; - rgb[2] /= 255; - - if (this.valpha !== 1) { - rgb.push(this.valpha); - } - - return rgb; - }, - - unitObject() { - const rgb = this.rgb().object(); - rgb.r /= 255; - rgb.g /= 255; - rgb.b /= 255; - - if (this.valpha !== 1) { - rgb.alpha = this.valpha; - } - - return rgb; - }, - - round(places) { - places = Math.max(places || 0, 0); - return new Color([...this.color.map(roundToPlace(places)), this.valpha], this.model); - }, - - alpha(value) { - if (value !== undefined) { - return new Color([...this.color, Math.max(0, Math.min(1, value))], this.model); - } - - return this.valpha; - }, - - // Rgb - red: getset('rgb', 0, maxfn(255)), - green: getset('rgb', 1, maxfn(255)), - blue: getset('rgb', 2, maxfn(255)), - - hue: getset(['hsl', 'hsv', 'hsl', 'hwb', 'hcg'], 0, value => ((value % 360) + 360) % 360), - - saturationl: getset('hsl', 1, maxfn(100)), - lightness: getset('hsl', 2, maxfn(100)), - - saturationv: getset('hsv', 1, maxfn(100)), - value: getset('hsv', 2, maxfn(100)), - - chroma: getset('hcg', 1, maxfn(100)), - gray: getset('hcg', 2, maxfn(100)), - - white: getset('hwb', 1, maxfn(100)), - wblack: getset('hwb', 2, maxfn(100)), - - cyan: getset('cmyk', 0, maxfn(100)), - magenta: getset('cmyk', 1, maxfn(100)), - yellow: getset('cmyk', 2, maxfn(100)), - black: getset('cmyk', 3, maxfn(100)), - - x: getset('xyz', 0, maxfn(95.047)), - y: getset('xyz', 1, maxfn(100)), - z: getset('xyz', 2, maxfn(108.833)), - - l: getset('lab', 0, maxfn(100)), - a: getset('lab', 1), - b: getset('lab', 2), - - keyword(value) { - if (value !== undefined) { - return new Color(value); - } - - return convert[this.model].keyword(this.color); - }, - - hex(value) { - if (value !== undefined) { - return new Color(value); - } - - return colorString.to.hex(this.rgb().round().color); - }, - - hexa(value) { - if (value !== undefined) { - return new Color(value); - } - - const rgbArray = this.rgb().round().color; - - let alphaHex = Math.round(this.valpha * 255).toString(16).toUpperCase(); - if (alphaHex.length === 1) { - alphaHex = '0' + alphaHex; - } - - return colorString.to.hex(rgbArray) + alphaHex; - }, - - rgbNumber() { - const rgb = this.rgb().color; - return ((rgb[0] & 0xFF) << 16) | ((rgb[1] & 0xFF) << 8) | (rgb[2] & 0xFF); - }, - - luminosity() { - // http://www.w3.org/TR/WCAG20/#relativeluminancedef - const rgb = this.rgb().color; - - const lum = []; - for (const [i, element] of rgb.entries()) { - const chan = element / 255; - lum[i] = (chan <= 0.04045) ? chan / 12.92 : ((chan + 0.055) / 1.055) ** 2.4; - } - - return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2]; - }, - - contrast(color2) { - // http://www.w3.org/TR/WCAG20/#contrast-ratiodef - const lum1 = this.luminosity(); - const lum2 = color2.luminosity(); - - if (lum1 > lum2) { - return (lum1 + 0.05) / (lum2 + 0.05); - } - - return (lum2 + 0.05) / (lum1 + 0.05); - }, - - level(color2) { - // https://www.w3.org/TR/WCAG/#contrast-enhanced - const contrastRatio = this.contrast(color2); - if (contrastRatio >= 7) { - return 'AAA'; - } - - return (contrastRatio >= 4.5) ? 'AA' : ''; - }, - - isDark() { - // YIQ equation from http://24ways.org/2010/calculating-color-contrast - const rgb = this.rgb().color; - const yiq = (rgb[0] * 2126 + rgb[1] * 7152 + rgb[2] * 722) / 10000; - return yiq < 128; - }, - - isLight() { - return !this.isDark(); - }, - - negate() { - const rgb = this.rgb(); - for (let i = 0; i < 3; i++) { - rgb.color[i] = 255 - rgb.color[i]; - } - - return rgb; - }, - - lighten(ratio) { - const hsl = this.hsl(); - hsl.color[2] += hsl.color[2] * ratio; - return hsl; - }, - - darken(ratio) { - const hsl = this.hsl(); - hsl.color[2] -= hsl.color[2] * ratio; - return hsl; - }, - - saturate(ratio) { - const hsl = this.hsl(); - hsl.color[1] += hsl.color[1] * ratio; - return hsl; - }, - - desaturate(ratio) { - const hsl = this.hsl(); - hsl.color[1] -= hsl.color[1] * ratio; - return hsl; - }, - - whiten(ratio) { - const hwb = this.hwb(); - hwb.color[1] += hwb.color[1] * ratio; - return hwb; - }, - - blacken(ratio) { - const hwb = this.hwb(); - hwb.color[2] += hwb.color[2] * ratio; - return hwb; - }, - - grayscale() { - // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale - const rgb = this.rgb().color; - const value = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11; - return Color.rgb(value, value, value); - }, - - fade(ratio) { - return this.alpha(this.valpha - (this.valpha * ratio)); - }, - - opaquer(ratio) { - return this.alpha(this.valpha + (this.valpha * ratio)); - }, - - rotate(degrees) { - const hsl = this.hsl(); - let hue = hsl.color[0]; - hue = (hue + degrees) % 360; - hue = hue < 0 ? 360 + hue : hue; - hsl.color[0] = hue; - return hsl; - }, - - mix(mixinColor, weight) { - // Ported from sass implementation in C - // https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209 - if (!mixinColor || !mixinColor.rgb) { - throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor); - } - - const color1 = mixinColor.rgb(); - const color2 = this.rgb(); - const p = weight === undefined ? 0.5 : weight; - - const w = 2 * p - 1; - const a = color1.alpha() - color2.alpha(); - - const w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2; - const w2 = 1 - w1; - - return Color.rgb( - w1 * color1.red() + w2 * color2.red(), - w1 * color1.green() + w2 * color2.green(), - w1 * color1.blue() + w2 * color2.blue(), - color1.alpha() * p + color2.alpha() * (1 - p)); - }, -}; - -// Model conversion methods and static constructors -for (const model of Object.keys(convert)) { - if (skippedModels.includes(model)) { - continue; - } - - const {channels} = convert[model]; - - // Conversion methods - Color.prototype[model] = function (...args) { - if (this.model === model) { - return new Color(this); - } - - if (args.length > 0) { - return new Color(args, model); - } - - return new Color([...assertArray(convert[this.model][model].raw(this.color)), this.valpha], model); - }; - - // 'static' construction methods - Color[model] = function (...args) { - let color = args[0]; - if (typeof color === 'number') { - color = zeroArray(args, channels); - } - - return new Color(color, model); - }; -} - -function roundTo(number, places) { - return Number(number.toFixed(places)); -} - -function roundToPlace(places) { - return function (number) { - return roundTo(number, places); - }; -} - -function getset(model, channel, modifier) { - model = Array.isArray(model) ? model : [model]; - - for (const m of model) { - (limiters[m] || (limiters[m] = []))[channel] = modifier; - } - - model = model[0]; - - return function (value) { - let result; - - if (value !== undefined) { - if (modifier) { - value = modifier(value); - } - - result = this[model](); - result.color[channel] = value; - return result; - } - - result = this[model]().color[channel]; - if (modifier) { - result = modifier(result); - } - - return result; - }; -} - -function maxfn(max) { - return function (v) { - return Math.max(0, Math.min(max, v)); - }; -} - -function assertArray(value) { - return Array.isArray(value) ? value : [value]; -} - -function zeroArray(array, length) { - for (let i = 0; i < length; i++) { - if (typeof array[i] !== 'number') { - array[i] = 0; - } - } - - return array; -} - -module.exports = Color; diff --git a/node_modules/color/package.json b/node_modules/color/package.json deleted file mode 100644 index 4cdb6e31..00000000 --- a/node_modules/color/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "color", - "version": "4.2.3", - "description": "Color conversion and manipulation with CSS string support", - "sideEffects": false, - "keywords": [ - "color", - "colour", - "css" - ], - "authors": [ - "Josh Junon ", - "Heather Arthur ", - "Maxime Thirouin" - ], - "license": "MIT", - "repository": "Qix-/color", - "xo": { - "rules": { - "no-cond-assign": 0, - "new-cap": 0, - "unicorn/prefer-module": 0, - "no-mixed-operators": 0, - "complexity": 0, - "unicorn/numeric-separators-style": 0 - } - }, - "files": [ - "LICENSE", - "index.js" - ], - "scripts": { - "pretest": "xo", - "test": "mocha" - }, - "engines": { - "node": ">=12.5.0" - }, - "dependencies": { - "color-convert": "^2.0.1", - "color-string": "^1.9.0" - }, - "devDependencies": { - "mocha": "9.0.2", - "xo": "0.42.0" - } -} diff --git a/node_modules/is-arrayish/LICENSE b/node_modules/is-arrayish/LICENSE deleted file mode 100644 index 0a5f461a..00000000 --- a/node_modules/is-arrayish/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 JD Ballard - -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/is-arrayish/README.md b/node_modules/is-arrayish/README.md deleted file mode 100644 index 7d360724..00000000 --- a/node_modules/is-arrayish/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# node-is-arrayish [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-is-arrayish.svg?style=flat-square)](https://travis-ci.org/Qix-/node-is-arrayish) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-is-arrayish.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-is-arrayish) -> Determines if an object can be used like an Array - -## Example -```javascript -var isArrayish = require('is-arrayish'); - -isArrayish([]); // true -isArrayish({__proto__: []}); // true -isArrayish({}); // false -isArrayish({length:10}); // false -``` - -## License -Licensed under the [MIT License](http://opensource.org/licenses/MIT). -You can find a copy of it in [LICENSE](LICENSE). diff --git a/node_modules/is-arrayish/index.js b/node_modules/is-arrayish/index.js deleted file mode 100644 index 729ca40c..00000000 --- a/node_modules/is-arrayish/index.js +++ /dev/null @@ -1,9 +0,0 @@ -module.exports = function isArrayish(obj) { - if (!obj || typeof obj === 'string') { - return false; - } - - return obj instanceof Array || Array.isArray(obj) || - (obj.length >= 0 && (obj.splice instanceof Function || - (Object.getOwnPropertyDescriptor(obj, (obj.length - 1)) && obj.constructor.name !== 'String'))); -}; diff --git a/node_modules/is-arrayish/package.json b/node_modules/is-arrayish/package.json deleted file mode 100644 index 8a54e33c..00000000 --- a/node_modules/is-arrayish/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "is-arrayish", - "description": "Determines if an object can be used as an array", - "version": "0.3.2", - "author": "Qix (http://github.com/qix-)", - "keywords": [ - "is", - "array", - "duck", - "type", - "arrayish", - "similar", - "proto", - "prototype", - "type" - ], - "license": "MIT", - "scripts": { - "test": "mocha --require coffeescript/register ./test/**/*.coffee", - "lint": "zeit-eslint --ext .jsx,.js .", - "lint-staged": "git diff --diff-filter=ACMRT --cached --name-only '*.js' '*.jsx' | xargs zeit-eslint" - }, - "repository": { - "type": "git", - "url": "https://github.com/qix-/node-is-arrayish.git" - }, - "devDependencies": { - "@zeit/eslint-config-node": "^0.3.0", - "@zeit/git-hooks": "^0.1.4", - "coffeescript": "^2.3.1", - "coveralls": "^3.0.1", - "eslint": "^4.19.1", - "istanbul": "^0.4.5", - "mocha": "^5.2.0", - "should": "^13.2.1" - }, - "eslintConfig": { - "extends": [ - "@zeit/eslint-config-node" - ] - }, - "git": { - "pre-commit": "lint-staged" - } -} diff --git a/node_modules/is-arrayish/yarn-error.log b/node_modules/is-arrayish/yarn-error.log deleted file mode 100644 index d3dcf37b..00000000 --- a/node_modules/is-arrayish/yarn-error.log +++ /dev/null @@ -1,1443 +0,0 @@ -Arguments: - /Users/junon/n/bin/node /Users/junon/.yarn/bin/yarn.js test - -PATH: - /Users/junon/.yarn/bin:/Users/junon/.config/yarn/global/node_modules/.bin:/Users/junon/perl5/bin:/Users/junon/google-cloud-sdk/bin:/usr/local/sbin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/Users/junon/bin:/Users/junon/.local/bin:/src/.go/bin:/src/llvm/llvm/build/bin:/Users/junon/Library/Android/sdk/platform-tools:/Users/junon/n/bin:/usr/local/texlive/2017/bin/x86_64-darwin/ - -Yarn version: - 1.5.1 - -Node version: - 9.6.1 - -Platform: - darwin x64 - -npm manifest: - { - "name": "is-arrayish", - "description": "Determines if an object can be used as an array", - "version": "0.3.1", - "author": "Qix (http://github.com/qix-)", - "keywords": [ - "is", - "array", - "duck", - "type", - "arrayish", - "similar", - "proto", - "prototype", - "type" - ], - "license": "MIT", - "scripts": { - "test": "mocha --require coffeescript/register", - "lint": "zeit-eslint --ext .jsx,.js .", - "lint-staged": "git diff --diff-filter=ACMRT --cached --name-only '*.js' '*.jsx' | xargs zeit-eslint" - }, - "repository": { - "type": "git", - "url": "https://github.com/qix-/node-is-arrayish.git" - }, - "devDependencies": { - "@zeit/eslint-config-node": "^0.3.0", - "@zeit/git-hooks": "^0.1.4", - "coffeescript": "^2.3.1", - "coveralls": "^3.0.1", - "eslint": "^4.19.1", - "istanbul": "^0.4.5", - "mocha": "^5.2.0", - "should": "^13.2.1" - }, - "eslintConfig": { - "extends": [ - "@zeit/eslint-config-node" - ] - }, - "git": { - "pre-commit": "lint-staged" - } - } - -yarn manifest: - No manifest - -Lockfile: - # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. - # yarn lockfile v1 - - - "@zeit/eslint-config-base@0.3.0": - version "0.3.0" - resolved "https://registry.yarnpkg.com/@zeit/eslint-config-base/-/eslint-config-base-0.3.0.tgz#32a58c3e52eca4025604758cb4591f3d28e22fb4" - dependencies: - arg "^1.0.0" - chalk "^2.3.0" - - "@zeit/eslint-config-node@^0.3.0": - version "0.3.0" - resolved "https://registry.yarnpkg.com/@zeit/eslint-config-node/-/eslint-config-node-0.3.0.tgz#6e328328f366f66c2a0549a69131bbcd9735f098" - dependencies: - "@zeit/eslint-config-base" "0.3.0" - - "@zeit/git-hooks@^0.1.4": - version "0.1.4" - resolved "https://registry.yarnpkg.com/@zeit/git-hooks/-/git-hooks-0.1.4.tgz#70583db5dd69726a62c7963520e67f2c3a33cc5f" - - abbrev@1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" - - abbrev@1.0.x: - version "1.0.9" - resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.0.9.tgz#91b4792588a7738c25f35dd6f63752a2f8776135" - - acorn-jsx@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-3.0.1.tgz#afdf9488fb1ecefc8348f6fb22f464e32a58b36b" - dependencies: - acorn "^3.0.4" - - acorn@^3.0.4: - version "3.3.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-3.3.0.tgz#45e37fb39e8da3f25baee3ff5369e2bb5f22017a" - - acorn@^5.5.0: - version "5.7.1" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-5.7.1.tgz#f095829297706a7c9776958c0afc8930a9b9d9d8" - - ajv-keywords@^2.1.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-2.1.1.tgz#617997fc5f60576894c435f940d819e135b80762" - - ajv@^5.1.0, ajv@^5.2.3, ajv@^5.3.0: - version "5.5.2" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-5.5.2.tgz#73b5eeca3fab653e3d3f9422b341ad42205dc965" - dependencies: - co "^4.6.0" - fast-deep-equal "^1.0.0" - fast-json-stable-stringify "^2.0.0" - json-schema-traverse "^0.3.0" - - align-text@^0.1.1, align-text@^0.1.3: - version "0.1.4" - resolved "https://registry.yarnpkg.com/align-text/-/align-text-0.1.4.tgz#0cd90a561093f35d0a99256c22b7069433fad117" - dependencies: - kind-of "^3.0.2" - longest "^1.0.1" - repeat-string "^1.5.2" - - amdefine@>=0.0.4: - version "1.0.1" - resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5" - - ansi-escapes@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-3.1.0.tgz#f73207bb81207d75fd6c83f125af26eea378ca30" - - ansi-regex@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" - - ansi-regex@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.0.tgz#ed0317c322064f79466c02966bddb605ab37d998" - - ansi-styles@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" - - ansi-styles@^3.2.1: - version "3.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" - dependencies: - color-convert "^1.9.0" - - arg@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/arg/-/arg-1.0.1.tgz#892a26d841bd5a64880bbc8f73dd64a705910ca3" - - argparse@^1.0.7: - version "1.0.10" - resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" - dependencies: - sprintf-js "~1.0.2" - - array-union@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/array-union/-/array-union-1.0.2.tgz#9a34410e4f4e3da23dea375be5be70f24778ec39" - dependencies: - array-uniq "^1.0.1" - - array-uniq@^1.0.1: - version "1.0.3" - resolved "https://registry.yarnpkg.com/array-uniq/-/array-uniq-1.0.3.tgz#af6ac877a25cc7f74e058894753858dfdb24fdb6" - - arrify@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" - - asn1@~0.2.3: - version "0.2.3" - resolved "https://registry.yarnpkg.com/asn1/-/asn1-0.2.3.tgz#dac8787713c9966849fc8180777ebe9c1ddf3b86" - - assert-plus@1.0.0, assert-plus@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525" - - async@1.x, async@^1.4.0: - version "1.5.2" - resolved "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a" - - asynckit@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" - - aws-sign2@~0.7.0: - version "0.7.0" - resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.7.0.tgz#b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8" - - aws4@^1.6.0: - version "1.7.0" - resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.7.0.tgz#d4d0e9b9dbfca77bf08eeb0a8a471550fe39e289" - - babel-code-frame@^6.22.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.26.0.tgz#63fd43f7dc1e3bb7ce35947db8fe369a3f58c74b" - dependencies: - chalk "^1.1.3" - esutils "^2.0.2" - js-tokens "^3.0.2" - - balanced-match@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" - - bcrypt-pbkdf@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.1.tgz#63bc5dcb61331b92bc05fd528953c33462a06f8d" - dependencies: - tweetnacl "^0.14.3" - - brace-expansion@^1.1.7: - version "1.1.11" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - - browser-stdout@1.3.1: - version "1.3.1" - resolved "https://registry.yarnpkg.com/browser-stdout/-/browser-stdout-1.3.1.tgz#baa559ee14ced73452229bad7326467c61fabd60" - - buffer-from@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.0.tgz#87fcaa3a298358e0ade6e442cfce840740d1ad04" - - caller-path@^0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/caller-path/-/caller-path-0.1.0.tgz#94085ef63581ecd3daa92444a8fe94e82577751f" - dependencies: - callsites "^0.2.0" - - callsites@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/callsites/-/callsites-0.2.0.tgz#afab96262910a7f33c19a5775825c69f34e350ca" - - camelcase@^1.0.2: - version "1.2.1" - resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-1.2.1.tgz#9bb5304d2e0b56698b2c758b08a3eaa9daa58a39" - - caseless@~0.12.0: - version "0.12.0" - resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc" - - center-align@^0.1.1: - version "0.1.3" - resolved "https://registry.yarnpkg.com/center-align/-/center-align-0.1.3.tgz#aa0d32629b6ee972200411cbd4461c907bc2b7ad" - dependencies: - align-text "^0.1.3" - lazy-cache "^1.0.3" - - chalk@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" - dependencies: - ansi-styles "^2.2.1" - escape-string-regexp "^1.0.2" - has-ansi "^2.0.0" - strip-ansi "^3.0.0" - supports-color "^2.0.0" - - chalk@^2.0.0, chalk@^2.1.0, chalk@^2.3.0: - version "2.4.1" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.1.tgz#18c49ab16a037b6eb0152cc83e3471338215b66e" - dependencies: - ansi-styles "^3.2.1" - escape-string-regexp "^1.0.5" - supports-color "^5.3.0" - - chardet@^0.4.0: - version "0.4.2" - resolved "https://registry.yarnpkg.com/chardet/-/chardet-0.4.2.tgz#b5473b33dc97c424e5d98dc87d55d4d8a29c8bf2" - - circular-json@^0.3.1: - version "0.3.3" - resolved "https://registry.yarnpkg.com/circular-json/-/circular-json-0.3.3.tgz#815c99ea84f6809529d2f45791bdf82711352d66" - - cli-cursor@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-2.1.0.tgz#b35dac376479facc3e94747d41d0d0f5238ffcb5" - dependencies: - restore-cursor "^2.0.0" - - cli-width@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-2.2.0.tgz#ff19ede8a9a5e579324147b0c11f0fbcbabed639" - - cliui@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-2.1.0.tgz#4b475760ff80264c762c3a1719032e91c7fea0d1" - dependencies: - center-align "^0.1.1" - right-align "^0.1.1" - wordwrap "0.0.2" - - co@^4.6.0: - version "4.6.0" - resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" - - coffeescript@^2.3.1: - version "2.3.1" - resolved "https://registry.yarnpkg.com/coffeescript/-/coffeescript-2.3.1.tgz#a25f69c251d25805c9842e57fc94bfc453ef6aed" - - color-convert@^1.9.0: - version "1.9.2" - resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.2.tgz#49881b8fba67df12a96bdf3f56c0aab9e7913147" - dependencies: - color-name "1.1.1" - - color-name@1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.1.tgz#4b1415304cf50028ea81643643bd82ea05803689" - - combined-stream@1.0.6, combined-stream@~1.0.5: - version "1.0.6" - resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.6.tgz#723e7df6e801ac5613113a7e445a9b69cb632818" - dependencies: - delayed-stream "~1.0.0" - - commander@2.15.1: - version "2.15.1" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.15.1.tgz#df46e867d0fc2aec66a34662b406a9ccafff5b0f" - - concat-map@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" - - concat-stream@^1.6.0: - version "1.6.2" - resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.2.tgz#904bdf194cd3122fc675c77fc4ac3d4ff0fd1a34" - dependencies: - buffer-from "^1.0.0" - inherits "^2.0.3" - readable-stream "^2.2.2" - typedarray "^0.0.6" - - core-util-is@1.0.2, core-util-is@~1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" - - coveralls@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/coveralls/-/coveralls-3.0.1.tgz#12e15914eaa29204e56869a5ece7b9e1492d2ae2" - dependencies: - js-yaml "^3.6.1" - lcov-parse "^0.0.10" - log-driver "^1.2.5" - minimist "^1.2.0" - request "^2.79.0" - - cross-spawn@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-5.1.0.tgz#e8bd0efee58fcff6f8f94510a0a554bbfa235449" - dependencies: - lru-cache "^4.0.1" - shebang-command "^1.2.0" - which "^1.2.9" - - dashdash@^1.12.0: - version "1.14.1" - resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0" - dependencies: - assert-plus "^1.0.0" - - debug@3.1.0, debug@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261" - dependencies: - ms "2.0.0" - - decamelize@^1.0.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" - - deep-is@~0.1.3: - version "0.1.3" - resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34" - - del@^2.0.2: - version "2.2.2" - resolved "https://registry.yarnpkg.com/del/-/del-2.2.2.tgz#c12c981d067846c84bcaf862cff930d907ffd1a8" - dependencies: - globby "^5.0.0" - is-path-cwd "^1.0.0" - is-path-in-cwd "^1.0.0" - object-assign "^4.0.1" - pify "^2.0.0" - pinkie-promise "^2.0.0" - rimraf "^2.2.8" - - delayed-stream@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" - - diff@3.5.0: - version "3.5.0" - resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12" - - doctrine@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-2.1.0.tgz#5cd01fc101621b42c4cd7f5d1a66243716d3f39d" - dependencies: - esutils "^2.0.2" - - ecc-jsbn@~0.1.1: - version "0.1.1" - resolved "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz#0fc73a9ed5f0d53c38193398523ef7e543777505" - dependencies: - jsbn "~0.1.0" - - escape-string-regexp@1.0.5, escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" - - escodegen@1.8.x: - version "1.8.1" - resolved "https://registry.yarnpkg.com/escodegen/-/escodegen-1.8.1.tgz#5a5b53af4693110bebb0867aa3430dd3b70a1018" - dependencies: - esprima "^2.7.1" - estraverse "^1.9.1" - esutils "^2.0.2" - optionator "^0.8.1" - optionalDependencies: - source-map "~0.2.0" - - eslint-scope@^3.7.1: - version "3.7.1" - resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-3.7.1.tgz#3d63c3edfda02e06e01a452ad88caacc7cdcb6e8" - dependencies: - esrecurse "^4.1.0" - estraverse "^4.1.1" - - eslint-visitor-keys@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz#3f3180fb2e291017716acb4c9d6d5b5c34a6a81d" - - eslint@^4.19.1: - version "4.19.1" - resolved "https://registry.yarnpkg.com/eslint/-/eslint-4.19.1.tgz#32d1d653e1d90408854bfb296f076ec7e186a300" - dependencies: - ajv "^5.3.0" - babel-code-frame "^6.22.0" - chalk "^2.1.0" - concat-stream "^1.6.0" - cross-spawn "^5.1.0" - debug "^3.1.0" - doctrine "^2.1.0" - eslint-scope "^3.7.1" - eslint-visitor-keys "^1.0.0" - espree "^3.5.4" - esquery "^1.0.0" - esutils "^2.0.2" - file-entry-cache "^2.0.0" - functional-red-black-tree "^1.0.1" - glob "^7.1.2" - globals "^11.0.1" - ignore "^3.3.3" - imurmurhash "^0.1.4" - inquirer "^3.0.6" - is-resolvable "^1.0.0" - js-yaml "^3.9.1" - json-stable-stringify-without-jsonify "^1.0.1" - levn "^0.3.0" - lodash "^4.17.4" - minimatch "^3.0.2" - mkdirp "^0.5.1" - natural-compare "^1.4.0" - optionator "^0.8.2" - path-is-inside "^1.0.2" - pluralize "^7.0.0" - progress "^2.0.0" - regexpp "^1.0.1" - require-uncached "^1.0.3" - semver "^5.3.0" - strip-ansi "^4.0.0" - strip-json-comments "~2.0.1" - table "4.0.2" - text-table "~0.2.0" - - espree@^3.5.4: - version "3.5.4" - resolved "https://registry.yarnpkg.com/espree/-/espree-3.5.4.tgz#b0f447187c8a8bed944b815a660bddf5deb5d1a7" - dependencies: - acorn "^5.5.0" - acorn-jsx "^3.0.0" - - esprima@2.7.x, esprima@^2.7.1: - version "2.7.3" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-2.7.3.tgz#96e3b70d5779f6ad49cd032673d1c312767ba581" - - esprima@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.0.tgz#4499eddcd1110e0b218bacf2fa7f7f59f55ca804" - - esquery@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.0.1.tgz#406c51658b1f5991a5f9b62b1dc25b00e3e5c708" - dependencies: - estraverse "^4.0.0" - - esrecurse@^4.1.0: - version "4.2.1" - resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.2.1.tgz#007a3b9fdbc2b3bb87e4879ea19c92fdbd3942cf" - dependencies: - estraverse "^4.1.0" - - estraverse@^1.9.1: - version "1.9.3" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-1.9.3.tgz#af67f2dc922582415950926091a4005d29c9bb44" - - estraverse@^4.0.0, estraverse@^4.1.0, estraverse@^4.1.1: - version "4.2.0" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.2.0.tgz#0dee3fed31fcd469618ce7342099fc1afa0bdb13" - - esutils@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b" - - extend@~3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.1.tgz#a755ea7bc1adfcc5a31ce7e762dbaadc5e636444" - - external-editor@^2.0.4: - version "2.2.0" - resolved "https://registry.yarnpkg.com/external-editor/-/external-editor-2.2.0.tgz#045511cfd8d133f3846673d1047c154e214ad3d5" - dependencies: - chardet "^0.4.0" - iconv-lite "^0.4.17" - tmp "^0.0.33" - - extsprintf@1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05" - - extsprintf@^1.2.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.0.tgz#e2689f8f356fad62cca65a3a91c5df5f9551692f" - - fast-deep-equal@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz#c053477817c86b51daa853c81e059b733d023614" - - fast-json-stable-stringify@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz#d5142c0caee6b1189f87d3a76111064f86c8bbf2" - - fast-levenshtein@~2.0.4: - version "2.0.6" - resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" - - figures@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/figures/-/figures-2.0.0.tgz#3ab1a2d2a62c8bfb431a0c94cb797a2fce27c962" - dependencies: - escape-string-regexp "^1.0.5" - - file-entry-cache@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-2.0.0.tgz#c392990c3e684783d838b8c84a45d8a048458361" - dependencies: - flat-cache "^1.2.1" - object-assign "^4.0.1" - - flat-cache@^1.2.1: - version "1.3.0" - resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-1.3.0.tgz#d3030b32b38154f4e3b7e9c709f490f7ef97c481" - dependencies: - circular-json "^0.3.1" - del "^2.0.2" - graceful-fs "^4.1.2" - write "^0.2.1" - - forever-agent@~0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91" - - form-data@~2.3.1: - version "2.3.2" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.2.tgz#4970498be604c20c005d4f5c23aecd21d6b49099" - dependencies: - asynckit "^0.4.0" - combined-stream "1.0.6" - mime-types "^2.1.12" - - fs.realpath@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" - - functional-red-black-tree@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327" - - getpass@^0.1.1: - version "0.1.7" - resolved "https://registry.yarnpkg.com/getpass/-/getpass-0.1.7.tgz#5eff8e3e684d569ae4cb2b1282604e8ba62149fa" - dependencies: - assert-plus "^1.0.0" - - glob@7.1.2, glob@^7.0.3, glob@^7.0.5, glob@^7.1.2: - version "7.1.2" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15" - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.0.4" - once "^1.3.0" - path-is-absolute "^1.0.0" - - glob@^5.0.15: - version "5.0.15" - resolved "https://registry.yarnpkg.com/glob/-/glob-5.0.15.tgz#1bc936b9e02f4a603fcc222ecf7633d30b8b93b1" - dependencies: - inflight "^1.0.4" - inherits "2" - minimatch "2 || 3" - once "^1.3.0" - path-is-absolute "^1.0.0" - - globals@^11.0.1: - version "11.5.0" - resolved "https://registry.yarnpkg.com/globals/-/globals-11.5.0.tgz#6bc840de6771173b191f13d3a9c94d441ee92642" - - globby@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/globby/-/globby-5.0.0.tgz#ebd84667ca0dbb330b99bcfc68eac2bc54370e0d" - dependencies: - array-union "^1.0.1" - arrify "^1.0.0" - glob "^7.0.3" - object-assign "^4.0.1" - pify "^2.0.0" - pinkie-promise "^2.0.0" - - graceful-fs@^4.1.2: - version "4.1.11" - resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.11.tgz#0e8bdfe4d1ddb8854d64e04ea7c00e2a026e5658" - - growl@1.10.5: - version "1.10.5" - resolved "https://registry.yarnpkg.com/growl/-/growl-1.10.5.tgz#f2735dc2283674fa67478b10181059355c369e5e" - - handlebars@^4.0.1: - version "4.0.11" - resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.0.11.tgz#630a35dfe0294bc281edae6ffc5d329fc7982dcc" - dependencies: - async "^1.4.0" - optimist "^0.6.1" - source-map "^0.4.4" - optionalDependencies: - uglify-js "^2.6" - - har-schema@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/har-schema/-/har-schema-2.0.0.tgz#a94c2224ebcac04782a0d9035521f24735b7ec92" - - har-validator@~5.0.3: - version "5.0.3" - resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-5.0.3.tgz#ba402c266194f15956ef15e0fcf242993f6a7dfd" - dependencies: - ajv "^5.1.0" - har-schema "^2.0.0" - - has-ansi@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" - dependencies: - ansi-regex "^2.0.0" - - has-flag@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-1.0.0.tgz#9d9e793165ce017a00f00418c43f942a7b1d11fa" - - has-flag@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" - - he@1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/he/-/he-1.1.1.tgz#93410fd21b009735151f8868c2f271f3427e23fd" - - http-signature@~1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.2.0.tgz#9aecd925114772f3d95b65a60abb8f7c18fbace1" - dependencies: - assert-plus "^1.0.0" - jsprim "^1.2.2" - sshpk "^1.7.0" - - iconv-lite@^0.4.17: - version "0.4.23" - resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.23.tgz#297871f63be507adcfbfca715d0cd0eed84e9a63" - dependencies: - safer-buffer ">= 2.1.2 < 3" - - ignore@^3.3.3: - version "3.3.8" - resolved "https://registry.yarnpkg.com/ignore/-/ignore-3.3.8.tgz#3f8e9c35d38708a3a7e0e9abb6c73e7ee7707b2b" - - imurmurhash@^0.1.4: - version "0.1.4" - resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" - - inflight@^1.0.4: - version "1.0.6" - resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" - dependencies: - once "^1.3.0" - wrappy "1" - - inherits@2, inherits@^2.0.3, inherits@~2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de" - - inquirer@^3.0.6: - version "3.3.0" - resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-3.3.0.tgz#9dd2f2ad765dcab1ff0443b491442a20ba227dc9" - dependencies: - ansi-escapes "^3.0.0" - chalk "^2.0.0" - cli-cursor "^2.1.0" - cli-width "^2.0.0" - external-editor "^2.0.4" - figures "^2.0.0" - lodash "^4.3.0" - mute-stream "0.0.7" - run-async "^2.2.0" - rx-lite "^4.0.8" - rx-lite-aggregates "^4.0.8" - string-width "^2.1.0" - strip-ansi "^4.0.0" - through "^2.3.6" - - is-buffer@^1.1.5: - version "1.1.6" - resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" - - is-fullwidth-code-point@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" - - is-path-cwd@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-path-cwd/-/is-path-cwd-1.0.0.tgz#d225ec23132e89edd38fda767472e62e65f1106d" - - is-path-in-cwd@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-path-in-cwd/-/is-path-in-cwd-1.0.1.tgz#5ac48b345ef675339bd6c7a48a912110b241cf52" - dependencies: - is-path-inside "^1.0.0" - - is-path-inside@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-1.0.1.tgz#8ef5b7de50437a3fdca6b4e865ef7aa55cb48036" - dependencies: - path-is-inside "^1.0.1" - - is-promise@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-promise/-/is-promise-2.1.0.tgz#79a2a9ece7f096e80f36d2b2f3bc16c1ff4bf3fa" - - is-resolvable@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/is-resolvable/-/is-resolvable-1.1.0.tgz#fb18f87ce1feb925169c9a407c19318a3206ed88" - - is-typedarray@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" - - isarray@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" - - isexe@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" - - isstream@~0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" - - istanbul@^0.4.5: - version "0.4.5" - resolved "https://registry.yarnpkg.com/istanbul/-/istanbul-0.4.5.tgz#65c7d73d4c4da84d4f3ac310b918fb0b8033733b" - dependencies: - abbrev "1.0.x" - async "1.x" - escodegen "1.8.x" - esprima "2.7.x" - glob "^5.0.15" - handlebars "^4.0.1" - js-yaml "3.x" - mkdirp "0.5.x" - nopt "3.x" - once "1.x" - resolve "1.1.x" - supports-color "^3.1.0" - which "^1.1.1" - wordwrap "^1.0.0" - - js-tokens@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.2.tgz#9866df395102130e38f7f996bceb65443209c25b" - - js-yaml@3.x, js-yaml@^3.6.1, js-yaml@^3.9.1: - version "3.12.0" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.12.0.tgz#eaed656ec8344f10f527c6bfa1b6e2244de167d1" - dependencies: - argparse "^1.0.7" - esprima "^4.0.0" - - jsbn@~0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" - - json-schema-traverse@^0.3.0: - version "0.3.1" - resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz#349a6d44c53a51de89b40805c5d5e59b417d3340" - - json-schema@0.2.3: - version "0.2.3" - resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13" - - json-stable-stringify-without-jsonify@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" - - json-stringify-safe@~5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" - - jsprim@^1.2.2: - version "1.4.1" - resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2" - dependencies: - assert-plus "1.0.0" - extsprintf "1.3.0" - json-schema "0.2.3" - verror "1.10.0" - - kind-of@^3.0.2: - version "3.2.2" - resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" - dependencies: - is-buffer "^1.1.5" - - lazy-cache@^1.0.3: - version "1.0.4" - resolved "https://registry.yarnpkg.com/lazy-cache/-/lazy-cache-1.0.4.tgz#a1d78fc3a50474cb80845d3b3b6e1da49a446e8e" - - lcov-parse@^0.0.10: - version "0.0.10" - resolved "https://registry.yarnpkg.com/lcov-parse/-/lcov-parse-0.0.10.tgz#1b0b8ff9ac9c7889250582b70b71315d9da6d9a3" - - levn@^0.3.0, levn@~0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/levn/-/levn-0.3.0.tgz#3b09924edf9f083c0490fdd4c0bc4421e04764ee" - dependencies: - prelude-ls "~1.1.2" - type-check "~0.3.2" - - lodash@^4.17.4, lodash@^4.3.0: - version "4.17.10" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.10.tgz#1b7793cf7259ea38fb3661d4d38b3260af8ae4e7" - - log-driver@^1.2.5: - version "1.2.7" - resolved "https://registry.yarnpkg.com/log-driver/-/log-driver-1.2.7.tgz#63b95021f0702fedfa2c9bb0a24e7797d71871d8" - - longest@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/longest/-/longest-1.0.1.tgz#30a0b2da38f73770e8294a0d22e6625ed77d0097" - - lru-cache@^4.0.1: - version "4.1.3" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.1.3.tgz#a1175cf3496dfc8436c156c334b4955992bce69c" - dependencies: - pseudomap "^1.0.2" - yallist "^2.1.2" - - mime-db@~1.33.0: - version "1.33.0" - resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.33.0.tgz#a3492050a5cb9b63450541e39d9788d2272783db" - - mime-types@^2.1.12, mime-types@~2.1.17: - version "2.1.18" - resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.18.tgz#6f323f60a83d11146f831ff11fd66e2fe5503bb8" - dependencies: - mime-db "~1.33.0" - - mimic-fn@^1.0.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-1.2.0.tgz#820c86a39334640e99516928bd03fca88057d022" - - "minimatch@2 || 3", minimatch@3.0.4, minimatch@^3.0.2, minimatch@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" - dependencies: - brace-expansion "^1.1.7" - - minimist@0.0.8: - version "0.0.8" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d" - - minimist@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284" - - minimist@~0.0.1: - version "0.0.10" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.10.tgz#de3f98543dbf96082be48ad1a0c7cda836301dcf" - - mkdirp@0.5.1, mkdirp@0.5.x, mkdirp@^0.5.1: - version "0.5.1" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" - dependencies: - minimist "0.0.8" - - mocha@^5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/mocha/-/mocha-5.2.0.tgz#6d8ae508f59167f940f2b5b3c4a612ae50c90ae6" - dependencies: - browser-stdout "1.3.1" - commander "2.15.1" - debug "3.1.0" - diff "3.5.0" - escape-string-regexp "1.0.5" - glob "7.1.2" - growl "1.10.5" - he "1.1.1" - minimatch "3.0.4" - mkdirp "0.5.1" - supports-color "5.4.0" - - ms@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" - - mute-stream@0.0.7: - version "0.0.7" - resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.7.tgz#3075ce93bc21b8fab43e1bc4da7e8115ed1e7bab" - - natural-compare@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" - - nopt@3.x: - version "3.0.6" - resolved "https://registry.yarnpkg.com/nopt/-/nopt-3.0.6.tgz#c6465dbf08abcd4db359317f79ac68a646b28ff9" - dependencies: - abbrev "1" - - oauth-sign@~0.8.2: - version "0.8.2" - resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.8.2.tgz#46a6ab7f0aead8deae9ec0565780b7d4efeb9d43" - - object-assign@^4.0.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" - - once@1.x, once@^1.3.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" - dependencies: - wrappy "1" - - onetime@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/onetime/-/onetime-2.0.1.tgz#067428230fd67443b2794b22bba528b6867962d4" - dependencies: - mimic-fn "^1.0.0" - - optimist@^0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/optimist/-/optimist-0.6.1.tgz#da3ea74686fa21a19a111c326e90eb15a0196686" - dependencies: - minimist "~0.0.1" - wordwrap "~0.0.2" - - optionator@^0.8.1, optionator@^0.8.2: - version "0.8.2" - resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.8.2.tgz#364c5e409d3f4d6301d6c0b4c05bba50180aeb64" - dependencies: - deep-is "~0.1.3" - fast-levenshtein "~2.0.4" - levn "~0.3.0" - prelude-ls "~1.1.2" - type-check "~0.3.2" - wordwrap "~1.0.0" - - os-tmpdir@~1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" - - path-is-absolute@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" - - path-is-inside@^1.0.1, path-is-inside@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/path-is-inside/-/path-is-inside-1.0.2.tgz#365417dede44430d1c11af61027facf074bdfc53" - - performance-now@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b" - - pify@^2.0.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" - - pinkie-promise@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa" - dependencies: - pinkie "^2.0.0" - - pinkie@^2.0.0: - version "2.0.4" - resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870" - - pluralize@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-7.0.0.tgz#298b89df8b93b0221dbf421ad2b1b1ea23fc6777" - - prelude-ls@~1.1.2: - version "1.1.2" - resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" - - process-nextick-args@~2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.0.tgz#a37d732f4271b4ab1ad070d35508e8290788ffaa" - - progress@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.0.tgz#8a1be366bf8fc23db2bd23f10c6fe920b4389d1f" - - pseudomap@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3" - - punycode@^1.4.1: - version "1.4.1" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e" - - qs@~6.5.1: - version "6.5.2" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.2.tgz#cb3ae806e8740444584ef154ce8ee98d403f3e36" - - readable-stream@^2.2.2: - version "2.3.6" - resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf" - dependencies: - core-util-is "~1.0.0" - inherits "~2.0.3" - isarray "~1.0.0" - process-nextick-args "~2.0.0" - safe-buffer "~5.1.1" - string_decoder "~1.1.1" - util-deprecate "~1.0.1" - - regexpp@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-1.1.0.tgz#0e3516dd0b7904f413d2d4193dce4618c3a689ab" - - repeat-string@^1.5.2: - version "1.6.1" - resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" - - request@^2.79.0: - version "2.87.0" - resolved "https://registry.yarnpkg.com/request/-/request-2.87.0.tgz#32f00235cd08d482b4d0d68db93a829c0ed5756e" - dependencies: - aws-sign2 "~0.7.0" - aws4 "^1.6.0" - caseless "~0.12.0" - combined-stream "~1.0.5" - extend "~3.0.1" - forever-agent "~0.6.1" - form-data "~2.3.1" - har-validator "~5.0.3" - http-signature "~1.2.0" - is-typedarray "~1.0.0" - isstream "~0.1.2" - json-stringify-safe "~5.0.1" - mime-types "~2.1.17" - oauth-sign "~0.8.2" - performance-now "^2.1.0" - qs "~6.5.1" - safe-buffer "^5.1.1" - tough-cookie "~2.3.3" - tunnel-agent "^0.6.0" - uuid "^3.1.0" - - require-uncached@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/require-uncached/-/require-uncached-1.0.3.tgz#4e0d56d6c9662fd31e43011c4b95aa49955421d3" - dependencies: - caller-path "^0.1.0" - resolve-from "^1.0.0" - - resolve-from@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-1.0.1.tgz#26cbfe935d1aeeeabb29bc3fe5aeb01e93d44226" - - resolve@1.1.x: - version "1.1.7" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.1.7.tgz#203114d82ad2c5ed9e8e0411b3932875e889e97b" - - restore-cursor@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-2.0.0.tgz#9f7ee287f82fd326d4fd162923d62129eee0dfaf" - dependencies: - onetime "^2.0.0" - signal-exit "^3.0.2" - - right-align@^0.1.1: - version "0.1.3" - resolved "https://registry.yarnpkg.com/right-align/-/right-align-0.1.3.tgz#61339b722fe6a3515689210d24e14c96148613ef" - dependencies: - align-text "^0.1.1" - - rimraf@^2.2.8: - version "2.6.2" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.2.tgz#2ed8150d24a16ea8651e6d6ef0f47c4158ce7a36" - dependencies: - glob "^7.0.5" - - run-async@^2.2.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/run-async/-/run-async-2.3.0.tgz#0371ab4ae0bdd720d4166d7dfda64ff7a445a6c0" - dependencies: - is-promise "^2.1.0" - - rx-lite-aggregates@^4.0.8: - version "4.0.8" - resolved "https://registry.yarnpkg.com/rx-lite-aggregates/-/rx-lite-aggregates-4.0.8.tgz#753b87a89a11c95467c4ac1626c4efc4e05c67be" - dependencies: - rx-lite "*" - - rx-lite@*, rx-lite@^4.0.8: - version "4.0.8" - resolved "https://registry.yarnpkg.com/rx-lite/-/rx-lite-4.0.8.tgz#0b1e11af8bc44836f04a6407e92da42467b79444" - - safe-buffer@^5.0.1, safe-buffer@^5.1.1, safe-buffer@~5.1.0, safe-buffer@~5.1.1: - version "5.1.2" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" - - "safer-buffer@>= 2.1.2 < 3", safer-buffer@^2.0.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" - - semver@^5.3.0: - version "5.5.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-5.5.0.tgz#dc4bbc7a6ca9d916dee5d43516f0092b58f7b8ab" - - shebang-command@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea" - dependencies: - shebang-regex "^1.0.0" - - shebang-regex@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-1.0.0.tgz#da42f49740c0b42db2ca9728571cb190c98efea3" - - should-equal@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/should-equal/-/should-equal-2.0.0.tgz#6072cf83047360867e68e98b09d71143d04ee0c3" - dependencies: - should-type "^1.4.0" - - should-format@^3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/should-format/-/should-format-3.0.3.tgz#9bfc8f74fa39205c53d38c34d717303e277124f1" - dependencies: - should-type "^1.3.0" - should-type-adaptors "^1.0.1" - - should-type-adaptors@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/should-type-adaptors/-/should-type-adaptors-1.1.0.tgz#401e7f33b5533033944d5cd8bf2b65027792e27a" - dependencies: - should-type "^1.3.0" - should-util "^1.0.0" - - should-type@^1.3.0, should-type@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/should-type/-/should-type-1.4.0.tgz#0756d8ce846dfd09843a6947719dfa0d4cff5cf3" - - should-util@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/should-util/-/should-util-1.0.0.tgz#c98cda374aa6b190df8ba87c9889c2b4db620063" - - should@^13.2.1: - version "13.2.1" - resolved "https://registry.yarnpkg.com/should/-/should-13.2.1.tgz#84e6ebfbb145c79e0ae42307b25b3f62dcaf574e" - dependencies: - should-equal "^2.0.0" - should-format "^3.0.3" - should-type "^1.4.0" - should-type-adaptors "^1.0.1" - should-util "^1.0.0" - - signal-exit@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d" - - slice-ansi@1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-1.0.0.tgz#044f1a49d8842ff307aad6b505ed178bd950134d" - dependencies: - is-fullwidth-code-point "^2.0.0" - - source-map@^0.4.4: - version "0.4.4" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.4.4.tgz#eba4f5da9c0dc999de68032d8b4f76173652036b" - dependencies: - amdefine ">=0.0.4" - - source-map@~0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.2.0.tgz#dab73fbcfc2ba819b4de03bd6f6eaa48164b3f9d" - dependencies: - amdefine ">=0.0.4" - - source-map@~0.5.1: - version "0.5.7" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" - - sprintf-js@~1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" - - sshpk@^1.7.0: - version "1.14.2" - resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.14.2.tgz#c6fc61648a3d9c4e764fd3fcdf4ea105e492ba98" - dependencies: - asn1 "~0.2.3" - assert-plus "^1.0.0" - dashdash "^1.12.0" - getpass "^0.1.1" - safer-buffer "^2.0.2" - optionalDependencies: - bcrypt-pbkdf "^1.0.0" - ecc-jsbn "~0.1.1" - jsbn "~0.1.0" - tweetnacl "~0.14.0" - - string-width@^2.1.0, string-width@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e" - dependencies: - is-fullwidth-code-point "^2.0.0" - strip-ansi "^4.0.0" - - string_decoder@~1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" - dependencies: - safe-buffer "~5.1.0" - - strip-ansi@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" - dependencies: - ansi-regex "^2.0.0" - - strip-ansi@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f" - dependencies: - ansi-regex "^3.0.0" - - strip-json-comments@~2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" - - supports-color@5.4.0, supports-color@^5.3.0: - version "5.4.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.4.0.tgz#1c6b337402c2137605efe19f10fec390f6faab54" - dependencies: - has-flag "^3.0.0" - - supports-color@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" - - supports-color@^3.1.0: - version "3.2.3" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-3.2.3.tgz#65ac0504b3954171d8a64946b2ae3cbb8a5f54f6" - dependencies: - has-flag "^1.0.0" - - table@4.0.2: - version "4.0.2" - resolved "https://registry.yarnpkg.com/table/-/table-4.0.2.tgz#a33447375391e766ad34d3486e6e2aedc84d2e36" - dependencies: - ajv "^5.2.3" - ajv-keywords "^2.1.0" - chalk "^2.1.0" - lodash "^4.17.4" - slice-ansi "1.0.0" - string-width "^2.1.1" - - text-table@~0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" - - through@^2.3.6: - version "2.3.8" - resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" - - tmp@^0.0.33: - version "0.0.33" - resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" - dependencies: - os-tmpdir "~1.0.2" - - tough-cookie@~2.3.3: - version "2.3.4" - resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.3.4.tgz#ec60cee38ac675063ffc97a5c18970578ee83655" - dependencies: - punycode "^1.4.1" - - tunnel-agent@^0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd" - dependencies: - safe-buffer "^5.0.1" - - tweetnacl@^0.14.3, tweetnacl@~0.14.0: - version "0.14.5" - resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64" - - type-check@~0.3.2: - version "0.3.2" - resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" - dependencies: - prelude-ls "~1.1.2" - - typedarray@^0.0.6: - version "0.0.6" - resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" - - uglify-js@^2.6: - version "2.8.29" - resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-2.8.29.tgz#29c5733148057bb4e1f75df35b7a9cb72e6a59dd" - dependencies: - source-map "~0.5.1" - yargs "~3.10.0" - optionalDependencies: - uglify-to-browserify "~1.0.0" - - uglify-to-browserify@~1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz#6e0924d6bda6b5afe349e39a6d632850a0f882b7" - - util-deprecate@~1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" - - uuid@^3.1.0: - version "3.2.1" - resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.2.1.tgz#12c528bb9d58d0b9265d9a2f6f0fe8be17ff1f14" - - verror@1.10.0: - version "1.10.0" - resolved "https://registry.yarnpkg.com/verror/-/verror-1.10.0.tgz#3a105ca17053af55d6e270c1f8288682e18da400" - dependencies: - assert-plus "^1.0.0" - core-util-is "1.0.2" - extsprintf "^1.2.0" - - which@^1.1.1, which@^1.2.9: - version "1.3.1" - resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" - dependencies: - isexe "^2.0.0" - - window-size@0.1.0: - version "0.1.0" - resolved "https://registry.yarnpkg.com/window-size/-/window-size-0.1.0.tgz#5438cd2ea93b202efa3a19fe8887aee7c94f9c9d" - - wordwrap@0.0.2: - version "0.0.2" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.2.tgz#b79669bb42ecb409f83d583cad52ca17eaa1643f" - - wordwrap@^1.0.0, wordwrap@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" - - wordwrap@~0.0.2: - version "0.0.3" - resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-0.0.3.tgz#a3d5da6cd5c0bc0008d37234bbaf1bed63059107" - - wrappy@1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" - - write@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/write/-/write-0.2.1.tgz#5fc03828e264cea3fe91455476f7a3c566cb0757" - dependencies: - mkdirp "^0.5.1" - - yallist@^2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.1.2.tgz#1c11f9218f076089a47dd512f93c6699a6a81d52" - - yargs@~3.10.0: - version "3.10.0" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-3.10.0.tgz#f7ee7bd857dd7c1d2d38c0e74efbd681d1431fd1" - dependencies: - camelcase "^1.0.2" - cliui "^2.1.0" - decamelize "^1.0.0" - window-size "0.1.0" - -Trace: - Error: Command failed. - Exit code: 1 - Command: sh - Arguments: -c mocha --require coffeescript/register - Directory: /src/qix-/node-is-arrayish - Output: - - at ProcessTermError.MessageError (/Users/junon/.yarn/lib/cli.js:186:110) - at new ProcessTermError (/Users/junon/.yarn/lib/cli.js:226:113) - at ChildProcess. (/Users/junon/.yarn/lib/cli.js:30281:17) - at ChildProcess.emit (events.js:127:13) - at maybeClose (internal/child_process.js:933:16) - at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5) diff --git a/node_modules/sharp/LICENSE b/node_modules/sharp/LICENSE deleted file mode 100644 index 37ec93a1..00000000 --- a/node_modules/sharp/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and -distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright -owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities -that control, are controlled by, or are under common control with that entity. -For the purposes of this definition, "control" means (i) the power, direct or -indirect, to cause the direction or management of such entity, whether by -contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the -outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising -permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including -but not limited to software source code, documentation source, and configuration -files. - -"Object" form shall mean any form resulting from mechanical transformation or -translation of a Source form, including but not limited to compiled object code, -generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made -available under the License, as indicated by a copyright notice that is included -in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that -is based on (or derived from) the Work and for which the editorial revisions, -annotations, elaborations, or other modifications represent, as a whole, an -original work of authorship. For the purposes of this License, Derivative Works -shall not include works that remain separable from, or merely link (or bind by -name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version -of the Work and any modifications or additions to that Work or Derivative Works -thereof, that is intentionally submitted to Licensor for inclusion in the Work -by the copyright owner or by an individual or Legal Entity authorized to submit -on behalf of the copyright owner. For the purposes of this definition, -"submitted" means any form of electronic, verbal, or written communication sent -to the Licensor or its representatives, including but not limited to -communication on electronic mailing lists, source code control systems, and -issue tracking systems that are managed by, or on behalf of, the Licensor for -the purpose of discussing and improving the Work, but excluding communication -that is conspicuously marked or otherwise designated in writing by the copyright -owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf -of whom a Contribution has been received by Licensor and subsequently -incorporated within the Work. - -2. Grant of Copyright License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable copyright license to reproduce, prepare Derivative Works of, -publicly display, publicly perform, sublicense, and distribute the Work and such -Derivative Works in Source or Object form. - -3. Grant of Patent License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable (except as stated in this section) patent license to make, have -made, use, offer to sell, sell, import, and otherwise transfer the Work, where -such license applies only to those patent claims licensable by such Contributor -that are necessarily infringed by their Contribution(s) alone or by combination -of their Contribution(s) with the Work to which such Contribution(s) was -submitted. If You institute patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Work or a -Contribution incorporated within the Work constitutes direct or contributory -patent infringement, then any patent licenses granted to You under this License -for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. - -You may reproduce and distribute copies of the Work or Derivative Works thereof -in any medium, with or without modifications, and in Source or Object form, -provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of -this License; and -You must cause any modified files to carry prominent notices stating that You -changed the files; and -You must retain, in the Source form of any Derivative Works that You distribute, -all copyright, patent, trademark, and attribution notices from the Source form -of the Work, excluding those notices that do not pertain to any part of the -Derivative Works; and -If the Work includes a "NOTICE" text file as part of its distribution, then any -Derivative Works that You distribute must include a readable copy of the -attribution notices contained within such NOTICE file, excluding those notices -that do not pertain to any part of the Derivative Works, in at least one of the -following places: within a NOTICE text file distributed as part of the -Derivative Works; within the Source form or documentation, if provided along -with the Derivative Works; or, within a display generated by the Derivative -Works, if and wherever such third-party notices normally appear. The contents of -the NOTICE file are for informational purposes only and do not modify the -License. You may add Your own attribution notices within Derivative Works that -You distribute, alongside or as an addendum to the NOTICE text from the Work, -provided that such additional attribution notices cannot be construed as -modifying the License. -You may add Your own copyright statement to Your modifications and may provide -additional or different license terms and conditions for use, reproduction, or -distribution of Your modifications, or for any such Derivative Works as a whole, -provided Your use, reproduction, and distribution of the Work otherwise complies -with the conditions stated in this License. - -5. Submission of Contributions. - -Unless You explicitly state otherwise, any Contribution intentionally submitted -for inclusion in the Work by You to the Licensor shall be under the terms and -conditions of this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify the terms of -any separate license agreement you may have executed with Licensor regarding -such Contributions. - -6. Trademarks. - -This License does not grant permission to use the trade names, trademarks, -service marks, or product names of the Licensor, except as required for -reasonable and customary use in describing the origin of the Work and -reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. - -Unless required by applicable law or agreed to in writing, Licensor provides the -Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, -including, without limitation, any warranties or conditions of TITLE, -NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are -solely responsible for determining the appropriateness of using or -redistributing the Work and assume any risks associated with Your exercise of -permissions under this License. - -8. Limitation of Liability. - -In no event and under no legal theory, whether in tort (including negligence), -contract, or otherwise, unless required by applicable law (such as deliberate -and grossly negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, incidental, -or consequential damages of any character arising as a result of this License or -out of the use or inability to use the Work (including but not limited to -damages for loss of goodwill, work stoppage, computer failure or malfunction, or -any and all other commercial damages or losses), even if such Contributor has -been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. - -While redistributing the Work or Derivative Works thereof, You may choose to -offer, and charge a fee for, acceptance of support, warranty, indemnity, or -other liability obligations and/or rights consistent with this License. However, -in accepting such obligations, You may act only on Your own behalf and on Your -sole responsibility, not on behalf of any other Contributor, and only if You -agree to indemnify, defend, and hold each Contributor harmless for any liability -incurred by, or claims asserted against, such Contributor by reason of your -accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work - -To apply the Apache License to your work, attach the following boilerplate -notice, with the fields enclosed by brackets "[]" replaced with your own -identifying information. (Don't include the brackets!) The text should be -enclosed in the appropriate comment syntax for the file format. We also -recommend that a file or class name and description of purpose be included on -the same "printed page" as the copyright notice for easier identification within -third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/node_modules/sharp/README.md b/node_modules/sharp/README.md deleted file mode 100644 index 1c52c0cd..00000000 --- a/node_modules/sharp/README.md +++ /dev/null @@ -1,118 +0,0 @@ -# sharp - -sharp logo - -The typical use case for this high speed Node-API module -is to convert large images in common formats to -smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions. - -It can be used with all JavaScript runtimes -that provide support for Node-API v9, including -Node.js (^18.17.0 or >= 20.3.0), Deno and Bun. - -Resizing an image is typically 4x-5x faster than using the -quickest ImageMagick and GraphicsMagick settings -due to its use of [libvips](https://github.com/libvips/libvips). - -Colour spaces, embedded ICC profiles and alpha transparency channels are all handled correctly. -Lanczos resampling ensures quality is not sacrificed for speed. - -As well as image resizing, operations such as -rotation, extraction, compositing and gamma correction are available. - -Most modern macOS, Windows and Linux systems -do not require any additional install or runtime dependencies. - -## Documentation - -Visit [sharp.pixelplumbing.com](https://sharp.pixelplumbing.com/) for complete -[installation instructions](https://sharp.pixelplumbing.com/install), -[API documentation](https://sharp.pixelplumbing.com/api-constructor), -[benchmark tests](https://sharp.pixelplumbing.com/performance) and -[changelog](https://sharp.pixelplumbing.com/changelog). - -## Examples - -```sh -npm install sharp -``` - -```javascript -const sharp = require('sharp'); -``` - -### Callback - -```javascript -sharp(inputBuffer) - .resize(320, 240) - .toFile('output.webp', (err, info) => { ... }); -``` - -### Promise - -```javascript -sharp('input.jpg') - .rotate() - .resize(200) - .jpeg({ mozjpeg: true }) - .toBuffer() - .then( data => { ... }) - .catch( err => { ... }); -``` - -### Async/await - -```javascript -const semiTransparentRedPng = await sharp({ - create: { - width: 48, - height: 48, - channels: 4, - background: { r: 255, g: 0, b: 0, alpha: 0.5 } - } -}) - .png() - .toBuffer(); -``` - -### Stream - -```javascript -const roundedCorners = Buffer.from( - '' -); - -const roundedCornerResizer = - sharp() - .resize(200, 200) - .composite([{ - input: roundedCorners, - blend: 'dest-in' - }]) - .png(); - -readableStream - .pipe(roundedCornerResizer) - .pipe(writableStream); -``` - -## Contributing - -A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md) -covers reporting bugs, requesting features and submitting code changes. - -## Licensing - -Copyright 2013 Lovell Fuller and others. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at -[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0) - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/node_modules/sharp/install/check.js b/node_modules/sharp/install/check.js deleted file mode 100644 index e23deaec..00000000 --- a/node_modules/sharp/install/check.js +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -try { - const { useGlobalLibvips, globalLibvipsVersion, log, spawnRebuild } = require('../lib/libvips'); - - const buildFromSource = (msg) => { - log(msg); - log('Attempting to build from source via node-gyp'); - try { - require('node-addon-api'); - log('Found node-addon-api'); - } catch (err) { - log('Please add node-addon-api to your dependencies'); - return; - } - try { - const gyp = require('node-gyp'); - log(`Found node-gyp version ${gyp().version}`); - } catch (err) { - log('Please add node-gyp to your dependencies'); - return; - } - log('See https://sharp.pixelplumbing.com/install#building-from-source'); - const status = spawnRebuild(); - if (status !== 0) { - process.exit(status); - } - }; - - if (useGlobalLibvips()) { - buildFromSource(`Detected globally-installed libvips v${globalLibvipsVersion()}`); - } else if (process.env.npm_config_build_from_source) { - buildFromSource('Detected --build-from-source flag'); - } -} catch (err) { - const summary = err.message.split(/\n/).slice(0, 1); - console.log(`sharp: skipping install check: ${summary}`); -} diff --git a/node_modules/sharp/lib/channel.js b/node_modules/sharp/lib/channel.js deleted file mode 100644 index 977ea386..00000000 --- a/node_modules/sharp/lib/channel.js +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const is = require('./is'); - -/** - * Boolean operations for bandbool. - * @private - */ -const bool = { - and: 'and', - or: 'or', - eor: 'eor' -}; - -/** - * Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel. - * - * See also {@link /api-operation#flatten|flatten}. - * - * @example - * sharp('rgba.png') - * .removeAlpha() - * .toFile('rgb.png', function(err, info) { - * // rgb.png is a 3 channel image without an alpha channel - * }); - * - * @returns {Sharp} - */ -function removeAlpha () { - this.options.removeAlpha = true; - return this; -} - -/** - * Ensure the output image has an alpha transparency channel. - * If missing, the added alpha channel will have the specified - * transparency level, defaulting to fully-opaque (1). - * This is a no-op if the image already has an alpha channel. - * - * @since 0.21.2 - * - * @example - * // rgba.png will be a 4 channel image with a fully-opaque alpha channel - * await sharp('rgb.jpg') - * .ensureAlpha() - * .toFile('rgba.png') - * - * @example - * // rgba is a 4 channel image with a fully-transparent alpha channel - * const rgba = await sharp(rgb) - * .ensureAlpha(0) - * .toBuffer(); - * - * @param {number} [alpha=1] - alpha transparency level (0=fully-transparent, 1=fully-opaque) - * @returns {Sharp} - * @throws {Error} Invalid alpha transparency level - */ -function ensureAlpha (alpha) { - if (is.defined(alpha)) { - if (is.number(alpha) && is.inRange(alpha, 0, 1)) { - this.options.ensureAlpha = alpha; - } else { - throw is.invalidParameterError('alpha', 'number between 0 and 1', alpha); - } - } else { - this.options.ensureAlpha = 1; - } - return this; -} - -/** - * Extract a single channel from a multi-channel image. - * - * @example - * // green.jpg is a greyscale image containing the green channel of the input - * await sharp(input) - * .extractChannel('green') - * .toFile('green.jpg'); - * - * @example - * // red1 is the red value of the first pixel, red2 the second pixel etc. - * const [red1, red2, ...] = await sharp(input) - * .extractChannel(0) - * .raw() - * .toBuffer(); - * - * @param {number|string} channel - zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`. - * @returns {Sharp} - * @throws {Error} Invalid channel - */ -function extractChannel (channel) { - const channelMap = { red: 0, green: 1, blue: 2, alpha: 3 }; - if (Object.keys(channelMap).includes(channel)) { - channel = channelMap[channel]; - } - if (is.integer(channel) && is.inRange(channel, 0, 4)) { - this.options.extractChannel = channel; - } else { - throw is.invalidParameterError('channel', 'integer or one of: red, green, blue, alpha', channel); - } - return this; -} - -/** - * Join one or more channels to the image. - * The meaning of the added channels depends on the output colourspace, set with `toColourspace()`. - * By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. - * Channel ordering follows vips convention: - * - sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha. - * - CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha. - * - * Buffers may be any of the image formats supported by sharp. - * For raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor. - * - * @param {Array|string|Buffer} images - one or more images (file paths, Buffers). - * @param {Object} options - image options, see `sharp()` constructor. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function joinChannel (images, options) { - if (Array.isArray(images)) { - images.forEach(function (image) { - this.options.joinChannelIn.push(this._createInputDescriptor(image, options)); - }, this); - } else { - this.options.joinChannelIn.push(this._createInputDescriptor(images, options)); - } - return this; -} - -/** - * Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image. - * - * @example - * sharp('3-channel-rgb-input.png') - * .bandbool(sharp.bool.and) - * .toFile('1-channel-output.png', function (err, info) { - * // The output will be a single channel image where each pixel `P = R & G & B`. - * // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]` - * // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`. - * }); - * - * @param {string} boolOp - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function bandbool (boolOp) { - if (is.string(boolOp) && is.inArray(boolOp, ['and', 'or', 'eor'])) { - this.options.bandBoolOp = boolOp; - } else { - throw is.invalidParameterError('boolOp', 'one of: and, or, eor', boolOp); - } - return this; -} - -/** - * Decorate the Sharp prototype with channel-related functions. - * @private - */ -module.exports = function (Sharp) { - Object.assign(Sharp.prototype, { - // Public instance functions - removeAlpha, - ensureAlpha, - extractChannel, - joinChannel, - bandbool - }); - // Class attributes - Sharp.bool = bool; -}; diff --git a/node_modules/sharp/lib/colour.js b/node_modules/sharp/lib/colour.js deleted file mode 100644 index 07b6e4f4..00000000 --- a/node_modules/sharp/lib/colour.js +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const color = require('color'); -const is = require('./is'); - -/** - * Colourspaces. - * @private - */ -const colourspace = { - multiband: 'multiband', - 'b-w': 'b-w', - bw: 'b-w', - cmyk: 'cmyk', - srgb: 'srgb' -}; - -/** - * Tint the image using the provided colour. - * An alpha channel may be present and will be unchanged by the operation. - * - * @example - * const output = await sharp(input) - * .tint({ r: 255, g: 240, b: 16 }) - * .toBuffer(); - * - * @param {string|Object} tint - Parsed by the [color](https://www.npmjs.org/package/color) module. - * @returns {Sharp} - * @throws {Error} Invalid parameter - */ -function tint (tint) { - this._setBackgroundColourOption('tint', tint); - return this; -} - -/** - * Convert to 8-bit greyscale; 256 shades of grey. - * This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results. - * By default the output image will be web-friendly sRGB and contain three (identical) color channels. - * This may be overridden by other sharp operations such as `toColourspace('b-w')`, - * which will produce an output image containing one color channel. - * An alpha channel may be present, and will be unchanged by the operation. - * - * @example - * const output = await sharp(input).greyscale().toBuffer(); - * - * @param {Boolean} [greyscale=true] - * @returns {Sharp} - */ -function greyscale (greyscale) { - this.options.greyscale = is.bool(greyscale) ? greyscale : true; - return this; -} - -/** - * Alternative spelling of `greyscale`. - * @param {Boolean} [grayscale=true] - * @returns {Sharp} - */ -function grayscale (grayscale) { - return this.greyscale(grayscale); -} - -/** - * Set the pipeline colourspace. - * - * The input image will be converted to the provided colourspace at the start of the pipeline. - * All operations will use this colourspace before converting to the output colourspace, - * as defined by {@link #tocolourspace|toColourspace}. - * - * This feature is experimental and has not yet been fully-tested with all operations. - * - * @since 0.29.0 - * - * @example - * // Run pipeline in 16 bits per channel RGB while converting final result to 8 bits per channel sRGB. - * await sharp(input) - * .pipelineColourspace('rgb16') - * .toColourspace('srgb') - * .toFile('16bpc-pipeline-to-8bpc-output.png') - * - * @param {string} [colourspace] - pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...](https://github.com/libvips/libvips/blob/41cff4e9d0838498487a00623462204eb10ee5b8/libvips/iofuncs/enumtypes.c#L774) - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function pipelineColourspace (colourspace) { - if (!is.string(colourspace)) { - throw is.invalidParameterError('colourspace', 'string', colourspace); - } - this.options.colourspacePipeline = colourspace; - return this; -} - -/** - * Alternative spelling of `pipelineColourspace`. - * @param {string} [colorspace] - pipeline colorspace. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function pipelineColorspace (colorspace) { - return this.pipelineColourspace(colorspace); -} - -/** - * Set the output colourspace. - * By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. - * - * @example - * // Output 16 bits per pixel RGB - * await sharp(input) - * .toColourspace('rgb16') - * .toFile('16-bpp.png') - * - * @param {string} [colourspace] - output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/3c0bfdf74ce1dc37a6429bed47fa76f16e2cd70a/libvips/iofuncs/enumtypes.c#L777-L794) - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function toColourspace (colourspace) { - if (!is.string(colourspace)) { - throw is.invalidParameterError('colourspace', 'string', colourspace); - } - this.options.colourspace = colourspace; - return this; -} - -/** - * Alternative spelling of `toColourspace`. - * @param {string} [colorspace] - output colorspace. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function toColorspace (colorspace) { - return this.toColourspace(colorspace); -} - -/** - * Update a colour attribute of the this.options Object. - * @private - * @param {string} key - * @param {string|Object} value - * @throws {Error} Invalid value - */ -function _setBackgroundColourOption (key, value) { - if (is.defined(value)) { - if (is.object(value) || is.string(value)) { - const colour = color(value); - this.options[key] = [ - colour.red(), - colour.green(), - colour.blue(), - Math.round(colour.alpha() * 255) - ]; - } else { - throw is.invalidParameterError('background', 'object or string', value); - } - } -} - -/** - * Decorate the Sharp prototype with colour-related functions. - * @private - */ -module.exports = function (Sharp) { - Object.assign(Sharp.prototype, { - // Public - tint, - greyscale, - grayscale, - pipelineColourspace, - pipelineColorspace, - toColourspace, - toColorspace, - // Private - _setBackgroundColourOption - }); - // Class attributes - Sharp.colourspace = colourspace; - Sharp.colorspace = colourspace; -}; diff --git a/node_modules/sharp/lib/composite.js b/node_modules/sharp/lib/composite.js deleted file mode 100644 index 28e83788..00000000 --- a/node_modules/sharp/lib/composite.js +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const is = require('./is'); - -/** - * Blend modes. - * @member - * @private - */ -const blend = { - clear: 'clear', - source: 'source', - over: 'over', - in: 'in', - out: 'out', - atop: 'atop', - dest: 'dest', - 'dest-over': 'dest-over', - 'dest-in': 'dest-in', - 'dest-out': 'dest-out', - 'dest-atop': 'dest-atop', - xor: 'xor', - add: 'add', - saturate: 'saturate', - multiply: 'multiply', - screen: 'screen', - overlay: 'overlay', - darken: 'darken', - lighten: 'lighten', - 'colour-dodge': 'colour-dodge', - 'color-dodge': 'colour-dodge', - 'colour-burn': 'colour-burn', - 'color-burn': 'colour-burn', - 'hard-light': 'hard-light', - 'soft-light': 'soft-light', - difference: 'difference', - exclusion: 'exclusion' -}; - -/** - * Composite image(s) over the processed (resized, extracted etc.) image. - * - * The images to composite must be the same size or smaller than the processed image. - * If both `top` and `left` options are provided, they take precedence over `gravity`. - * - * Any resize, rotate or extract operations in the same processing pipeline - * will always be applied to the input image before composition. - * - * The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`, - * `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`, - * `xor`, `add`, `saturate`, `multiply`, `screen`, `overlay`, `darken`, `lighten`, - * `colour-dodge`, `color-dodge`, `colour-burn`,`color-burn`, - * `hard-light`, `soft-light`, `difference`, `exclusion`. - * - * More information about blend modes can be found at - * https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode - * and https://www.cairographics.org/operators/ - * - * @since 0.22.0 - * - * @example - * await sharp(background) - * .composite([ - * { input: layer1, gravity: 'northwest' }, - * { input: layer2, gravity: 'southeast' }, - * ]) - * .toFile('combined.png'); - * - * @example - * const output = await sharp('input.gif', { animated: true }) - * .composite([ - * { input: 'overlay.png', tile: true, blend: 'saturate' } - * ]) - * .toBuffer(); - * - * @example - * sharp('input.png') - * .rotate(180) - * .resize(300) - * .flatten( { background: '#ff6600' } ) - * .composite([{ input: 'overlay.png', gravity: 'southeast' }]) - * .sharpen() - * .withMetadata() - * .webp( { quality: 90 } ) - * .toBuffer() - * .then(function(outputBuffer) { - * // outputBuffer contains upside down, 300px wide, alpha channel flattened - * // onto orange background, composited with overlay.png with SE gravity, - * // sharpened, with metadata, 90% quality WebP image data. Phew! - * }); - * - * @param {Object[]} images - Ordered list of images to composite - * @param {Buffer|String} [images[].input] - Buffer containing image data, String containing the path to an image file, or Create object (see below) - * @param {Object} [images[].input.create] - describes a blank overlay to be created. - * @param {Number} [images[].input.create.width] - * @param {Number} [images[].input.create.height] - * @param {Number} [images[].input.create.channels] - 3-4 - * @param {String|Object} [images[].input.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. - * @param {Object} [images[].input.text] - describes a new text image to be created. - * @param {string} [images[].input.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. - * @param {string} [images[].input.text.font] - font name to render with. - * @param {string} [images[].input.text.fontfile] - absolute filesystem path to a font file that can be used by `font`. - * @param {number} [images[].input.text.width=0] - integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. - * @param {number} [images[].input.text.height=0] - integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. - * @param {string} [images[].input.text.align='left'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). - * @param {boolean} [images[].input.text.justify=false] - set this to true to apply justification to the text. - * @param {number} [images[].input.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified. - * @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `Red!`. - * @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified. - * @param {String} [images[].blend='over'] - how to blend this image with the image below. - * @param {String} [images[].gravity='centre'] - gravity at which to place the overlay. - * @param {Number} [images[].top] - the pixel offset from the top edge. - * @param {Number} [images[].left] - the pixel offset from the left edge. - * @param {Boolean} [images[].tile=false] - set to true to repeat the overlay image across the entire image with the given `gravity`. - * @param {Boolean} [images[].premultiplied=false] - set to true to avoid premultiplying the image below. Equivalent to the `--premultiplied` vips option. - * @param {Number} [images[].density=72] - number representing the DPI for vector overlay image. - * @param {Object} [images[].raw] - describes overlay when using raw pixel data. - * @param {Number} [images[].raw.width] - * @param {Number} [images[].raw.height] - * @param {Number} [images[].raw.channels] - * @param {boolean} [images[].animated=false] - Set to `true` to read all frames/pages of an animated image. - * @param {string} [images[].failOn='warning'] - @see {@link /api-constructor#parameters|constructor parameters} - * @param {number|boolean} [images[].limitInputPixels=268402689] - @see {@link /api-constructor#parameters|constructor parameters} - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function composite (images) { - if (!Array.isArray(images)) { - throw is.invalidParameterError('images to composite', 'array', images); - } - this.options.composite = images.map(image => { - if (!is.object(image)) { - throw is.invalidParameterError('image to composite', 'object', image); - } - const inputOptions = this._inputOptionsFromObject(image); - const composite = { - input: this._createInputDescriptor(image.input, inputOptions, { allowStream: false }), - blend: 'over', - tile: false, - left: 0, - top: 0, - hasOffset: false, - gravity: 0, - premultiplied: false - }; - if (is.defined(image.blend)) { - if (is.string(blend[image.blend])) { - composite.blend = blend[image.blend]; - } else { - throw is.invalidParameterError('blend', 'valid blend name', image.blend); - } - } - if (is.defined(image.tile)) { - if (is.bool(image.tile)) { - composite.tile = image.tile; - } else { - throw is.invalidParameterError('tile', 'boolean', image.tile); - } - } - if (is.defined(image.left)) { - if (is.integer(image.left)) { - composite.left = image.left; - } else { - throw is.invalidParameterError('left', 'integer', image.left); - } - } - if (is.defined(image.top)) { - if (is.integer(image.top)) { - composite.top = image.top; - } else { - throw is.invalidParameterError('top', 'integer', image.top); - } - } - if (is.defined(image.top) !== is.defined(image.left)) { - throw new Error('Expected both left and top to be set'); - } else { - composite.hasOffset = is.integer(image.top) && is.integer(image.left); - } - if (is.defined(image.gravity)) { - if (is.integer(image.gravity) && is.inRange(image.gravity, 0, 8)) { - composite.gravity = image.gravity; - } else if (is.string(image.gravity) && is.integer(this.constructor.gravity[image.gravity])) { - composite.gravity = this.constructor.gravity[image.gravity]; - } else { - throw is.invalidParameterError('gravity', 'valid gravity', image.gravity); - } - } - if (is.defined(image.premultiplied)) { - if (is.bool(image.premultiplied)) { - composite.premultiplied = image.premultiplied; - } else { - throw is.invalidParameterError('premultiplied', 'boolean', image.premultiplied); - } - } - return composite; - }); - return this; -} - -/** - * Decorate the Sharp prototype with composite-related functions. - * @private - */ -module.exports = function (Sharp) { - Sharp.prototype.composite = composite; - Sharp.blend = blend; -}; diff --git a/node_modules/sharp/lib/constructor.js b/node_modules/sharp/lib/constructor.js deleted file mode 100644 index f6741509..00000000 --- a/node_modules/sharp/lib/constructor.js +++ /dev/null @@ -1,450 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const util = require('node:util'); -const stream = require('node:stream'); -const is = require('./is'); - -require('./sharp'); - -// Use NODE_DEBUG=sharp to enable libvips warnings -const debuglog = util.debuglog('sharp'); - -/** - * Constructor factory to create an instance of `sharp`, to which further methods are chained. - * - * JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object. - * When using Stream based output, derived attributes are available from the `info` event. - * - * Non-critical problems encountered during processing are emitted as `warning` events. - * - * Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class. - * - * When loading more than one page/frame of an animated image, - * these are combined as a vertically-stacked "toilet roll" image - * where the overall height is the `pageHeight` multiplied by the number of `pages`. - * - * @constructs Sharp - * - * @emits Sharp#info - * @emits Sharp#warning - * - * @example - * sharp('input.jpg') - * .resize(300, 200) - * .toFile('output.jpg', function(err) { - * // output.jpg is a 300 pixels wide and 200 pixels high image - * // containing a scaled and cropped version of input.jpg - * }); - * - * @example - * // Read image data from remote URL, - * // resize to 300 pixels wide, - * // emit an 'info' event with calculated dimensions - * // and finally write image data to writableStream - * const { body } = fetch('https://...'); - * const readableStream = Readable.fromWeb(body); - * const transformer = sharp() - * .resize(300) - * .on('info', ({ height }) => { - * console.log(`Image height is ${height}`); - * }); - * readableStream.pipe(transformer).pipe(writableStream); - * - * @example - * // Create a blank 300x200 PNG image of semi-translucent red pixels - * sharp({ - * create: { - * width: 300, - * height: 200, - * channels: 4, - * background: { r: 255, g: 0, b: 0, alpha: 0.5 } - * } - * }) - * .png() - * .toBuffer() - * .then( ... ); - * - * @example - * // Convert an animated GIF to an animated WebP - * await sharp('in.gif', { animated: true }).toFile('out.webp'); - * - * @example - * // Read a raw array of pixels and save it to a png - * const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray - * const image = sharp(input, { - * // because the input does not contain its dimensions or how many channels it has - * // we need to specify it in the constructor options - * raw: { - * width: 2, - * height: 1, - * channels: 3 - * } - * }); - * await image.toFile('my-two-pixels.png'); - * - * @example - * // Generate RGB Gaussian noise - * await sharp({ - * create: { - * width: 300, - * height: 200, - * channels: 3, - * noise: { - * type: 'gaussian', - * mean: 128, - * sigma: 30 - * } - * } - * }).toFile('noise.png'); - * - * @example - * // Generate an image from text - * await sharp({ - * text: { - * text: 'Hello, world!', - * width: 400, // max width - * height: 300 // max height - * } - * }).toFile('text_bw.png'); - * - * @example - * // Generate an rgba image from text using pango markup and font - * await sharp({ - * text: { - * text: 'Red!blue', - * font: 'sans', - * rgba: true, - * dpi: 300 - * } - * }).toFile('text_rgba.png'); - * - * @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string)} [input] - if present, can be - * a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or - * a TypedArray containing raw pixel image data, or - * a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. - * JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. - * @param {Object} [options] - if present, is an Object with optional attributes. - * @param {string} [options.failOn='warning'] - When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort. - * @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels - * (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted. - * An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). - * @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). - * @param {boolean} [options.sequentialRead=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically. - * @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000. - * @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored. - * @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages. - * @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based. - * @param {number} [options.subifd=-1] - subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. - * @param {number} [options.level=0] - level to extract from a multi-level input (OpenSlide), zero based. - * @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`. - * @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering. - * @param {number} [options.raw.width] - integral number of pixels wide. - * @param {number} [options.raw.height] - integral number of pixels high. - * @param {number} [options.raw.channels] - integral number of channels, between 1 and 4. - * @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true` - * to avoid sharp premultiplying the image. (optional, default `false`) - * @param {Object} [options.create] - describes a new image to be created. - * @param {number} [options.create.width] - integral number of pixels wide. - * @param {number} [options.create.height] - integral number of pixels high. - * @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA). - * @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. - * @param {Object} [options.create.noise] - describes a noise to be created. - * @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported. - * @param {number} [options.create.noise.mean] - mean of pixels in generated noise. - * @param {number} [options.create.noise.sigma] - standard deviation of pixels in generated noise. - * @param {Object} [options.text] - describes a new text image to be created. - * @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. - * @param {string} [options.text.font] - font name to render with. - * @param {string} [options.text.fontfile] - absolute filesystem path to a font file that can be used by `font`. - * @param {number} [options.text.width=0] - Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. - * @param {number} [options.text.height=0] - Maximum integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. - * @param {string} [options.text.align='left'] - Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`). - * @param {boolean} [options.text.justify=false] - set this to true to apply justification to the text. - * @param {number} [options.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified. - * @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `Red!`. - * @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified. - * @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -const Sharp = function (input, options) { - if (arguments.length === 1 && !is.defined(input)) { - throw new Error('Invalid input'); - } - if (!(this instanceof Sharp)) { - return new Sharp(input, options); - } - stream.Duplex.call(this); - this.options = { - // resize options - topOffsetPre: -1, - leftOffsetPre: -1, - widthPre: -1, - heightPre: -1, - topOffsetPost: -1, - leftOffsetPost: -1, - widthPost: -1, - heightPost: -1, - width: -1, - height: -1, - canvas: 'crop', - position: 0, - resizeBackground: [0, 0, 0, 255], - useExifOrientation: false, - angle: 0, - rotationAngle: 0, - rotationBackground: [0, 0, 0, 255], - rotateBeforePreExtract: false, - flip: false, - flop: false, - extendTop: 0, - extendBottom: 0, - extendLeft: 0, - extendRight: 0, - extendBackground: [0, 0, 0, 255], - extendWith: 'background', - withoutEnlargement: false, - withoutReduction: false, - affineMatrix: [], - affineBackground: [0, 0, 0, 255], - affineIdx: 0, - affineIdy: 0, - affineOdx: 0, - affineOdy: 0, - affineInterpolator: this.constructor.interpolators.bilinear, - kernel: 'lanczos3', - fastShrinkOnLoad: true, - // operations - tint: [-1, 0, 0, 0], - flatten: false, - flattenBackground: [0, 0, 0], - unflatten: false, - negate: false, - negateAlpha: true, - medianSize: 0, - blurSigma: 0, - sharpenSigma: 0, - sharpenM1: 1, - sharpenM2: 2, - sharpenX1: 2, - sharpenY2: 10, - sharpenY3: 20, - threshold: 0, - thresholdGrayscale: true, - trimBackground: [], - trimThreshold: -1, - trimLineArt: false, - gamma: 0, - gammaOut: 0, - greyscale: false, - normalise: false, - normaliseLower: 1, - normaliseUpper: 99, - claheWidth: 0, - claheHeight: 0, - claheMaxSlope: 3, - brightness: 1, - saturation: 1, - hue: 0, - lightness: 0, - booleanBufferIn: null, - booleanFileIn: '', - joinChannelIn: [], - extractChannel: -1, - removeAlpha: false, - ensureAlpha: -1, - colourspace: 'srgb', - colourspacePipeline: 'last', - composite: [], - // output - fileOut: '', - formatOut: 'input', - streamOut: false, - keepMetadata: 0, - withMetadataOrientation: -1, - withMetadataDensity: 0, - withIccProfile: '', - withExif: {}, - withExifMerge: true, - resolveWithObject: false, - // output format - jpegQuality: 80, - jpegProgressive: false, - jpegChromaSubsampling: '4:2:0', - jpegTrellisQuantisation: false, - jpegOvershootDeringing: false, - jpegOptimiseScans: false, - jpegOptimiseCoding: true, - jpegQuantisationTable: 0, - pngProgressive: false, - pngCompressionLevel: 6, - pngAdaptiveFiltering: false, - pngPalette: false, - pngQuality: 100, - pngEffort: 7, - pngBitdepth: 8, - pngDither: 1, - jp2Quality: 80, - jp2TileHeight: 512, - jp2TileWidth: 512, - jp2Lossless: false, - jp2ChromaSubsampling: '4:4:4', - webpQuality: 80, - webpAlphaQuality: 100, - webpLossless: false, - webpNearLossless: false, - webpSmartSubsample: false, - webpPreset: 'default', - webpEffort: 4, - webpMinSize: false, - webpMixed: false, - gifBitdepth: 8, - gifEffort: 7, - gifDither: 1, - gifInterFrameMaxError: 0, - gifInterPaletteMaxError: 3, - gifReuse: true, - gifProgressive: false, - tiffQuality: 80, - tiffCompression: 'jpeg', - tiffPredictor: 'horizontal', - tiffPyramid: false, - tiffMiniswhite: false, - tiffBitdepth: 8, - tiffTile: false, - tiffTileHeight: 256, - tiffTileWidth: 256, - tiffXres: 1.0, - tiffYres: 1.0, - tiffResolutionUnit: 'inch', - heifQuality: 50, - heifLossless: false, - heifCompression: 'av1', - heifEffort: 4, - heifChromaSubsampling: '4:4:4', - heifBitdepth: 8, - jxlDistance: 1, - jxlDecodingTier: 0, - jxlEffort: 7, - jxlLossless: false, - rawDepth: 'uchar', - tileSize: 256, - tileOverlap: 0, - tileContainer: 'fs', - tileLayout: 'dz', - tileFormat: 'last', - tileDepth: 'last', - tileAngle: 0, - tileSkipBlanks: -1, - tileBackground: [255, 255, 255, 255], - tileCentre: false, - tileId: 'https://example.com/iiif', - tileBasename: '', - timeoutSeconds: 0, - linearA: [], - linearB: [], - // Function to notify of libvips warnings - debuglog: warning => { - this.emit('warning', warning); - debuglog(warning); - }, - // Function to notify of queue length changes - queueListener: function (queueLength) { - Sharp.queue.emit('change', queueLength); - } - }; - this.options.input = this._createInputDescriptor(input, options, { allowStream: true }); - return this; -}; -Object.setPrototypeOf(Sharp.prototype, stream.Duplex.prototype); -Object.setPrototypeOf(Sharp, stream.Duplex); - -/** - * Take a "snapshot" of the Sharp instance, returning a new instance. - * Cloned instances inherit the input of their parent instance. - * This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream. - * - * @example - * const pipeline = sharp().rotate(); - * pipeline.clone().resize(800, 600).pipe(firstWritableStream); - * pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream); - * readableStream.pipe(pipeline); - * // firstWritableStream receives auto-rotated, resized readableStream - * // secondWritableStream receives auto-rotated, extracted region of readableStream - * - * @example - * // Create a pipeline that will download an image, resize it and format it to different files - * // Using Promises to know when the pipeline is complete - * const fs = require("fs"); - * const got = require("got"); - * const sharpStream = sharp({ failOn: 'none' }); - * - * const promises = []; - * - * promises.push( - * sharpStream - * .clone() - * .jpeg({ quality: 100 }) - * .toFile("originalFile.jpg") - * ); - * - * promises.push( - * sharpStream - * .clone() - * .resize({ width: 500 }) - * .jpeg({ quality: 80 }) - * .toFile("optimized-500.jpg") - * ); - * - * promises.push( - * sharpStream - * .clone() - * .resize({ width: 500 }) - * .webp({ quality: 80 }) - * .toFile("optimized-500.webp") - * ); - * - * // https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md - * got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream); - * - * Promise.all(promises) - * .then(res => { console.log("Done!", res); }) - * .catch(err => { - * console.error("Error processing files, let's clean it up", err); - * try { - * fs.unlinkSync("originalFile.jpg"); - * fs.unlinkSync("optimized-500.jpg"); - * fs.unlinkSync("optimized-500.webp"); - * } catch (e) {} - * }); - * - * @returns {Sharp} - */ -function clone () { - // Clone existing options - const clone = this.constructor.call(); - const { debuglog, queueListener, ...options } = this.options; - clone.options = structuredClone(options); - clone.options.debuglog = debuglog; - clone.options.queueListener = queueListener; - // Pass 'finish' event to clone for Stream-based input - if (this._isStreamInput()) { - this.on('finish', () => { - // Clone inherits input data - this._flattenBufferIn(); - clone.options.input.buffer = this.options.input.buffer; - clone.emit('finish'); - }); - } - return clone; -} -Object.assign(Sharp.prototype, { clone }); - -/** - * Export constructor. - * @private - */ -module.exports = Sharp; diff --git a/node_modules/sharp/lib/index.d.ts b/node_modules/sharp/lib/index.d.ts deleted file mode 100644 index c31ccdfc..00000000 --- a/node_modules/sharp/lib/index.d.ts +++ /dev/null @@ -1,1727 +0,0 @@ -/** - * Copyright 2017 François Nguyen and others. - * - * Billy Kwok - * Bradley Odell - * Espen Hovlandsdal - * Floris de Bijl - * François Nguyen - * Jamie Woodbury - * Wooseop Kim - * - * 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. - */ - -// SPDX-License-Identifier: MIT - -/// - -import { Duplex } from 'stream'; - -//#region Constructor functions - -/** - * Creates a sharp instance from an image - * @param input Buffer containing JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data, or String containing the path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. - * @param options Object with optional attributes. - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ -declare function sharp(options?: sharp.SharpOptions): sharp.Sharp; -declare function sharp( - input?: - | Buffer - | ArrayBuffer - | Uint8Array - | Uint8ClampedArray - | Int8Array - | Uint16Array - | Int16Array - | Uint32Array - | Int32Array - | Float32Array - | Float64Array - | string, - options?: sharp.SharpOptions, -): sharp.Sharp; - -declare namespace sharp { - /** Object containing nested boolean values representing the available input and output formats/methods. */ - const format: FormatEnum; - - /** An Object containing the version numbers of sharp, libvips and its dependencies. */ - const versions: { - vips: string; - cairo?: string | undefined; - croco?: string | undefined; - exif?: string | undefined; - expat?: string | undefined; - ffi?: string | undefined; - fontconfig?: string | undefined; - freetype?: string | undefined; - gdkpixbuf?: string | undefined; - gif?: string | undefined; - glib?: string | undefined; - gsf?: string | undefined; - harfbuzz?: string | undefined; - jpeg?: string | undefined; - lcms?: string | undefined; - orc?: string | undefined; - pango?: string | undefined; - pixman?: string | undefined; - png?: string | undefined; - sharp?: string | undefined; - svg?: string | undefined; - tiff?: string | undefined; - webp?: string | undefined; - avif?: string | undefined; - heif?: string | undefined; - xml?: string | undefined; - zlib?: string | undefined; - }; - - /** An Object containing the available interpolators and their proper values */ - const interpolators: Interpolators; - - /** An EventEmitter that emits a change event when a task is either queued, waiting for libuv to provide a worker thread, complete */ - const queue: NodeJS.EventEmitter; - - //#endregion - - //#region Utility functions - - /** - * Gets or, when options are provided, sets the limits of libvips' operation cache. - * Existing entries in the cache will be trimmed after any change in limits. - * This method always returns cache statistics, useful for determining how much working memory is required for a particular task. - * @param options Object with the following attributes, or Boolean where true uses default cache settings and false removes all caching (optional, default true) - * @returns The cache results. - */ - function cache(options?: boolean | CacheOptions): CacheResult; - - /** - * Gets or sets the number of threads libvips' should create to process each image. - * The default value is the number of CPU cores. A value of 0 will reset to this default. - * The maximum number of images that can be processed in parallel is limited by libuv's UV_THREADPOOL_SIZE environment variable. - * @param concurrency The new concurrency value. - * @returns The current concurrency value. - */ - function concurrency(concurrency?: number): number; - - /** - * Provides access to internal task counters. - * @returns Object containing task counters - */ - function counters(): SharpCounters; - - /** - * Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with highway support. - * Improves the performance of resize, blur and sharpen operations by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON. - * @param enable enable or disable use of SIMD vector unit instructions - * @returns true if usage of SIMD vector unit instructions is enabled - */ - function simd(enable?: boolean): boolean; - - /** - * Block libvips operations at runtime. - * - * This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable, - * which when set will block all "untrusted" operations. - * - * @since 0.32.4 - * - * @example Block all TIFF input. - * sharp.block({ - * operation: ['VipsForeignLoadTiff'] - * }); - * - * @param {Object} options - * @param {Array} options.operation - List of libvips low-level operation names to block. - */ - function block(options: { operation: string[] }): void; - - /** - * Unblock libvips operations at runtime. - * - * This is useful for defining a list of allowed operations. - * - * @since 0.32.4 - * - * @example Block all input except WebP from the filesystem. - * sharp.block({ - * operation: ['VipsForeignLoad'] - * }); - * sharp.unblock({ - * operation: ['VipsForeignLoadWebpFile'] - * }); - * - * @example Block all input except JPEG and PNG from a Buffer or Stream. - * sharp.block({ - * operation: ['VipsForeignLoad'] - * }); - * sharp.unblock({ - * operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer'] - * }); - * - * @param {Object} options - * @param {Array} options.operation - List of libvips low-level operation names to unblock. - */ - function unblock(options: { operation: string[] }): void; - - //#endregion - - const gravity: GravityEnum; - const strategy: StrategyEnum; - const kernel: KernelEnum; - const fit: FitEnum; - const bool: BoolEnum; - - interface Sharp extends Duplex { - //#region Channel functions - - /** - * Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel. - * @returns A sharp instance that can be used to chain operations - */ - removeAlpha(): Sharp; - - /** - * Ensure alpha channel, if missing. The added alpha channel will be fully opaque. This is a no-op if the image already has an alpha channel. - * @param alpha transparency level (0=fully-transparent, 1=fully-opaque) (optional, default 1). - * @returns A sharp instance that can be used to chain operations - */ - ensureAlpha(alpha?: number): Sharp; - - /** - * Extract a single channel from a multi-channel image. - * @param channel zero-indexed channel/band number to extract, or red, green, blue or alpha. - * @throws {Error} Invalid channel - * @returns A sharp instance that can be used to chain operations - */ - extractChannel(channel: 0 | 1 | 2 | 3 | 'red' | 'green' | 'blue' | 'alpha'): Sharp; - - /** - * Join one or more channels to the image. The meaning of the added channels depends on the output colourspace, set with toColourspace(). - * By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. Channel ordering follows vips convention: - * - sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha. - * - CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha. - * - * Buffers may be any of the image formats supported by sharp. - * For raw pixel input, the options object should contain a raw attribute, which follows the format of the attribute of the same name in the sharp() constructor. - * @param images one or more images (file paths, Buffers). - * @param options image options, see sharp() constructor. - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - joinChannel(images: string | Buffer | ArrayLike, options?: SharpOptions): Sharp; - - /** - * Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image. - * @param boolOp one of "and", "or" or "eor" to perform that bitwise operation, like the C logic operators &, | and ^ respectively. - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - bandbool(boolOp: keyof BoolEnum): Sharp; - - //#endregion - - //#region Color functions - - /** - * Tint the image using the provided colour. - * An alpha channel may be present and will be unchanged by the operation. - * @param tint Parsed by the color module. - * @returns A sharp instance that can be used to chain operations - */ - tint(tint: Color): Sharp; - - /** - * Convert to 8-bit greyscale; 256 shades of grey. - * This is a linear operation. - * If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results. - * By default the output image will be web-friendly sRGB and contain three (identical) color channels. - * This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one color channel. - * An alpha channel may be present, and will be unchanged by the operation. - * @param greyscale true to enable and false to disable (defaults to true) - * @returns A sharp instance that can be used to chain operations - */ - greyscale(greyscale?: boolean): Sharp; - - /** - * Alternative spelling of greyscale(). - * @param grayscale true to enable and false to disable (defaults to true) - * @returns A sharp instance that can be used to chain operations - */ - grayscale(grayscale?: boolean): Sharp; - - /** - * Set the pipeline colourspace. - * The input image will be converted to the provided colourspace at the start of the pipeline. - * All operations will use this colourspace before converting to the output colourspace, as defined by toColourspace. - * This feature is experimental and has not yet been fully-tested with all operations. - * - * @param colourspace pipeline colourspace e.g. rgb16, scrgb, lab, grey16 ... - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - pipelineColourspace(colourspace?: string): Sharp; - - /** - * Alternative spelling of pipelineColourspace - * @param colorspace pipeline colourspace e.g. rgb16, scrgb, lab, grey16 ... - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - pipelineColorspace(colorspace?: string): Sharp; - - /** - * Set the output colourspace. - * By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. - * @param colourspace output colourspace e.g. srgb, rgb, cmyk, lab, b-w ... - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - toColourspace(colourspace?: string): Sharp; - - /** - * Alternative spelling of toColourspace(). - * @param colorspace output colorspace e.g. srgb, rgb, cmyk, lab, b-w ... - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - toColorspace(colorspace: string): Sharp; - - //#endregion - - //#region Composite functions - - /** - * Composite image(s) over the processed (resized, extracted etc.) image. - * - * The images to composite must be the same size or smaller than the processed image. - * If both `top` and `left` options are provided, they take precedence over `gravity`. - * @param images - Ordered list of images to composite - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - composite(images: OverlayOptions[]): Sharp; - - //#endregion - - //#region Input functions - - /** - * Take a "snapshot" of the Sharp instance, returning a new instance. - * Cloned instances inherit the input of their parent instance. - * This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream. - * @returns A sharp instance that can be used to chain operations - */ - clone(): Sharp; - - /** - * Fast access to (uncached) image metadata without decoding any compressed image data. - * @returns A sharp instance that can be used to chain operations - */ - metadata(callback: (err: Error, metadata: Metadata) => void): Sharp; - - /** - * Fast access to (uncached) image metadata without decoding any compressed image data. - * @returns A promise that resolves with a metadata object - */ - metadata(): Promise; - - /** - * Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image. - * @returns A sharp instance that can be used to chain operations - */ - keepMetadata(): Sharp; - - /** - * Access to pixel-derived image statistics for every channel in the image. - * @returns A sharp instance that can be used to chain operations - */ - stats(callback: (err: Error, stats: Stats) => void): Sharp; - - /** - * Access to pixel-derived image statistics for every channel in the image. - * @returns A promise that resolves with a stats object - */ - stats(): Promise; - - //#endregion - - //#region Operation functions - - /** - * Rotate the output image by either an explicit angle or auto-orient based on the EXIF Orientation tag. - * - * If an angle is provided, it is converted to a valid positive degree rotation. For example, -450 will produce a 270deg rotation. - * - * When rotating by an angle other than a multiple of 90, the background colour can be provided with the background option. - * - * If no angle is provided, it is determined from the EXIF data. Mirroring is supported and may infer the use of a flip operation. - * - * The use of rotate implies the removal of the EXIF Orientation tag, if any. - * - * Method order is important when both rotating and extracting regions, for example rotate(x).extract(y) will produce a different result to extract(y).rotate(x). - * @param angle angle of rotation. (optional, default auto) - * @param options if present, is an Object with optional attributes. - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - rotate(angle?: number, options?: RotateOptions): Sharp; - - /** - * Flip the image about the vertical Y axis. This always occurs after rotation, if any. - * The use of flip implies the removal of the EXIF Orientation tag, if any. - * @param flip true to enable and false to disable (defaults to true) - * @returns A sharp instance that can be used to chain operations - */ - flip(flip?: boolean): Sharp; - - /** - * Flop the image about the horizontal X axis. This always occurs after rotation, if any. - * The use of flop implies the removal of the EXIF Orientation tag, if any. - * @param flop true to enable and false to disable (defaults to true) - * @returns A sharp instance that can be used to chain operations - */ - flop(flop?: boolean): Sharp; - - /** - * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any. - * You must provide an array of length 4 or a 2x2 affine transformation matrix. - * By default, new pixels are filled with a black background. You can provide a background color with the `background` option. - * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`. - * - * In the case of a 2x2 matrix, the transform is: - * X = matrix[0, 0] * (x + idx) + matrix[0, 1] * (y + idy) + odx - * Y = matrix[1, 0] * (x + idx) + matrix[1, 1] * (y + idy) + ody - * - * where: - * - * x and y are the coordinates in input image. - * X and Y are the coordinates in output image. - * (0,0) is the upper left corner. - * - * @param matrix Affine transformation matrix, may either by a array of length four or a 2x2 matrix array - * @param options if present, is an Object with optional attributes. - * - * @returns A sharp instance that can be used to chain operations - */ - affine(matrix: [number, number, number, number] | Matrix2x2, options?: AffineOptions): Sharp; - - /** - * Sharpen the image. - * When used without parameters, performs a fast, mild sharpen of the output image. - * When a sigma is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. - * Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available. - * @param options if present, is an Object with optional attributes - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - sharpen(options?: SharpenOptions): Sharp; - - /** - * Sharpen the image. - * When used without parameters, performs a fast, mild sharpen of the output image. - * When a sigma is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. - * Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available. - * @param sigma the sigma of the Gaussian mask, where sigma = 1 + radius / 2. - * @param flat the level of sharpening to apply to "flat" areas. (optional, default 1.0) - * @param jagged the level of sharpening to apply to "jagged" areas. (optional, default 2.0) - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - * - * @deprecated Use the object parameter `sharpen({sigma, m1, m2, x1, y2, y3})` instead - */ - sharpen(sigma?: number, flat?: number, jagged?: number): Sharp; - - /** - * Apply median filter. When used without parameters the default window is 3x3. - * @param size square mask size: size x size (optional, default 3) - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - median(size?: number): Sharp; - - /** - * Blur the image. - * When used without parameters, performs a fast, mild blur of the output image. - * When a sigma is provided, performs a slower, more accurate Gaussian blur. - * When a boolean sigma is provided, ether blur mild or disable blur - * @param sigma a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where sigma = 1 + radius / 2. - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - blur(sigma?: number | boolean): Sharp; - - /** - * Merge alpha transparency channel, if any, with background. - * @param flatten true to enable and false to disable (defaults to true) - * @returns A sharp instance that can be used to chain operations - */ - flatten(flatten?: boolean | FlattenOptions): Sharp; - - /** - * Ensure the image has an alpha channel with all white pixel values made fully transparent. - * Existing alpha channel values for non-white pixels remain unchanged. - * @returns A sharp instance that can be used to chain operations - */ - unflatten(): Sharp; - - /** - * Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of 1/gamma then increasing the encoding (brighten) post-resize at a factor of gamma. - * This can improve the perceived brightness of a resized image in non-linear colour spaces. - * JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation when applying a gamma correction. - * Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases. - * @param gamma value between 1.0 and 3.0. (optional, default 2.2) - * @param gammaOut value between 1.0 and 3.0. (optional, defaults to same as gamma) - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - gamma(gamma?: number, gammaOut?: number): Sharp; - - /** - * Produce the "negative" of the image. - * @param negate true to enable and false to disable, or an object of options (defaults to true) - * @returns A sharp instance that can be used to chain operations - */ - negate(negate?: boolean | NegateOptions): Sharp; - - /** - * Enhance output image contrast by stretching its luminance to cover a full dynamic range. - * - * Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes. - * - * Luminance values below the `lower` percentile will be underexposed by clipping to zero. - * Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value. - * - * @param normalise options - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - normalise(normalise?: NormaliseOptions): Sharp; - - /** - * Alternative spelling of normalise. - * @param normalize options - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - normalize(normalize?: NormaliseOptions): Sharp; - - /** - * Perform contrast limiting adaptive histogram equalization (CLAHE) - * - * This will, in general, enhance the clarity of the image by bringing out - * darker details. Please read more about CLAHE here: - * https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE - * - * @param options clahe options - */ - clahe(options: ClaheOptions): Sharp; - - /** - * Convolve the image with the specified kernel. - * @param kernel the specified kernel - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - convolve(kernel: Kernel): Sharp; - - /** - * Any pixel value greather than or equal to the threshold value will be set to 255, otherwise it will be set to 0. - * @param threshold a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default 128) - * @param options threshold options - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - threshold(threshold?: number, options?: ThresholdOptions): Sharp; - - /** - * Perform a bitwise boolean operation with operand image. - * This operation creates an output image where each pixel is the result of the selected bitwise boolean operation between the corresponding pixels of the input images. - * @param operand Buffer containing image data or String containing the path to an image file. - * @param operator one of "and", "or" or "eor" to perform that bitwise operation, like the C logic operators &, | and ^ respectively. - * @param options describes operand when using raw pixel data. - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - boolean(operand: string | Buffer, operator: keyof BoolEnum, options?: { raw: Raw }): Sharp; - - /** - * Apply the linear formula a * input + b to the image (levels adjustment) - * @param a multiplier (optional, default 1.0) - * @param b offset (optional, default 0.0) - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - linear(a?: number | number[] | null, b?: number | 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; - - /** - * Transforms the image using brightness, saturation, hue rotation and lightness. - * Brightness and lightness both operate on luminance, with the difference being that brightness is multiplicative whereas lightness is additive. - * @param options describes the modulation - * @returns A sharp instance that can be used to chain operations - */ - modulate(options?: { - brightness?: number | undefined; - saturation?: number | undefined; - hue?: number | undefined; - lightness?: number | undefined; - }): Sharp; - - //#endregion - - //#region Output functions - - /** - * Write output image data to a file. - * If an explicit output format is not selected, it will be inferred from the extension, with JPEG, PNG, WebP, AVIF, TIFF, DZI, and libvips' V format supported. - * Note that raw pixel data is only supported for buffer output. - * @param fileOut The path to write the image data to. - * @param callback Callback function called on completion with two arguments (err, info). info contains the output image format, size (bytes), width, height and channels. - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - toFile(fileOut: string, callback: (err: Error, info: OutputInfo) => void): Sharp; - - /** - * Write output image data to a file. - * @param fileOut The path to write the image data to. - * @throws {Error} Invalid parameters - * @returns A promise that fulfills with an object containing information on the resulting file - */ - toFile(fileOut: string): Promise; - - /** - * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported. - * By default, the format will match the input image, except SVG input which becomes PNG output. - * @param callback Callback function called on completion with three arguments (err, buffer, info). - * @returns A sharp instance that can be used to chain operations - */ - toBuffer(callback: (err: Error, buffer: Buffer, info: OutputInfo) => void): Sharp; - - /** - * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported. - * By default, the format will match the input image, except SVG input which becomes PNG output. - * @param options resolve options - * @param options.resolveWithObject Resolve the Promise with an Object containing data and info properties instead of resolving only with data. - * @returns A promise that resolves with the Buffer data. - */ - toBuffer(options?: { resolveWithObject: false }): Promise; - - /** - * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported. - * By default, the format will match the input image, except SVG input which becomes PNG output. - * @param options resolve options - * @param options.resolveWithObject Resolve the Promise with an Object containing data and info properties instead of resolving only with data. - * @returns A promise that resolves with an object containing the Buffer data and an info object containing the output image format, size (bytes), width, height and channels - */ - toBuffer(options: { resolveWithObject: true }): Promise<{ data: Buffer; info: OutputInfo }>; - - /** - * Keep all EXIF metadata from the input image in the output image. - * EXIF metadata is unsupported for TIFF output. - * @returns A sharp instance that can be used to chain operations - */ - keepExif(): Sharp; - - /** - * Set EXIF metadata in the output image, ignoring any EXIF in the input image. - * @param {Exif} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. - * @returns A sharp instance that can be used to chain operations - * @throws {Error} Invalid parameters - */ - withExif(exif: Exif): Sharp; - - /** - * Update EXIF metadata from the input image in the output image. - * @param {Exif} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. - * @returns A sharp instance that can be used to chain operations - * @throws {Error} Invalid parameters - */ - withExifMerge(exif: Exif): Sharp; - - /** - * Keep ICC profile from the input image in the output image where possible. - * @returns A sharp instance that can be used to chain operations - */ - keepIccProfile(): Sharp; - - /** - * Transform using an ICC profile and attach to the output image. - * @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk). - * @returns A sharp instance that can be used to chain operations - * @throws {Error} Invalid parameters - */ - withIccProfile(icc: string, options?: WithIccProfileOptions): Sharp; - - /** - * Include all metadata (EXIF, XMP, IPTC) from the input image in the output image. - * The default behaviour, when withMetadata is not used, is to strip all metadata and convert to the device-independent sRGB colour space. - * This will also convert to and add a web-friendly sRGB ICC profile. - * @param withMetadata - * @throws {Error} Invalid parameters. - */ - withMetadata(withMetadata?: WriteableMetadata): Sharp; - - /** - * Use these JPEG options for output image. - * @param options Output options. - * @throws {Error} Invalid options - * @returns A sharp instance that can be used to chain operations - */ - jpeg(options?: JpegOptions): Sharp; - - /** - * Use these JP2 (JPEG 2000) options for output image. - * @param options Output options. - * @throws {Error} Invalid options - * @returns A sharp instance that can be used to chain operations - */ - jp2(options?: Jp2Options): Sharp; - - /** - * Use these JPEG-XL (JXL) options for output image. - * This feature is experimental, please do not use in production systems. - * Requires libvips compiled with support for libjxl. - * The prebuilt binaries do not include this. - * Image metadata (EXIF, XMP) is unsupported. - * @param options Output options. - * @throws {Error} Invalid options - * @returns A sharp instance that can be used to chain operations - */ - jxl(options?: JxlOptions): Sharp; - - /** - * Use these PNG options for output image. - * PNG output is always full colour at 8 or 16 bits per pixel. - * Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel. - * @param options Output options. - * @throws {Error} Invalid options - * @returns A sharp instance that can be used to chain operations - */ - png(options?: PngOptions): Sharp; - - /** - * Use these WebP options for output image. - * @param options Output options. - * @throws {Error} Invalid options - * @returns A sharp instance that can be used to chain operations - */ - webp(options?: WebpOptions): Sharp; - - /** - * Use these GIF options for output image. - * Requires libvips compiled with support for ImageMagick or GraphicsMagick. The prebuilt binaries do not include this - see installing a custom libvips. - * @param options Output options. - * @throws {Error} Invalid options - * @returns A sharp instance that can be used to chain operations - */ - gif(options?: GifOptions): Sharp; - - /** - * Use these AVIF options for output image. - * @param options Output options. - * @throws {Error} Invalid options - * @returns A sharp instance that can be used to chain operations - */ - avif(options?: AvifOptions): Sharp; - - /** - * Use these HEIF options for output image. - * Support for patent-encumbered HEIC images requires the use of a globally-installed libvips compiled with support for libheif, libde265 and x265. - * @param options Output options. - * @throws {Error} Invalid options - * @returns A sharp instance that can be used to chain operations - */ - heif(options?: HeifOptions): Sharp; - - /** - * Use these TIFF options for output image. - * @param options Output options. - * @throws {Error} Invalid options - * @returns A sharp instance that can be used to chain operations - */ - tiff(options?: TiffOptions): Sharp; - - /** - * Force output to be raw, uncompressed uint8 pixel data. - * @param options Raw output options. - * @throws {Error} Invalid options - * @returns A sharp instance that can be used to chain operations - */ - raw(options?: RawOptions): Sharp; - - /** - * Force output to a given format. - * @param format a String or an Object with an 'id' attribute - * @param options output options - * @throws {Error} Unsupported format or options - * @returns A sharp instance that can be used to chain operations - */ - toFormat( - format: keyof FormatEnum | AvailableFormatInfo, - options?: - | OutputOptions - | JpegOptions - | PngOptions - | WebpOptions - | AvifOptions - | HeifOptions - | JxlOptions - | GifOptions - | Jp2Options - | TiffOptions, - ): Sharp; - - /** - * Use tile-based deep zoom (image pyramid) output. - * Set the format and options for tile images via the toFormat, jpeg, png or webp functions. - * Use a .zip or .szi file extension with toFile to write to a compressed archive file format. - * - * Warning: multiple sharp instances concurrently producing tile output can expose a possible race condition in some versions of libgsf. - * @param tile tile options - * @throws {Error} Invalid options - * @returns A sharp instance that can be used to chain operations - */ - tile(tile?: TileOptions): Sharp; - - /** - * Set a timeout for processing, in seconds. Use a value of zero to continue processing indefinitely, the default behaviour. - * The clock starts when libvips opens an input image for processing. Time spent waiting for a libuv thread to become available is not included. - * @param options Object with a `seconds` attribute between 0 and 3600 (number) - * @throws {Error} Invalid options - * @returns A sharp instance that can be used to chain operations - */ - timeout(options: TimeoutOptions): Sharp; - - //#endregion - - //#region Resize functions - - /** - * Resize image to width, height or width x height. - * - * When both a width and height are provided, the possible methods by which the image should fit these are: - * - cover: Crop to cover both provided dimensions (the default). - * - contain: Embed within both provided dimensions. - * - fill: Ignore the aspect ratio of the input and stretch to both provided dimensions. - * - inside: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified. - * - outside: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified. - * Some of these values are based on the object-fit CSS property. - * - * When using a fit of cover or contain, the default position is centre. Other options are: - * - sharp.position: top, right top, right, right bottom, bottom, left bottom, left, left top. - * - sharp.gravity: north, northeast, east, southeast, south, southwest, west, northwest, center or centre. - * - sharp.strategy: cover only, dynamically crop using either the entropy or attention strategy. Some of these values are based on the object-position CSS property. - * - * The experimental strategy-based approach resizes so one dimension is at its target length then repeatedly ranks edge regions, - * discarding the edge with the lowest score based on the selected strategy. - * - entropy: focus on the region with the highest Shannon entropy. - * - attention: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones. - * - * Possible interpolation kernels are: - * - nearest: Use nearest neighbour interpolation. - * - cubic: Use a Catmull-Rom spline. - * - lanczos2: Use a Lanczos kernel with a=2. - * - lanczos3: Use a Lanczos kernel with a=3 (the default). - * - * @param width pixels wide the resultant image should be. Use null or undefined to auto-scale the width to match the height. - * @param height pixels high the resultant image should be. Use null or undefined to auto-scale the height to match the width. - * @param options resize options - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - resize(widthOrOptions?: number | ResizeOptions | null, height?: number | null, options?: ResizeOptions): Sharp; - - /** - * Shorthand for resize(null, null, options); - * - * @param options resize options - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - resize(options: ResizeOptions): Sharp; - - /** - * Extend / pad / extrude one or more edges of the image with either - * the provided background colour or pixels derived from the image. - * This operation will always occur after resizing and extraction, if any. - * @param extend single pixel count to add to all edges or an Object with per-edge counts - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - extend(extend: number | ExtendOptions): Sharp; - - /** - * Extract a region of the image. - * - Use extract() before resize() for pre-resize extraction. - * - Use extract() after resize() for post-resize extraction. - * - Use extract() before and after for both. - * - * @param region The region to extract - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - extract(region: Region): Sharp; - - /** - * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel. - * Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels. - * The info response Object will contain trimOffsetLeft and trimOffsetTop properties. - * @param options trim options - * @throws {Error} Invalid parameters - * @returns A sharp instance that can be used to chain operations - */ - trim(options?: TrimOptions): Sharp; - - //#endregion - } - - interface SharpOptions { - /** - * When to abort processing of invalid pixel data, one of (in order of sensitivity): - * 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort. (optional, default 'warning') - */ - failOn?: FailOnOptions | undefined; - /** - * By default halt processing and raise an error when loading invalid images. - * Set this flag to false if you'd rather apply a "best effort" to decode images, - * even if the data is corrupt or invalid. (optional, default true) - * - * @deprecated Use `failOn` instead - */ - failOnError?: boolean | undefined; - /** - * Do not process input images where the number of pixels (width x height) exceeds this limit. - * Assumes image dimensions contained in the input metadata can be trusted. - * An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). (optional, default 268402689) - */ - limitInputPixels?: number | boolean | undefined; - /** Set this to true to remove safety features that help prevent memory exhaustion (SVG, PNG). (optional, default false) */ - unlimited?: boolean | undefined; - /** Set this to false to use random access rather than sequential read. Some operations will do this automatically. */ - sequentialRead?: boolean | undefined; - /** Number representing the DPI for vector images in the range 1 to 100000. (optional, default 72) */ - density?: number | undefined; - /** Should the embedded ICC profile, if any, be ignored. */ - ignoreIcc?: boolean | undefined; - /** Number of pages to extract for multi-page input (GIF, TIFF, PDF), use -1 for all pages */ - pages?: number | undefined; - /** Page number to start extracting from for multi-page input (GIF, TIFF, PDF), zero based. (optional, default 0) */ - page?: number | undefined; - /** subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. (optional, default -1) */ - subifd?: number | undefined; - /** Level to extract from a multi-level input (OpenSlide), zero based. (optional, default 0) */ - level?: number | undefined; - /** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default false) */ - animated?: boolean | undefined; - /** Describes raw pixel input image data. See raw() for pixel ordering. */ - raw?: CreateRaw | undefined; - /** Describes a new image to be created. */ - create?: Create | undefined; - /** Describes a new text image to be created. */ - text?: CreateText | undefined; - } - - interface CacheOptions { - /** Is the maximum memory in MB to use for this cache (optional, default 50) */ - memory?: number | undefined; - /** Is the maximum number of files to hold open (optional, default 20) */ - files?: number | undefined; - /** Is the maximum number of operations to cache (optional, default 100) */ - items?: number | undefined; - } - - interface TimeoutOptions { - /** Number of seconds after which processing will be stopped (default 0, eg disabled) */ - seconds: number; - } - - interface SharpCounters { - /** The number of tasks this module has queued waiting for libuv to provide a worker thread from its pool. */ - queue: number; - /** The number of resize tasks currently being processed. */ - process: number; - } - - interface Raw { - width: number; - height: number; - channels: 1 | 2 | 3 | 4; - } - - interface CreateRaw extends Raw { - /** Specifies that the raw input has already been premultiplied, set to true to avoid sharp premultiplying the image. (optional, default false) */ - premultiplied?: boolean | undefined; - } - - interface Create { - /** Number of pixels wide. */ - width: number; - /** Number of pixels high. */ - height: number; - /** Number of bands e.g. 3 for RGB, 4 for RGBA */ - channels: Channels; - /** Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. */ - background: Color; - /** Describes a noise to be created. */ - noise?: Noise | undefined; - } - - interface CreateText { - /** Text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. */ - text: string; - /** Font name to render with. */ - font?: string; - /** Absolute filesystem path to a font file that can be used by `font`. */ - fontfile?: string; - /** Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. (optional, default `0`) */ - width?: number; - /** - * Integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution - * defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. (optional, default `0`) - */ - height?: number; - /** Text alignment ('left', 'centre', 'center', 'right'). (optional, default 'left') */ - align?: TextAlign; - /** Set this to true to apply justification to the text. (optional, default `false`) */ - justify?: boolean; - /** The resolution (size) at which to render the text. Does not take effect if `height` is specified. (optional, default `72`) */ - dpi?: number; - /** - * Set this to true to enable RGBA output. This is useful for colour emoji rendering, - * or support for pango markup features like `Red!`. (optional, default `false`) - */ - rgba?: boolean; - /** Text line height in points. Will use the font line height if none is specified. (optional, default `0`) */ - spacing?: number; - /** Word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none' */ - wrap?: TextWrap; - } - - interface ExifDir { - [k: string]: string; - } - - interface Exif { - 'IFD0'?: ExifDir; - 'IFD1'?: ExifDir; - 'IFD2'?: ExifDir; - 'IFD3'?: ExifDir; - } - - interface WriteableMetadata { - /** Number of pixels per inch (DPI) */ - density?: number | undefined; - /** Value between 1 and 8, used to update the EXIF Orientation tag. */ - orientation?: number | undefined; - /** - * Filesystem path to output ICC profile, defaults to sRGB. - * @deprecated Use `withIccProfile()` instead. - */ - icc?: string | undefined; - /** - * Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. - * @deprecated Use `withExif()` or `withExifMerge()` instead. - */ - exif?: Exif | undefined; - } - - interface Metadata { - /** Number value of the EXIF Orientation header, if present */ - orientation?: number | undefined; - /** Name of decoder used to decompress image data e.g. jpeg, png, webp, gif, svg */ - format?: keyof FormatEnum | undefined; - /** Total size of image in bytes, for Stream and Buffer input only */ - size?: number | undefined; - /** Number of pixels wide (EXIF orientation is not taken into consideration) */ - width?: number | undefined; - /** Number of pixels high (EXIF orientation is not taken into consideration) */ - height?: number | undefined; - /** Name of colour space interpretation */ - space?: keyof ColourspaceEnum | undefined; - /** Number of bands e.g. 3 for sRGB, 4 for CMYK */ - channels?: Channels | undefined; - /** Name of pixel depth format e.g. uchar, char, ushort, float ... */ - depth?: string | undefined; - /** Number of pixels per inch (DPI), if present */ - density?: number | undefined; - /** String containing JPEG chroma subsampling, 4:2:0 or 4:4:4 for RGB, 4:2:0:4 or 4:4:4:4 for CMYK */ - chromaSubsampling: string; - /** Boolean indicating whether the image is interlaced using a progressive scan */ - isProgressive?: boolean | undefined; - /** Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP */ - pages?: number | undefined; - /** Number of pixels high each page in a multi-page image will be. */ - pageHeight?: number | undefined; - /** Number of times to loop an animated image, zero refers to a continuous loop. */ - loop?: number | undefined; - /** Delay in ms between each page in an animated image, provided as an array of integers. */ - delay?: number[] | undefined; - /** Number of the primary page in a HEIF image */ - pagePrimary?: number | undefined; - /** Boolean indicating the presence of an embedded ICC profile */ - hasProfile?: boolean | undefined; - /** Boolean indicating the presence of an alpha transparency channel */ - hasAlpha?: boolean | undefined; - /** Buffer containing raw EXIF data, if present */ - exif?: Buffer | undefined; - /** Buffer containing raw ICC profile data, if present */ - icc?: Buffer | undefined; - /** Buffer containing raw IPTC data, if present */ - iptc?: Buffer | undefined; - /** Buffer containing raw XMP data, if present */ - xmp?: Buffer | undefined; - /** Buffer containing raw TIFFTAG_PHOTOSHOP data, if present */ - tifftagPhotoshop?: Buffer | undefined; - /** The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) */ - compression?: 'av1' | 'hevc'; - /** Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value */ - background?: { r: number; g: number; b: number } | number; - /** Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide */ - levels?: LevelMetadata[] | undefined; - /** Number of Sub Image File Directories in an OME-TIFF image */ - subifds?: number | undefined; - /** The unit of resolution (density) */ - resolutionUnit?: 'inch' | 'cm' | undefined; - /** String containing format for images loaded via *magick */ - formatMagick?: string | undefined; - } - - interface LevelMetadata { - width: number; - height: number; - } - - interface Stats { - /** Array of channel statistics for each channel in the image. */ - channels: ChannelStats[]; - /** Value to identify if the image is opaque or transparent, based on the presence and use of alpha channel */ - isOpaque: boolean; - /** Histogram-based estimation of greyscale entropy, discarding alpha channel if any (experimental) */ - entropy: number; - /** Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any (experimental) */ - sharpness: number; - /** Object containing most dominant sRGB colour based on a 4096-bin 3D histogram (experimental) */ - dominant: { r: number; g: number; b: number }; - } - - interface ChannelStats { - /** minimum value in the channel */ - min: number; - /** maximum value in the channel */ - max: number; - /** sum of all values in a channel */ - sum: number; - /** sum of squared values in a channel */ - squaresSum: number; - /** mean of the values in a channel */ - mean: number; - /** standard deviation for the values in a channel */ - stdev: number; - /** x-coordinate of one of the pixel where the minimum lies */ - minX: number; - /** y-coordinate of one of the pixel where the minimum lies */ - minY: number; - /** x-coordinate of one of the pixel where the maximum lies */ - maxX: number; - /** y-coordinate of one of the pixel where the maximum lies */ - maxY: number; - } - - interface OutputOptions { - /** Force format output, otherwise attempt to use input format (optional, default true) */ - force?: boolean | undefined; - } - - interface WithIccProfileOptions { - /** Should the ICC profile be included in the output image metadata? (optional, default true) */ - attach?: boolean | undefined; - } - - interface JpegOptions extends OutputOptions { - /** Quality, integer 1-100 (optional, default 80) */ - quality?: number | undefined; - /** Use progressive (interlace) scan (optional, default false) */ - progressive?: boolean | undefined; - /** Set to '4:4:4' to prevent chroma subsampling when quality <= 90 (optional, default '4:2:0') */ - chromaSubsampling?: string | undefined; - /** Apply trellis quantisation (optional, default false) */ - trellisQuantisation?: boolean | undefined; - /** Apply overshoot deringing (optional, default false) */ - overshootDeringing?: boolean | undefined; - /** Optimise progressive scans, forces progressive (optional, default false) */ - optimiseScans?: boolean | undefined; - /** Alternative spelling of optimiseScans (optional, default false) */ - optimizeScans?: boolean | undefined; - /** Optimise Huffman coding tables (optional, default true) */ - optimiseCoding?: boolean | undefined; - /** Alternative spelling of optimiseCoding (optional, default true) */ - optimizeCoding?: boolean | undefined; - /** Quantization table to use, integer 0-8 (optional, default 0) */ - quantisationTable?: number | undefined; - /** Alternative spelling of quantisationTable (optional, default 0) */ - quantizationTable?: number | undefined; - /** Use mozjpeg defaults (optional, default false) */ - mozjpeg?: boolean | undefined; - } - - interface Jp2Options extends OutputOptions { - /** Quality, integer 1-100 (optional, default 80) */ - quality?: number; - /** Use lossless compression mode (optional, default false) */ - lossless?: boolean; - /** Horizontal tile size (optional, default 512) */ - tileWidth?: number; - /** Vertical tile size (optional, default 512) */ - tileHeight?: number; - /** Set to '4:2:0' to enable chroma subsampling (optional, default '4:4:4') */ - chromaSubsampling?: '4:4:4' | '4:2:0'; - } - - interface JxlOptions extends OutputOptions { - /** Maximum encoding error, between 0 (highest quality) and 15 (lowest quality) (optional, default 1.0) */ - distance?: number; - /** Calculate distance based on JPEG-like quality, between 1 and 100, overrides distance if specified */ - quality?: number; - /** Target decode speed tier, between 0 (highest quality) and 4 (lowest quality) (optional, default 0) */ - decodingTier?: number; - /** Use lossless compression (optional, default false) */ - lossless?: boolean; - /** CPU effort, between 3 (fastest) and 9 (slowest) (optional, default 7) */ - effort?: number | undefined; - } - - interface WebpOptions extends OutputOptions, AnimationOptions { - /** Quality, integer 1-100 (optional, default 80) */ - quality?: number | undefined; - /** Quality of alpha layer, number from 0-100 (optional, default 100) */ - alphaQuality?: number | undefined; - /** Use lossless compression mode (optional, default false) */ - lossless?: boolean | undefined; - /** Use near_lossless compression mode (optional, default false) */ - nearLossless?: boolean | undefined; - /** Use high quality chroma subsampling (optional, default false) */ - smartSubsample?: boolean | undefined; - /** Level of CPU effort to reduce file size, integer 0-6 (optional, default 4) */ - effort?: number | undefined; - /** Prevent use of animation key frames to minimise file size (slow) (optional, default false) */ - minSize?: boolean; - /** Allow mixture of lossy and lossless animation frames (slow) (optional, default false) */ - mixed?: boolean; - /** Preset options: one of default, photo, picture, drawing, icon, text (optional, default 'default') */ - preset?: keyof PresetEnum | undefined; - } - - interface AvifOptions extends OutputOptions { - /** quality, integer 1-100 (optional, default 50) */ - quality?: number | undefined; - /** use lossless compression (optional, default false) */ - lossless?: boolean | undefined; - /** Level of CPU effort to reduce file size, between 0 (fastest) and 9 (slowest) (optional, default 4) */ - effort?: number | undefined; - /** set to '4:2:0' to use chroma subsampling, requires libvips v8.11.0 (optional, default '4:4:4') */ - chromaSubsampling?: string | undefined; - /** Set bitdepth to 8, 10 or 12 bit (optional, default 8) */ - bitdepth?: 8 | 10 | 12 | undefined; - } - - interface HeifOptions extends OutputOptions { - /** quality, integer 1-100 (optional, default 50) */ - quality?: number | undefined; - /** compression format: av1, hevc (optional, default 'av1') */ - compression?: 'av1' | 'hevc' | undefined; - /** use lossless compression (optional, default false) */ - lossless?: boolean | undefined; - /** Level of CPU effort to reduce file size, between 0 (fastest) and 9 (slowest) (optional, default 4) */ - effort?: number | undefined; - /** set to '4:2:0' to use chroma subsampling (optional, default '4:4:4') */ - chromaSubsampling?: string | undefined; - /** Set bitdepth to 8, 10 or 12 bit (optional, default 8) */ - bitdepth?: 8 | 10 | 12 | undefined; - } - - interface GifOptions extends OutputOptions, AnimationOptions { - /** Re-use existing palette, otherwise generate new (slow) */ - reuse?: boolean | undefined; - /** Use progressive (interlace) scan */ - progressive?: boolean | undefined; - /** Maximum number of palette entries, including transparency, between 2 and 256 (optional, default 256) */ - colours?: number | undefined; - /** Alternative spelling of "colours". Maximum number of palette entries, including transparency, between 2 and 256 (optional, default 256) */ - colors?: number | undefined; - /** Level of CPU effort to reduce file size, between 1 (fastest) and 10 (slowest) (optional, default 7) */ - effort?: number | undefined; - /** Level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (optional, default 1.0) */ - dither?: number | undefined; - /** Maximum inter-frame error for transparency, between 0 (lossless) and 32 (optional, default 0) */ - interFrameMaxError?: number; - /** Maximum inter-palette error for palette reuse, between 0 and 256 (optional, default 3) */ - interPaletteMaxError?: number; - } - - interface TiffOptions extends OutputOptions { - /** Quality, integer 1-100 (optional, default 80) */ - quality?: number | undefined; - /** Compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k (optional, default 'jpeg') */ - compression?: string | undefined; - /** Compression predictor options: none, horizontal, float (optional, default 'horizontal') */ - predictor?: string | undefined; - /** Write an image pyramid (optional, default false) */ - pyramid?: boolean | undefined; - /** Write a tiled tiff (optional, default false) */ - tile?: boolean | undefined; - /** Horizontal tile size (optional, default 256) */ - tileWidth?: number | undefined; - /** Vertical tile size (optional, default 256) */ - tileHeight?: number | undefined; - /** Horizontal resolution in pixels/mm (optional, default 1.0) */ - xres?: number | undefined; - /** Vertical resolution in pixels/mm (optional, default 1.0) */ - yres?: number | undefined; - /** Reduce bitdepth to 1, 2 or 4 bit (optional, default 8) */ - bitdepth?: 1 | 2 | 4 | 8 | undefined; - /** Write 1-bit images as miniswhite (optional, default false) */ - miniswhite?: boolean | undefined; - /** Resolution unit options: inch, cm (optional, default 'inch') */ - resolutionUnit?: 'inch' | 'cm' | undefined; - } - - interface PngOptions extends OutputOptions { - /** Use progressive (interlace) scan (optional, default false) */ - progressive?: boolean | undefined; - /** zlib compression level, 0-9 (optional, default 6) */ - compressionLevel?: number | undefined; - /** Use adaptive row filtering (optional, default false) */ - adaptiveFiltering?: boolean | undefined; - /** Use the lowest number of colours needed to achieve given quality (optional, default `100`) */ - quality?: number | undefined; - /** Level of CPU effort to reduce file size, between 1 (fastest) and 10 (slowest), sets palette to true (optional, default 7) */ - effort?: number | undefined; - /** Quantise to a palette-based image with alpha transparency support (optional, default false) */ - palette?: boolean | undefined; - /** Maximum number of palette entries (optional, default 256) */ - colours?: number | undefined; - /** Alternative Spelling of "colours". Maximum number of palette entries (optional, default 256) */ - colors?: number | undefined; - /** Level of Floyd-Steinberg error diffusion (optional, default 1.0) */ - dither?: number | undefined; - } - - interface RotateOptions { - /** parsed by the color module to extract values for red, green, blue and alpha. (optional, default "#000000") */ - background?: Color | undefined; - } - - interface FlattenOptions { - /** background colour, parsed by the color module, defaults to black. (optional, default {r:0,g:0,b:0}) */ - background?: Color | undefined; - } - - interface NegateOptions { - /** whether or not to negate any alpha channel. (optional, default true) */ - alpha?: boolean | undefined; - } - - interface NormaliseOptions { - /** Percentile below which luminance values will be underexposed. */ - lower?: number | undefined; - /** Percentile above which luminance values will be overexposed. */ - upper?: number | undefined; - } - - interface ResizeOptions { - /** Alternative means of specifying width. If both are present this takes priority. */ - width?: number | undefined; - /** Alternative means of specifying height. If both are present this takes priority. */ - height?: number | undefined; - /** How the image should be resized to fit both provided dimensions, one of cover, contain, fill, inside or outside. (optional, default 'cover') */ - fit?: keyof FitEnum | undefined; - /** Position, gravity or strategy to use when fit is cover or contain. (optional, default 'centre') */ - position?: number | string | undefined; - /** Background colour when using a fit of contain, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */ - background?: Color | undefined; - /** The kernel to use for image reduction. (optional, default 'lanczos3') */ - kernel?: keyof KernelEnum | undefined; - /** Do not enlarge if the width or height are already less than the specified dimensions, equivalent to GraphicsMagick's > geometry option. (optional, default false) */ - withoutEnlargement?: boolean | undefined; - /** Do not reduce if the width or height are already greater than the specified dimensions, equivalent to GraphicsMagick's < geometry option. (optional, default false) */ - withoutReduction?: boolean | undefined; - /** Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, default true) */ - fastShrinkOnLoad?: boolean | undefined; - } - - interface Region { - /** zero-indexed offset from left edge */ - left: number; - /** zero-indexed offset from top edge */ - top: number; - /** dimension of extracted image */ - width: number; - /** dimension of extracted image */ - height: number; - } - - interface Noise { - /** type of generated noise, currently only gaussian is supported. */ - type?: 'gaussian' | undefined; - /** mean of pixels in generated noise. */ - mean?: number | undefined; - /** standard deviation of pixels in generated noise. */ - sigma?: number | undefined; - } - - type ExtendWith = 'background' | 'copy' | 'repeat' | 'mirror'; - - interface ExtendOptions { - /** single pixel count to top edge (optional, default 0) */ - top?: number | undefined; - /** single pixel count to left edge (optional, default 0) */ - left?: number | undefined; - /** single pixel count to bottom edge (optional, default 0) */ - bottom?: number | undefined; - /** single pixel count to right edge (optional, default 0) */ - right?: number | undefined; - /** background colour, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */ - background?: Color | undefined; - /** how the extension is done, one of: "background", "copy", "repeat", "mirror" (optional, default `'background'`) */ - extendWith?: ExtendWith | undefined; - } - - interface TrimOptions { - /** Background colour, parsed by the color module, defaults to that of the top-left pixel. (optional) */ - background?: Color | undefined; - /** Allowed difference from the above colour, a positive number. (optional, default 10) */ - threshold?: number | undefined; - /** Does the input more closely resemble line art (e.g. vector) rather than being photographic? (optional, default false) */ - lineArt?: boolean | undefined; - } - - interface RawOptions { - depth?: 'char' | 'uchar' | 'short' | 'ushort' | 'int' | 'uint' | 'float' | 'complex' | 'double' | 'dpcomplex'; - } - - /** 3 for sRGB, 4 for CMYK */ - type Channels = 3 | 4; - - interface RGBA { - r?: number | undefined; - g?: number | undefined; - b?: number | undefined; - alpha?: number | undefined; - } - - type Color = string | RGBA; - - interface Kernel { - /** width of the kernel in pixels. */ - width: number; - /** height of the kernel in pixels. */ - height: number; - /** Array of length width*height containing the kernel values. */ - kernel: ArrayLike; - /** the scale of the kernel in pixels. (optional, default sum) */ - scale?: number | undefined; - /** the offset of the kernel in pixels. (optional, default 0) */ - offset?: number | undefined; - } - - interface ClaheOptions { - /** width of the region */ - width: number; - /** height of the region */ - height: number; - /** max slope of the cumulative contrast. A value of 0 disables contrast limiting. Valid values are integers in the range 0-100 (inclusive) (optional, default 3) */ - maxSlope?: number | undefined; - } - - interface ThresholdOptions { - /** convert to single channel greyscale. (optional, default true) */ - greyscale?: boolean | undefined; - /** alternative spelling for greyscale. (optional, default true) */ - grayscale?: boolean | undefined; - } - - interface OverlayOptions extends SharpOptions { - /** Buffer containing image data, String containing the path to an image file, or Create object */ - input?: string | Buffer | { create: Create } | { text: CreateText } | { raw: CreateRaw } | undefined; - /** how to blend this image with the image below. (optional, default `'over'`) */ - blend?: Blend | undefined; - /** gravity at which to place the overlay. (optional, default 'centre') */ - gravity?: Gravity | undefined; - /** the pixel offset from the top edge. */ - top?: number | undefined; - /** the pixel offset from the left edge. */ - left?: number | undefined; - /** set to true to repeat the overlay image across the entire image with the given gravity. (optional, default false) */ - tile?: boolean | undefined; - /** Set to true to avoid premultipling the image below. Equivalent to the --premultiplied vips option. */ - premultiplied?: boolean | undefined; - } - - interface TileOptions { - /** Tile size in pixels, a value between 1 and 8192. (optional, default 256) */ - size?: number | undefined; - /** Tile overlap in pixels, a value between 0 and 8192. (optional, default 0) */ - overlap?: number | undefined; - /** Tile angle of rotation, must be a multiple of 90. (optional, default 0) */ - angle?: number | undefined; - /** background colour, parsed by the color module, defaults to white without transparency. (optional, default {r:255,g:255,b:255,alpha:1}) */ - background?: string | RGBA | undefined; - /** How deep to make the pyramid, possible values are "onepixel", "onetile" or "one" (default based on layout) */ - depth?: string | undefined; - /** Threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images */ - skipBlanks?: number | undefined; - /** Tile container, with value fs (filesystem) or zip (compressed file). (optional, default 'fs') */ - container?: TileContainer | undefined; - /** Filesystem layout, possible values are dz, iiif, iiif3, zoomify or google. (optional, default 'dz') */ - layout?: TileLayout | undefined; - /** Centre image in tile. (optional, default false) */ - centre?: boolean | undefined; - /** Alternative spelling of centre. (optional, default false) */ - center?: boolean | undefined; - /** When layout is iiif/iiif3, sets the @id/id attribute of info.json (optional, default 'https://example.com/iiif') */ - id?: string | undefined; - /** The name of the directory within the zip file when container is `zip`. */ - basename?: string | undefined; - } - - interface AnimationOptions { - /** Number of animation iterations, a value between 0 and 65535. Use 0 for infinite animation. (optional, default 0) */ - loop?: number | undefined; - /** delay(s) between animation frames (in milliseconds), each value between 0 and 65535. (optional) */ - delay?: number | number[] | undefined; - } - - interface SharpenOptions { - /** The sigma of the Gaussian mask, where sigma = 1 + radius / 2, between 0.000001 and 10000 */ - sigma: number; - /** The level of sharpening to apply to "flat" areas, between 0 and 1000000 (optional, default 1.0) */ - m1?: number | undefined; - /** The level of sharpening to apply to "jagged" areas, between 0 and 1000000 (optional, default 2.0) */ - m2?: number | undefined; - /** Threshold between "flat" and "jagged", between 0 and 1000000 (optional, default 2.0) */ - x1?: number | undefined; - /** Maximum amount of brightening, between 0 and 1000000 (optional, default 10.0) */ - y2?: number | undefined; - /** Maximum amount of darkening, between 0 and 1000000 (optional, default 20.0) */ - y3?: number | undefined; - } - - interface AffineOptions { - /** Parsed by the color module to extract values for red, green, blue and alpha. (optional, default "#000000") */ - background?: string | object | undefined; - /** Input horizontal offset (optional, default 0) */ - idx?: number | undefined; - /** Input vertical offset (optional, default 0) */ - idy?: number | undefined; - /** Output horizontal offset (optional, default 0) */ - odx?: number | undefined; - /** Output horizontal offset (optional, default 0) */ - ody?: number | undefined; - /** Interpolator (optional, default sharp.interpolators.bicubic) */ - interpolator?: Interpolators[keyof Interpolators] | undefined; - } - - interface OutputInfo { - format: string; - size: number; - width: number; - height: number; - channels: 1 | 2 | 3 | 4; - /** indicating if premultiplication was used */ - premultiplied: boolean; - /** Only defined when using a crop strategy */ - cropOffsetLeft?: number | undefined; - /** Only defined when using a crop strategy */ - cropOffsetTop?: number | undefined; - /** Only defined when using a trim method */ - trimOffsetLeft?: number | undefined; - /** Only defined when using a trim method */ - trimOffsetTop?: number | undefined; - /** DPI the font was rendered at, only defined when using `text` input */ - textAutofitDpi?: number | undefined; - /** When using the attention crop strategy, the focal point of the cropped region */ - attentionX?: number | undefined; - attentionY?: number | undefined; - } - - interface AvailableFormatInfo { - id: string; - input: { file: boolean; buffer: boolean; stream: boolean; fileSuffix?: string[] }; - output: { file: boolean; buffer: boolean; stream: boolean; alias?: string[] }; - } - - interface FitEnum { - contain: 'contain'; - cover: 'cover'; - fill: 'fill'; - inside: 'inside'; - outside: 'outside'; - } - - interface KernelEnum { - nearest: 'nearest'; - cubic: 'cubic'; - mitchell: 'mitchell'; - lanczos2: 'lanczos2'; - lanczos3: 'lanczos3'; - } - - interface PresetEnum { - default: 'default'; - picture: 'picture'; - photo: 'photo'; - drawing: 'drawing'; - icon: 'icon'; - text: 'text'; - } - - interface BoolEnum { - and: 'and'; - or: 'or'; - eor: 'eor'; - } - - interface ColourspaceEnum { - multiband: string; - 'b-w': string; - bw: string; - cmyk: string; - srgb: string; - } - - type FailOnOptions = 'none' | 'truncated' | 'error' | 'warning'; - - type TextAlign = 'left' | 'centre' | 'center' | 'right'; - - type TextWrap = 'word' | 'char' | 'word-char' | 'none'; - - type TileContainer = 'fs' | 'zip'; - - type TileLayout = 'dz' | 'iiif' | 'iiif3' | 'zoomify' | 'google'; - - type Blend = - | 'clear' - | 'source' - | 'over' - | 'in' - | 'out' - | 'atop' - | 'dest' - | 'dest-over' - | 'dest-in' - | 'dest-out' - | 'dest-atop' - | 'xor' - | 'add' - | 'saturate' - | 'multiply' - | 'screen' - | 'overlay' - | 'darken' - | 'lighten' - | 'color-dodge' - | 'colour-dodge' - | 'color-burn' - | 'colour-burn' - | 'hard-light' - | 'soft-light' - | 'difference' - | 'exclusion'; - - type Gravity = number | string; - - interface GravityEnum { - north: number; - northeast: number; - southeast: number; - south: number; - southwest: number; - west: number; - northwest: number; - east: number; - center: number; - centre: number; - } - - interface StrategyEnum { - entropy: number; - attention: number; - } - - interface FormatEnum { - avif: AvailableFormatInfo; - dz: AvailableFormatInfo; - fits: AvailableFormatInfo; - gif: AvailableFormatInfo; - heif: AvailableFormatInfo; - input: AvailableFormatInfo; - jpeg: AvailableFormatInfo; - jpg: AvailableFormatInfo; - jp2: AvailableFormatInfo; - jxl: AvailableFormatInfo; - magick: AvailableFormatInfo; - openslide: AvailableFormatInfo; - pdf: AvailableFormatInfo; - png: AvailableFormatInfo; - ppm: AvailableFormatInfo; - raw: AvailableFormatInfo; - svg: AvailableFormatInfo; - tiff: AvailableFormatInfo; - tif: AvailableFormatInfo; - v: AvailableFormatInfo; - webp: AvailableFormatInfo; - } - - interface CacheResult { - memory: { current: number; high: number; max: number }; - files: { current: number; max: number }; - items: { current: number; max: number }; - } - - interface Interpolators { - /** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */ - nearest: 'nearest'; - /** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */ - bilinear: 'bilinear'; - /** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */ - bicubic: 'bicubic'; - /** - * [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). - * Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2. - */ - locallyBoundedBicubic: 'lbb'; - /** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */ - nohalo: 'nohalo'; - /** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */ - vertexSplitQuadraticBasisSpline: 'vsqbs'; - } - - type Matrix2x2 = [[number, number], [number, number]]; - type Matrix3x3 = [[number, number, number], [number, number, number], [number, number, number]]; -} - -export = sharp; diff --git a/node_modules/sharp/lib/index.js b/node_modules/sharp/lib/index.js deleted file mode 100644 index 8cfc08a8..00000000 --- a/node_modules/sharp/lib/index.js +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const Sharp = require('./constructor'); -require('./input')(Sharp); -require('./resize')(Sharp); -require('./composite')(Sharp); -require('./operation')(Sharp); -require('./colour')(Sharp); -require('./channel')(Sharp); -require('./output')(Sharp); -require('./utility')(Sharp); - -module.exports = Sharp; diff --git a/node_modules/sharp/lib/input.js b/node_modules/sharp/lib/input.js deleted file mode 100644 index e212dc14..00000000 --- a/node_modules/sharp/lib/input.js +++ /dev/null @@ -1,657 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const color = require('color'); -const is = require('./is'); -const sharp = require('./sharp'); - -/** - * Justication alignment - * @member - * @private - */ -const align = { - left: 'low', - center: 'centre', - centre: 'centre', - right: 'high' -}; - -/** - * Extract input options, if any, from an object. - * @private - */ -function _inputOptionsFromObject (obj) { - const { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } = obj; - return [raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd].some(is.defined) - ? { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } - : undefined; -} - -/** - * Create Object containing input and input-related options. - * @private - */ -function _createInputDescriptor (input, inputOptions, containerOptions) { - const inputDescriptor = { - failOn: 'warning', - limitInputPixels: Math.pow(0x3FFF, 2), - ignoreIcc: false, - unlimited: false, - sequentialRead: true - }; - if (is.string(input)) { - // filesystem - inputDescriptor.file = input; - } else if (is.buffer(input)) { - // Buffer - if (input.length === 0) { - throw Error('Input Buffer is empty'); - } - inputDescriptor.buffer = input; - } else if (is.arrayBuffer(input)) { - if (input.byteLength === 0) { - throw Error('Input bit Array is empty'); - } - inputDescriptor.buffer = Buffer.from(input, 0, input.byteLength); - } else if (is.typedArray(input)) { - if (input.length === 0) { - throw Error('Input Bit Array is empty'); - } - inputDescriptor.buffer = Buffer.from(input.buffer, input.byteOffset, input.byteLength); - } else if (is.plainObject(input) && !is.defined(inputOptions)) { - // Plain Object descriptor, e.g. create - inputOptions = input; - if (_inputOptionsFromObject(inputOptions)) { - // Stream with options - inputDescriptor.buffer = []; - } - } else if (!is.defined(input) && !is.defined(inputOptions) && is.object(containerOptions) && containerOptions.allowStream) { - // Stream without options - inputDescriptor.buffer = []; - } else { - throw new Error(`Unsupported input '${input}' of type ${typeof input}${ - is.defined(inputOptions) ? ` when also providing options of type ${typeof inputOptions}` : '' - }`); - } - if (is.object(inputOptions)) { - // Deprecated: failOnError - if (is.defined(inputOptions.failOnError)) { - if (is.bool(inputOptions.failOnError)) { - inputDescriptor.failOn = inputOptions.failOnError ? 'warning' : 'none'; - } else { - throw is.invalidParameterError('failOnError', 'boolean', inputOptions.failOnError); - } - } - // failOn - if (is.defined(inputOptions.failOn)) { - if (is.string(inputOptions.failOn) && is.inArray(inputOptions.failOn, ['none', 'truncated', 'error', 'warning'])) { - inputDescriptor.failOn = inputOptions.failOn; - } else { - throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn); - } - } - // Density - if (is.defined(inputOptions.density)) { - if (is.inRange(inputOptions.density, 1, 100000)) { - inputDescriptor.density = inputOptions.density; - } else { - throw is.invalidParameterError('density', 'number between 1 and 100000', inputOptions.density); - } - } - // Ignore embeddded ICC profile - if (is.defined(inputOptions.ignoreIcc)) { - if (is.bool(inputOptions.ignoreIcc)) { - inputDescriptor.ignoreIcc = inputOptions.ignoreIcc; - } else { - throw is.invalidParameterError('ignoreIcc', 'boolean', inputOptions.ignoreIcc); - } - } - // limitInputPixels - if (is.defined(inputOptions.limitInputPixels)) { - if (is.bool(inputOptions.limitInputPixels)) { - inputDescriptor.limitInputPixels = inputOptions.limitInputPixels - ? Math.pow(0x3FFF, 2) - : 0; - } else if (is.integer(inputOptions.limitInputPixels) && is.inRange(inputOptions.limitInputPixels, 0, Number.MAX_SAFE_INTEGER)) { - inputDescriptor.limitInputPixels = inputOptions.limitInputPixels; - } else { - throw is.invalidParameterError('limitInputPixels', 'positive integer', inputOptions.limitInputPixels); - } - } - // unlimited - if (is.defined(inputOptions.unlimited)) { - if (is.bool(inputOptions.unlimited)) { - inputDescriptor.unlimited = inputOptions.unlimited; - } else { - throw is.invalidParameterError('unlimited', 'boolean', inputOptions.unlimited); - } - } - // sequentialRead - if (is.defined(inputOptions.sequentialRead)) { - if (is.bool(inputOptions.sequentialRead)) { - inputDescriptor.sequentialRead = inputOptions.sequentialRead; - } else { - throw is.invalidParameterError('sequentialRead', 'boolean', inputOptions.sequentialRead); - } - } - // Raw pixel input - if (is.defined(inputOptions.raw)) { - if ( - is.object(inputOptions.raw) && - is.integer(inputOptions.raw.width) && inputOptions.raw.width > 0 && - is.integer(inputOptions.raw.height) && inputOptions.raw.height > 0 && - is.integer(inputOptions.raw.channels) && is.inRange(inputOptions.raw.channels, 1, 4) - ) { - inputDescriptor.rawWidth = inputOptions.raw.width; - inputDescriptor.rawHeight = inputOptions.raw.height; - inputDescriptor.rawChannels = inputOptions.raw.channels; - inputDescriptor.rawPremultiplied = !!inputOptions.raw.premultiplied; - - switch (input.constructor) { - case Uint8Array: - case Uint8ClampedArray: - inputDescriptor.rawDepth = 'uchar'; - break; - case Int8Array: - inputDescriptor.rawDepth = 'char'; - break; - case Uint16Array: - inputDescriptor.rawDepth = 'ushort'; - break; - case Int16Array: - inputDescriptor.rawDepth = 'short'; - break; - case Uint32Array: - inputDescriptor.rawDepth = 'uint'; - break; - case Int32Array: - inputDescriptor.rawDepth = 'int'; - break; - case Float32Array: - inputDescriptor.rawDepth = 'float'; - break; - case Float64Array: - inputDescriptor.rawDepth = 'double'; - break; - default: - inputDescriptor.rawDepth = 'uchar'; - break; - } - } else { - throw new Error('Expected width, height and channels for raw pixel input'); - } - } - // Multi-page input (GIF, TIFF, PDF) - if (is.defined(inputOptions.animated)) { - if (is.bool(inputOptions.animated)) { - inputDescriptor.pages = inputOptions.animated ? -1 : 1; - } else { - throw is.invalidParameterError('animated', 'boolean', inputOptions.animated); - } - } - if (is.defined(inputOptions.pages)) { - if (is.integer(inputOptions.pages) && is.inRange(inputOptions.pages, -1, 100000)) { - inputDescriptor.pages = inputOptions.pages; - } else { - throw is.invalidParameterError('pages', 'integer between -1 and 100000', inputOptions.pages); - } - } - if (is.defined(inputOptions.page)) { - if (is.integer(inputOptions.page) && is.inRange(inputOptions.page, 0, 100000)) { - inputDescriptor.page = inputOptions.page; - } else { - throw is.invalidParameterError('page', 'integer between 0 and 100000', inputOptions.page); - } - } - // Multi-level input (OpenSlide) - if (is.defined(inputOptions.level)) { - if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) { - inputDescriptor.level = inputOptions.level; - } else { - throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level); - } - } - // Sub Image File Directory (TIFF) - if (is.defined(inputOptions.subifd)) { - if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) { - inputDescriptor.subifd = inputOptions.subifd; - } else { - throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd); - } - } - // Create new image - if (is.defined(inputOptions.create)) { - if ( - is.object(inputOptions.create) && - is.integer(inputOptions.create.width) && inputOptions.create.width > 0 && - is.integer(inputOptions.create.height) && inputOptions.create.height > 0 && - is.integer(inputOptions.create.channels) - ) { - inputDescriptor.createWidth = inputOptions.create.width; - inputDescriptor.createHeight = inputOptions.create.height; - inputDescriptor.createChannels = inputOptions.create.channels; - // Noise - if (is.defined(inputOptions.create.noise)) { - if (!is.object(inputOptions.create.noise)) { - throw new Error('Expected noise to be an object'); - } - if (!is.inArray(inputOptions.create.noise.type, ['gaussian'])) { - throw new Error('Only gaussian noise is supported at the moment'); - } - if (!is.inRange(inputOptions.create.channels, 1, 4)) { - throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels); - } - inputDescriptor.createNoiseType = inputOptions.create.noise.type; - if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) { - inputDescriptor.createNoiseMean = inputOptions.create.noise.mean; - } else { - throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean); - } - if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) { - inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma; - } else { - throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma); - } - } else if (is.defined(inputOptions.create.background)) { - if (!is.inRange(inputOptions.create.channels, 3, 4)) { - throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels); - } - const background = color(inputOptions.create.background); - inputDescriptor.createBackground = [ - background.red(), - background.green(), - background.blue(), - Math.round(background.alpha() * 255) - ]; - } else { - throw new Error('Expected valid noise or background to create a new input image'); - } - delete inputDescriptor.buffer; - } else { - throw new Error('Expected valid width, height and channels to create a new input image'); - } - } - // Create a new image with text - if (is.defined(inputOptions.text)) { - if (is.object(inputOptions.text) && is.string(inputOptions.text.text)) { - inputDescriptor.textValue = inputOptions.text.text; - if (is.defined(inputOptions.text.height) && is.defined(inputOptions.text.dpi)) { - throw new Error('Expected only one of dpi or height'); - } - if (is.defined(inputOptions.text.font)) { - if (is.string(inputOptions.text.font)) { - inputDescriptor.textFont = inputOptions.text.font; - } else { - throw is.invalidParameterError('text.font', 'string', inputOptions.text.font); - } - } - if (is.defined(inputOptions.text.fontfile)) { - if (is.string(inputOptions.text.fontfile)) { - inputDescriptor.textFontfile = inputOptions.text.fontfile; - } else { - throw is.invalidParameterError('text.fontfile', 'string', inputOptions.text.fontfile); - } - } - if (is.defined(inputOptions.text.width)) { - if (is.number(inputOptions.text.width)) { - inputDescriptor.textWidth = inputOptions.text.width; - } else { - throw is.invalidParameterError('text.textWidth', 'number', inputOptions.text.width); - } - } - if (is.defined(inputOptions.text.height)) { - if (is.number(inputOptions.text.height)) { - inputDescriptor.textHeight = inputOptions.text.height; - } else { - throw is.invalidParameterError('text.height', 'number', inputOptions.text.height); - } - } - if (is.defined(inputOptions.text.align)) { - if (is.string(inputOptions.text.align) && is.string(this.constructor.align[inputOptions.text.align])) { - inputDescriptor.textAlign = this.constructor.align[inputOptions.text.align]; - } else { - throw is.invalidParameterError('text.align', 'valid alignment', inputOptions.text.align); - } - } - if (is.defined(inputOptions.text.justify)) { - if (is.bool(inputOptions.text.justify)) { - inputDescriptor.textJustify = inputOptions.text.justify; - } else { - throw is.invalidParameterError('text.justify', 'boolean', inputOptions.text.justify); - } - } - if (is.defined(inputOptions.text.dpi)) { - if (is.number(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 100000)) { - inputDescriptor.textDpi = inputOptions.text.dpi; - } else { - throw is.invalidParameterError('text.dpi', 'number between 1 and 100000', inputOptions.text.dpi); - } - } - if (is.defined(inputOptions.text.rgba)) { - if (is.bool(inputOptions.text.rgba)) { - inputDescriptor.textRgba = inputOptions.text.rgba; - } else { - throw is.invalidParameterError('text.rgba', 'bool', inputOptions.text.rgba); - } - } - if (is.defined(inputOptions.text.spacing)) { - if (is.number(inputOptions.text.spacing)) { - inputDescriptor.textSpacing = inputOptions.text.spacing; - } else { - throw is.invalidParameterError('text.spacing', 'number', inputOptions.text.spacing); - } - } - if (is.defined(inputOptions.text.wrap)) { - if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'word-char', 'none'])) { - inputDescriptor.textWrap = inputOptions.text.wrap; - } else { - throw is.invalidParameterError('text.wrap', 'one of: word, char, word-char, none', inputOptions.text.wrap); - } - } - delete inputDescriptor.buffer; - } else { - throw new Error('Expected a valid string to create an image with text.'); - } - } - } else if (is.defined(inputOptions)) { - throw new Error('Invalid input options ' + inputOptions); - } - return inputDescriptor; -} - -/** - * Handle incoming Buffer chunk on Writable Stream. - * @private - * @param {Buffer} chunk - * @param {string} encoding - unused - * @param {Function} callback - */ -function _write (chunk, encoding, callback) { - /* istanbul ignore else */ - if (Array.isArray(this.options.input.buffer)) { - /* istanbul ignore else */ - if (is.buffer(chunk)) { - if (this.options.input.buffer.length === 0) { - this.on('finish', () => { - this.streamInFinished = true; - }); - } - this.options.input.buffer.push(chunk); - callback(); - } else { - callback(new Error('Non-Buffer data on Writable Stream')); - } - } else { - callback(new Error('Unexpected data on Writable Stream')); - } -} - -/** - * Flattens the array of chunks accumulated in input.buffer. - * @private - */ -function _flattenBufferIn () { - if (this._isStreamInput()) { - this.options.input.buffer = Buffer.concat(this.options.input.buffer); - } -} - -/** - * Are we expecting Stream-based input? - * @private - * @returns {boolean} - */ -function _isStreamInput () { - return Array.isArray(this.options.input.buffer); -} - -/** - * Fast access to (uncached) image metadata without decoding any compressed pixel data. - * - * This is read from the header of the input image. - * It does not take into consideration any operations to be applied to the output image, - * such as resize or rotate. - * - * Dimensions in the response will respect the `page` and `pages` properties of the - * {@link /api-constructor#parameters|constructor parameters}. - * - * A `Promise` is returned when `callback` is not provided. - * - * - `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg` - * - `size`: Total size of image in bytes, for Stream and Buffer input only - * - `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below) - * - `height`: Number of pixels high (EXIF orientation is not taken into consideration, see example below) - * - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://www.libvips.org/API/current/VipsImage.html#VipsInterpretation) - * - `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK - * - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://www.libvips.org/API/current/VipsImage.html#VipsBandFormat) - * - `density`: Number of pixels per inch (DPI), if present - * - `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK - * - `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan - * - `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP - * - `pageHeight`: Number of pixels high each page in a multi-page image will be. - * - `paletteBitDepth`: Bit depth of palette-based image (GIF, PNG). - * - `loop`: Number of times to loop an animated image, zero refers to a continuous loop. - * - `delay`: Delay in ms between each page in an animated image, provided as an array of integers. - * - `pagePrimary`: Number of the primary page in a HEIF image - * - `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide - * - `subifds`: Number of Sub Image File Directories in an OME-TIFF image - * - `background`: Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value - * - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) - * - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present - * - `hasProfile`: Boolean indicating the presence of an embedded ICC profile - * - `hasAlpha`: Boolean indicating the presence of an alpha transparency channel - * - `orientation`: Number value of the EXIF Orientation header, if present - * - `exif`: Buffer containing raw EXIF data, if present - * - `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present - * - `iptc`: Buffer containing raw IPTC data, if present - * - `xmp`: Buffer containing raw XMP data, if present - * - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present - * - `formatMagick`: String containing format for images loaded via *magick - * - * @example - * const metadata = await sharp(input).metadata(); - * - * @example - * const image = sharp(inputJpg); - * image - * .metadata() - * .then(function(metadata) { - * return image - * .resize(Math.round(metadata.width / 2)) - * .webp() - * .toBuffer(); - * }) - * .then(function(data) { - * // data contains a WebP image half the width and height of the original JPEG - * }); - * - * @example - * // Based on EXIF rotation metadata, get the right-side-up width and height: - * - * const size = getNormalSize(await sharp(input).metadata()); - * - * function getNormalSize({ width, height, orientation }) { - * return (orientation || 0) >= 5 - * ? { width: height, height: width } - * : { width, height }; - * } - * - * @param {Function} [callback] - called with the arguments `(err, metadata)` - * @returns {Promise|Sharp} - */ -function metadata (callback) { - const stack = Error(); - if (is.fn(callback)) { - if (this._isStreamInput()) { - this.on('finish', () => { - this._flattenBufferIn(); - sharp.metadata(this.options, (err, metadata) => { - if (err) { - callback(is.nativeError(err, stack)); - } else { - callback(null, metadata); - } - }); - }); - } else { - sharp.metadata(this.options, (err, metadata) => { - if (err) { - callback(is.nativeError(err, stack)); - } else { - callback(null, metadata); - } - }); - } - return this; - } else { - if (this._isStreamInput()) { - return new Promise((resolve, reject) => { - const finished = () => { - this._flattenBufferIn(); - sharp.metadata(this.options, (err, metadata) => { - if (err) { - reject(is.nativeError(err, stack)); - } else { - resolve(metadata); - } - }); - }; - if (this.writableFinished) { - finished(); - } else { - this.once('finish', finished); - } - }); - } else { - return new Promise((resolve, reject) => { - sharp.metadata(this.options, (err, metadata) => { - if (err) { - reject(is.nativeError(err, stack)); - } else { - resolve(metadata); - } - }); - }); - } - } -} - -/** - * Access to pixel-derived image statistics for every channel in the image. - * A `Promise` is returned when `callback` is not provided. - * - * - `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains - * - `min` (minimum value in the channel) - * - `max` (maximum value in the channel) - * - `sum` (sum of all values in a channel) - * - `squaresSum` (sum of squared values in a channel) - * - `mean` (mean of the values in a channel) - * - `stdev` (standard deviation for the values in a channel) - * - `minX` (x-coordinate of one of the pixel where the minimum lies) - * - `minY` (y-coordinate of one of the pixel where the minimum lies) - * - `maxX` (x-coordinate of one of the pixel where the maximum lies) - * - `maxY` (y-coordinate of one of the pixel where the maximum lies) - * - `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque. - * - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any. - * - `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any. - * - `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram. - * - * **Note**: Statistics are derived from the original input image. Any operations performed on the image must first be - * written to a buffer in order to run `stats` on the result (see third example). - * - * @example - * const image = sharp(inputJpg); - * image - * .stats() - * .then(function(stats) { - * // stats contains the channel-wise statistics array and the isOpaque value - * }); - * - * @example - * const { entropy, sharpness, dominant } = await sharp(input).stats(); - * const { r, g, b } = dominant; - * - * @example - * const image = sharp(input); - * // store intermediate result - * const part = await image.extract(region).toBuffer(); - * // create new instance to obtain statistics of extracted region - * const stats = await sharp(part).stats(); - * - * @param {Function} [callback] - called with the arguments `(err, stats)` - * @returns {Promise} - */ -function stats (callback) { - const stack = Error(); - if (is.fn(callback)) { - if (this._isStreamInput()) { - this.on('finish', () => { - this._flattenBufferIn(); - sharp.stats(this.options, (err, stats) => { - if (err) { - callback(is.nativeError(err, stack)); - } else { - callback(null, stats); - } - }); - }); - } else { - sharp.stats(this.options, (err, stats) => { - if (err) { - callback(is.nativeError(err, stack)); - } else { - callback(null, stats); - } - }); - } - return this; - } else { - if (this._isStreamInput()) { - return new Promise((resolve, reject) => { - this.on('finish', function () { - this._flattenBufferIn(); - sharp.stats(this.options, (err, stats) => { - if (err) { - reject(is.nativeError(err, stack)); - } else { - resolve(stats); - } - }); - }); - }); - } else { - return new Promise((resolve, reject) => { - sharp.stats(this.options, (err, stats) => { - if (err) { - reject(is.nativeError(err, stack)); - } else { - resolve(stats); - } - }); - }); - } - } -} - -/** - * Decorate the Sharp prototype with input-related functions. - * @private - */ -module.exports = function (Sharp) { - Object.assign(Sharp.prototype, { - // Private - _inputOptionsFromObject, - _createInputDescriptor, - _write, - _flattenBufferIn, - _isStreamInput, - // Public - metadata, - stats - }); - // Class attributes - Sharp.align = align; -}; diff --git a/node_modules/sharp/lib/is.js b/node_modules/sharp/lib/is.js deleted file mode 100644 index a63cb206..00000000 --- a/node_modules/sharp/lib/is.js +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -/** - * Is this value defined and not null? - * @private - */ -const defined = function (val) { - return typeof val !== 'undefined' && val !== null; -}; - -/** - * Is this value an object? - * @private - */ -const object = function (val) { - return typeof val === 'object'; -}; - -/** - * Is this value a plain object? - * @private - */ -const plainObject = function (val) { - return Object.prototype.toString.call(val) === '[object Object]'; -}; - -/** - * Is this value a function? - * @private - */ -const fn = function (val) { - return typeof val === 'function'; -}; - -/** - * Is this value a boolean? - * @private - */ -const bool = function (val) { - return typeof val === 'boolean'; -}; - -/** - * Is this value a Buffer object? - * @private - */ -const buffer = function (val) { - return val instanceof Buffer; -}; - -/** - * Is this value a typed array object?. E.g. Uint8Array or Uint8ClampedArray? - * @private - */ -const typedArray = function (val) { - if (defined(val)) { - switch (val.constructor) { - case Uint8Array: - case Uint8ClampedArray: - case Int8Array: - case Uint16Array: - case Int16Array: - case Uint32Array: - case Int32Array: - case Float32Array: - case Float64Array: - return true; - } - } - - return false; -}; - -/** - * Is this value an ArrayBuffer object? - * @private - */ -const arrayBuffer = function (val) { - return val instanceof ArrayBuffer; -}; - -/** - * Is this value a non-empty string? - * @private - */ -const string = function (val) { - return typeof val === 'string' && val.length > 0; -}; - -/** - * Is this value a real number? - * @private - */ -const number = function (val) { - return typeof val === 'number' && !Number.isNaN(val); -}; - -/** - * Is this value an integer? - * @private - */ -const integer = function (val) { - return Number.isInteger(val); -}; - -/** - * Is this value within an inclusive given range? - * @private - */ -const inRange = function (val, min, max) { - return val >= min && val <= max; -}; - -/** - * Is this value within the elements of an array? - * @private - */ -const inArray = function (val, list) { - return list.includes(val); -}; - -/** - * Create an Error with a message relating to an invalid parameter. - * - * @param {string} name - parameter name. - * @param {string} expected - description of the type/value/range expected. - * @param {*} actual - the value received. - * @returns {Error} Containing the formatted message. - * @private - */ -const invalidParameterError = function (name, expected, actual) { - return new Error( - `Expected ${expected} for ${name} but received ${actual} of type ${typeof actual}` - ); -}; - -/** - * Ensures an Error from C++ contains a JS stack. - * - * @param {Error} native - Error with message from C++. - * @param {Error} context - Error with stack from JS. - * @returns {Error} Error with message and stack. - * @private - */ -const nativeError = function (native, context) { - context.message = native.message; - return context; -}; - -module.exports = { - defined, - object, - plainObject, - fn, - bool, - buffer, - typedArray, - arrayBuffer, - string, - number, - integer, - inRange, - inArray, - invalidParameterError, - nativeError -}; diff --git a/node_modules/sharp/lib/libvips.js b/node_modules/sharp/lib/libvips.js deleted file mode 100644 index a24c70eb..00000000 --- a/node_modules/sharp/lib/libvips.js +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const { spawnSync } = require('node:child_process'); -const { createHash } = require('node:crypto'); -const semverCoerce = require('semver/functions/coerce'); -const semverGreaterThanOrEqualTo = require('semver/functions/gte'); -const semverSatisfies = require('semver/functions/satisfies'); -const detectLibc = require('detect-libc'); - -const { engines, optionalDependencies } = require('../package.json'); - -const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || /* istanbul ignore next */ - engines.libvips; -const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version; - -const prebuiltPlatforms = [ - 'darwin-arm64', 'darwin-x64', - 'linux-arm', 'linux-arm64', 'linux-s390x', 'linux-x64', - 'linuxmusl-arm64', 'linuxmusl-x64', - 'win32-ia32', 'win32-x64' -]; - -const spawnSyncOptions = { - encoding: 'utf8', - shell: true -}; - -const log = (item) => { - if (item instanceof Error) { - console.error(`sharp: Installation error: ${item.message}`); - } else { - console.log(`sharp: ${item}`); - } -}; - -/* istanbul ignore next */ -const runtimeLibc = () => detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : ''; - -const runtimePlatformArch = () => `${process.platform}${runtimeLibc()}-${process.arch}`; - -/* istanbul ignore next */ -const buildPlatformArch = () => { - if (isEmscripten()) { - return 'wasm32'; - } - /* eslint camelcase: ["error", { allow: ["^npm_config_"] }] */ - const { npm_config_arch, npm_config_platform, npm_config_libc } = process.env; - const libc = typeof npm_config_libc === 'string' ? npm_config_libc : runtimeLibc(); - return `${npm_config_platform || process.platform}${libc}-${npm_config_arch || process.arch}`; -}; - -const buildSharpLibvipsIncludeDir = () => { - try { - return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/include`); - } catch { - try { - return require('@img/sharp-libvips-dev/include'); - } catch {} - } - /* istanbul ignore next */ - return ''; -}; - -const buildSharpLibvipsCPlusPlusDir = () => { - try { - return require('@img/sharp-libvips-dev/cplusplus'); - } catch {} - /* istanbul ignore next */ - return ''; -}; - -const buildSharpLibvipsLibDir = () => { - try { - return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/lib`); - } catch { - try { - return require(`@img/sharp-libvips-${buildPlatformArch()}/lib`); - } catch {} - } - /* istanbul ignore next */ - return ''; -}; - -const isUnsupportedNodeRuntime = () => { - /* istanbul ignore next */ - if (process.release?.name === 'node' && process.versions) { - if (!semverSatisfies(process.versions.node, engines.node)) { - return { found: process.versions.node, expected: engines.node }; - } - } -}; - -/* istanbul ignore next */ -const isEmscripten = () => { - const { CC } = process.env; - return Boolean(CC && CC.endsWith('/emcc')); -}; - -const isRosetta = () => { - /* istanbul ignore next */ - if (process.platform === 'darwin' && process.arch === 'x64') { - const translated = spawnSync('sysctl sysctl.proc_translated', spawnSyncOptions).stdout; - return (translated || '').trim() === 'sysctl.proc_translated: 1'; - } - return false; -}; - -const sha512 = (s) => createHash('sha512').update(s).digest('hex'); - -const yarnLocator = () => { - try { - const identHash = sha512(`imgsharp-libvips-${buildPlatformArch()}`); - const npmVersion = semverCoerce(optionalDependencies[`@img/sharp-libvips-${buildPlatformArch()}`]).version; - return sha512(`${identHash}npm:${npmVersion}`).slice(0, 10); - } catch {} - return ''; -}; - -/* istanbul ignore next */ -const spawnRebuild = () => - spawnSync(`node-gyp rebuild --directory=src ${isEmscripten() ? '--nodedir=emscripten' : ''}`, { - ...spawnSyncOptions, - stdio: 'inherit' - }).status; - -const globalLibvipsVersion = () => { - if (process.platform !== 'win32') { - const globalLibvipsVersion = spawnSync('pkg-config --modversion vips-cpp', { - ...spawnSyncOptions, - env: { - ...process.env, - PKG_CONFIG_PATH: pkgConfigPath() - } - }).stdout; - /* istanbul ignore next */ - return (globalLibvipsVersion || '').trim(); - } else { - return ''; - } -}; - -/* istanbul ignore next */ -const pkgConfigPath = () => { - if (process.platform !== 'win32') { - const brewPkgConfigPath = spawnSync( - 'which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d" " -f2', - spawnSyncOptions - ).stdout || ''; - return [ - brewPkgConfigPath.trim(), - process.env.PKG_CONFIG_PATH, - '/usr/local/lib/pkgconfig', - '/usr/lib/pkgconfig', - '/usr/local/libdata/pkgconfig', - '/usr/libdata/pkgconfig' - ].filter(Boolean).join(':'); - } else { - return ''; - } -}; - -const useGlobalLibvips = () => { - if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) { - log('Detected SHARP_IGNORE_GLOBAL_LIBVIPS, skipping search for globally-installed libvips'); - return false; - } - /* istanbul ignore next */ - if (isRosetta()) { - log('Detected Rosetta, skipping search for globally-installed libvips'); - return false; - } - const globalVipsVersion = globalLibvipsVersion(); - return !!globalVipsVersion && /* istanbul ignore next */ - semverGreaterThanOrEqualTo(globalVipsVersion, minimumLibvipsVersion); -}; - -module.exports = { - minimumLibvipsVersion, - prebuiltPlatforms, - buildPlatformArch, - buildSharpLibvipsIncludeDir, - buildSharpLibvipsCPlusPlusDir, - buildSharpLibvipsLibDir, - isUnsupportedNodeRuntime, - runtimePlatformArch, - log, - yarnLocator, - spawnRebuild, - globalLibvipsVersion, - pkgConfigPath, - useGlobalLibvips -}; diff --git a/node_modules/sharp/lib/operation.js b/node_modules/sharp/lib/operation.js deleted file mode 100644 index ed6df834..00000000 --- a/node_modules/sharp/lib/operation.js +++ /dev/null @@ -1,921 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const color = require('color'); -const is = require('./is'); - -/** - * Rotate the output image by either an explicit angle - * or auto-orient based on the EXIF `Orientation` tag. - * - * If an angle is provided, it is converted to a valid positive degree rotation. - * For example, `-450` will produce a 270 degree rotation. - * - * When rotating by an angle other than a multiple of 90, - * the background colour can be provided with the `background` option. - * - * If no angle is provided, it is determined from the EXIF data. - * Mirroring is supported and may infer the use of a flip operation. - * - * The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any. - * - * Only one rotation can occur per pipeline. - * Previous calls to `rotate` in the same pipeline will be ignored. - * - * Multi-page images can only be rotated by 180 degrees. - * - * Method order is important when rotating, resizing and/or extracting regions, - * for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`. - * - * @example - * const pipeline = sharp() - * .rotate() - * .resize(null, 200) - * .toBuffer(function (err, outputBuffer, info) { - * // outputBuffer contains 200px high JPEG image data, - * // auto-rotated using EXIF Orientation tag - * // info.width and info.height contain the dimensions of the resized image - * }); - * readableStream.pipe(pipeline); - * - * @example - * const rotateThenResize = await sharp(input) - * .rotate(90) - * .resize({ width: 16, height: 8, fit: 'fill' }) - * .toBuffer(); - * const resizeThenRotate = await sharp(input) - * .resize({ width: 16, height: 8, fit: 'fill' }) - * .rotate(90) - * .toBuffer(); - * - * @param {number} [angle=auto] angle of rotation. - * @param {Object} [options] - if present, is an Object with optional attributes. - * @param {string|Object} [options.background="#000000"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function rotate (angle, options) { - if (this.options.useExifOrientation || this.options.angle || this.options.rotationAngle) { - this.options.debuglog('ignoring previous rotate options'); - } - if (!is.defined(angle)) { - this.options.useExifOrientation = true; - } else if (is.integer(angle) && !(angle % 90)) { - this.options.angle = angle; - } else if (is.number(angle)) { - this.options.rotationAngle = angle; - if (is.object(options) && options.background) { - const backgroundColour = color(options.background); - this.options.rotationBackground = [ - backgroundColour.red(), - backgroundColour.green(), - backgroundColour.blue(), - Math.round(backgroundColour.alpha() * 255) - ]; - } - } else { - throw is.invalidParameterError('angle', 'numeric', angle); - } - return this; -} - -/** - * Mirror the image vertically (up-down) about the x-axis. - * This always occurs before rotation, if any. - * - * This operation does not work correctly with multi-page images. - * - * @example - * const output = await sharp(input).flip().toBuffer(); - * - * @param {Boolean} [flip=true] - * @returns {Sharp} - */ -function flip (flip) { - this.options.flip = is.bool(flip) ? flip : true; - return this; -} - -/** - * Mirror the image horizontally (left-right) about the y-axis. - * This always occurs before rotation, if any. - * - * @example - * const output = await sharp(input).flop().toBuffer(); - * - * @param {Boolean} [flop=true] - * @returns {Sharp} - */ -function flop (flop) { - this.options.flop = is.bool(flop) ? flop : true; - return this; -} - -/** - * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any. - * - * You must provide an array of length 4 or a 2x2 affine transformation matrix. - * By default, new pixels are filled with a black background. You can provide a background color with the `background` option. - * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`. - * - * In the case of a 2x2 matrix, the transform is: - * - X = `matrix[0, 0]` \* (x + `idx`) + `matrix[0, 1]` \* (y + `idy`) + `odx` - * - Y = `matrix[1, 0]` \* (x + `idx`) + `matrix[1, 1]` \* (y + `idy`) + `ody` - * - * where: - * - x and y are the coordinates in input image. - * - X and Y are the coordinates in output image. - * - (0,0) is the upper left corner. - * - * @since 0.27.0 - * - * @example - * const pipeline = sharp() - * .affine([[1, 0.3], [0.1, 0.7]], { - * background: 'white', - * interpolator: sharp.interpolators.nohalo - * }) - * .toBuffer((err, outputBuffer, info) => { - * // outputBuffer contains the transformed image - * // info.width and info.height contain the new dimensions - * }); - * - * inputStream - * .pipe(pipeline); - * - * @param {Array>|Array} matrix - affine transformation matrix - * @param {Object} [options] - if present, is an Object with optional attributes. - * @param {String|Object} [options.background="#000000"] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. - * @param {Number} [options.idx=0] - input horizontal offset - * @param {Number} [options.idy=0] - input vertical offset - * @param {Number} [options.odx=0] - output horizontal offset - * @param {Number} [options.ody=0] - output vertical offset - * @param {String} [options.interpolator=sharp.interpolators.bicubic] - interpolator - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function affine (matrix, options) { - const flatMatrix = [].concat(...matrix); - if (flatMatrix.length === 4 && flatMatrix.every(is.number)) { - this.options.affineMatrix = flatMatrix; - } else { - throw is.invalidParameterError('matrix', '1x4 or 2x2 array', matrix); - } - - if (is.defined(options)) { - if (is.object(options)) { - this._setBackgroundColourOption('affineBackground', options.background); - if (is.defined(options.idx)) { - if (is.number(options.idx)) { - this.options.affineIdx = options.idx; - } else { - throw is.invalidParameterError('options.idx', 'number', options.idx); - } - } - if (is.defined(options.idy)) { - if (is.number(options.idy)) { - this.options.affineIdy = options.idy; - } else { - throw is.invalidParameterError('options.idy', 'number', options.idy); - } - } - if (is.defined(options.odx)) { - if (is.number(options.odx)) { - this.options.affineOdx = options.odx; - } else { - throw is.invalidParameterError('options.odx', 'number', options.odx); - } - } - if (is.defined(options.ody)) { - if (is.number(options.ody)) { - this.options.affineOdy = options.ody; - } else { - throw is.invalidParameterError('options.ody', 'number', options.ody); - } - } - if (is.defined(options.interpolator)) { - if (is.inArray(options.interpolator, Object.values(this.constructor.interpolators))) { - this.options.affineInterpolator = options.interpolator; - } else { - throw is.invalidParameterError('options.interpolator', 'valid interpolator name', options.interpolator); - } - } - } else { - throw is.invalidParameterError('options', 'object', options); - } - } - - return this; -} - -/** - * Sharpen the image. - * - * When used without parameters, performs a fast, mild sharpen of the output image. - * - * When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. - * Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available. - * - * See {@link https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen|libvips sharpen} operation. - * - * @example - * const data = await sharp(input).sharpen().toBuffer(); - * - * @example - * const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer(); - * - * @example - * const data = await sharp(input) - * .sharpen({ - * sigma: 2, - * m1: 0, - * m2: 3, - * x1: 3, - * y2: 15, - * y3: 15, - * }) - * .toBuffer(); - * - * @param {Object|number} [options] - if present, is an Object with attributes - * @param {number} [options.sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10 - * @param {number} [options.m1=1.0] - the level of sharpening to apply to "flat" areas, between 0 and 1000000 - * @param {number} [options.m2=2.0] - the level of sharpening to apply to "jagged" areas, between 0 and 1000000 - * @param {number} [options.x1=2.0] - threshold between "flat" and "jagged", between 0 and 1000000 - * @param {number} [options.y2=10.0] - maximum amount of brightening, between 0 and 1000000 - * @param {number} [options.y3=20.0] - maximum amount of darkening, between 0 and 1000000 - * @param {number} [flat] - (deprecated) see `options.m1`. - * @param {number} [jagged] - (deprecated) see `options.m2`. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function sharpen (options, flat, jagged) { - if (!is.defined(options)) { - // No arguments: default to mild sharpen - this.options.sharpenSigma = -1; - } else if (is.bool(options)) { - // Deprecated boolean argument: apply mild sharpen? - this.options.sharpenSigma = options ? -1 : 0; - } else if (is.number(options) && is.inRange(options, 0.01, 10000)) { - // Deprecated numeric argument: specific sigma - this.options.sharpenSigma = options; - // Deprecated control over flat areas - if (is.defined(flat)) { - if (is.number(flat) && is.inRange(flat, 0, 10000)) { - this.options.sharpenM1 = flat; - } else { - throw is.invalidParameterError('flat', 'number between 0 and 10000', flat); - } - } - // Deprecated control over jagged areas - if (is.defined(jagged)) { - if (is.number(jagged) && is.inRange(jagged, 0, 10000)) { - this.options.sharpenM2 = jagged; - } else { - throw is.invalidParameterError('jagged', 'number between 0 and 10000', jagged); - } - } - } else if (is.plainObject(options)) { - if (is.number(options.sigma) && is.inRange(options.sigma, 0.000001, 10)) { - this.options.sharpenSigma = options.sigma; - } else { - throw is.invalidParameterError('options.sigma', 'number between 0.000001 and 10', options.sigma); - } - if (is.defined(options.m1)) { - if (is.number(options.m1) && is.inRange(options.m1, 0, 1000000)) { - this.options.sharpenM1 = options.m1; - } else { - throw is.invalidParameterError('options.m1', 'number between 0 and 1000000', options.m1); - } - } - if (is.defined(options.m2)) { - if (is.number(options.m2) && is.inRange(options.m2, 0, 1000000)) { - this.options.sharpenM2 = options.m2; - } else { - throw is.invalidParameterError('options.m2', 'number between 0 and 1000000', options.m2); - } - } - if (is.defined(options.x1)) { - if (is.number(options.x1) && is.inRange(options.x1, 0, 1000000)) { - this.options.sharpenX1 = options.x1; - } else { - throw is.invalidParameterError('options.x1', 'number between 0 and 1000000', options.x1); - } - } - if (is.defined(options.y2)) { - if (is.number(options.y2) && is.inRange(options.y2, 0, 1000000)) { - this.options.sharpenY2 = options.y2; - } else { - throw is.invalidParameterError('options.y2', 'number between 0 and 1000000', options.y2); - } - } - if (is.defined(options.y3)) { - if (is.number(options.y3) && is.inRange(options.y3, 0, 1000000)) { - this.options.sharpenY3 = options.y3; - } else { - throw is.invalidParameterError('options.y3', 'number between 0 and 1000000', options.y3); - } - } - } else { - throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', options); - } - return this; -} - -/** - * Apply median filter. - * When used without parameters the default window is 3x3. - * - * @example - * const output = await sharp(input).median().toBuffer(); - * - * @example - * const output = await sharp(input).median(5).toBuffer(); - * - * @param {number} [size=3] square mask size: size x size - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function median (size) { - if (!is.defined(size)) { - // No arguments: default to 3x3 - this.options.medianSize = 3; - } else if (is.integer(size) && is.inRange(size, 1, 1000)) { - // Numeric argument: specific sigma - this.options.medianSize = size; - } else { - throw is.invalidParameterError('size', 'integer between 1 and 1000', size); - } - return this; -} - -/** - * Blur the image. - * - * When used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter). - * - * When a `sigma` is provided, performs a slower, more accurate Gaussian blur. - * - * @example - * const boxBlurred = await sharp(input) - * .blur() - * .toBuffer(); - * - * @example - * const gaussianBlurred = await sharp(input) - * .blur(5) - * .toBuffer(); - * - * @param {number} [sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function blur (sigma) { - if (!is.defined(sigma)) { - // No arguments: default to mild blur - this.options.blurSigma = -1; - } else if (is.bool(sigma)) { - // Boolean argument: apply mild blur? - this.options.blurSigma = sigma ? -1 : 0; - } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) { - // Numeric argument: specific sigma - this.options.blurSigma = sigma; - } else { - throw is.invalidParameterError('sigma', 'number between 0.3 and 1000', sigma); - } - return this; -} - -/** - * Merge alpha transparency channel, if any, with a background, then remove the alpha channel. - * - * See also {@link /api-channel#removealpha|removeAlpha}. - * - * @example - * await sharp(rgbaInput) - * .flatten({ background: '#F0A703' }) - * .toBuffer(); - * - * @param {Object} [options] - * @param {string|Object} [options.background={r: 0, g: 0, b: 0}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black. - * @returns {Sharp} - */ -function flatten (options) { - this.options.flatten = is.bool(options) ? options : true; - if (is.object(options)) { - this._setBackgroundColourOption('flattenBackground', options.background); - } - return this; -} - -/** - * Ensure the image has an alpha channel - * with all white pixel values made fully transparent. - * - * Existing alpha channel values for non-white pixels remain unchanged. - * - * This feature is experimental and the API may change. - * - * @since 0.32.1 - * - * @example - * await sharp(rgbInput) - * .unflatten() - * .toBuffer(); - * - * @example - * await sharp(rgbInput) - * .threshold(128, { grayscale: false }) // converter bright pixels to white - * .unflatten() - * .toBuffer(); - */ -function unflatten () { - this.options.unflatten = true; - return this; -} - -/** - * Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma` - * then increasing the encoding (brighten) post-resize at a factor of `gamma`. - * This can improve the perceived brightness of a resized image in non-linear colour spaces. - * JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation - * when applying a gamma correction. - * - * Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases. - * - * @param {number} [gamma=2.2] value between 1.0 and 3.0. - * @param {number} [gammaOut] value between 1.0 and 3.0. (optional, defaults to same as `gamma`) - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function gamma (gamma, gammaOut) { - if (!is.defined(gamma)) { - // Default gamma correction of 2.2 (sRGB) - this.options.gamma = 2.2; - } else if (is.number(gamma) && is.inRange(gamma, 1, 3)) { - this.options.gamma = gamma; - } else { - throw is.invalidParameterError('gamma', 'number between 1.0 and 3.0', gamma); - } - if (!is.defined(gammaOut)) { - // Default gamma correction for output is same as input - this.options.gammaOut = this.options.gamma; - } else if (is.number(gammaOut) && is.inRange(gammaOut, 1, 3)) { - this.options.gammaOut = gammaOut; - } else { - throw is.invalidParameterError('gammaOut', 'number between 1.0 and 3.0', gammaOut); - } - return this; -} - -/** - * Produce the "negative" of the image. - * - * @example - * const output = await sharp(input) - * .negate() - * .toBuffer(); - * - * @example - * const output = await sharp(input) - * .negate({ alpha: false }) - * .toBuffer(); - * - * @param {Object} [options] - * @param {Boolean} [options.alpha=true] Whether or not to negate any alpha channel - * @returns {Sharp} - */ -function negate (options) { - this.options.negate = is.bool(options) ? options : true; - if (is.plainObject(options) && 'alpha' in options) { - if (!is.bool(options.alpha)) { - throw is.invalidParameterError('alpha', 'should be boolean value', options.alpha); - } else { - this.options.negateAlpha = options.alpha; - } - } - return this; -} - -/** - * Enhance output image contrast by stretching its luminance to cover a full dynamic range. - * - * Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes. - * - * Luminance values below the `lower` percentile will be underexposed by clipping to zero. - * Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value. - * - * @example - * const output = await sharp(input) - * .normalise() - * .toBuffer(); - * - * @example - * const output = await sharp(input) - * .normalise({ lower: 0, upper: 100 }) - * .toBuffer(); - * - * @param {Object} [options] - * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed. - * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed. - * @returns {Sharp} - */ -function normalise (options) { - if (is.plainObject(options)) { - if (is.defined(options.lower)) { - if (is.number(options.lower) && is.inRange(options.lower, 0, 99)) { - this.options.normaliseLower = options.lower; - } else { - throw is.invalidParameterError('lower', 'number between 0 and 99', options.lower); - } - } - if (is.defined(options.upper)) { - if (is.number(options.upper) && is.inRange(options.upper, 1, 100)) { - this.options.normaliseUpper = options.upper; - } else { - throw is.invalidParameterError('upper', 'number between 1 and 100', options.upper); - } - } - } - if (this.options.normaliseLower >= this.options.normaliseUpper) { - throw is.invalidParameterError('range', 'lower to be less than upper', - `${this.options.normaliseLower} >= ${this.options.normaliseUpper}`); - } - this.options.normalise = true; - return this; -} - -/** - * Alternative spelling of normalise. - * - * @example - * const output = await sharp(input) - * .normalize() - * .toBuffer(); - * - * @param {Object} [options] - * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed. - * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed. - * @returns {Sharp} - */ -function normalize (options) { - return this.normalise(options); -} - -/** - * Perform contrast limiting adaptive histogram equalization - * {@link https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE|CLAHE}. - * - * This will, in general, enhance the clarity of the image by bringing out darker details. - * - * @since 0.28.3 - * - * @example - * const output = await sharp(input) - * .clahe({ - * width: 3, - * height: 3, - * }) - * .toBuffer(); - * - * @param {Object} options - * @param {number} options.width - Integral width of the search window, in pixels. - * @param {number} options.height - Integral height of the search window, in pixels. - * @param {number} [options.maxSlope=3] - Integral level of brightening, between 0 and 100, where 0 disables contrast limiting. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function clahe (options) { - if (is.plainObject(options)) { - if (is.integer(options.width) && options.width > 0) { - this.options.claheWidth = options.width; - } else { - throw is.invalidParameterError('width', 'integer greater than zero', options.width); - } - if (is.integer(options.height) && options.height > 0) { - this.options.claheHeight = options.height; - } else { - throw is.invalidParameterError('height', 'integer greater than zero', options.height); - } - if (is.defined(options.maxSlope)) { - if (is.integer(options.maxSlope) && is.inRange(options.maxSlope, 0, 100)) { - this.options.claheMaxSlope = options.maxSlope; - } else { - throw is.invalidParameterError('maxSlope', 'integer between 0 and 100', options.maxSlope); - } - } - } else { - throw is.invalidParameterError('options', 'plain object', options); - } - return this; -} - -/** - * Convolve the image with the specified kernel. - * - * @example - * sharp(input) - * .convolve({ - * width: 3, - * height: 3, - * kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1] - * }) - * .raw() - * .toBuffer(function(err, data, info) { - * // data contains the raw pixel data representing the convolution - * // of the input image with the horizontal Sobel operator - * }); - * - * @param {Object} kernel - * @param {number} kernel.width - width of the kernel in pixels. - * @param {number} kernel.height - height of the kernel in pixels. - * @param {Array} kernel.kernel - Array of length `width*height` containing the kernel values. - * @param {number} [kernel.scale=sum] - the scale of the kernel in pixels. - * @param {number} [kernel.offset=0] - the offset of the kernel in pixels. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function convolve (kernel) { - if (!is.object(kernel) || !Array.isArray(kernel.kernel) || - !is.integer(kernel.width) || !is.integer(kernel.height) || - !is.inRange(kernel.width, 3, 1001) || !is.inRange(kernel.height, 3, 1001) || - kernel.height * kernel.width !== kernel.kernel.length - ) { - // must pass in a kernel - throw new Error('Invalid convolution kernel'); - } - // Default scale is sum of kernel values - if (!is.integer(kernel.scale)) { - kernel.scale = kernel.kernel.reduce(function (a, b) { - return a + b; - }, 0); - } - // Clip scale to a minimum value of 1 - if (kernel.scale < 1) { - kernel.scale = 1; - } - if (!is.integer(kernel.offset)) { - kernel.offset = 0; - } - this.options.convKernel = kernel; - return this; -} - -/** - * Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0. - * @param {number} [threshold=128] - a value in the range 0-255 representing the level at which the threshold will be applied. - * @param {Object} [options] - * @param {Boolean} [options.greyscale=true] - convert to single channel greyscale. - * @param {Boolean} [options.grayscale=true] - alternative spelling for greyscale. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function threshold (threshold, options) { - if (!is.defined(threshold)) { - this.options.threshold = 128; - } else if (is.bool(threshold)) { - this.options.threshold = threshold ? 128 : 0; - } else if (is.integer(threshold) && is.inRange(threshold, 0, 255)) { - this.options.threshold = threshold; - } else { - throw is.invalidParameterError('threshold', 'integer between 0 and 255', threshold); - } - if (!is.object(options) || options.greyscale === true || options.grayscale === true) { - this.options.thresholdGrayscale = true; - } else { - this.options.thresholdGrayscale = false; - } - return this; -} - -/** - * Perform a bitwise boolean operation with operand image. - * - * This operation creates an output image where each pixel is the result of - * the selected bitwise boolean `operation` between the corresponding pixels of the input images. - * - * @param {Buffer|string} operand - Buffer containing image data or string containing the path to an image file. - * @param {string} operator - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. - * @param {Object} [options] - * @param {Object} [options.raw] - describes operand when using raw pixel data. - * @param {number} [options.raw.width] - * @param {number} [options.raw.height] - * @param {number} [options.raw.channels] - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function boolean (operand, operator, options) { - this.options.boolean = this._createInputDescriptor(operand, options); - if (is.string(operator) && is.inArray(operator, ['and', 'or', 'eor'])) { - this.options.booleanOp = operator; - } else { - throw is.invalidParameterError('operator', 'one of: and, or, eor', operator); - } - return this; -} - -/** - * Apply the linear formula `a` * input + `b` to the image to adjust image levels. - * - * When a single number is provided, it will be used for all image channels. - * When an array of numbers is provided, the array length must match the number of channels. - * - * @example - * await sharp(input) - * .linear(0.5, 2) - * .toBuffer(); - * - * @example - * await sharp(rgbInput) - * .linear( - * [0.25, 0.5, 0.75], - * [150, 100, 50] - * ) - * .toBuffer(); - * - * @param {(number|number[])} [a=[]] multiplier - * @param {(number|number[])} [b=[]] offset - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function linear (a, b) { - if (!is.defined(a) && is.number(b)) { - a = 1.0; - } else if (is.number(a) && !is.defined(b)) { - b = 0.0; - } - if (!is.defined(a)) { - this.options.linearA = []; - } else if (is.number(a)) { - this.options.linearA = [a]; - } else if (Array.isArray(a) && a.length && a.every(is.number)) { - this.options.linearA = a; - } else { - throw is.invalidParameterError('a', 'number or array of numbers', a); - } - if (!is.defined(b)) { - this.options.linearB = []; - } else if (is.number(b)) { - this.options.linearB = [b]; - } else if (Array.isArray(b) && b.length && b.every(is.number)) { - this.options.linearB = b; - } else { - throw is.invalidParameterError('b', 'number or array of numbers', b); - } - if (this.options.linearA.length !== this.options.linearB.length) { - throw new Error('Expected a and b to be arrays of the same length'); - } - return this; -} - -/** - * Recombine the image with the specified matrix. - * - * @since 0.21.1 - * - * @example - * sharp(input) - * .recomb([ - * [0.3588, 0.7044, 0.1368], - * [0.2990, 0.5870, 0.1140], - * [0.2392, 0.4696, 0.0912], - * ]) - * .raw() - * .toBuffer(function(err, data, info) { - * // data contains the raw pixel data after applying the matrix - * // With this example input, a sepia filter has been applied - * }); - * - * @param {Array>} inputMatrix - 3x3 Recombination matrix - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function recomb (inputMatrix) { - if (!Array.isArray(inputMatrix) || inputMatrix.length !== 3 || - inputMatrix[0].length !== 3 || - inputMatrix[1].length !== 3 || - inputMatrix[2].length !== 3 - ) { - // must pass in a kernel - throw new Error('Invalid recombination matrix'); - } - this.options.recombMatrix = [ - inputMatrix[0][0], inputMatrix[0][1], inputMatrix[0][2], - inputMatrix[1][0], inputMatrix[1][1], inputMatrix[1][2], - inputMatrix[2][0], inputMatrix[2][1], inputMatrix[2][2] - ].map(Number); - return this; -} - -/** - * Transforms the image using brightness, saturation, hue rotation, and lightness. - * Brightness and lightness both operate on luminance, with the difference being that - * brightness is multiplicative whereas lightness is additive. - * - * @since 0.22.1 - * - * @example - * // increase brightness by a factor of 2 - * const output = await sharp(input) - * .modulate({ - * brightness: 2 - * }) - * .toBuffer(); - * - * @example - * // hue-rotate by 180 degrees - * const output = await sharp(input) - * .modulate({ - * hue: 180 - * }) - * .toBuffer(); - * - * @example - * // increase lightness by +50 - * const output = await sharp(input) - * .modulate({ - * lightness: 50 - * }) - * .toBuffer(); - * - * @example - * // decrease brightness and saturation while also hue-rotating by 90 degrees - * const output = await sharp(input) - * .modulate({ - * brightness: 0.5, - * saturation: 0.5, - * hue: 90, - * }) - * .toBuffer(); - * - * @param {Object} [options] - * @param {number} [options.brightness] Brightness multiplier - * @param {number} [options.saturation] Saturation multiplier - * @param {number} [options.hue] Degrees for hue rotation - * @param {number} [options.lightness] Lightness addend - * @returns {Sharp} - */ -function modulate (options) { - if (!is.plainObject(options)) { - throw is.invalidParameterError('options', 'plain object', options); - } - if ('brightness' in options) { - if (is.number(options.brightness) && options.brightness >= 0) { - this.options.brightness = options.brightness; - } else { - throw is.invalidParameterError('brightness', 'number above zero', options.brightness); - } - } - if ('saturation' in options) { - if (is.number(options.saturation) && options.saturation >= 0) { - this.options.saturation = options.saturation; - } else { - throw is.invalidParameterError('saturation', 'number above zero', options.saturation); - } - } - if ('hue' in options) { - if (is.integer(options.hue)) { - this.options.hue = options.hue % 360; - } else { - throw is.invalidParameterError('hue', 'number', options.hue); - } - } - if ('lightness' in options) { - if (is.number(options.lightness)) { - this.options.lightness = options.lightness; - } else { - throw is.invalidParameterError('lightness', 'number', options.lightness); - } - } - return this; -} - -/** - * Decorate the Sharp prototype with operation-related functions. - * @private - */ -module.exports = function (Sharp) { - Object.assign(Sharp.prototype, { - rotate, - flip, - flop, - affine, - sharpen, - median, - blur, - flatten, - unflatten, - gamma, - negate, - normalise, - normalize, - clahe, - convolve, - threshold, - boolean, - linear, - recomb, - modulate - }); -}; diff --git a/node_modules/sharp/lib/output.js b/node_modules/sharp/lib/output.js deleted file mode 100644 index d7b07121..00000000 --- a/node_modules/sharp/lib/output.js +++ /dev/null @@ -1,1585 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const path = require('node:path'); -const is = require('./is'); -const sharp = require('./sharp'); - -const formats = new Map([ - ['heic', 'heif'], - ['heif', 'heif'], - ['avif', 'avif'], - ['jpeg', 'jpeg'], - ['jpg', 'jpeg'], - ['jpe', 'jpeg'], - ['tile', 'tile'], - ['dz', 'tile'], - ['png', 'png'], - ['raw', 'raw'], - ['tiff', 'tiff'], - ['tif', 'tiff'], - ['webp', 'webp'], - ['gif', 'gif'], - ['jp2', 'jp2'], - ['jpx', 'jp2'], - ['j2k', 'jp2'], - ['j2c', 'jp2'], - ['jxl', 'jxl'] -]); - -const jp2Regex = /\.(jp[2x]|j2[kc])$/i; - -const errJp2Save = () => new Error('JP2 output requires libvips with support for OpenJPEG'); - -const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math.log2(colours))); - -/** - * Write output image data to a file. - * - * If an explicit output format is not selected, it will be inferred from the extension, - * with JPEG, PNG, WebP, AVIF, TIFF, GIF, DZI, and libvips' V format supported. - * Note that raw pixel data is only supported for buffer output. - * - * By default all metadata will be removed, which includes EXIF-based orientation. - * See {@link #withmetadata|withMetadata} for control over this. - * - * The caller is responsible for ensuring directory structures and permissions exist. - * - * A `Promise` is returned when `callback` is not provided. - * - * @example - * sharp(input) - * .toFile('output.png', (err, info) => { ... }); - * - * @example - * sharp(input) - * .toFile('output.png') - * .then(info => { ... }) - * .catch(err => { ... }); - * - * @param {string} fileOut - the path to write the image data to. - * @param {Function} [callback] - called on completion with two arguments `(err, info)`. - * `info` contains the output image `format`, `size` (bytes), `width`, `height`, - * `channels` and `premultiplied` (indicating if premultiplication was used). - * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. - * When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region. - * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. - * @returns {Promise} - when no callback is provided - * @throws {Error} Invalid parameters - */ -function toFile (fileOut, callback) { - let err; - if (!is.string(fileOut)) { - err = new Error('Missing output file path'); - } else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) { - err = new Error('Cannot use same file for input and output'); - } else if (jp2Regex.test(path.extname(fileOut)) && !this.constructor.format.jp2k.output.file) { - err = errJp2Save(); - } - if (err) { - if (is.fn(callback)) { - callback(err); - } else { - return Promise.reject(err); - } - } else { - this.options.fileOut = fileOut; - const stack = Error(); - return this._pipeline(callback, stack); - } - return this; -} - -/** - * Write output to a Buffer. - * JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported. - * - * Use {@link #toformat|toFormat} or one of the format-specific functions such as {@link jpeg}, {@link png} etc. to set the output format. - * - * If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output. - * - * By default all metadata will be removed, which includes EXIF-based orientation. - * See {@link #withmetadata|withMetadata} for control over this. - * - * `callback`, if present, gets three arguments `(err, data, info)` where: - * - `err` is an error, if any. - * - `data` is the output image data. - * - `info` contains the output image `format`, `size` (bytes), `width`, `height`, - * `channels` and `premultiplied` (indicating if premultiplication was used). - * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. - * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. - * - * A `Promise` is returned when `callback` is not provided. - * - * @example - * sharp(input) - * .toBuffer((err, data, info) => { ... }); - * - * @example - * sharp(input) - * .toBuffer() - * .then(data => { ... }) - * .catch(err => { ... }); - * - * @example - * sharp(input) - * .png() - * .toBuffer({ resolveWithObject: true }) - * .then(({ data, info }) => { ... }) - * .catch(err => { ... }); - * - * @example - * const { data, info } = await sharp('my-image.jpg') - * // output the raw pixels - * .raw() - * .toBuffer({ resolveWithObject: true }); - * - * // create a more type safe way to work with the raw pixel data - * // this will not copy the data, instead it will change `data`s underlying ArrayBuffer - * // so `data` and `pixelArray` point to the same memory location - * const pixelArray = new Uint8ClampedArray(data.buffer); - * - * // When you are done changing the pixelArray, sharp takes the `pixelArray` as an input - * const { width, height, channels } = info; - * await sharp(pixelArray, { raw: { width, height, channels } }) - * .toFile('my-changed-image.jpg'); - * - * @param {Object} [options] - * @param {boolean} [options.resolveWithObject] Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`. - * @param {Function} [callback] - * @returns {Promise} - when no callback is provided - */ -function toBuffer (options, callback) { - if (is.object(options)) { - this._setBooleanOption('resolveWithObject', options.resolveWithObject); - } else if (this.options.resolveWithObject) { - this.options.resolveWithObject = false; - } - this.options.fileOut = ''; - const stack = Error(); - return this._pipeline(is.fn(options) ? options : callback, stack); -} - -/** - * Keep all EXIF metadata from the input image in the output image. - * - * EXIF metadata is unsupported for TIFF output. - * - * @since 0.33.0 - * - * @example - * const outputWithExif = await sharp(inputWithExif) - * .keepExif() - * .toBuffer(); - * - * @returns {Sharp} - */ -function keepExif () { - this.options.keepMetadata |= 0b00001; - return this; -} - -/** - * Set EXIF metadata in the output image, ignoring any EXIF in the input image. - * - * @since 0.33.0 - * - * @example - * const dataWithExif = await sharp(input) - * .withExif({ - * IFD0: { - * Copyright: 'The National Gallery' - * }, - * IFD3: { - * GPSLatitudeRef: 'N', - * GPSLatitude: '51/1 30/1 3230/100', - * GPSLongitudeRef: 'W', - * GPSLongitude: '0/1 7/1 4366/100' - * } - * }) - * .toBuffer(); - * - * @param {Object>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function withExif (exif) { - if (is.object(exif)) { - for (const [ifd, entries] of Object.entries(exif)) { - if (is.object(entries)) { - for (const [k, v] of Object.entries(entries)) { - if (is.string(v)) { - this.options.withExif[`exif-${ifd.toLowerCase()}-${k}`] = v; - } else { - throw is.invalidParameterError(`${ifd}.${k}`, 'string', v); - } - } - } else { - throw is.invalidParameterError(ifd, 'object', entries); - } - } - } else { - throw is.invalidParameterError('exif', 'object', exif); - } - this.options.withExifMerge = false; - return this.keepExif(); -} - -/** - * Update EXIF metadata from the input image in the output image. - * - * @since 0.33.0 - * - * @example - * const dataWithMergedExif = await sharp(inputWithExif) - * .withExifMerge({ - * IFD0: { - * Copyright: 'The National Gallery' - * } - * }) - * .toBuffer(); - * - * @param {Object>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function withExifMerge (exif) { - this.withExif(exif); - this.options.withExifMerge = true; - return this; -} - -/** - * Keep ICC profile from the input image in the output image. - * - * Where necessary, will attempt to convert the output colour space to match the profile. - * - * @since 0.33.0 - * - * @example - * const outputWithIccProfile = await sharp(inputWithIccProfile) - * .keepIccProfile() - * .toBuffer(); - * - * @returns {Sharp} - */ -function keepIccProfile () { - this.options.keepMetadata |= 0b01000; - return this; -} - -/** - * Transform using an ICC profile and attach to the output image. - * - * This can either be an absolute filesystem path or - * built-in profile name (`srgb`, `p3`, `cmyk`). - * - * @since 0.33.0 - * - * @example - * const outputWithP3 = await sharp(input) - * .withIccProfile('p3') - * .toBuffer(); - * - * @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk). - * @param {Object} [options] - * @param {number} [options.attach=true] Should the ICC profile be included in the output image metadata? - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function withIccProfile (icc, options) { - if (is.string(icc)) { - this.options.withIccProfile = icc; - } else { - throw is.invalidParameterError('icc', 'string', icc); - } - this.keepIccProfile(); - if (is.object(options)) { - if (is.defined(options.attach)) { - if (is.bool(options.attach)) { - if (!options.attach) { - this.options.keepMetadata &= ~0b01000; - } - } else { - throw is.invalidParameterError('attach', 'boolean', options.attach); - } - } - } - return this; -} - -/** - * Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image. - * - * The default behaviour, when `keepMetadata` is not used, is to convert to the device-independent - * sRGB colour space and strip all metadata, including the removal of any ICC profile. - * - * @since 0.33.0 - * - * @example - * const outputWithMetadata = await sharp(inputWithMetadata) - * .keepMetadata() - * .toBuffer(); - * - * @returns {Sharp} - */ -function keepMetadata () { - this.options.keepMetadata = 0b11111; - return this; -} - -/** - * Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image. - * - * This will also convert to and add a web-friendly sRGB ICC profile if appropriate. - * - * Allows orientation and density to be set or updated. - * - * @example - * const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata) - * .withMetadata() - * .toBuffer(); - * - * @example - * // Set output metadata to 96 DPI - * const data = await sharp(input) - * .withMetadata({ density: 96 }) - * .toBuffer(); - * - * @param {Object} [options] - * @param {number} [options.orientation] Used to update the EXIF `Orientation` tag, integer between 1 and 8. - * @param {number} [options.density] Number of pixels per inch (DPI). - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function withMetadata (options) { - this.keepMetadata(); - this.withIccProfile('srgb'); - if (is.object(options)) { - if (is.defined(options.orientation)) { - if (is.integer(options.orientation) && is.inRange(options.orientation, 1, 8)) { - this.options.withMetadataOrientation = options.orientation; - } else { - throw is.invalidParameterError('orientation', 'integer between 1 and 8', options.orientation); - } - } - if (is.defined(options.density)) { - if (is.number(options.density) && options.density > 0) { - this.options.withMetadataDensity = options.density; - } else { - throw is.invalidParameterError('density', 'positive number', options.density); - } - } - if (is.defined(options.icc)) { - this.withIccProfile(options.icc); - } - if (is.defined(options.exif)) { - this.withExifMerge(options.exif); - } - } - return this; -} - -/** - * Force output to a given format. - * - * @example - * // Convert any input to PNG output - * const data = await sharp(input) - * .toFormat('png') - * .toBuffer(); - * - * @param {(string|Object)} format - as a string or an Object with an 'id' attribute - * @param {Object} options - output options - * @returns {Sharp} - * @throws {Error} unsupported format or options - */ -function toFormat (format, options) { - const actualFormat = formats.get((is.object(format) && is.string(format.id) ? format.id : format).toLowerCase()); - if (!actualFormat) { - throw is.invalidParameterError('format', `one of: ${[...formats.keys()].join(', ')}`, format); - } - return this[actualFormat](options); -} - -/** - * Use these JPEG options for output image. - * - * @example - * // Convert any input to very high quality JPEG output - * const data = await sharp(input) - * .jpeg({ - * quality: 100, - * chromaSubsampling: '4:4:4' - * }) - * .toBuffer(); - * - * @example - * // Use mozjpeg to reduce output JPEG file size (slower) - * const data = await sharp(input) - * .jpeg({ mozjpeg: true }) - * .toBuffer(); - * - * @param {Object} [options] - output options - * @param {number} [options.quality=80] - quality, integer 1-100 - * @param {boolean} [options.progressive=false] - use progressive (interlace) scan - * @param {string} [options.chromaSubsampling='4:2:0'] - set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling - * @param {boolean} [options.optimiseCoding=true] - optimise Huffman coding tables - * @param {boolean} [options.optimizeCoding=true] - alternative spelling of optimiseCoding - * @param {boolean} [options.mozjpeg=false] - use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }` - * @param {boolean} [options.trellisQuantisation=false] - apply trellis quantisation - * @param {boolean} [options.overshootDeringing=false] - apply overshoot deringing - * @param {boolean} [options.optimiseScans=false] - optimise progressive scans, forces progressive - * @param {boolean} [options.optimizeScans=false] - alternative spelling of optimiseScans - * @param {number} [options.quantisationTable=0] - quantization table to use, integer 0-8 - * @param {number} [options.quantizationTable=0] - alternative spelling of quantisationTable - * @param {boolean} [options.force=true] - force JPEG output, otherwise attempt to use input format - * @returns {Sharp} - * @throws {Error} Invalid options - */ -function jpeg (options) { - if (is.object(options)) { - if (is.defined(options.quality)) { - if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { - this.options.jpegQuality = options.quality; - } else { - throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); - } - } - if (is.defined(options.progressive)) { - this._setBooleanOption('jpegProgressive', options.progressive); - } - if (is.defined(options.chromaSubsampling)) { - if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { - this.options.jpegChromaSubsampling = options.chromaSubsampling; - } else { - throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling); - } - } - const optimiseCoding = is.bool(options.optimizeCoding) ? options.optimizeCoding : options.optimiseCoding; - if (is.defined(optimiseCoding)) { - this._setBooleanOption('jpegOptimiseCoding', optimiseCoding); - } - if (is.defined(options.mozjpeg)) { - if (is.bool(options.mozjpeg)) { - if (options.mozjpeg) { - this.options.jpegTrellisQuantisation = true; - this.options.jpegOvershootDeringing = true; - this.options.jpegOptimiseScans = true; - this.options.jpegProgressive = true; - this.options.jpegQuantisationTable = 3; - } - } else { - throw is.invalidParameterError('mozjpeg', 'boolean', options.mozjpeg); - } - } - const trellisQuantisation = is.bool(options.trellisQuantization) ? options.trellisQuantization : options.trellisQuantisation; - if (is.defined(trellisQuantisation)) { - this._setBooleanOption('jpegTrellisQuantisation', trellisQuantisation); - } - if (is.defined(options.overshootDeringing)) { - this._setBooleanOption('jpegOvershootDeringing', options.overshootDeringing); - } - const optimiseScans = is.bool(options.optimizeScans) ? options.optimizeScans : options.optimiseScans; - if (is.defined(optimiseScans)) { - this._setBooleanOption('jpegOptimiseScans', optimiseScans); - if (optimiseScans) { - this.options.jpegProgressive = true; - } - } - const quantisationTable = is.number(options.quantizationTable) ? options.quantizationTable : options.quantisationTable; - if (is.defined(quantisationTable)) { - if (is.integer(quantisationTable) && is.inRange(quantisationTable, 0, 8)) { - this.options.jpegQuantisationTable = quantisationTable; - } else { - throw is.invalidParameterError('quantisationTable', 'integer between 0 and 8', quantisationTable); - } - } - } - return this._updateFormatOut('jpeg', options); -} - -/** - * Use these PNG options for output image. - * - * By default, PNG output is full colour at 8 bits per pixel. - * - * Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel. - * Set `palette` to `true` for slower, indexed PNG output. - * - * For 16 bits per pixel output, convert to `rgb16` via - * {@link /api-colour#tocolourspace|toColourspace}. - * - * @example - * // Convert any input to full colour PNG output - * const data = await sharp(input) - * .png() - * .toBuffer(); - * - * @example - * // Convert any input to indexed PNG output (slower) - * const data = await sharp(input) - * .png({ palette: true }) - * .toBuffer(); - * - * @example - * // Output 16 bits per pixel RGB(A) - * const data = await sharp(input) - * .toColourspace('rgb16') - * .png() - * .toBuffer(); - * - * @param {Object} [options] - * @param {boolean} [options.progressive=false] - use progressive (interlace) scan - * @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) - * @param {boolean} [options.adaptiveFiltering=false] - use adaptive row filtering - * @param {boolean} [options.palette=false] - quantise to a palette-based image with alpha transparency support - * @param {number} [options.quality=100] - use the lowest number of colours needed to achieve given quality, sets `palette` to `true` - * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true` - * @param {number} [options.colours=256] - maximum number of palette entries, sets `palette` to `true` - * @param {number} [options.colors=256] - alternative spelling of `options.colours`, sets `palette` to `true` - * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, sets `palette` to `true` - * @param {boolean} [options.force=true] - force PNG output, otherwise attempt to use input format - * @returns {Sharp} - * @throws {Error} Invalid options - */ -function png (options) { - if (is.object(options)) { - if (is.defined(options.progressive)) { - this._setBooleanOption('pngProgressive', options.progressive); - } - if (is.defined(options.compressionLevel)) { - if (is.integer(options.compressionLevel) && is.inRange(options.compressionLevel, 0, 9)) { - this.options.pngCompressionLevel = options.compressionLevel; - } else { - throw is.invalidParameterError('compressionLevel', 'integer between 0 and 9', options.compressionLevel); - } - } - if (is.defined(options.adaptiveFiltering)) { - this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering); - } - const colours = options.colours || options.colors; - if (is.defined(colours)) { - if (is.integer(colours) && is.inRange(colours, 2, 256)) { - this.options.pngBitdepth = bitdepthFromColourCount(colours); - } else { - throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); - } - } - if (is.defined(options.palette)) { - this._setBooleanOption('pngPalette', options.palette); - } else if ([options.quality, options.effort, options.colours, options.colors, options.dither].some(is.defined)) { - this._setBooleanOption('pngPalette', true); - } - if (this.options.pngPalette) { - if (is.defined(options.quality)) { - if (is.integer(options.quality) && is.inRange(options.quality, 0, 100)) { - this.options.pngQuality = options.quality; - } else { - throw is.invalidParameterError('quality', 'integer between 0 and 100', options.quality); - } - } - if (is.defined(options.effort)) { - if (is.integer(options.effort) && is.inRange(options.effort, 1, 10)) { - this.options.pngEffort = options.effort; - } else { - throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort); - } - } - if (is.defined(options.dither)) { - if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) { - this.options.pngDither = options.dither; - } else { - throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither); - } - } - } - } - return this._updateFormatOut('png', options); -} - -/** - * Use these WebP options for output image. - * - * @example - * // Convert any input to lossless WebP output - * const data = await sharp(input) - * .webp({ lossless: true }) - * .toBuffer(); - * - * @example - * // Optimise the file size of an animated WebP - * const outputWebp = await sharp(inputWebp, { animated: true }) - * .webp({ effort: 6 }) - * .toBuffer(); - * - * @param {Object} [options] - output options - * @param {number} [options.quality=80] - quality, integer 1-100 - * @param {number} [options.alphaQuality=100] - quality of alpha layer, integer 0-100 - * @param {boolean} [options.lossless=false] - use lossless compression mode - * @param {boolean} [options.nearLossless=false] - use near_lossless compression mode - * @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling - * @param {string} [options.preset='default'] - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text - * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest) - * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation - * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds) - * @param {boolean} [options.minSize=false] - prevent use of animation key frames to minimise file size (slow) - * @param {boolean} [options.mixed=false] - allow mixture of lossy and lossless animation frames (slow) - * @param {boolean} [options.force=true] - force WebP output, otherwise attempt to use input format - * @returns {Sharp} - * @throws {Error} Invalid options - */ -function webp (options) { - if (is.object(options)) { - if (is.defined(options.quality)) { - if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { - this.options.webpQuality = options.quality; - } else { - throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); - } - } - if (is.defined(options.alphaQuality)) { - if (is.integer(options.alphaQuality) && is.inRange(options.alphaQuality, 0, 100)) { - this.options.webpAlphaQuality = options.alphaQuality; - } else { - throw is.invalidParameterError('alphaQuality', 'integer between 0 and 100', options.alphaQuality); - } - } - if (is.defined(options.lossless)) { - this._setBooleanOption('webpLossless', options.lossless); - } - if (is.defined(options.nearLossless)) { - this._setBooleanOption('webpNearLossless', options.nearLossless); - } - if (is.defined(options.smartSubsample)) { - this._setBooleanOption('webpSmartSubsample', options.smartSubsample); - } - if (is.defined(options.preset)) { - if (is.string(options.preset) && is.inArray(options.preset, ['default', 'photo', 'picture', 'drawing', 'icon', 'text'])) { - this.options.webpPreset = options.preset; - } else { - throw is.invalidParameterError('preset', 'one of: default, photo, picture, drawing, icon, text', options.preset); - } - } - if (is.defined(options.effort)) { - if (is.integer(options.effort) && is.inRange(options.effort, 0, 6)) { - this.options.webpEffort = options.effort; - } else { - throw is.invalidParameterError('effort', 'integer between 0 and 6', options.effort); - } - } - if (is.defined(options.minSize)) { - this._setBooleanOption('webpMinSize', options.minSize); - } - if (is.defined(options.mixed)) { - this._setBooleanOption('webpMixed', options.mixed); - } - } - trySetAnimationOptions(options, this.options); - return this._updateFormatOut('webp', options); -} - -/** - * Use these GIF options for the output image. - * - * The first entry in the palette is reserved for transparency. - * - * The palette of the input image will be re-used if possible. - * - * @since 0.30.0 - * - * @example - * // Convert PNG to GIF - * await sharp(pngBuffer) - * .gif() - * .toBuffer(); - * - * @example - * // Convert animated WebP to animated GIF - * await sharp('animated.webp', { animated: true }) - * .toFile('animated.gif'); - * - * @example - * // Create a 128x128, cropped, non-dithered, animated thumbnail of an animated GIF - * const out = await sharp('in.gif', { animated: true }) - * .resize({ width: 128, height: 128 }) - * .gif({ dither: 0 }) - * .toBuffer(); - * - * @example - * // Lossy file size reduction of animated GIF - * await sharp('in.gif', { animated: true }) - * .gif({ interFrameMaxError: 8 }) - * .toFile('optim.gif'); - * - * @param {Object} [options] - output options - * @param {boolean} [options.reuse=true] - re-use existing palette, otherwise generate new (slow) - * @param {boolean} [options.progressive=false] - use progressive (interlace) scan - * @param {number} [options.colours=256] - maximum number of palette entries, including transparency, between 2 and 256 - * @param {number} [options.colors=256] - alternative spelling of `options.colours` - * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest) - * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) - * @param {number} [options.interFrameMaxError=0] - maximum inter-frame error for transparency, between 0 (lossless) and 32 - * @param {number} [options.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256 - * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation - * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds) - * @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format - * @returns {Sharp} - * @throws {Error} Invalid options - */ -function gif (options) { - if (is.object(options)) { - if (is.defined(options.reuse)) { - this._setBooleanOption('gifReuse', options.reuse); - } - if (is.defined(options.progressive)) { - this._setBooleanOption('gifProgressive', options.progressive); - } - const colours = options.colours || options.colors; - if (is.defined(colours)) { - if (is.integer(colours) && is.inRange(colours, 2, 256)) { - this.options.gifBitdepth = bitdepthFromColourCount(colours); - } else { - throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); - } - } - if (is.defined(options.effort)) { - if (is.number(options.effort) && is.inRange(options.effort, 1, 10)) { - this.options.gifEffort = options.effort; - } else { - throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort); - } - } - if (is.defined(options.dither)) { - if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) { - this.options.gifDither = options.dither; - } else { - throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither); - } - } - if (is.defined(options.interFrameMaxError)) { - if (is.number(options.interFrameMaxError) && is.inRange(options.interFrameMaxError, 0, 32)) { - this.options.gifInterFrameMaxError = options.interFrameMaxError; - } else { - throw is.invalidParameterError('interFrameMaxError', 'number between 0.0 and 32.0', options.interFrameMaxError); - } - } - if (is.defined(options.interPaletteMaxError)) { - if (is.number(options.interPaletteMaxError) && is.inRange(options.interPaletteMaxError, 0, 256)) { - this.options.gifInterPaletteMaxError = options.interPaletteMaxError; - } else { - throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError); - } - } - } - trySetAnimationOptions(options, this.options); - return this._updateFormatOut('gif', options); -} - -/* istanbul ignore next */ -/** - * Use these JP2 options for output image. - * - * Requires libvips compiled with support for OpenJPEG. - * The prebuilt binaries do not include this - see - * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}. - * - * @example - * // Convert any input to lossless JP2 output - * const data = await sharp(input) - * .jp2({ lossless: true }) - * .toBuffer(); - * - * @example - * // Convert any input to very high quality JP2 output - * const data = await sharp(input) - * .jp2({ - * quality: 100, - * chromaSubsampling: '4:4:4' - * }) - * .toBuffer(); - * - * @since 0.29.1 - * - * @param {Object} [options] - output options - * @param {number} [options.quality=80] - quality, integer 1-100 - * @param {boolean} [options.lossless=false] - use lossless compression mode - * @param {number} [options.tileWidth=512] - horizontal tile size - * @param {number} [options.tileHeight=512] - vertical tile size - * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling - * @returns {Sharp} - * @throws {Error} Invalid options - */ -function jp2 (options) { - if (!this.constructor.format.jp2k.output.buffer) { - throw errJp2Save(); - } - if (is.object(options)) { - if (is.defined(options.quality)) { - if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { - this.options.jp2Quality = options.quality; - } else { - throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); - } - } - if (is.defined(options.lossless)) { - if (is.bool(options.lossless)) { - this.options.jp2Lossless = options.lossless; - } else { - throw is.invalidParameterError('lossless', 'boolean', options.lossless); - } - } - if (is.defined(options.tileWidth)) { - if (is.integer(options.tileWidth) && is.inRange(options.tileWidth, 1, 32768)) { - this.options.jp2TileWidth = options.tileWidth; - } else { - throw is.invalidParameterError('tileWidth', 'integer between 1 and 32768', options.tileWidth); - } - } - if (is.defined(options.tileHeight)) { - if (is.integer(options.tileHeight) && is.inRange(options.tileHeight, 1, 32768)) { - this.options.jp2TileHeight = options.tileHeight; - } else { - throw is.invalidParameterError('tileHeight', 'integer between 1 and 32768', options.tileHeight); - } - } - if (is.defined(options.chromaSubsampling)) { - if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { - this.options.jp2ChromaSubsampling = options.chromaSubsampling; - } else { - throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling); - } - } - } - return this._updateFormatOut('jp2', options); -} - -/** - * Set animation options if available. - * @private - * - * @param {Object} [source] - output options - * @param {number} [source.loop=0] - number of animation iterations, use 0 for infinite animation - * @param {number[]} [source.delay] - list of delays between animation frames (in milliseconds) - * @param {Object} [target] - target object for valid options - * @throws {Error} Invalid options - */ -function trySetAnimationOptions (source, target) { - if (is.object(source) && is.defined(source.loop)) { - if (is.integer(source.loop) && is.inRange(source.loop, 0, 65535)) { - target.loop = source.loop; - } else { - throw is.invalidParameterError('loop', 'integer between 0 and 65535', source.loop); - } - } - if (is.object(source) && is.defined(source.delay)) { - // We allow singular values as well - if (is.integer(source.delay) && is.inRange(source.delay, 0, 65535)) { - target.delay = [source.delay]; - } else if ( - Array.isArray(source.delay) && - source.delay.every(is.integer) && - source.delay.every(v => is.inRange(v, 0, 65535))) { - target.delay = source.delay; - } else { - throw is.invalidParameterError('delay', 'integer or an array of integers between 0 and 65535', source.delay); - } - } -} - -/** - * Use these TIFF options for output image. - * - * The `density` can be set in pixels/inch via {@link #withmetadata|withMetadata} - * instead of providing `xres` and `yres` in pixels/mm. - * - * @example - * // Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output - * sharp('input.svg') - * .tiff({ - * compression: 'lzw', - * bitdepth: 1 - * }) - * .toFile('1-bpp-output.tiff') - * .then(info => { ... }); - * - * @param {Object} [options] - output options - * @param {number} [options.quality=80] - quality, integer 1-100 - * @param {boolean} [options.force=true] - force TIFF output, otherwise attempt to use input format - * @param {string} [options.compression='jpeg'] - compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k - * @param {string} [options.predictor='horizontal'] - compression predictor options: none, horizontal, float - * @param {boolean} [options.pyramid=false] - write an image pyramid - * @param {boolean} [options.tile=false] - write a tiled tiff - * @param {number} [options.tileWidth=256] - horizontal tile size - * @param {number} [options.tileHeight=256] - vertical tile size - * @param {number} [options.xres=1.0] - horizontal resolution in pixels/mm - * @param {number} [options.yres=1.0] - vertical resolution in pixels/mm - * @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm - * @param {number} [options.bitdepth=8] - reduce bitdepth to 1, 2 or 4 bit - * @param {boolean} [options.miniswhite=false] - write 1-bit images as miniswhite - * @returns {Sharp} - * @throws {Error} Invalid options - */ -function tiff (options) { - if (is.object(options)) { - if (is.defined(options.quality)) { - if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { - this.options.tiffQuality = options.quality; - } else { - throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); - } - } - if (is.defined(options.bitdepth)) { - if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [1, 2, 4, 8])) { - this.options.tiffBitdepth = options.bitdepth; - } else { - throw is.invalidParameterError('bitdepth', '1, 2, 4 or 8', options.bitdepth); - } - } - // tiling - if (is.defined(options.tile)) { - this._setBooleanOption('tiffTile', options.tile); - } - if (is.defined(options.tileWidth)) { - if (is.integer(options.tileWidth) && options.tileWidth > 0) { - this.options.tiffTileWidth = options.tileWidth; - } else { - throw is.invalidParameterError('tileWidth', 'integer greater than zero', options.tileWidth); - } - } - if (is.defined(options.tileHeight)) { - if (is.integer(options.tileHeight) && options.tileHeight > 0) { - this.options.tiffTileHeight = options.tileHeight; - } else { - throw is.invalidParameterError('tileHeight', 'integer greater than zero', options.tileHeight); - } - } - // miniswhite - if (is.defined(options.miniswhite)) { - this._setBooleanOption('tiffMiniswhite', options.miniswhite); - } - // pyramid - if (is.defined(options.pyramid)) { - this._setBooleanOption('tiffPyramid', options.pyramid); - } - // resolution - if (is.defined(options.xres)) { - if (is.number(options.xres) && options.xres > 0) { - this.options.tiffXres = options.xres; - } else { - throw is.invalidParameterError('xres', 'number greater than zero', options.xres); - } - } - if (is.defined(options.yres)) { - if (is.number(options.yres) && options.yres > 0) { - this.options.tiffYres = options.yres; - } else { - throw is.invalidParameterError('yres', 'number greater than zero', options.yres); - } - } - // compression - if (is.defined(options.compression)) { - if (is.string(options.compression) && is.inArray(options.compression, ['none', 'jpeg', 'deflate', 'packbits', 'ccittfax4', 'lzw', 'webp', 'zstd', 'jp2k'])) { - this.options.tiffCompression = options.compression; - } else { - throw is.invalidParameterError('compression', 'one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k', options.compression); - } - } - // predictor - if (is.defined(options.predictor)) { - if (is.string(options.predictor) && is.inArray(options.predictor, ['none', 'horizontal', 'float'])) { - this.options.tiffPredictor = options.predictor; - } else { - throw is.invalidParameterError('predictor', 'one of: none, horizontal, float', options.predictor); - } - } - // resolutionUnit - if (is.defined(options.resolutionUnit)) { - if (is.string(options.resolutionUnit) && is.inArray(options.resolutionUnit, ['inch', 'cm'])) { - this.options.tiffResolutionUnit = options.resolutionUnit; - } else { - throw is.invalidParameterError('resolutionUnit', 'one of: inch, cm', options.resolutionUnit); - } - } - } - return this._updateFormatOut('tiff', options); -} - -/** - * Use these AVIF options for output image. - * - * AVIF image sequences are not supported. - * Prebuilt binaries support a bitdepth of 8 only. - * - * @example - * const data = await sharp(input) - * .avif({ effort: 2 }) - * .toBuffer(); - * - * @example - * const data = await sharp(input) - * .avif({ lossless: true }) - * .toBuffer(); - * - * @since 0.27.0 - * - * @param {Object} [options] - output options - * @param {number} [options.quality=50] - quality, integer 1-100 - * @param {boolean} [options.lossless=false] - use lossless compression - * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest) - * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling - * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit - * @returns {Sharp} - * @throws {Error} Invalid options - */ -function avif (options) { - return this.heif({ ...options, compression: 'av1' }); -} - -/** - * Use these HEIF options for output image. - * - * Support for patent-encumbered HEIC images using `hevc` compression requires the use of a - * globally-installed libvips compiled with support for libheif, libde265 and x265. - * - * @example - * const data = await sharp(input) - * .heif({ compression: 'hevc' }) - * .toBuffer(); - * - * @since 0.23.0 - * - * @param {Object} options - output options - * @param {string} options.compression - compression format: av1, hevc - * @param {number} [options.quality=50] - quality, integer 1-100 - * @param {boolean} [options.lossless=false] - use lossless compression - * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest) - * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling - * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit - * @returns {Sharp} - * @throws {Error} Invalid options - */ -function heif (options) { - if (is.object(options)) { - if (is.string(options.compression) && is.inArray(options.compression, ['av1', 'hevc'])) { - this.options.heifCompression = options.compression; - } else { - throw is.invalidParameterError('compression', 'one of: av1, hevc', options.compression); - } - if (is.defined(options.quality)) { - if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { - this.options.heifQuality = options.quality; - } else { - throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); - } - } - if (is.defined(options.lossless)) { - if (is.bool(options.lossless)) { - this.options.heifLossless = options.lossless; - } else { - throw is.invalidParameterError('lossless', 'boolean', options.lossless); - } - } - if (is.defined(options.effort)) { - if (is.integer(options.effort) && is.inRange(options.effort, 0, 9)) { - this.options.heifEffort = options.effort; - } else { - throw is.invalidParameterError('effort', 'integer between 0 and 9', options.effort); - } - } - if (is.defined(options.chromaSubsampling)) { - if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { - this.options.heifChromaSubsampling = options.chromaSubsampling; - } else { - throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling); - } - } - if (is.defined(options.bitdepth)) { - if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [8, 10, 12])) { - if (options.bitdepth !== 8 && this.constructor.versions.heif) { - throw is.invalidParameterError('bitdepth when using prebuilt binaries', 8, options.bitdepth); - } - this.options.heifBitdepth = options.bitdepth; - } else { - throw is.invalidParameterError('bitdepth', '8, 10 or 12', options.bitdepth); - } - } - } else { - throw is.invalidParameterError('options', 'Object', options); - } - return this._updateFormatOut('heif', options); -} - -/** - * Use these JPEG-XL (JXL) options for output image. - * - * This feature is experimental, please do not use in production systems. - * - * Requires libvips compiled with support for libjxl. - * The prebuilt binaries do not include this - see - * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}. - * - * Image metadata (EXIF, XMP) is unsupported. - * - * @since 0.31.3 - * - * @param {Object} [options] - output options - * @param {number} [options.distance=1.0] - maximum encoding error, between 0 (highest quality) and 15 (lowest quality) - * @param {number} [options.quality] - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified - * @param {number} [options.decodingTier=0] - target decode speed tier, between 0 (highest quality) and 4 (lowest quality) - * @param {boolean} [options.lossless=false] - use lossless compression - * @param {number} [options.effort=7] - CPU effort, between 3 (fastest) and 9 (slowest) - * @returns {Sharp} - * @throws {Error} Invalid options - */ -function jxl (options) { - if (is.object(options)) { - if (is.defined(options.quality)) { - if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { - // https://github.com/libjxl/libjxl/blob/0aeea7f180bafd6893c1db8072dcb67d2aa5b03d/tools/cjxl_main.cc#L640-L644 - this.options.jxlDistance = options.quality >= 30 - ? 0.1 + (100 - options.quality) * 0.09 - : 53 / 3000 * options.quality * options.quality - 23 / 20 * options.quality + 25; - } else { - throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); - } - } else if (is.defined(options.distance)) { - if (is.number(options.distance) && is.inRange(options.distance, 0, 15)) { - this.options.jxlDistance = options.distance; - } else { - throw is.invalidParameterError('distance', 'number between 0.0 and 15.0', options.distance); - } - } - if (is.defined(options.decodingTier)) { - if (is.integer(options.decodingTier) && is.inRange(options.decodingTier, 0, 4)) { - this.options.jxlDecodingTier = options.decodingTier; - } else { - throw is.invalidParameterError('decodingTier', 'integer between 0 and 4', options.decodingTier); - } - } - if (is.defined(options.lossless)) { - if (is.bool(options.lossless)) { - this.options.jxlLossless = options.lossless; - } else { - throw is.invalidParameterError('lossless', 'boolean', options.lossless); - } - } - if (is.defined(options.effort)) { - if (is.integer(options.effort) && is.inRange(options.effort, 3, 9)) { - this.options.jxlEffort = options.effort; - } else { - throw is.invalidParameterError('effort', 'integer between 3 and 9', options.effort); - } - } - } - return this._updateFormatOut('jxl', options); -} - -/** - * Force output to be raw, uncompressed pixel data. - * Pixel ordering is left-to-right, top-to-bottom, without padding. - * Channel ordering will be RGB or RGBA for non-greyscale colourspaces. - * - * @example - * // Extract raw, unsigned 8-bit RGB pixel data from JPEG input - * const { data, info } = await sharp('input.jpg') - * .raw() - * .toBuffer({ resolveWithObject: true }); - * - * @example - * // Extract alpha channel as raw, unsigned 16-bit pixel data from PNG input - * const data = await sharp('input.png') - * .ensureAlpha() - * .extractChannel(3) - * .toColourspace('b-w') - * .raw({ depth: 'ushort' }) - * .toBuffer(); - * - * @param {Object} [options] - output options - * @param {string} [options.depth='uchar'] - bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex - * @returns {Sharp} - * @throws {Error} Invalid options - */ -function raw (options) { - if (is.object(options)) { - if (is.defined(options.depth)) { - if (is.string(options.depth) && is.inArray(options.depth, - ['char', 'uchar', 'short', 'ushort', 'int', 'uint', 'float', 'complex', 'double', 'dpcomplex'] - )) { - this.options.rawDepth = options.depth; - } else { - throw is.invalidParameterError('depth', 'one of: char, uchar, short, ushort, int, uint, float, complex, double, dpcomplex', options.depth); - } - } - } - return this._updateFormatOut('raw'); -} - -/** - * Use tile-based deep zoom (image pyramid) output. - * - * Set the format and options for tile images via the `toFormat`, `jpeg`, `png` or `webp` functions. - * Use a `.zip` or `.szi` file extension with `toFile` to write to a compressed archive file format. - * - * The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`. - * - * Requires libvips compiled with support for libgsf. - * The prebuilt binaries do not include this - see - * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}. - * - * @example - * sharp('input.tiff') - * .png() - * .tile({ - * size: 512 - * }) - * .toFile('output.dz', function(err, info) { - * // output.dzi is the Deep Zoom XML definition - * // output_files contains 512x512 tiles grouped by zoom level - * }); - * - * @example - * const zipFileWithTiles = await sharp(input) - * .tile({ basename: "tiles" }) - * .toBuffer(); - * - * @example - * const iiififier = sharp().tile({ layout: "iiif" }); - * readableStream - * .pipe(iiififier) - * .pipe(writeableStream); - * - * @param {Object} [options] - * @param {number} [options.size=256] tile size in pixels, a value between 1 and 8192. - * @param {number} [options.overlap=0] tile overlap in pixels, a value between 0 and 8192. - * @param {number} [options.angle=0] tile angle of rotation, must be a multiple of 90. - * @param {string|Object} [options.background={r: 255, g: 255, b: 255, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency. - * @param {string} [options.depth] how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout. - * @param {number} [options.skipBlanks=-1] Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for `google` layout, -1 (no skip) otherwise. - * @param {string} [options.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file). - * @param {string} [options.layout='dz'] filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`. - * @param {boolean} [options.centre=false] centre image in tile. - * @param {boolean} [options.center=false] alternative spelling of centre. - * @param {string} [options.id='https://example.com/iiif'] when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json` - * @param {string} [options.basename] the name of the directory within the zip file when container is `zip`. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function tile (options) { - if (is.object(options)) { - // Size of square tiles, in pixels - if (is.defined(options.size)) { - if (is.integer(options.size) && is.inRange(options.size, 1, 8192)) { - this.options.tileSize = options.size; - } else { - throw is.invalidParameterError('size', 'integer between 1 and 8192', options.size); - } - } - // Overlap of tiles, in pixels - if (is.defined(options.overlap)) { - if (is.integer(options.overlap) && is.inRange(options.overlap, 0, 8192)) { - if (options.overlap > this.options.tileSize) { - throw is.invalidParameterError('overlap', `<= size (${this.options.tileSize})`, options.overlap); - } - this.options.tileOverlap = options.overlap; - } else { - throw is.invalidParameterError('overlap', 'integer between 0 and 8192', options.overlap); - } - } - // Container - if (is.defined(options.container)) { - if (is.string(options.container) && is.inArray(options.container, ['fs', 'zip'])) { - this.options.tileContainer = options.container; - } else { - throw is.invalidParameterError('container', 'one of: fs, zip', options.container); - } - } - // Layout - if (is.defined(options.layout)) { - if (is.string(options.layout) && is.inArray(options.layout, ['dz', 'google', 'iiif', 'iiif3', 'zoomify'])) { - this.options.tileLayout = options.layout; - } else { - throw is.invalidParameterError('layout', 'one of: dz, google, iiif, iiif3, zoomify', options.layout); - } - } - // Angle of rotation, - if (is.defined(options.angle)) { - if (is.integer(options.angle) && !(options.angle % 90)) { - this.options.tileAngle = options.angle; - } else { - throw is.invalidParameterError('angle', 'positive/negative multiple of 90', options.angle); - } - } - // Background colour - this._setBackgroundColourOption('tileBackground', options.background); - // Depth of tiles - if (is.defined(options.depth)) { - if (is.string(options.depth) && is.inArray(options.depth, ['onepixel', 'onetile', 'one'])) { - this.options.tileDepth = options.depth; - } else { - throw is.invalidParameterError('depth', 'one of: onepixel, onetile, one', options.depth); - } - } - // Threshold to skip blank tiles - if (is.defined(options.skipBlanks)) { - if (is.integer(options.skipBlanks) && is.inRange(options.skipBlanks, -1, 65535)) { - this.options.tileSkipBlanks = options.skipBlanks; - } else { - throw is.invalidParameterError('skipBlanks', 'integer between -1 and 255/65535', options.skipBlanks); - } - } else if (is.defined(options.layout) && options.layout === 'google') { - this.options.tileSkipBlanks = 5; - } - // Center image in tile - const centre = is.bool(options.center) ? options.center : options.centre; - if (is.defined(centre)) { - this._setBooleanOption('tileCentre', centre); - } - // @id attribute for IIIF layout - if (is.defined(options.id)) { - if (is.string(options.id)) { - this.options.tileId = options.id; - } else { - throw is.invalidParameterError('id', 'string', options.id); - } - } - // Basename for zip container - if (is.defined(options.basename)) { - if (is.string(options.basename)) { - this.options.tileBasename = options.basename; - } else { - throw is.invalidParameterError('basename', 'string', options.basename); - } - } - } - // Format - if (is.inArray(this.options.formatOut, ['jpeg', 'png', 'webp'])) { - this.options.tileFormat = this.options.formatOut; - } else if (this.options.formatOut !== 'input') { - throw is.invalidParameterError('format', 'one of: jpeg, png, webp', this.options.formatOut); - } - return this._updateFormatOut('dz'); -} - -/** - * Set a timeout for processing, in seconds. - * Use a value of zero to continue processing indefinitely, the default behaviour. - * - * The clock starts when libvips opens an input image for processing. - * Time spent waiting for a libuv thread to become available is not included. - * - * @example - * // Ensure processing takes no longer than 3 seconds - * try { - * const data = await sharp(input) - * .blur(1000) - * .timeout({ seconds: 3 }) - * .toBuffer(); - * } catch (err) { - * if (err.message.includes('timeout')) { ... } - * } - * - * @since 0.29.2 - * - * @param {Object} options - * @param {number} options.seconds - Number of seconds after which processing will be stopped - * @returns {Sharp} - */ -function timeout (options) { - if (!is.plainObject(options)) { - throw is.invalidParameterError('options', 'object', options); - } - if (is.integer(options.seconds) && is.inRange(options.seconds, 0, 3600)) { - this.options.timeoutSeconds = options.seconds; - } else { - throw is.invalidParameterError('seconds', 'integer between 0 and 3600', options.seconds); - } - return this; -} - -/** - * Update the output format unless options.force is false, - * in which case revert to input format. - * @private - * @param {string} formatOut - * @param {Object} [options] - * @param {boolean} [options.force=true] - force output format, otherwise attempt to use input format - * @returns {Sharp} - */ -function _updateFormatOut (formatOut, options) { - if (!(is.object(options) && options.force === false)) { - this.options.formatOut = formatOut; - } - return this; -} - -/** - * Update a boolean attribute of the this.options Object. - * @private - * @param {string} key - * @param {boolean} val - * @throws {Error} Invalid key - */ -function _setBooleanOption (key, val) { - if (is.bool(val)) { - this.options[key] = val; - } else { - throw is.invalidParameterError(key, 'boolean', val); - } -} - -/** - * Called by a WriteableStream to notify us it is ready for data. - * @private - */ -function _read () { - /* istanbul ignore else */ - if (!this.options.streamOut) { - this.options.streamOut = true; - const stack = Error(); - this._pipeline(undefined, stack); - } -} - -/** - * Invoke the C++ image processing pipeline - * Supports callback, stream and promise variants - * @private - */ -function _pipeline (callback, stack) { - if (typeof callback === 'function') { - // output=file/buffer - if (this._isStreamInput()) { - // output=file/buffer, input=stream - this.on('finish', () => { - this._flattenBufferIn(); - sharp.pipeline(this.options, (err, data, info) => { - if (err) { - callback(is.nativeError(err, stack)); - } else { - callback(null, data, info); - } - }); - }); - } else { - // output=file/buffer, input=file/buffer - sharp.pipeline(this.options, (err, data, info) => { - if (err) { - callback(is.nativeError(err, stack)); - } else { - callback(null, data, info); - } - }); - } - return this; - } else if (this.options.streamOut) { - // output=stream - if (this._isStreamInput()) { - // output=stream, input=stream - this.once('finish', () => { - this._flattenBufferIn(); - sharp.pipeline(this.options, (err, data, info) => { - if (err) { - this.emit('error', is.nativeError(err, stack)); - } else { - this.emit('info', info); - this.push(data); - } - this.push(null); - this.on('end', () => this.emit('close')); - }); - }); - if (this.streamInFinished) { - this.emit('finish'); - } - } else { - // output=stream, input=file/buffer - sharp.pipeline(this.options, (err, data, info) => { - if (err) { - this.emit('error', is.nativeError(err, stack)); - } else { - this.emit('info', info); - this.push(data); - } - this.push(null); - this.on('end', () => this.emit('close')); - }); - } - return this; - } else { - // output=promise - if (this._isStreamInput()) { - // output=promise, input=stream - return new Promise((resolve, reject) => { - this.once('finish', () => { - this._flattenBufferIn(); - sharp.pipeline(this.options, (err, data, info) => { - if (err) { - reject(is.nativeError(err, stack)); - } else { - if (this.options.resolveWithObject) { - resolve({ data, info }); - } else { - resolve(data); - } - } - }); - }); - }); - } else { - // output=promise, input=file/buffer - return new Promise((resolve, reject) => { - sharp.pipeline(this.options, (err, data, info) => { - if (err) { - reject(is.nativeError(err, stack)); - } else { - if (this.options.resolveWithObject) { - resolve({ data, info }); - } else { - resolve(data); - } - } - }); - }); - } - } -} - -/** - * Decorate the Sharp prototype with output-related functions. - * @private - */ -module.exports = function (Sharp) { - Object.assign(Sharp.prototype, { - // Public - toFile, - toBuffer, - keepExif, - withExif, - withExifMerge, - keepIccProfile, - withIccProfile, - keepMetadata, - withMetadata, - toFormat, - jpeg, - jp2, - png, - webp, - tiff, - avif, - heif, - jxl, - gif, - raw, - tile, - timeout, - // Private - _updateFormatOut, - _setBooleanOption, - _read, - _pipeline - }); -}; diff --git a/node_modules/sharp/lib/resize.js b/node_modules/sharp/lib/resize.js deleted file mode 100644 index e4fcdd61..00000000 --- a/node_modules/sharp/lib/resize.js +++ /dev/null @@ -1,582 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const is = require('./is'); - -/** - * Weighting to apply when using contain/cover fit. - * @member - * @private - */ -const gravity = { - center: 0, - centre: 0, - north: 1, - east: 2, - south: 3, - west: 4, - northeast: 5, - southeast: 6, - southwest: 7, - northwest: 8 -}; - -/** - * Position to apply when using contain/cover fit. - * @member - * @private - */ -const position = { - top: 1, - right: 2, - bottom: 3, - left: 4, - 'right top': 5, - 'right bottom': 6, - 'left bottom': 7, - 'left top': 8 -}; - -/** - * How to extend the image. - * @member - * @private - */ -const extendWith = { - background: 'background', - copy: 'copy', - repeat: 'repeat', - mirror: 'mirror' -}; - -/** - * Strategies for automagic cover behaviour. - * @member - * @private - */ -const strategy = { - entropy: 16, - attention: 17 -}; - -/** - * Reduction kernels. - * @member - * @private - */ -const kernel = { - nearest: 'nearest', - cubic: 'cubic', - mitchell: 'mitchell', - lanczos2: 'lanczos2', - lanczos3: 'lanczos3' -}; - -/** - * Methods by which an image can be resized to fit the provided dimensions. - * @member - * @private - */ -const fit = { - contain: 'contain', - cover: 'cover', - fill: 'fill', - inside: 'inside', - outside: 'outside' -}; - -/** - * Map external fit property to internal canvas property. - * @member - * @private - */ -const mapFitToCanvas = { - contain: 'embed', - cover: 'crop', - fill: 'ignore_aspect', - inside: 'max', - outside: 'min' -}; - -/** - * @private - */ -function isRotationExpected (options) { - return (options.angle % 360) !== 0 || options.useExifOrientation === true || options.rotationAngle !== 0; -} - -/** - * @private - */ -function isResizeExpected (options) { - return options.width !== -1 || options.height !== -1; -} - -/** - * Resize image to `width`, `height` or `width x height`. - * - * When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are: - * - `cover`: (default) Preserving aspect ratio, attempt to ensure the image covers both provided dimensions by cropping/clipping to fit. - * - `contain`: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary. - * - `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions. - * - `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified. - * - `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified. - * - * Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property. - * - * Examples of various values for the fit property when resizing - * - * When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are: - * - `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`. - * - `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`. - * - `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy. - * - * Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property. - * - * The experimental strategy-based approach resizes so one dimension is at its target length - * then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy. - * - `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29). - * - `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones. - * - * Possible interpolation kernels are: - * - `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). - * - `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline). - * - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf). - * - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`. - * - `lanczos3`: Use a Lanczos kernel with `a=3` (the default). - * - * Only one resize can occur per pipeline. - * Previous calls to `resize` in the same pipeline will be ignored. - * - * @example - * sharp(input) - * .resize({ width: 100 }) - * .toBuffer() - * .then(data => { - * // 100 pixels wide, auto-scaled height - * }); - * - * @example - * sharp(input) - * .resize({ height: 100 }) - * .toBuffer() - * .then(data => { - * // 100 pixels high, auto-scaled width - * }); - * - * @example - * sharp(input) - * .resize(200, 300, { - * kernel: sharp.kernel.nearest, - * fit: 'contain', - * position: 'right top', - * background: { r: 255, g: 255, b: 255, alpha: 0.5 } - * }) - * .toFile('output.png') - * .then(() => { - * // output.png is a 200 pixels wide and 300 pixels high image - * // containing a nearest-neighbour scaled version - * // contained within the north-east corner of a semi-transparent white canvas - * }); - * - * @example - * const transformer = sharp() - * .resize({ - * width: 200, - * height: 200, - * fit: sharp.fit.cover, - * position: sharp.strategy.entropy - * }); - * // Read image data from readableStream - * // Write 200px square auto-cropped image data to writableStream - * readableStream - * .pipe(transformer) - * .pipe(writableStream); - * - * @example - * sharp(input) - * .resize(200, 200, { - * fit: sharp.fit.inside, - * withoutEnlargement: true - * }) - * .toFormat('jpeg') - * .toBuffer() - * .then(function(outputBuffer) { - * // outputBuffer contains JPEG image data - * // no wider and no higher than 200 pixels - * // and no larger than the input image - * }); - * - * @example - * sharp(input) - * .resize(200, 200, { - * fit: sharp.fit.outside, - * withoutReduction: true - * }) - * .toFormat('jpeg') - * .toBuffer() - * .then(function(outputBuffer) { - * // outputBuffer contains JPEG image data - * // of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio - * // and no smaller than the input image - * }); - * - * @example - * const scaleByHalf = await sharp(input) - * .metadata() - * .then(({ width }) => sharp(input) - * .resize(Math.round(width * 0.5)) - * .toBuffer() - * ); - * - * @param {number} [width] - How many pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height. - * @param {number} [height] - How many pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width. - * @param {Object} [options] - * @param {number} [options.width] - An alternative means of specifying `width`. If both are present this takes priority. - * @param {number} [options.height] - An alternative means of specifying `height`. If both are present this takes priority. - * @param {String} [options.fit='cover'] - How the image should be resized/cropped to fit the target dimension(s), one of `cover`, `contain`, `fill`, `inside` or `outside`. - * @param {String} [options.position='centre'] - A position, gravity or strategy to use when `fit` is `cover` or `contain`. - * @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. - * @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load. - * @param {Boolean} [options.withoutEnlargement=false] - Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions. - * @param {Boolean} [options.withoutReduction=false] - Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions. - * @param {Boolean} [options.fastShrinkOnLoad=true] - Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension. - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function resize (widthOrOptions, height, options) { - if (isResizeExpected(this.options)) { - this.options.debuglog('ignoring previous resize options'); - } - if (this.options.widthPost !== -1) { - this.options.debuglog('operation order will be: extract, resize, extract'); - } - if (is.defined(widthOrOptions)) { - if (is.object(widthOrOptions) && !is.defined(options)) { - options = widthOrOptions; - } else if (is.integer(widthOrOptions) && widthOrOptions > 0) { - this.options.width = widthOrOptions; - } else { - throw is.invalidParameterError('width', 'positive integer', widthOrOptions); - } - } else { - this.options.width = -1; - } - if (is.defined(height)) { - if (is.integer(height) && height > 0) { - this.options.height = height; - } else { - throw is.invalidParameterError('height', 'positive integer', height); - } - } else { - this.options.height = -1; - } - if (is.object(options)) { - // Width - if (is.defined(options.width)) { - if (is.integer(options.width) && options.width > 0) { - this.options.width = options.width; - } else { - throw is.invalidParameterError('width', 'positive integer', options.width); - } - } - // Height - if (is.defined(options.height)) { - if (is.integer(options.height) && options.height > 0) { - this.options.height = options.height; - } else { - throw is.invalidParameterError('height', 'positive integer', options.height); - } - } - // Fit - if (is.defined(options.fit)) { - const canvas = mapFitToCanvas[options.fit]; - if (is.string(canvas)) { - this.options.canvas = canvas; - } else { - throw is.invalidParameterError('fit', 'valid fit', options.fit); - } - } - // Position - if (is.defined(options.position)) { - const pos = is.integer(options.position) - ? options.position - : strategy[options.position] || position[options.position] || gravity[options.position]; - if (is.integer(pos) && (is.inRange(pos, 0, 8) || is.inRange(pos, 16, 17))) { - this.options.position = pos; - } else { - throw is.invalidParameterError('position', 'valid position/gravity/strategy', options.position); - } - } - // Background - this._setBackgroundColourOption('resizeBackground', options.background); - // Kernel - if (is.defined(options.kernel)) { - if (is.string(kernel[options.kernel])) { - this.options.kernel = kernel[options.kernel]; - } else { - throw is.invalidParameterError('kernel', 'valid kernel name', options.kernel); - } - } - // Without enlargement - if (is.defined(options.withoutEnlargement)) { - this._setBooleanOption('withoutEnlargement', options.withoutEnlargement); - } - // Without reduction - if (is.defined(options.withoutReduction)) { - this._setBooleanOption('withoutReduction', options.withoutReduction); - } - // Shrink on load - if (is.defined(options.fastShrinkOnLoad)) { - this._setBooleanOption('fastShrinkOnLoad', options.fastShrinkOnLoad); - } - } - if (isRotationExpected(this.options) && isResizeExpected(this.options)) { - this.options.rotateBeforePreExtract = true; - } - return this; -} - -/** - * Extend / pad / extrude one or more edges of the image with either - * the provided background colour or pixels derived from the image. - * This operation will always occur after resizing and extraction, if any. - * - * @example - * // Resize to 140 pixels wide, then add 10 transparent pixels - * // to the top, left and right edges and 20 to the bottom edge - * sharp(input) - * .resize(140) - * .extend({ - * top: 10, - * bottom: 20, - * left: 10, - * right: 10, - * background: { r: 0, g: 0, b: 0, alpha: 0 } - * }) - * ... - * -* @example - * // Add a row of 10 red pixels to the bottom - * sharp(input) - * .extend({ - * bottom: 10, - * background: 'red' - * }) - * ... - * - * @example - * // Extrude image by 8 pixels to the right, mirroring existing right hand edge - * sharp(input) - * .extend({ - * right: 8, - * background: 'mirror' - * }) - * ... - * - * @param {(number|Object)} extend - single pixel count to add to all edges or an Object with per-edge counts - * @param {number} [extend.top=0] - * @param {number} [extend.left=0] - * @param {number} [extend.bottom=0] - * @param {number} [extend.right=0] - * @param {String} [extend.extendWith='background'] - populate new pixels using this method, one of: background, copy, repeat, mirror. - * @param {String|Object} [extend.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. - * @returns {Sharp} - * @throws {Error} Invalid parameters -*/ -function extend (extend) { - if (is.integer(extend) && extend > 0) { - this.options.extendTop = extend; - this.options.extendBottom = extend; - this.options.extendLeft = extend; - this.options.extendRight = extend; - } else if (is.object(extend)) { - if (is.defined(extend.top)) { - if (is.integer(extend.top) && extend.top >= 0) { - this.options.extendTop = extend.top; - } else { - throw is.invalidParameterError('top', 'positive integer', extend.top); - } - } - if (is.defined(extend.bottom)) { - if (is.integer(extend.bottom) && extend.bottom >= 0) { - this.options.extendBottom = extend.bottom; - } else { - throw is.invalidParameterError('bottom', 'positive integer', extend.bottom); - } - } - if (is.defined(extend.left)) { - if (is.integer(extend.left) && extend.left >= 0) { - this.options.extendLeft = extend.left; - } else { - throw is.invalidParameterError('left', 'positive integer', extend.left); - } - } - if (is.defined(extend.right)) { - if (is.integer(extend.right) && extend.right >= 0) { - this.options.extendRight = extend.right; - } else { - throw is.invalidParameterError('right', 'positive integer', extend.right); - } - } - this._setBackgroundColourOption('extendBackground', extend.background); - if (is.defined(extend.extendWith)) { - if (is.string(extendWith[extend.extendWith])) { - this.options.extendWith = extendWith[extend.extendWith]; - } else { - throw is.invalidParameterError('extendWith', 'one of: background, copy, repeat, mirror', extend.extendWith); - } - } - } else { - throw is.invalidParameterError('extend', 'integer or object', extend); - } - return this; -} - -/** - * Extract/crop a region of the image. - * - * - Use `extract` before `resize` for pre-resize extraction. - * - Use `extract` after `resize` for post-resize extraction. - * - Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order. - * - * @example - * sharp(input) - * .extract({ left: left, top: top, width: width, height: height }) - * .toFile(output, function(err) { - * // Extract a region of the input image, saving in the same format. - * }); - * @example - * sharp(input) - * .extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre }) - * .resize(width, height) - * .extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost }) - * .toFile(output, function(err) { - * // Extract a region, resize, then extract from the resized image - * }); - * - * @param {Object} options - describes the region to extract using integral pixel values - * @param {number} options.left - zero-indexed offset from left edge - * @param {number} options.top - zero-indexed offset from top edge - * @param {number} options.width - width of region to extract - * @param {number} options.height - height of region to extract - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function extract (options) { - const suffix = isResizeExpected(this.options) || this.options.widthPre !== -1 ? 'Post' : 'Pre'; - if (this.options[`width${suffix}`] !== -1) { - this.options.debuglog('ignoring previous extract options'); - } - ['left', 'top', 'width', 'height'].forEach(function (name) { - const value = options[name]; - if (is.integer(value) && value >= 0) { - this.options[name + (name === 'left' || name === 'top' ? 'Offset' : '') + suffix] = value; - } else { - throw is.invalidParameterError(name, 'integer', value); - } - }, this); - // Ensure existing rotation occurs before pre-resize extraction - if (isRotationExpected(this.options) && !isResizeExpected(this.options)) { - if (this.options.widthPre === -1 || this.options.widthPost === -1) { - this.options.rotateBeforePreExtract = true; - } - } - return this; -} - -/** - * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel. - * - * Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels. - * - * If the result of this operation would trim an image to nothing then no change is made. - * - * The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties. - * - * @example - * // Trim pixels with a colour similar to that of the top-left pixel. - * await sharp(input) - * .trim() - * .toFile(output); - * - * @example - * // Trim pixels with the exact same colour as that of the top-left pixel. - * await sharp(input) - * .trim({ - * threshold: 0 - * }) - * .toFile(output); - * - * @example - * // Assume input is line art and trim only pixels with a similar colour to red. - * const output = await sharp(input) - * .trim({ - * background: "#FF0000", - * lineArt: true - * }) - * .toBuffer(); - * - * @example - * // Trim all "yellow-ish" pixels, being more lenient with the higher threshold. - * const output = await sharp(input) - * .trim({ - * background: "yellow", - * threshold: 42, - * }) - * .toBuffer(); - * - * @param {Object} [options] - * @param {string|Object} [options.background='top-left pixel'] - Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel. - * @param {number} [options.threshold=10] - Allowed difference from the above colour, a positive number. - * @param {boolean} [options.lineArt=false] - Does the input more closely resemble line art (e.g. vector) rather than being photographic? - * @returns {Sharp} - * @throws {Error} Invalid parameters - */ -function trim (options) { - this.options.trimThreshold = 10; - if (is.defined(options)) { - if (is.object(options)) { - if (is.defined(options.background)) { - this._setBackgroundColourOption('trimBackground', options.background); - } - if (is.defined(options.threshold)) { - if (is.number(options.threshold) && options.threshold >= 0) { - this.options.trimThreshold = options.threshold; - } else { - throw is.invalidParameterError('threshold', 'positive number', options.threshold); - } - } - if (is.defined(options.lineArt)) { - this._setBooleanOption('trimLineArt', options.lineArt); - } - } else { - throw is.invalidParameterError('trim', 'object', options); - } - } - if (isRotationExpected(this.options)) { - this.options.rotateBeforePreExtract = true; - } - return this; -} - -/** - * Decorate the Sharp prototype with resize-related functions. - * @private - */ -module.exports = function (Sharp) { - Object.assign(Sharp.prototype, { - resize, - extend, - extract, - trim - }); - // Class attributes - Sharp.gravity = gravity; - Sharp.strategy = strategy; - Sharp.kernel = kernel; - Sharp.fit = fit; - Sharp.position = position; -}; diff --git a/node_modules/sharp/lib/sharp.js b/node_modules/sharp/lib/sharp.js deleted file mode 100644 index 44c7463a..00000000 --- a/node_modules/sharp/lib/sharp.js +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -// Inspects the runtime environment and exports the relevant sharp.node binary - -const { familySync, versionSync } = require('detect-libc'); - -const { runtimePlatformArch, isUnsupportedNodeRuntime, prebuiltPlatforms, minimumLibvipsVersion } = require('./libvips'); -const runtimePlatform = runtimePlatformArch(); - -const paths = [ - `../src/build/Release/sharp-${runtimePlatform}.node`, - '../src/build/Release/sharp-wasm32.node', - `@img/sharp-${runtimePlatform}/sharp.node`, - '@img/sharp-wasm32/sharp.node' -]; - -let sharp; -const errors = []; -for (const path of paths) { - try { - sharp = require(path); - break; - } catch (err) { - /* istanbul ignore next */ - errors.push(err); - } -} - -/* istanbul ignore next */ -if (sharp) { - module.exports = sharp; -} else { - const [isLinux, isMacOs, isWindows] = ['linux', 'darwin', 'win32'].map(os => runtimePlatform.startsWith(os)); - - const help = [`Could not load the "sharp" module using the ${runtimePlatform} runtime`]; - errors.forEach(err => { - if (err.code !== 'MODULE_NOT_FOUND') { - help.push(`${err.code}: ${err.message}`); - } - }); - const messages = errors.map(err => err.message).join(' '); - help.push('Possible solutions:'); - // Common error messages - if (isUnsupportedNodeRuntime()) { - const { found, expected } = isUnsupportedNodeRuntime(); - help.push( - '- Please upgrade Node.js:', - ` Found ${found}`, - ` Requires ${expected}` - ); - } else if (prebuiltPlatforms.includes(runtimePlatform)) { - const [os, cpu] = runtimePlatform.split('-'); - const libc = os.endsWith('musl') ? ' --libc=musl' : ''; - help.push( - '- Ensure optional dependencies can be installed:', - ' npm install --include=optional sharp', - ' yarn add sharp --ignore-engines', - '- Ensure your package manager supports multi-platform installation:', - ' See https://sharp.pixelplumbing.com/install#cross-platform', - '- Add platform-specific dependencies:', - ` npm install --os=${os.replace('musl', '')}${libc} --cpu=${cpu} sharp` - ); - } else { - help.push( - `- Manually install libvips >= ${minimumLibvipsVersion}`, - '- Add experimental WebAssembly-based dependencies:', - ' npm install --cpu=wasm32 sharp', - ' npm install @img/sharp-wasm32' - ); - } - if (isLinux && /(symbol not found|CXXABI_)/i.test(messages)) { - try { - const { engines } = require(`@img/sharp-libvips-${runtimePlatform}/package`); - const libcFound = `${familySync()} ${versionSync()}`; - const libcRequires = `${engines.musl ? 'musl' : 'glibc'} ${engines.musl || engines.glibc}`; - help.push( - '- Update your OS:', - ` Found ${libcFound}`, - ` Requires ${libcRequires}` - ); - } catch (errEngines) {} - } - if (isLinux && /\/snap\/core[0-9]{2}/.test(messages)) { - help.push( - '- Remove the Node.js Snap, which does not support native modules', - ' snap remove node' - ); - } - if (isMacOs && /Incompatible library version/.test(messages)) { - help.push( - '- Update Homebrew:', - ' brew update && brew upgrade vips' - ); - } - if (errors.some(err => err.code === 'ERR_DLOPEN_DISABLED')) { - help.push('- Run Node.js without using the --no-addons flag'); - } - // Link to installation docs - if (isWindows && /The specified procedure could not be found/.test(messages)) { - help.push( - '- Using the canvas package on Windows?', - ' See https://sharp.pixelplumbing.com/install#canvas-and-windows', - '- Check for outdated versions of sharp in the dependency tree:', - ' npm ls sharp' - ); - } - help.push( - '- Consult the installation documentation:', - ' See https://sharp.pixelplumbing.com/install' - ); - throw new Error(help.join('\n')); -} diff --git a/node_modules/sharp/lib/utility.js b/node_modules/sharp/lib/utility.js deleted file mode 100644 index 3af1b69a..00000000 --- a/node_modules/sharp/lib/utility.js +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const events = require('node:events'); -const detectLibc = require('detect-libc'); - -const is = require('./is'); -const { runtimePlatformArch } = require('./libvips'); -const sharp = require('./sharp'); - -const runtimePlatform = runtimePlatformArch(); -const libvipsVersion = sharp.libvipsVersion(); - -/** - * An Object containing nested boolean values representing the available input and output formats/methods. - * @member - * @example - * console.log(sharp.format); - * @returns {Object} - */ -const format = sharp.format(); -format.heif.output.alias = ['avif', 'heic']; -format.jpeg.output.alias = ['jpe', 'jpg']; -format.tiff.output.alias = ['tif']; -format.jp2k.output.alias = ['j2c', 'j2k', 'jp2', 'jpx']; - -/** - * An Object containing the available interpolators and their proper values - * @readonly - * @enum {string} - */ -const interpolators = { - /** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */ - nearest: 'nearest', - /** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */ - bilinear: 'bilinear', - /** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */ - bicubic: 'bicubic', - /** [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2. */ - locallyBoundedBicubic: 'lbb', - /** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */ - nohalo: 'nohalo', - /** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */ - vertexSplitQuadraticBasisSpline: 'vsqbs' -}; - -/** - * An Object containing the version numbers of sharp, libvips - * and (when using prebuilt binaries) its dependencies. - * - * @member - * @example - * console.log(sharp.versions); - */ -let versions = { - vips: libvipsVersion.semver -}; -/* istanbul ignore next */ -if (!libvipsVersion.isGlobal) { - if (!libvipsVersion.isWasm) { - try { - versions = require(`@img/sharp-${runtimePlatform}/versions`); - } catch (_) { - try { - versions = require(`@img/sharp-libvips-${runtimePlatform}/versions`); - } catch (_) {} - } - } else { - try { - versions = require('@img/sharp-wasm32/versions'); - } catch (_) {} - } -} -versions.sharp = require('../package.json').version; - -/** - * Gets or, when options are provided, sets the limits of _libvips'_ operation cache. - * Existing entries in the cache will be trimmed after any change in limits. - * This method always returns cache statistics, - * useful for determining how much working memory is required for a particular task. - * - * @example - * const stats = sharp.cache(); - * @example - * sharp.cache( { items: 200 } ); - * sharp.cache( { files: 0 } ); - * sharp.cache(false); - * - * @param {Object|boolean} [options=true] - Object with the following attributes, or boolean where true uses default cache settings and false removes all caching - * @param {number} [options.memory=50] - is the maximum memory in MB to use for this cache - * @param {number} [options.files=20] - is the maximum number of files to hold open - * @param {number} [options.items=100] - is the maximum number of operations to cache - * @returns {Object} - */ -function cache (options) { - if (is.bool(options)) { - if (options) { - // Default cache settings of 50MB, 20 files, 100 items - return sharp.cache(50, 20, 100); - } else { - return sharp.cache(0, 0, 0); - } - } else if (is.object(options)) { - return sharp.cache(options.memory, options.files, options.items); - } else { - return sharp.cache(); - } -} -cache(true); - -/** - * Gets or, when a concurrency is provided, sets - * the maximum number of threads _libvips_ should use to process _each image_. - * These are from a thread pool managed by glib, - * which helps avoid the overhead of creating new threads. - * - * This method always returns the current concurrency. - * - * The default value is the number of CPU cores, - * except when using glibc-based Linux without jemalloc, - * where the default is `1` to help reduce memory fragmentation. - * - * A value of `0` will reset this to the number of CPU cores. - * - * Some image format libraries spawn additional threads, - * e.g. libaom manages its own 4 threads when encoding AVIF images, - * and these are independent of the value set here. - * - * The maximum number of images that sharp can process in parallel - * is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable, - * which defaults to 4. - * - * https://nodejs.org/api/cli.html#uv_threadpool_sizesize - * - * For example, by default, a machine with 8 CPU cores will process - * 4 images in parallel and use up to 8 threads per image, - * so there will be up to 32 concurrent threads. - * - * @example - * const threads = sharp.concurrency(); // 4 - * sharp.concurrency(2); // 2 - * sharp.concurrency(0); // 4 - * - * @param {number} [concurrency] - * @returns {number} concurrency - */ -function concurrency (concurrency) { - return sharp.concurrency(is.integer(concurrency) ? concurrency : null); -} -/* istanbul ignore next */ -if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) { - // Reduce default concurrency to 1 when using glibc memory allocator - sharp.concurrency(1); -} - -/** - * An EventEmitter that emits a `change` event when a task is either: - * - queued, waiting for _libuv_ to provide a worker thread - * - complete - * @member - * @example - * sharp.queue.on('change', function(queueLength) { - * console.log('Queue contains ' + queueLength + ' task(s)'); - * }); - */ -const queue = new events.EventEmitter(); - -/** - * Provides access to internal task counters. - * - queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool. - * - process is the number of resize tasks currently being processed. - * - * @example - * const counters = sharp.counters(); // { queue: 2, process: 4 } - * - * @returns {Object} - */ -function counters () { - return sharp.counters(); -} - -/** - * Get and set use of SIMD vector unit instructions. - * Requires libvips to have been compiled with highway support. - * - * Improves the performance of `resize`, `blur` and `sharpen` operations - * by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON. - * - * @example - * const simd = sharp.simd(); - * // simd is `true` if the runtime use of highway is currently enabled - * @example - * const simd = sharp.simd(false); - * // prevent libvips from using highway at runtime - * - * @param {boolean} [simd=true] - * @returns {boolean} - */ -function simd (simd) { - return sharp.simd(is.bool(simd) ? simd : null); -} - -/** - * Block libvips operations at runtime. - * - * This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable, - * which when set will block all "untrusted" operations. - * - * @since 0.32.4 - * - * @example Block all TIFF input. - * sharp.block({ - * operation: ['VipsForeignLoadTiff'] - * }); - * - * @param {Object} options - * @param {Array} options.operation - List of libvips low-level operation names to block. - */ -function block (options) { - if (is.object(options)) { - if (Array.isArray(options.operation) && options.operation.every(is.string)) { - sharp.block(options.operation, true); - } else { - throw is.invalidParameterError('operation', 'Array', options.operation); - } - } else { - throw is.invalidParameterError('options', 'object', options); - } -} - -/** - * Unblock libvips operations at runtime. - * - * This is useful for defining a list of allowed operations. - * - * @since 0.32.4 - * - * @example Block all input except WebP from the filesystem. - * sharp.block({ - * operation: ['VipsForeignLoad'] - * }); - * sharp.unblock({ - * operation: ['VipsForeignLoadWebpFile'] - * }); - * - * @example Block all input except JPEG and PNG from a Buffer or Stream. - * sharp.block({ - * operation: ['VipsForeignLoad'] - * }); - * sharp.unblock({ - * operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer'] - * }); - * - * @param {Object} options - * @param {Array} options.operation - List of libvips low-level operation names to unblock. - */ -function unblock (options) { - if (is.object(options)) { - if (Array.isArray(options.operation) && options.operation.every(is.string)) { - sharp.block(options.operation, false); - } else { - throw is.invalidParameterError('operation', 'Array', options.operation); - } - } else { - throw is.invalidParameterError('options', 'object', options); - } -} - -/** - * Decorate the Sharp class with utility-related functions. - * @private - */ -module.exports = function (Sharp) { - Sharp.cache = cache; - Sharp.concurrency = concurrency; - Sharp.counters = counters; - Sharp.simd = simd; - Sharp.format = format; - Sharp.interpolators = interpolators; - Sharp.versions = versions; - Sharp.queue = queue; - Sharp.block = block; - Sharp.unblock = unblock; -}; diff --git a/node_modules/sharp/package.json b/node_modules/sharp/package.json deleted file mode 100644 index 645e73b3..00000000 --- a/node_modules/sharp/package.json +++ /dev/null @@ -1,219 +0,0 @@ -{ - "name": "sharp", - "description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images", - "version": "0.33.3", - "author": "Lovell Fuller ", - "homepage": "https://sharp.pixelplumbing.com", - "contributors": [ - "Pierre Inglebert ", - "Jonathan Ong ", - "Chanon Sajjamanochai ", - "Juliano Julio ", - "Daniel Gasienica ", - "Julian Walker ", - "Amit Pitaru ", - "Brandon Aaron ", - "Andreas Lind ", - "Maurus Cuelenaere ", - "Linus Unnebäck ", - "Victor Mateevitsi ", - "Alaric Holloway ", - "Bernhard K. Weisshuhn ", - "Chris Riley ", - "David Carley ", - "John Tobin ", - "Kenton Gray ", - "Felix Bünemann ", - "Samy Al Zahrani ", - "Chintan Thakkar ", - "F. Orlando Galashan ", - "Kleis Auke Wolthuizen ", - "Matt Hirsch ", - "Matthias Thoemmes ", - "Patrick Paskaris ", - "Jérémy Lal ", - "Rahul Nanwani ", - "Alice Monday ", - "Kristo Jorgenson ", - "YvesBos ", - "Guy Maliar ", - "Nicolas Coden ", - "Matt Parrish ", - "Marcel Bretschneider ", - "Matthew McEachen ", - "Jarda Kotěšovec ", - "Kenric D'Souza ", - "Oleh Aleinyk ", - "Marcel Bretschneider ", - "Andrea Bianco ", - "Rik Heywood ", - "Thomas Parisot ", - "Nathan Graves ", - "Tom Lokhorst ", - "Espen Hovlandsdal ", - "Sylvain Dumont ", - "Alun Davies ", - "Aidan Hoolachan ", - "Axel Eirola ", - "Freezy ", - "Daiz ", - "Julian Aubourg ", - "Keith Belovay ", - "Michael B. Klein ", - "Jordan Prudhomme ", - "Ilya Ovdin ", - "Andargor ", - "Paul Neave ", - "Brendan Kennedy ", - "Brychan Bennett-Odlum ", - "Edward Silverton ", - "Roman Malieiev ", - "Tomas Szabo ", - "Robert O'Rourke ", - "Guillermo Alfonso Varela Chouciño ", - "Christian Flintrup ", - "Manan Jadhav ", - "Leon Radley ", - "alza54 ", - "Jacob Smith ", - "Michael Nutt ", - "Brad Parham ", - "Taneli Vatanen ", - "Joris Dugué ", - "Chris Banks ", - "Ompal Singh ", - "Brodan ", - "Brahim Ait elhaj ", - "Mart Jansink ", - "Lachlan Newman ", - "Dennis Beatty ", - "Ingvar Stepanyan " - ], - "scripts": { - "install": "node install/check", - "clean": "rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*", - "test": "npm run test-lint && npm run test-unit && npm run test-licensing && npm run test-types", - "test-lint": "semistandard && cpplint", - "test-unit": "nyc --reporter=lcov --reporter=text --check-coverage --branches=100 mocha", - "test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;LGPL-3.0-or-later;MIT\"", - "test-leak": "./test/leak/leak.sh", - "test-types": "tsd", - "package-from-local-build": "node npm/from-local-build", - "package-from-github-release": "node npm/from-github-release", - "docs-build": "node docs/build && node docs/search-index/build", - "docs-serve": "cd docs && npx serve", - "docs-publish": "cd docs && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp" - }, - "type": "commonjs", - "main": "lib/index.js", - "types": "lib/index.d.ts", - "files": [ - "install", - "lib", - "src/*.{cc,h,gyp}" - ], - "repository": { - "type": "git", - "url": "git://github.com/lovell/sharp.git" - }, - "keywords": [ - "jpeg", - "png", - "webp", - "avif", - "tiff", - "gif", - "svg", - "jp2", - "dzi", - "image", - "resize", - "thumbnail", - "crop", - "embed", - "libvips", - "vips" - ], - "dependencies": { - "color": "^4.2.3", - "detect-libc": "^2.0.3", - "semver": "^7.6.0" - }, - "optionalDependencies": { - "@img/sharp-darwin-arm64": "0.33.3", - "@img/sharp-darwin-x64": "0.33.3", - "@img/sharp-libvips-darwin-arm64": "1.0.2", - "@img/sharp-libvips-darwin-x64": "1.0.2", - "@img/sharp-libvips-linux-arm": "1.0.2", - "@img/sharp-libvips-linux-arm64": "1.0.2", - "@img/sharp-libvips-linux-s390x": "1.0.2", - "@img/sharp-libvips-linux-x64": "1.0.2", - "@img/sharp-libvips-linuxmusl-arm64": "1.0.2", - "@img/sharp-libvips-linuxmusl-x64": "1.0.2", - "@img/sharp-linux-arm": "0.33.3", - "@img/sharp-linux-arm64": "0.33.3", - "@img/sharp-linux-s390x": "0.33.3", - "@img/sharp-linux-x64": "0.33.3", - "@img/sharp-linuxmusl-arm64": "0.33.3", - "@img/sharp-linuxmusl-x64": "0.33.3", - "@img/sharp-wasm32": "0.33.3", - "@img/sharp-win32-ia32": "0.33.3", - "@img/sharp-win32-x64": "0.33.3" - }, - "devDependencies": { - "@emnapi/runtime": "^1.1.0", - "@img/sharp-libvips-dev": "1.0.2", - "@img/sharp-libvips-dev-wasm32": "1.0.3", - "@img/sharp-libvips-win32-ia32": "1.0.2", - "@img/sharp-libvips-win32-x64": "1.0.2", - "@types/node": "*", - "async": "^3.2.5", - "cc": "^3.0.1", - "emnapi": "^1.1.0", - "exif-reader": "^2.0.1", - "extract-zip": "^2.0.1", - "icc": "^3.0.0", - "jsdoc-to-markdown": "^8.0.1", - "license-checker": "^25.0.1", - "mocha": "^10.3.0", - "node-addon-api": "^8.0.0", - "nyc": "^15.1.0", - "prebuild": "^13.0.0", - "semistandard": "^17.0.0", - "tar-fs": "^3.0.5", - "tsd": "^0.30.7" - }, - "license": "Apache-2.0", - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0", - "libvips": ">=8.15.2" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "binary": { - "napi_versions": [ - 9 - ] - }, - "semistandard": { - "env": [ - "mocha" - ] - }, - "cc": { - "linelength": "120", - "filter": [ - "build/include" - ] - }, - "nyc": { - "include": [ - "lib" - ] - }, - "tsd": { - "directory": "test/types/" - } -} diff --git a/node_modules/sharp/src/binding.gyp b/node_modules/sharp/src/binding.gyp deleted file mode 100644 index f1fc6091..00000000 --- a/node_modules/sharp/src/binding.gyp +++ /dev/null @@ -1,280 +0,0 @@ -# Copyright 2013 Lovell Fuller and others. -# SPDX-License-Identifier: Apache-2.0 - -{ - 'variables': { - 'vips_version': ' -#include -#include -#include -#include -#include -#include // NOLINT(build/c++11) - -#include -#include - -#include "common.h" - -using vips::VImage; - -namespace sharp { - - // Convenience methods to access the attributes of a Napi::Object - bool HasAttr(Napi::Object obj, std::string attr) { - return obj.Has(attr); - } - std::string AttrAsStr(Napi::Object obj, std::string attr) { - return obj.Get(attr).As(); - } - std::string AttrAsStr(Napi::Object obj, unsigned int const attr) { - return obj.Get(attr).As(); - } - uint32_t AttrAsUint32(Napi::Object obj, std::string attr) { - return obj.Get(attr).As().Uint32Value(); - } - int32_t AttrAsInt32(Napi::Object obj, std::string attr) { - return obj.Get(attr).As().Int32Value(); - } - int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr) { - return obj.Get(attr).As().Int32Value(); - } - int64_t AttrAsInt64(Napi::Object obj, std::string attr) { - return obj.Get(attr).As().Int64Value(); - } - double AttrAsDouble(Napi::Object obj, std::string attr) { - return obj.Get(attr).As().DoubleValue(); - } - double AttrAsDouble(Napi::Object obj, unsigned int const attr) { - return obj.Get(attr).As().DoubleValue(); - } - bool AttrAsBool(Napi::Object obj, std::string attr) { - return obj.Get(attr).As().Value(); - } - std::vector AttrAsVectorOfDouble(Napi::Object obj, std::string attr) { - Napi::Array napiArray = obj.Get(attr).As(); - std::vector vectorOfDouble(napiArray.Length()); - for (unsigned int i = 0; i < napiArray.Length(); i++) { - vectorOfDouble[i] = AttrAsDouble(napiArray, i); - } - return vectorOfDouble; - } - std::vector AttrAsInt32Vector(Napi::Object obj, std::string attr) { - Napi::Array array = obj.Get(attr).As(); - std::vector vector(array.Length()); - for (unsigned int i = 0; i < array.Length(); i++) { - vector[i] = AttrAsInt32(array, i); - } - return vector; - } - - // Create an InputDescriptor instance from a Napi::Object describing an input image - InputDescriptor* CreateInputDescriptor(Napi::Object input) { - InputDescriptor *descriptor = new InputDescriptor; - if (HasAttr(input, "file")) { - descriptor->file = AttrAsStr(input, "file"); - } else if (HasAttr(input, "buffer")) { - Napi::Buffer buffer = input.Get("buffer").As>(); - descriptor->bufferLength = buffer.Length(); - descriptor->buffer = buffer.Data(); - descriptor->isBuffer = TRUE; - } - descriptor->failOn = AttrAsEnum(input, "failOn", VIPS_TYPE_FAIL_ON); - // Density for vector-based input - if (HasAttr(input, "density")) { - descriptor->density = AttrAsDouble(input, "density"); - } - // Should we ignore any embedded ICC profile - if (HasAttr(input, "ignoreIcc")) { - descriptor->ignoreIcc = AttrAsBool(input, "ignoreIcc"); - } - // Raw pixel input - if (HasAttr(input, "rawChannels")) { - descriptor->rawDepth = AttrAsEnum(input, "rawDepth", VIPS_TYPE_BAND_FORMAT); - descriptor->rawChannels = AttrAsUint32(input, "rawChannels"); - descriptor->rawWidth = AttrAsUint32(input, "rawWidth"); - descriptor->rawHeight = AttrAsUint32(input, "rawHeight"); - descriptor->rawPremultiplied = AttrAsBool(input, "rawPremultiplied"); - } - // Multi-page input (GIF, TIFF, PDF) - if (HasAttr(input, "pages")) { - descriptor->pages = AttrAsInt32(input, "pages"); - } - if (HasAttr(input, "page")) { - descriptor->page = AttrAsUint32(input, "page"); - } - // Multi-level input (OpenSlide) - if (HasAttr(input, "level")) { - descriptor->level = AttrAsUint32(input, "level"); - } - // subIFD (OME-TIFF) - if (HasAttr(input, "subifd")) { - descriptor->subifd = AttrAsInt32(input, "subifd"); - } - // Create new image - if (HasAttr(input, "createChannels")) { - descriptor->createChannels = AttrAsUint32(input, "createChannels"); - descriptor->createWidth = AttrAsUint32(input, "createWidth"); - descriptor->createHeight = AttrAsUint32(input, "createHeight"); - if (HasAttr(input, "createNoiseType")) { - descriptor->createNoiseType = AttrAsStr(input, "createNoiseType"); - descriptor->createNoiseMean = AttrAsDouble(input, "createNoiseMean"); - descriptor->createNoiseSigma = AttrAsDouble(input, "createNoiseSigma"); - } else { - descriptor->createBackground = AttrAsVectorOfDouble(input, "createBackground"); - } - } - // Create new image with text - if (HasAttr(input, "textValue")) { - descriptor->textValue = AttrAsStr(input, "textValue"); - if (HasAttr(input, "textFont")) { - descriptor->textFont = AttrAsStr(input, "textFont"); - } - if (HasAttr(input, "textFontfile")) { - descriptor->textFontfile = AttrAsStr(input, "textFontfile"); - } - if (HasAttr(input, "textWidth")) { - descriptor->textWidth = AttrAsUint32(input, "textWidth"); - } - if (HasAttr(input, "textHeight")) { - descriptor->textHeight = AttrAsUint32(input, "textHeight"); - } - if (HasAttr(input, "textAlign")) { - descriptor->textAlign = AttrAsEnum(input, "textAlign", VIPS_TYPE_ALIGN); - } - if (HasAttr(input, "textJustify")) { - descriptor->textJustify = AttrAsBool(input, "textJustify"); - } - if (HasAttr(input, "textDpi")) { - descriptor->textDpi = AttrAsUint32(input, "textDpi"); - } - if (HasAttr(input, "textRgba")) { - descriptor->textRgba = AttrAsBool(input, "textRgba"); - } - if (HasAttr(input, "textSpacing")) { - descriptor->textSpacing = AttrAsUint32(input, "textSpacing"); - } - if (HasAttr(input, "textWrap")) { - descriptor->textWrap = AttrAsEnum(input, "textWrap", VIPS_TYPE_TEXT_WRAP); - } - } - // Limit input images to a given number of pixels, where pixels = width * height - descriptor->limitInputPixels = static_cast(AttrAsInt64(input, "limitInputPixels")); - // Allow switch from random to sequential access - descriptor->access = AttrAsBool(input, "sequentialRead") ? VIPS_ACCESS_SEQUENTIAL : VIPS_ACCESS_RANDOM; - // Remove safety features and allow unlimited input - descriptor->unlimited = AttrAsBool(input, "unlimited"); - return descriptor; - } - - // How many tasks are in the queue? - std::atomic counterQueue{0}; - - // How many tasks are being processed? - std::atomic counterProcess{0}; - - // Filename extension checkers - static bool EndsWith(std::string const &str, std::string const &end) { - return str.length() >= end.length() && 0 == str.compare(str.length() - end.length(), end.length(), end); - } - bool IsJpeg(std::string const &str) { - return EndsWith(str, ".jpg") || EndsWith(str, ".jpeg") || EndsWith(str, ".JPG") || EndsWith(str, ".JPEG"); - } - bool IsPng(std::string const &str) { - return EndsWith(str, ".png") || EndsWith(str, ".PNG"); - } - bool IsWebp(std::string const &str) { - return EndsWith(str, ".webp") || EndsWith(str, ".WEBP"); - } - bool IsGif(std::string const &str) { - return EndsWith(str, ".gif") || EndsWith(str, ".GIF"); - } - bool IsJp2(std::string const &str) { - return EndsWith(str, ".jp2") || EndsWith(str, ".jpx") || EndsWith(str, ".j2k") || EndsWith(str, ".j2c") - || EndsWith(str, ".JP2") || EndsWith(str, ".JPX") || EndsWith(str, ".J2K") || EndsWith(str, ".J2C"); - } - bool IsTiff(std::string const &str) { - return EndsWith(str, ".tif") || EndsWith(str, ".tiff") || EndsWith(str, ".TIF") || EndsWith(str, ".TIFF"); - } - bool IsHeic(std::string const &str) { - return EndsWith(str, ".heic") || EndsWith(str, ".HEIC"); - } - bool IsHeif(std::string const &str) { - return EndsWith(str, ".heif") || EndsWith(str, ".HEIF") || IsHeic(str) || IsAvif(str); - } - bool IsAvif(std::string const &str) { - return EndsWith(str, ".avif") || EndsWith(str, ".AVIF"); - } - bool IsJxl(std::string const &str) { - return EndsWith(str, ".jxl") || EndsWith(str, ".JXL"); - } - bool IsDz(std::string const &str) { - return EndsWith(str, ".dzi") || EndsWith(str, ".DZI"); - } - bool IsDzZip(std::string const &str) { - return EndsWith(str, ".zip") || EndsWith(str, ".ZIP") || EndsWith(str, ".szi") || EndsWith(str, ".SZI"); - } - bool IsV(std::string const &str) { - return EndsWith(str, ".v") || EndsWith(str, ".V") || EndsWith(str, ".vips") || EndsWith(str, ".VIPS"); - } - - /* - Trim space from end of string. - */ - std::string TrimEnd(std::string const &str) { - return str.substr(0, str.find_last_not_of(" \n\r\f") + 1); - } - - /* - Provide a string identifier for the given image type. - */ - std::string ImageTypeId(ImageType const imageType) { - std::string id; - switch (imageType) { - case ImageType::JPEG: id = "jpeg"; break; - case ImageType::PNG: id = "png"; break; - case ImageType::WEBP: id = "webp"; break; - case ImageType::TIFF: id = "tiff"; break; - case ImageType::GIF: id = "gif"; break; - case ImageType::JP2: id = "jp2"; break; - case ImageType::SVG: id = "svg"; break; - case ImageType::HEIF: id = "heif"; break; - case ImageType::PDF: id = "pdf"; break; - case ImageType::MAGICK: id = "magick"; break; - case ImageType::OPENSLIDE: id = "openslide"; break; - case ImageType::PPM: id = "ppm"; break; - case ImageType::FITS: id = "fits"; break; - case ImageType::EXR: id = "exr"; break; - case ImageType::JXL: id = "jxl"; break; - case ImageType::VIPS: id = "vips"; break; - case ImageType::RAW: id = "raw"; break; - case ImageType::UNKNOWN: id = "unknown"; break; - case ImageType::MISSING: id = "missing"; break; - } - return id; - } - - /** - * Regenerate this table with something like: - * - * $ vips -l foreign | grep -i load | awk '{ print $2, $1; }' - * - * Plus a bit of editing. - */ - std::map loaderToType = { - { "VipsForeignLoadJpegFile", ImageType::JPEG }, - { "VipsForeignLoadJpegBuffer", ImageType::JPEG }, - { "VipsForeignLoadPngFile", ImageType::PNG }, - { "VipsForeignLoadPngBuffer", ImageType::PNG }, - { "VipsForeignLoadWebpFile", ImageType::WEBP }, - { "VipsForeignLoadWebpBuffer", ImageType::WEBP }, - { "VipsForeignLoadTiffFile", ImageType::TIFF }, - { "VipsForeignLoadTiffBuffer", ImageType::TIFF }, - { "VipsForeignLoadGifFile", ImageType::GIF }, - { "VipsForeignLoadGifBuffer", ImageType::GIF }, - { "VipsForeignLoadNsgifFile", ImageType::GIF }, - { "VipsForeignLoadNsgifBuffer", ImageType::GIF }, - { "VipsForeignLoadJp2kBuffer", ImageType::JP2 }, - { "VipsForeignLoadJp2kFile", ImageType::JP2 }, - { "VipsForeignLoadSvgFile", ImageType::SVG }, - { "VipsForeignLoadSvgBuffer", ImageType::SVG }, - { "VipsForeignLoadHeifFile", ImageType::HEIF }, - { "VipsForeignLoadHeifBuffer", ImageType::HEIF }, - { "VipsForeignLoadPdfFile", ImageType::PDF }, - { "VipsForeignLoadPdfBuffer", ImageType::PDF }, - { "VipsForeignLoadMagickFile", ImageType::MAGICK }, - { "VipsForeignLoadMagickBuffer", ImageType::MAGICK }, - { "VipsForeignLoadMagick7File", ImageType::MAGICK }, - { "VipsForeignLoadMagick7Buffer", ImageType::MAGICK }, - { "VipsForeignLoadOpenslideFile", ImageType::OPENSLIDE }, - { "VipsForeignLoadPpmFile", ImageType::PPM }, - { "VipsForeignLoadFitsFile", ImageType::FITS }, - { "VipsForeignLoadOpenexr", ImageType::EXR }, - { "VipsForeignLoadJxlFile", ImageType::JXL }, - { "VipsForeignLoadJxlBuffer", ImageType::JXL }, - { "VipsForeignLoadVips", ImageType::VIPS }, - { "VipsForeignLoadVipsFile", ImageType::VIPS }, - { "VipsForeignLoadRaw", ImageType::RAW } - }; - - /* - Determine image format of a buffer. - */ - ImageType DetermineImageType(void *buffer, size_t const length) { - ImageType imageType = ImageType::UNKNOWN; - char const *load = vips_foreign_find_load_buffer(buffer, length); - if (load != nullptr) { - auto it = loaderToType.find(load); - if (it != loaderToType.end()) { - imageType = it->second; - } - } - return imageType; - } - - /* - Determine image format, reads the first few bytes of the file - */ - ImageType DetermineImageType(char const *file) { - ImageType imageType = ImageType::UNKNOWN; - char const *load = vips_foreign_find_load(file); - if (load != nullptr) { - auto it = loaderToType.find(load); - if (it != loaderToType.end()) { - imageType = it->second; - } - } else { - if (EndsWith(vips::VError().what(), " does not exist\n")) { - imageType = ImageType::MISSING; - } - } - return imageType; - } - - /* - Does this image type support multiple pages? - */ - bool ImageTypeSupportsPage(ImageType imageType) { - return - imageType == ImageType::WEBP || - imageType == ImageType::MAGICK || - imageType == ImageType::GIF || - imageType == ImageType::JP2 || - imageType == ImageType::TIFF || - imageType == ImageType::HEIF || - imageType == ImageType::PDF; - } - - /* - Does this image type support removal of safety limits? - */ - bool ImageTypeSupportsUnlimited(ImageType imageType) { - return - imageType == ImageType::JPEG || - imageType == ImageType::PNG || - imageType == ImageType::SVG || - imageType == ImageType::HEIF; - } - - /* - Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data) - */ - std::tuple OpenInput(InputDescriptor *descriptor) { - VImage image; - ImageType imageType; - if (descriptor->isBuffer) { - if (descriptor->rawChannels > 0) { - // Raw, uncompressed pixel data - bool const is8bit = vips_band_format_is8bit(descriptor->rawDepth); - image = VImage::new_from_memory(descriptor->buffer, descriptor->bufferLength, - descriptor->rawWidth, descriptor->rawHeight, descriptor->rawChannels, descriptor->rawDepth); - if (descriptor->rawChannels < 3) { - image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_GREY16; - } else { - image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_sRGB : VIPS_INTERPRETATION_RGB16; - } - if (descriptor->rawPremultiplied) { - image = image.unpremultiply(); - } - imageType = ImageType::RAW; - } else { - // Compressed data - imageType = DetermineImageType(descriptor->buffer, descriptor->bufferLength); - if (imageType != ImageType::UNKNOWN) { - try { - vips::VOption *option = VImage::option() - ->set("access", descriptor->access) - ->set("fail_on", descriptor->failOn); - if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) { - option->set("unlimited", TRUE); - } - if (imageType == ImageType::SVG || imageType == ImageType::PDF) { - option->set("dpi", descriptor->density); - } - if (imageType == ImageType::MAGICK) { - option->set("density", std::to_string(descriptor->density).data()); - } - if (ImageTypeSupportsPage(imageType)) { - option->set("n", descriptor->pages); - option->set("page", descriptor->page); - } - if (imageType == ImageType::OPENSLIDE) { - option->set("level", descriptor->level); - } - if (imageType == ImageType::TIFF) { - option->set("subifd", descriptor->subifd); - } - image = VImage::new_from_buffer(descriptor->buffer, descriptor->bufferLength, nullptr, option); - if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) { - image = SetDensity(image, descriptor->density); - } - } catch (vips::VError const &err) { - throw vips::VError(std::string("Input buffer has corrupt header: ") + err.what()); - } - } else { - throw vips::VError("Input buffer contains unsupported image format"); - } - } - } else { - int const channels = descriptor->createChannels; - if (channels > 0) { - // Create new image - if (descriptor->createNoiseType == "gaussian") { - std::vector bands = {}; - bands.reserve(channels); - for (int _band = 0; _band < channels; _band++) { - bands.push_back(VImage::gaussnoise(descriptor->createWidth, descriptor->createHeight, VImage::option() - ->set("mean", descriptor->createNoiseMean) - ->set("sigma", descriptor->createNoiseSigma))); - } - image = VImage::bandjoin(bands).copy(VImage::option()->set("interpretation", - channels < 3 ? VIPS_INTERPRETATION_B_W: VIPS_INTERPRETATION_sRGB)); - } else { - std::vector background = { - descriptor->createBackground[0], - descriptor->createBackground[1], - descriptor->createBackground[2] - }; - if (channels == 4) { - background.push_back(descriptor->createBackground[3]); - } - image = VImage::new_matrix(descriptor->createWidth, descriptor->createHeight) - .copy(VImage::option()->set("interpretation", - channels < 3 ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_sRGB)) - .new_from_image(background); - } - image = image.cast(VIPS_FORMAT_UCHAR); - imageType = ImageType::RAW; - } else if (descriptor->textValue.length() > 0) { - // Create a new image with text - vips::VOption *textOptions = VImage::option() - ->set("align", descriptor->textAlign) - ->set("justify", descriptor->textJustify) - ->set("rgba", descriptor->textRgba) - ->set("spacing", descriptor->textSpacing) - ->set("wrap", descriptor->textWrap) - ->set("autofit_dpi", &descriptor->textAutofitDpi); - if (descriptor->textWidth > 0) { - textOptions->set("width", descriptor->textWidth); - } - // Ignore dpi if height is set - if (descriptor->textWidth > 0 && descriptor->textHeight > 0) { - textOptions->set("height", descriptor->textHeight); - } else if (descriptor->textDpi > 0) { - textOptions->set("dpi", descriptor->textDpi); - } - if (descriptor->textFont.length() > 0) { - textOptions->set("font", const_cast(descriptor->textFont.data())); - } - if (descriptor->textFontfile.length() > 0) { - textOptions->set("fontfile", const_cast(descriptor->textFontfile.data())); - } - image = VImage::text(const_cast(descriptor->textValue.data()), textOptions); - if (!descriptor->textRgba) { - image = image.copy(VImage::option()->set("interpretation", VIPS_INTERPRETATION_B_W)); - } - imageType = ImageType::RAW; - } else { - // From filesystem - imageType = DetermineImageType(descriptor->file.data()); - if (imageType == ImageType::MISSING) { - if (descriptor->file.find("file.substr(0, 8) + "...')?"); - } - throw vips::VError("Input file is missing: " + descriptor->file); - } - if (imageType != ImageType::UNKNOWN) { - try { - vips::VOption *option = VImage::option() - ->set("access", descriptor->access) - ->set("fail_on", descriptor->failOn); - if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) { - option->set("unlimited", TRUE); - } - if (imageType == ImageType::SVG || imageType == ImageType::PDF) { - option->set("dpi", descriptor->density); - } - if (imageType == ImageType::MAGICK) { - option->set("density", std::to_string(descriptor->density).data()); - } - if (ImageTypeSupportsPage(imageType)) { - option->set("n", descriptor->pages); - option->set("page", descriptor->page); - } - if (imageType == ImageType::OPENSLIDE) { - option->set("level", descriptor->level); - } - if (imageType == ImageType::TIFF) { - option->set("subifd", descriptor->subifd); - } - image = VImage::new_from_file(descriptor->file.data(), option); - if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) { - image = SetDensity(image, descriptor->density); - } - } catch (vips::VError const &err) { - throw vips::VError(std::string("Input file has corrupt header: ") + err.what()); - } - } else { - throw vips::VError("Input file contains unsupported image format"); - } - } - } - - // Limit input images to a given number of pixels, where pixels = width * height - if (descriptor->limitInputPixels > 0 && - static_cast(image.width()) * image.height() > descriptor->limitInputPixels) { - throw vips::VError("Input image exceeds pixel limit"); - } - return std::make_tuple(image, imageType); - } - - /* - Does this image have an embedded profile? - */ - bool HasProfile(VImage image) { - return image.get_typeof(VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB; - } - - /* - Get copy of embedded profile. - */ - std::pair GetProfile(VImage image) { - std::pair icc(nullptr, 0); - if (HasProfile(image)) { - size_t length; - const void *data = image.get_blob(VIPS_META_ICC_NAME, &length); - icc.first = static_cast(g_malloc(length)); - icc.second = length; - memcpy(icc.first, data, length); - } - return icc; - } - - /* - Set embedded profile. - */ - VImage SetProfile(VImage image, std::pair icc) { - if (icc.first != nullptr) { - image = image.copy(); - image.set(VIPS_META_ICC_NAME, reinterpret_cast(vips_area_free_cb), icc.first, icc.second); - } - return image; - } - - /* - Does this image have an alpha channel? - Uses colour space interpretation with number of channels to guess this. - */ - bool HasAlpha(VImage image) { - return image.has_alpha(); - } - - static void* RemoveExifCallback(VipsImage *image, char const *field, GValue *value, void *data) { - std::vector *fieldNames = static_cast *>(data); - std::string fieldName(field); - if (fieldName.substr(0, 8) == ("exif-ifd")) { - fieldNames->push_back(fieldName); - } - return nullptr; - } - - /* - Remove all EXIF-related image fields. - */ - VImage RemoveExif(VImage image) { - std::vector fieldNames; - vips_image_map(image.get_image(), static_cast(RemoveExifCallback), &fieldNames); - for (const auto& f : fieldNames) { - image.remove(f.data()); - } - return image; - } - - /* - Get EXIF Orientation of image, if any. - */ - int ExifOrientation(VImage image) { - int orientation = 0; - if (image.get_typeof(VIPS_META_ORIENTATION) != 0) { - orientation = image.get_int(VIPS_META_ORIENTATION); - } - return orientation; - } - - /* - Set EXIF Orientation of image. - */ - VImage SetExifOrientation(VImage image, int const orientation) { - VImage copy = image.copy(); - copy.set(VIPS_META_ORIENTATION, orientation); - return copy; - } - - /* - Remove EXIF Orientation from image. - */ - VImage RemoveExifOrientation(VImage image) { - VImage copy = image.copy(); - copy.remove(VIPS_META_ORIENTATION); - copy.remove("exif-ifd0-Orientation"); - return copy; - } - - /* - Set animation properties if necessary. - */ - VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector delay, int loop) { - bool hasDelay = !delay.empty(); - - // Avoid a copy if none of the animation properties are needed. - if (nPages == 1 && !hasDelay && loop == -1) return image; - - if (delay.size() == 1) { - // We have just one delay, repeat that value for all frames. - delay.insert(delay.end(), nPages - 1, delay[0]); - } - - // Attaching metadata, need to copy the image. - VImage copy = image.copy(); - - // Only set page-height if we have more than one page, or this could - // accidentally turn into an animated image later. - if (nPages > 1) copy.set(VIPS_META_PAGE_HEIGHT, pageHeight); - if (hasDelay) copy.set("delay", delay); - if (loop != -1) copy.set("loop", loop); - - return copy; - } - - /* - Remove animation properties from image. - */ - VImage RemoveAnimationProperties(VImage image) { - VImage copy = image.copy(); - copy.remove(VIPS_META_PAGE_HEIGHT); - copy.remove("delay"); - copy.remove("loop"); - return copy; - } - - /* - Remove GIF palette from image. - */ - VImage RemoveGifPalette(VImage image) { - VImage copy = image.copy(); - copy.remove("gif-palette"); - return copy; - } - - /* - Does this image have a non-default density? - */ - bool HasDensity(VImage image) { - return image.xres() > 1.0; - } - - /* - Get pixels/mm resolution as pixels/inch density. - */ - int GetDensity(VImage image) { - return static_cast(round(image.xres() * 25.4)); - } - - /* - Set pixels/mm resolution based on a pixels/inch density. - */ - VImage SetDensity(VImage image, const double density) { - const double pixelsPerMm = density / 25.4; - VImage copy = image.copy(); - copy.get_image()->Xres = pixelsPerMm; - copy.get_image()->Yres = pixelsPerMm; - return copy; - } - - /* - Multi-page images can have a page height. Fetch it, and sanity check it. - If page-height is not set, it defaults to the image height - */ - int GetPageHeight(VImage image) { - return vips_image_get_page_height(image.get_image()); - } - - /* - Check the proposed format supports the current dimensions. - */ - void AssertImageTypeDimensions(VImage image, ImageType const imageType) { - const int height = image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT - ? image.get_int(VIPS_META_PAGE_HEIGHT) - : image.height(); - if (imageType == ImageType::JPEG) { - if (image.width() > 65535 || height > 65535) { - throw vips::VError("Processed image is too large for the JPEG format"); - } - } else if (imageType == ImageType::WEBP) { - if (image.width() > 16383 || height > 16383) { - throw vips::VError("Processed image is too large for the WebP format"); - } - } else if (imageType == ImageType::GIF) { - if (image.width() > 65535 || height > 65535) { - throw vips::VError("Processed image is too large for the GIF format"); - } - } else if (imageType == ImageType::HEIF) { - if (image.width() > 16384 || height > 16384) { - throw vips::VError("Processed image is too large for the HEIF format"); - } - } - } - - /* - Called when a Buffer undergoes GC, required to support mixed runtime libraries in Windows - */ - std::function FreeCallback = [](void*, char* data) { - g_free(data); - }; - - /* - Temporary buffer of warnings - */ - std::queue vipsWarnings; - std::mutex vipsWarningsMutex; - - /* - Called with warnings from the glib-registered "VIPS" domain - */ - void VipsWarningCallback(char const* log_domain, GLogLevelFlags log_level, char const* message, void* ignore) { - std::lock_guard lock(vipsWarningsMutex); - vipsWarnings.emplace(message); - } - - /* - Pop the oldest warning message from the queue - */ - std::string VipsWarningPop() { - std::string warning; - std::lock_guard lock(vipsWarningsMutex); - if (!vipsWarnings.empty()) { - warning = vipsWarnings.front(); - vipsWarnings.pop(); - } - return warning; - } - - /* - Attach an event listener for progress updates, used to detect timeout - */ - void SetTimeout(VImage image, int const seconds) { - if (seconds > 0) { - VipsImage *im = image.get_image(); - if (im->progress_signal == NULL) { - int *timeout = VIPS_NEW(im, int); - *timeout = seconds; - g_signal_connect(im, "eval", G_CALLBACK(VipsProgressCallBack), timeout); - vips_image_set_progress(im, TRUE); - } - } - } - - /* - Event listener for progress updates, used to detect timeout - */ - void VipsProgressCallBack(VipsImage *im, VipsProgress *progress, int *timeout) { - if (*timeout > 0 && progress->run >= *timeout) { - vips_image_set_kill(im, TRUE); - vips_error("timeout", "%d%% complete", progress->percent); - *timeout = 0; - } - } - - /* - Calculate the (left, top) coordinates of the output image - within the input image, applying the given gravity during an embed. - - @Azurebyte: We are basically swapping the inWidth and outWidth, inHeight and outHeight from the CalculateCrop function. - */ - std::tuple CalculateEmbedPosition(int const inWidth, int const inHeight, - int const outWidth, int const outHeight, int const gravity) { - - int left = 0; - int top = 0; - switch (gravity) { - case 1: - // North - left = (outWidth - inWidth) / 2; - break; - case 2: - // East - left = outWidth - inWidth; - top = (outHeight - inHeight) / 2; - break; - case 3: - // South - left = (outWidth - inWidth) / 2; - top = outHeight - inHeight; - break; - case 4: - // West - top = (outHeight - inHeight) / 2; - break; - case 5: - // Northeast - left = outWidth - inWidth; - break; - case 6: - // Southeast - left = outWidth - inWidth; - top = outHeight - inHeight; - break; - case 7: - // Southwest - top = outHeight - inHeight; - break; - case 8: - // Northwest - // Which is the default is 0,0 so we do not assign anything here. - break; - default: - // Centre - left = (outWidth - inWidth) / 2; - top = (outHeight - inHeight) / 2; - } - return std::make_tuple(left, top); - } - - /* - Calculate the (left, top) coordinates of the output image - within the input image, applying the given gravity during a crop. - */ - std::tuple CalculateCrop(int const inWidth, int const inHeight, - int const outWidth, int const outHeight, int const gravity) { - - int left = 0; - int top = 0; - switch (gravity) { - case 1: - // North - left = (inWidth - outWidth + 1) / 2; - break; - case 2: - // East - left = inWidth - outWidth; - top = (inHeight - outHeight + 1) / 2; - break; - case 3: - // South - left = (inWidth - outWidth + 1) / 2; - top = inHeight - outHeight; - break; - case 4: - // West - top = (inHeight - outHeight + 1) / 2; - break; - case 5: - // Northeast - left = inWidth - outWidth; - break; - case 6: - // Southeast - left = inWidth - outWidth; - top = inHeight - outHeight; - break; - case 7: - // Southwest - top = inHeight - outHeight; - break; - case 8: - // Northwest - break; - default: - // Centre - left = (inWidth - outWidth + 1) / 2; - top = (inHeight - outHeight + 1) / 2; - } - return std::make_tuple(left, top); - } - - /* - Calculate the (left, top) coordinates of the output image - within the input image, applying the given x and y offsets. - */ - std::tuple CalculateCrop(int const inWidth, int const inHeight, - int const outWidth, int const outHeight, int const x, int const y) { - - // default values - int left = 0; - int top = 0; - - // assign only if valid - if (x < (inWidth - outWidth)) { - left = x; - } else if (x >= (inWidth - outWidth)) { - left = inWidth - outWidth; - } - - if (y < (inHeight - outHeight)) { - top = y; - } else if (y >= (inHeight - outHeight)) { - top = inHeight - outHeight; - } - - return std::make_tuple(left, top); - } - - /* - Are pixel values in this image 16-bit integer? - */ - bool Is16Bit(VipsInterpretation const interpretation) { - return interpretation == VIPS_INTERPRETATION_RGB16 || interpretation == VIPS_INTERPRETATION_GREY16; - } - - /* - Return the image alpha maximum. Useful for combining alpha bands. scRGB - images are 0 - 1 for image data, but the alpha is 0 - 255. - */ - double MaximumImageAlpha(VipsInterpretation const interpretation) { - return Is16Bit(interpretation) ? 65535.0 : 255.0; - } - - /* - Convert RGBA value to another colourspace - */ - std::vector GetRgbaAsColourspace(std::vector const rgba, - VipsInterpretation const interpretation, bool premultiply) { - int const bands = static_cast(rgba.size()); - if (bands < 3) { - return rgba; - } - VImage pixel = VImage::new_matrix(1, 1); - pixel.set("bands", bands); - pixel = pixel - .new_from_image(rgba) - .colourspace(interpretation, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB)); - if (premultiply) { - pixel = pixel.premultiply(); - } - return pixel(0, 0); - } - - /* - Apply the alpha channel to a given colour - */ - std::tuple> ApplyAlpha(VImage image, std::vector colour, bool premultiply) { - // Scale up 8-bit values to match 16-bit input image - double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0; - // Create alphaColour colour - std::vector alphaColour; - if (image.bands() > 2) { - alphaColour = { - multiplier * colour[0], - multiplier * colour[1], - multiplier * colour[2] - }; - } else { - // Convert sRGB to greyscale - alphaColour = { multiplier * ( - 0.2126 * colour[0] + - 0.7152 * colour[1] + - 0.0722 * colour[2]) - }; - } - // Add alpha channel to alphaColour colour - if (colour[3] < 255.0 || HasAlpha(image)) { - alphaColour.push_back(colour[3] * multiplier); - } - // Ensure alphaColour colour uses correct colourspace - alphaColour = sharp::GetRgbaAsColourspace(alphaColour, image.interpretation(), premultiply); - // Add non-transparent alpha channel, if required - if (colour[3] < 255.0 && !HasAlpha(image)) { - image = image.bandjoin( - VImage::new_matrix(image.width(), image.height()).new_from_image(255 * multiplier).cast(image.format())); - } - return std::make_tuple(image, alphaColour); - } - - /* - Removes alpha channel, if any. - */ - VImage RemoveAlpha(VImage image) { - if (HasAlpha(image)) { - image = image.extract_band(0, VImage::option()->set("n", image.bands() - 1)); - } - return image; - } - - /* - Ensures alpha channel, if missing. - */ - VImage EnsureAlpha(VImage image, double const value) { - if (!HasAlpha(image)) { - std::vector alpha; - alpha.push_back(value * sharp::MaximumImageAlpha(image.interpretation())); - image = image.bandjoin_const(alpha); - } - return image; - } - - std::pair ResolveShrink(int width, int height, int targetWidth, int targetHeight, - Canvas canvas, bool withoutEnlargement, bool withoutReduction) { - double hshrink = 1.0; - double vshrink = 1.0; - - if (targetWidth > 0 && targetHeight > 0) { - // Fixed width and height - hshrink = static_cast(width) / targetWidth; - vshrink = static_cast(height) / targetHeight; - - switch (canvas) { - case Canvas::CROP: - case Canvas::MIN: - if (hshrink < vshrink) { - vshrink = hshrink; - } else { - hshrink = vshrink; - } - break; - case Canvas::EMBED: - case Canvas::MAX: - if (hshrink > vshrink) { - vshrink = hshrink; - } else { - hshrink = vshrink; - } - break; - case Canvas::IGNORE_ASPECT: - break; - } - } else if (targetWidth > 0) { - // Fixed width - hshrink = static_cast(width) / targetWidth; - - if (canvas != Canvas::IGNORE_ASPECT) { - // Auto height - vshrink = hshrink; - } - } else if (targetHeight > 0) { - // Fixed height - vshrink = static_cast(height) / targetHeight; - - if (canvas != Canvas::IGNORE_ASPECT) { - // Auto width - hshrink = vshrink; - } - } - - // We should not reduce or enlarge the output image, if - // withoutReduction or withoutEnlargement is specified. - if (withoutReduction) { - // Equivalent of VIPS_SIZE_UP - hshrink = std::min(1.0, hshrink); - vshrink = std::min(1.0, vshrink); - } else if (withoutEnlargement) { - // Equivalent of VIPS_SIZE_DOWN - hshrink = std::max(1.0, hshrink); - vshrink = std::max(1.0, vshrink); - } - - // We don't want to shrink so much that we send an axis to 0 - hshrink = std::min(hshrink, static_cast(width)); - vshrink = std::min(vshrink, static_cast(height)); - - return std::make_pair(hshrink, vshrink); - } - - /* - Ensure decoding remains sequential. - */ - VImage StaySequential(VImage image, VipsAccess access, bool condition) { - if (access == VIPS_ACCESS_SEQUENTIAL && condition) { - return image.copy_memory(); - } - return image; - } -} // namespace sharp diff --git a/node_modules/sharp/src/common.h b/node_modules/sharp/src/common.h deleted file mode 100644 index dbde766c..00000000 --- a/node_modules/sharp/src/common.h +++ /dev/null @@ -1,393 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -#ifndef SRC_COMMON_H_ -#define SRC_COMMON_H_ - -#include -#include -#include -#include - -#include -#include - -// Verify platform and compiler compatibility - -#if (VIPS_MAJOR_VERSION < 8) || \ - (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 15) || \ - (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 15 && VIPS_MICRO_VERSION < 2) -#error "libvips version 8.15.2+ is required - please see https://sharp.pixelplumbing.com/install" -#endif - -#if ((!defined(__clang__)) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6))) -#error "GCC version 4.6+ is required for C++11 features - please see https://sharp.pixelplumbing.com/install" -#endif - -#if (defined(__clang__) && defined(__has_feature)) -#if (!__has_feature(cxx_range_for)) -#error "clang version 3.0+ is required for C++11 features - please see https://sharp.pixelplumbing.com/install" -#endif -#endif - -using vips::VImage; - -namespace sharp { - - struct InputDescriptor { // NOLINT(runtime/indentation_namespace) - std::string name; - std::string file; - char *buffer; - VipsFailOn failOn; - uint64_t limitInputPixels; - bool unlimited; - VipsAccess access; - size_t bufferLength; - bool isBuffer; - double density; - bool ignoreIcc; - VipsBandFormat rawDepth; - int rawChannels; - int rawWidth; - int rawHeight; - bool rawPremultiplied; - int pages; - int page; - int level; - int subifd; - int createChannels; - int createWidth; - int createHeight; - std::vector createBackground; - std::string createNoiseType; - double createNoiseMean; - double createNoiseSigma; - std::string textValue; - std::string textFont; - std::string textFontfile; - int textWidth; - int textHeight; - VipsAlign textAlign; - bool textJustify; - int textDpi; - bool textRgba; - int textSpacing; - VipsTextWrap textWrap; - int textAutofitDpi; - - InputDescriptor(): - buffer(nullptr), - failOn(VIPS_FAIL_ON_WARNING), - limitInputPixels(0x3FFF * 0x3FFF), - unlimited(FALSE), - access(VIPS_ACCESS_RANDOM), - bufferLength(0), - isBuffer(FALSE), - density(72.0), - ignoreIcc(FALSE), - rawDepth(VIPS_FORMAT_UCHAR), - rawChannels(0), - rawWidth(0), - rawHeight(0), - rawPremultiplied(false), - pages(1), - page(0), - level(0), - subifd(-1), - createChannels(0), - createWidth(0), - createHeight(0), - createBackground{ 0.0, 0.0, 0.0, 255.0 }, - createNoiseMean(0.0), - createNoiseSigma(0.0), - textWidth(0), - textHeight(0), - textAlign(VIPS_ALIGN_LOW), - textJustify(FALSE), - textDpi(72), - textRgba(FALSE), - textSpacing(0), - textWrap(VIPS_TEXT_WRAP_WORD), - textAutofitDpi(0) {} - }; - - // Convenience methods to access the attributes of a Napi::Object - bool HasAttr(Napi::Object obj, std::string attr); - std::string AttrAsStr(Napi::Object obj, std::string attr); - std::string AttrAsStr(Napi::Object obj, unsigned int const attr); - uint32_t AttrAsUint32(Napi::Object obj, std::string attr); - int32_t AttrAsInt32(Napi::Object obj, std::string attr); - int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr); - double AttrAsDouble(Napi::Object obj, std::string attr); - double AttrAsDouble(Napi::Object obj, unsigned int const attr); - bool AttrAsBool(Napi::Object obj, std::string attr); - std::vector AttrAsVectorOfDouble(Napi::Object obj, std::string attr); - std::vector AttrAsInt32Vector(Napi::Object obj, std::string attr); - template T AttrAsEnum(Napi::Object obj, std::string attr, GType type) { - return static_cast( - vips_enum_from_nick(nullptr, type, AttrAsStr(obj, attr).data())); - } - - // Create an InputDescriptor instance from a Napi::Object describing an input image - InputDescriptor* CreateInputDescriptor(Napi::Object input); - - enum class ImageType { - JPEG, - PNG, - WEBP, - JP2, - TIFF, - GIF, - SVG, - HEIF, - PDF, - MAGICK, - OPENSLIDE, - PPM, - FITS, - EXR, - JXL, - VIPS, - RAW, - UNKNOWN, - MISSING - }; - - enum class Canvas { - CROP, - EMBED, - MAX, - MIN, - IGNORE_ASPECT - }; - - // How many tasks are in the queue? - extern std::atomic counterQueue; - - // How many tasks are being processed? - extern std::atomic counterProcess; - - // Filename extension checkers - bool IsJpeg(std::string const &str); - bool IsPng(std::string const &str); - bool IsWebp(std::string const &str); - bool IsJp2(std::string const &str); - bool IsGif(std::string const &str); - bool IsTiff(std::string const &str); - bool IsHeic(std::string const &str); - bool IsHeif(std::string const &str); - bool IsAvif(std::string const &str); - bool IsJxl(std::string const &str); - bool IsDz(std::string const &str); - bool IsDzZip(std::string const &str); - bool IsV(std::string const &str); - - /* - Trim space from end of string. - */ - std::string TrimEnd(std::string const &str); - - /* - Provide a string identifier for the given image type. - */ - std::string ImageTypeId(ImageType const imageType); - - /* - Determine image format of a buffer. - */ - ImageType DetermineImageType(void *buffer, size_t const length); - - /* - Determine image format of a file. - */ - ImageType DetermineImageType(char const *file); - - /* - Does this image type support multiple pages? - */ - bool ImageTypeSupportsPage(ImageType imageType); - - /* - Does this image type support removal of safety limits? - */ - bool ImageTypeSupportsUnlimited(ImageType imageType); - - /* - Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data) - */ - std::tuple OpenInput(InputDescriptor *descriptor); - - /* - Does this image have an embedded profile? - */ - bool HasProfile(VImage image); - - /* - Get copy of embedded profile. - */ - std::pair GetProfile(VImage image); - - /* - Set embedded profile. - */ - VImage SetProfile(VImage image, std::pair icc); - - /* - Does this image have an alpha channel? - Uses colour space interpretation with number of channels to guess this. - */ - bool HasAlpha(VImage image); - - /* - Remove all EXIF-related image fields. - */ - VImage RemoveExif(VImage image); - - /* - Get EXIF Orientation of image, if any. - */ - int ExifOrientation(VImage image); - - /* - Set EXIF Orientation of image. - */ - VImage SetExifOrientation(VImage image, int const orientation); - - /* - Remove EXIF Orientation from image. - */ - VImage RemoveExifOrientation(VImage image); - - /* - Set animation properties if necessary. - */ - VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector delay, int loop); - - /* - Remove animation properties from image. - */ - VImage RemoveAnimationProperties(VImage image); - - /* - Remove GIF palette from image. - */ - VImage RemoveGifPalette(VImage image); - - /* - Does this image have a non-default density? - */ - bool HasDensity(VImage image); - - /* - Get pixels/mm resolution as pixels/inch density. - */ - int GetDensity(VImage image); - - /* - Set pixels/mm resolution based on a pixels/inch density. - */ - VImage SetDensity(VImage image, const double density); - - /* - Multi-page images can have a page height. Fetch it, and sanity check it. - If page-height is not set, it defaults to the image height - */ - int GetPageHeight(VImage image); - - /* - Check the proposed format supports the current dimensions. - */ - void AssertImageTypeDimensions(VImage image, ImageType const imageType); - - /* - Called when a Buffer undergoes GC, required to support mixed runtime libraries in Windows - */ - extern std::function FreeCallback; - - /* - Called with warnings from the glib-registered "VIPS" domain - */ - void VipsWarningCallback(char const* log_domain, GLogLevelFlags log_level, char const* message, void* ignore); - - /* - Pop the oldest warning message from the queue - */ - std::string VipsWarningPop(); - - /* - Attach an event listener for progress updates, used to detect timeout - */ - void SetTimeout(VImage image, int const timeoutSeconds); - - /* - Event listener for progress updates, used to detect timeout - */ - void VipsProgressCallBack(VipsImage *image, VipsProgress *progress, int *timeoutSeconds); - - /* - Calculate the (left, top) coordinates of the output image - within the input image, applying the given gravity during an embed. - */ - std::tuple CalculateEmbedPosition(int const inWidth, int const inHeight, - int const outWidth, int const outHeight, int const gravity); - - /* - Calculate the (left, top) coordinates of the output image - within the input image, applying the given gravity. - */ - std::tuple CalculateCrop(int const inWidth, int const inHeight, - int const outWidth, int const outHeight, int const gravity); - - /* - Calculate the (left, top) coordinates of the output image - within the input image, applying the given x and y offsets of the output image. - */ - std::tuple CalculateCrop(int const inWidth, int const inHeight, - int const outWidth, int const outHeight, int const x, int const y); - - /* - Are pixel values in this image 16-bit integer? - */ - bool Is16Bit(VipsInterpretation const interpretation); - - /* - Return the image alpha maximum. Useful for combining alpha bands. scRGB - images are 0 - 1 for image data, but the alpha is 0 - 255. - */ - double MaximumImageAlpha(VipsInterpretation const interpretation); - - /* - Convert RGBA value to another colourspace - */ - std::vector GetRgbaAsColourspace(std::vector const rgba, - VipsInterpretation const interpretation, bool premultiply); - - /* - Apply the alpha channel to a given colour - */ - std::tuple> ApplyAlpha(VImage image, std::vector colour, bool premultiply); - - /* - Removes alpha channel, if any. - */ - VImage RemoveAlpha(VImage image); - - /* - Ensures alpha channel, if missing. - */ - VImage EnsureAlpha(VImage image, double const value); - - /* - Calculate the horizontal and vertical shrink factors, taking the canvas mode into account. - */ - std::pair ResolveShrink(int width, int height, int targetWidth, int targetHeight, - Canvas canvas, bool withoutEnlargement, bool withoutReduction); - - /* - Ensure decoding remains sequential. - */ - VImage StaySequential(VImage image, VipsAccess access, bool condition = TRUE); - -} // namespace sharp - -#endif // SRC_COMMON_H_ diff --git a/node_modules/sharp/src/metadata.cc b/node_modules/sharp/src/metadata.cc deleted file mode 100644 index 29e41ebb..00000000 --- a/node_modules/sharp/src/metadata.cc +++ /dev/null @@ -1,287 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -#include -#include - -#include -#include - -#include "common.h" -#include "metadata.h" - -class MetadataWorker : public Napi::AsyncWorker { - public: - MetadataWorker(Napi::Function callback, MetadataBaton *baton, Napi::Function debuglog) : - Napi::AsyncWorker(callback), baton(baton), debuglog(Napi::Persistent(debuglog)) {} - ~MetadataWorker() {} - - void Execute() { - // Decrement queued task counter - sharp::counterQueue--; - - vips::VImage image; - sharp::ImageType imageType = sharp::ImageType::UNKNOWN; - try { - std::tie(image, imageType) = OpenInput(baton->input); - } catch (vips::VError const &err) { - (baton->err).append(err.what()); - } - if (imageType != sharp::ImageType::UNKNOWN) { - // Image type - baton->format = sharp::ImageTypeId(imageType); - // VipsImage attributes - baton->width = image.width(); - baton->height = image.height(); - baton->space = vips_enum_nick(VIPS_TYPE_INTERPRETATION, image.interpretation()); - baton->channels = image.bands(); - baton->depth = vips_enum_nick(VIPS_TYPE_BAND_FORMAT, image.format()); - if (sharp::HasDensity(image)) { - baton->density = sharp::GetDensity(image); - } - if (image.get_typeof("jpeg-chroma-subsample") == VIPS_TYPE_REF_STRING) { - baton->chromaSubsampling = image.get_string("jpeg-chroma-subsample"); - } - if (image.get_typeof("interlaced") == G_TYPE_INT) { - baton->isProgressive = image.get_int("interlaced") == 1; - } - if (image.get_typeof("palette-bit-depth") == G_TYPE_INT) { - baton->paletteBitDepth = image.get_int("palette-bit-depth"); - } - if (image.get_typeof(VIPS_META_N_PAGES) == G_TYPE_INT) { - baton->pages = image.get_int(VIPS_META_N_PAGES); - } - if (image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT) { - baton->pageHeight = image.get_int(VIPS_META_PAGE_HEIGHT); - } - if (image.get_typeof("loop") == G_TYPE_INT) { - baton->loop = image.get_int("loop"); - } - if (image.get_typeof("delay") == VIPS_TYPE_ARRAY_INT) { - baton->delay = image.get_array_int("delay"); - } - if (image.get_typeof("heif-primary") == G_TYPE_INT) { - baton->pagePrimary = image.get_int("heif-primary"); - } - if (image.get_typeof("heif-compression") == VIPS_TYPE_REF_STRING) { - baton->compression = image.get_string("heif-compression"); - } - if (image.get_typeof(VIPS_META_RESOLUTION_UNIT) == VIPS_TYPE_REF_STRING) { - baton->resolutionUnit = image.get_string(VIPS_META_RESOLUTION_UNIT); - } - if (image.get_typeof("magick-format") == VIPS_TYPE_REF_STRING) { - baton->formatMagick = image.get_string("magick-format"); - } - if (image.get_typeof("openslide.level-count") == VIPS_TYPE_REF_STRING) { - int const levels = std::stoi(image.get_string("openslide.level-count")); - for (int l = 0; l < levels; l++) { - std::string prefix = "openslide.level[" + std::to_string(l) + "]."; - int const width = std::stoi(image.get_string((prefix + "width").data())); - int const height = std::stoi(image.get_string((prefix + "height").data())); - baton->levels.push_back(std::pair(width, height)); - } - } - if (image.get_typeof(VIPS_META_N_SUBIFDS) == G_TYPE_INT) { - baton->subifds = image.get_int(VIPS_META_N_SUBIFDS); - } - baton->hasProfile = sharp::HasProfile(image); - if (image.get_typeof("background") == VIPS_TYPE_ARRAY_DOUBLE) { - baton->background = image.get_array_double("background"); - } - // Derived attributes - baton->hasAlpha = sharp::HasAlpha(image); - baton->orientation = sharp::ExifOrientation(image); - // EXIF - if (image.get_typeof(VIPS_META_EXIF_NAME) == VIPS_TYPE_BLOB) { - size_t exifLength; - void const *exif = image.get_blob(VIPS_META_EXIF_NAME, &exifLength); - baton->exif = static_cast(g_malloc(exifLength)); - memcpy(baton->exif, exif, exifLength); - baton->exifLength = exifLength; - } - // ICC profile - if (image.get_typeof(VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB) { - size_t iccLength; - void const *icc = image.get_blob(VIPS_META_ICC_NAME, &iccLength); - baton->icc = static_cast(g_malloc(iccLength)); - memcpy(baton->icc, icc, iccLength); - baton->iccLength = iccLength; - } - // IPTC - if (image.get_typeof(VIPS_META_IPTC_NAME) == VIPS_TYPE_BLOB) { - size_t iptcLength; - void const *iptc = image.get_blob(VIPS_META_IPTC_NAME, &iptcLength); - baton->iptc = static_cast(g_malloc(iptcLength)); - memcpy(baton->iptc, iptc, iptcLength); - baton->iptcLength = iptcLength; - } - // XMP - if (image.get_typeof(VIPS_META_XMP_NAME) == VIPS_TYPE_BLOB) { - size_t xmpLength; - void const *xmp = image.get_blob(VIPS_META_XMP_NAME, &xmpLength); - baton->xmp = static_cast(g_malloc(xmpLength)); - memcpy(baton->xmp, xmp, xmpLength); - baton->xmpLength = xmpLength; - } - // TIFFTAG_PHOTOSHOP - if (image.get_typeof(VIPS_META_PHOTOSHOP_NAME) == VIPS_TYPE_BLOB) { - size_t tifftagPhotoshopLength; - void const *tifftagPhotoshop = image.get_blob(VIPS_META_PHOTOSHOP_NAME, &tifftagPhotoshopLength); - baton->tifftagPhotoshop = static_cast(g_malloc(tifftagPhotoshopLength)); - memcpy(baton->tifftagPhotoshop, tifftagPhotoshop, tifftagPhotoshopLength); - baton->tifftagPhotoshopLength = tifftagPhotoshopLength; - } - } - - // Clean up - vips_error_clear(); - vips_thread_shutdown(); - } - - void OnOK() { - Napi::Env env = Env(); - Napi::HandleScope scope(env); - - // Handle warnings - std::string warning = sharp::VipsWarningPop(); - while (!warning.empty()) { - debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) }); - warning = sharp::VipsWarningPop(); - } - - if (baton->err.empty()) { - Napi::Object info = Napi::Object::New(env); - info.Set("format", baton->format); - if (baton->input->bufferLength > 0) { - info.Set("size", baton->input->bufferLength); - } - info.Set("width", baton->width); - info.Set("height", baton->height); - info.Set("space", baton->space); - info.Set("channels", baton->channels); - info.Set("depth", baton->depth); - if (baton->density > 0) { - info.Set("density", baton->density); - } - if (!baton->chromaSubsampling.empty()) { - info.Set("chromaSubsampling", baton->chromaSubsampling); - } - info.Set("isProgressive", baton->isProgressive); - if (baton->paletteBitDepth > 0) { - info.Set("paletteBitDepth", baton->paletteBitDepth); - } - if (baton->pages > 0) { - info.Set("pages", baton->pages); - } - if (baton->pageHeight > 0) { - info.Set("pageHeight", baton->pageHeight); - } - if (baton->loop >= 0) { - info.Set("loop", baton->loop); - } - if (!baton->delay.empty()) { - int i = 0; - Napi::Array delay = Napi::Array::New(env, static_cast(baton->delay.size())); - for (int const d : baton->delay) { - delay.Set(i++, d); - } - info.Set("delay", delay); - } - if (baton->pagePrimary > -1) { - info.Set("pagePrimary", baton->pagePrimary); - } - if (!baton->compression.empty()) { - info.Set("compression", baton->compression); - } - if (!baton->resolutionUnit.empty()) { - info.Set("resolutionUnit", baton->resolutionUnit == "in" ? "inch" : baton->resolutionUnit); - } - if (!baton->formatMagick.empty()) { - info.Set("formatMagick", baton->formatMagick); - } - if (!baton->levels.empty()) { - int i = 0; - Napi::Array levels = Napi::Array::New(env, static_cast(baton->levels.size())); - for (std::pair const &l : baton->levels) { - Napi::Object level = Napi::Object::New(env); - level.Set("width", l.first); - level.Set("height", l.second); - levels.Set(i++, level); - } - info.Set("levels", levels); - } - if (baton->subifds > 0) { - info.Set("subifds", baton->subifds); - } - if (!baton->background.empty()) { - if (baton->background.size() == 3) { - Napi::Object background = Napi::Object::New(env); - background.Set("r", baton->background[0]); - background.Set("g", baton->background[1]); - background.Set("b", baton->background[2]); - info.Set("background", background); - } else { - info.Set("background", baton->background[0]); - } - } - info.Set("hasProfile", baton->hasProfile); - info.Set("hasAlpha", baton->hasAlpha); - if (baton->orientation > 0) { - info.Set("orientation", baton->orientation); - } - if (baton->exifLength > 0) { - info.Set("exif", Napi::Buffer::NewOrCopy(env, baton->exif, baton->exifLength, sharp::FreeCallback)); - } - if (baton->iccLength > 0) { - info.Set("icc", Napi::Buffer::NewOrCopy(env, baton->icc, baton->iccLength, sharp::FreeCallback)); - } - if (baton->iptcLength > 0) { - info.Set("iptc", Napi::Buffer::NewOrCopy(env, baton->iptc, baton->iptcLength, sharp::FreeCallback)); - } - if (baton->xmpLength > 0) { - info.Set("xmp", Napi::Buffer::NewOrCopy(env, baton->xmp, baton->xmpLength, sharp::FreeCallback)); - } - if (baton->tifftagPhotoshopLength > 0) { - info.Set("tifftagPhotoshop", - Napi::Buffer::NewOrCopy(env, baton->tifftagPhotoshop, - baton->tifftagPhotoshopLength, sharp::FreeCallback)); - } - Callback().Call(Receiver().Value(), { env.Null(), info }); - } else { - Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() }); - } - - delete baton->input; - delete baton; - } - - private: - MetadataBaton* baton; - Napi::FunctionReference debuglog; -}; - -/* - metadata(options, callback) -*/ -Napi::Value metadata(const Napi::CallbackInfo& info) { - // V8 objects are converted to non-V8 types held in the baton struct - MetadataBaton *baton = new MetadataBaton; - Napi::Object options = info[size_t(0)].As(); - - // Input - baton->input = sharp::CreateInputDescriptor(options.Get("input").As()); - - // Function to notify of libvips warnings - Napi::Function debuglog = options.Get("debuglog").As(); - - // Join queue for worker thread - Napi::Function callback = info[size_t(1)].As(); - MetadataWorker *worker = new MetadataWorker(callback, baton, debuglog); - worker->Receiver().Set("options", options); - worker->Queue(); - - // Increment queued task counter - sharp::counterQueue++; - - return info.Env().Undefined(); -} diff --git a/node_modules/sharp/src/metadata.h b/node_modules/sharp/src/metadata.h deleted file mode 100644 index 3030ae29..00000000 --- a/node_modules/sharp/src/metadata.h +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -#ifndef SRC_METADATA_H_ -#define SRC_METADATA_H_ - -#include -#include - -#include "./common.h" - -struct MetadataBaton { - // Input - sharp::InputDescriptor *input; - // Output - std::string format; - int width; - int height; - std::string space; - int channels; - std::string depth; - int density; - std::string chromaSubsampling; - bool isProgressive; - int paletteBitDepth; - int pages; - int pageHeight; - int loop; - std::vector delay; - int pagePrimary; - std::string compression; - std::string resolutionUnit; - std::string formatMagick; - std::vector> levels; - int subifds; - std::vector background; - bool hasProfile; - bool hasAlpha; - int orientation; - char *exif; - size_t exifLength; - char *icc; - size_t iccLength; - char *iptc; - size_t iptcLength; - char *xmp; - size_t xmpLength; - char *tifftagPhotoshop; - size_t tifftagPhotoshopLength; - std::string err; - - MetadataBaton(): - input(nullptr), - width(0), - height(0), - channels(0), - density(0), - isProgressive(false), - paletteBitDepth(0), - pages(0), - pageHeight(0), - loop(-1), - pagePrimary(-1), - subifds(0), - hasProfile(false), - hasAlpha(false), - orientation(0), - exif(nullptr), - exifLength(0), - icc(nullptr), - iccLength(0), - iptc(nullptr), - iptcLength(0), - xmp(nullptr), - xmpLength(0), - tifftagPhotoshop(nullptr), - tifftagPhotoshopLength(0) {} -}; - -Napi::Value metadata(const Napi::CallbackInfo& info); - -#endif // SRC_METADATA_H_ diff --git a/node_modules/sharp/src/operations.cc b/node_modules/sharp/src/operations.cc deleted file mode 100644 index e23411b4..00000000 --- a/node_modules/sharp/src/operations.cc +++ /dev/null @@ -1,471 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -#include -#include -#include -#include -#include -#include - -#include "common.h" -#include "operations.h" - -using vips::VImage; -using vips::VError; - -namespace sharp { - /* - * Tint an image using the provided RGB. - */ - VImage Tint(VImage image, std::vector const tint) { - std::vector const tintLab = (VImage::black(1, 1) + tint) - .colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB)) - .getpoint(0, 0); - // LAB identity function - VImage identityLab = VImage::identity(VImage::option()->set("bands", 3)) - .colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB)); - // Scale luminance range, 0.0 to 1.0 - VImage l = identityLab[0] / 100; - // Weighting functions - VImage weightL = 1.0 - 4.0 * ((l - 0.5) * (l - 0.5)); - VImage weightAB = (weightL * tintLab).extract_band(1, VImage::option()->set("n", 2)); - identityLab = identityLab[0].bandjoin(weightAB); - // Convert lookup table to sRGB - VImage lut = identityLab.colourspace(VIPS_INTERPRETATION_sRGB, - VImage::option()->set("source_space", VIPS_INTERPRETATION_LAB)); - // Original colourspace - VipsInterpretation typeBeforeTint = image.interpretation(); - if (typeBeforeTint == VIPS_INTERPRETATION_RGB) { - typeBeforeTint = VIPS_INTERPRETATION_sRGB; - } - // Apply lookup table - if (HasAlpha(image)) { - VImage alpha = image[image.bands() - 1]; - image = RemoveAlpha(image) - .colourspace(VIPS_INTERPRETATION_B_W) - .maplut(lut) - .colourspace(typeBeforeTint) - .bandjoin(alpha); - } else { - image = image - .colourspace(VIPS_INTERPRETATION_B_W) - .maplut(lut) - .colourspace(typeBeforeTint); - } - return image; - } - - /* - * Stretch luminance to cover full dynamic range. - */ - VImage Normalise(VImage image, int const lower, int const upper) { - // Get original colourspace - VipsInterpretation typeBeforeNormalize = image.interpretation(); - if (typeBeforeNormalize == VIPS_INTERPRETATION_RGB) { - typeBeforeNormalize = VIPS_INTERPRETATION_sRGB; - } - // Convert to LAB colourspace - VImage lab = image.colourspace(VIPS_INTERPRETATION_LAB); - // Extract luminance - VImage luminance = lab[0]; - - // Find luminance range - int const min = lower == 0 ? luminance.min() : luminance.percent(lower); - int const max = upper == 100 ? luminance.max() : luminance.percent(upper); - - if (std::abs(max - min) > 1) { - // Extract chroma - VImage chroma = lab.extract_band(1, VImage::option()->set("n", 2)); - // Calculate multiplication factor and addition - double f = 100.0 / (max - min); - double a = -(min * f); - // Scale luminance, join to chroma, convert back to original colourspace - VImage normalized = luminance.linear(f, a).bandjoin(chroma).colourspace(typeBeforeNormalize); - // Attach original alpha channel, if any - if (HasAlpha(image)) { - // Extract original alpha channel - VImage alpha = image[image.bands() - 1]; - // Join alpha channel to normalised image - return normalized.bandjoin(alpha); - } else { - return normalized; - } - } - return image; - } - - /* - * Contrast limiting adapative histogram equalization (CLAHE) - */ - VImage Clahe(VImage image, int const width, int const height, int const maxSlope) { - return image.hist_local(width, height, VImage::option()->set("max_slope", maxSlope)); - } - - /* - * Gamma encoding/decoding - */ - VImage Gamma(VImage image, double const exponent) { - if (HasAlpha(image)) { - // Separate alpha channel - VImage alpha = image[image.bands() - 1]; - return RemoveAlpha(image).gamma(VImage::option()->set("exponent", exponent)).bandjoin(alpha); - } else { - return image.gamma(VImage::option()->set("exponent", exponent)); - } - } - - /* - * Flatten image to remove alpha channel - */ - VImage Flatten(VImage image, std::vector flattenBackground) { - double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0; - std::vector background { - flattenBackground[0] * multiplier, - flattenBackground[1] * multiplier, - flattenBackground[2] * multiplier - }; - return image.flatten(VImage::option()->set("background", background)); - } - - /** - * Produce the "negative" of the image. - */ - VImage Negate(VImage image, bool const negateAlpha) { - if (HasAlpha(image) && !negateAlpha) { - // Separate alpha channel - VImage alpha = image[image.bands() - 1]; - return RemoveAlpha(image).invert().bandjoin(alpha); - } else { - return image.invert(); - } - } - - /* - * Gaussian blur. Use sigma of -1.0 for fast blur. - */ - VImage Blur(VImage image, double const sigma) { - if (sigma == -1.0) { - // Fast, mild blur - averages neighbouring pixels - VImage blur = VImage::new_matrixv(3, 3, - 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0); - blur.set("scale", 9.0); - return image.conv(blur); - } else { - // Slower, accurate Gaussian blur - return StaySequential(image, VIPS_ACCESS_SEQUENTIAL).gaussblur(sigma); - } - } - - /* - * Convolution with a kernel. - */ - VImage Convolve(VImage image, int const width, int const height, - double const scale, double const offset, - std::unique_ptr const &kernel_v - ) { - VImage kernel = VImage::new_from_memory( - kernel_v.get(), - width * height * sizeof(double), - width, - height, - 1, - VIPS_FORMAT_DOUBLE); - kernel.set("scale", scale); - kernel.set("offset", offset); - - return image.conv(kernel); - } - - /* - * Recomb with a Matrix of the given bands/channel size. - * Eg. RGB will be a 3x3 matrix. - */ - VImage Recomb(VImage image, std::unique_ptr const &matrix) { - double *m = matrix.get(); - image = image.colourspace(VIPS_INTERPRETATION_sRGB); - return image - .recomb(image.bands() == 3 - ? VImage::new_from_memory( - m, 9 * sizeof(double), 3, 3, 1, VIPS_FORMAT_DOUBLE - ) - : VImage::new_matrixv(4, 4, - m[0], m[1], m[2], 0.0, - m[3], m[4], m[5], 0.0, - m[6], m[7], m[8], 0.0, - 0.0, 0.0, 0.0, 1.0)); - } - - VImage Modulate(VImage image, double const brightness, double const saturation, - int const hue, double const lightness) { - VipsInterpretation colourspaceBeforeModulate = image.interpretation(); - if (HasAlpha(image)) { - // Separate alpha channel - VImage alpha = image[image.bands() - 1]; - return RemoveAlpha(image) - .colourspace(VIPS_INTERPRETATION_LCH) - .linear( - { brightness, saturation, 1}, - { lightness, 0.0, static_cast(hue) } - ) - .colourspace(colourspaceBeforeModulate) - .bandjoin(alpha); - } else { - return image - .colourspace(VIPS_INTERPRETATION_LCH) - .linear( - { brightness, saturation, 1 }, - { lightness, 0.0, static_cast(hue) } - ) - .colourspace(colourspaceBeforeModulate); - } - } - - /* - * Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen. - */ - VImage Sharpen(VImage image, double const sigma, double const m1, double const m2, - double const x1, double const y2, double const y3) { - if (sigma == -1.0) { - // Fast, mild sharpen - VImage sharpen = VImage::new_matrixv(3, 3, - -1.0, -1.0, -1.0, - -1.0, 32.0, -1.0, - -1.0, -1.0, -1.0); - sharpen.set("scale", 24.0); - return image.conv(sharpen); - } else { - // Slow, accurate sharpen in LAB colour space, with control over flat vs jagged areas - VipsInterpretation colourspaceBeforeSharpen = image.interpretation(); - if (colourspaceBeforeSharpen == VIPS_INTERPRETATION_RGB) { - colourspaceBeforeSharpen = VIPS_INTERPRETATION_sRGB; - } - return image - .sharpen(VImage::option() - ->set("sigma", sigma) - ->set("m1", m1) - ->set("m2", m2) - ->set("x1", x1) - ->set("y2", y2) - ->set("y3", y3)) - .colourspace(colourspaceBeforeSharpen); - } - } - - VImage Threshold(VImage image, double const threshold, bool const thresholdGrayscale) { - if (!thresholdGrayscale) { - return image >= threshold; - } - return image.colourspace(VIPS_INTERPRETATION_B_W) >= threshold; - } - - /* - Perform boolean/bitwise operation on image color channels - results in one channel image - */ - VImage Bandbool(VImage image, VipsOperationBoolean const boolean) { - image = image.bandbool(boolean); - return image.copy(VImage::option()->set("interpretation", VIPS_INTERPRETATION_B_W)); - } - - /* - Perform bitwise boolean operation between images - */ - VImage Boolean(VImage image, VImage imageR, VipsOperationBoolean const boolean) { - return image.boolean(imageR, boolean); - } - - /* - Trim an image - */ - VImage Trim(VImage image, std::vector background, double threshold, bool const lineArt) { - if (image.width() < 3 && image.height() < 3) { - throw VError("Image to trim must be at least 3x3 pixels"); - } - if (background.size() == 0) { - // Top-left pixel provides the default background colour if none is given - background = image.extract_area(0, 0, 1, 1)(0, 0); - } else if (sharp::Is16Bit(image.interpretation())) { - for (size_t i = 0; i < background.size(); i++) { - background[i] *= 256.0; - } - threshold *= 256.0; - } - std::vector backgroundAlpha({ background.back() }); - if (HasAlpha(image)) { - background.pop_back(); - } else { - background.resize(image.bands()); - } - int left, top, width, height; - left = image.find_trim(&top, &width, &height, VImage::option() - ->set("background", background) - ->set("line_art", lineArt) - ->set("threshold", threshold)); - if (HasAlpha(image)) { - // Search alpha channel (A) - int leftA, topA, widthA, heightA; - VImage alpha = image[image.bands() - 1]; - leftA = alpha.find_trim(&topA, &widthA, &heightA, VImage::option() - ->set("background", backgroundAlpha) - ->set("line_art", lineArt) - ->set("threshold", threshold)); - if (widthA > 0 && heightA > 0) { - if (width > 0 && height > 0) { - // Combined bounding box (B) - int const leftB = std::min(left, leftA); - int const topB = std::min(top, topA); - int const widthB = std::max(left + width, leftA + widthA) - leftB; - int const heightB = std::max(top + height, topA + heightA) - topB; - return image.extract_area(leftB, topB, widthB, heightB); - } else { - // Use alpha only - return image.extract_area(leftA, topA, widthA, heightA); - } - } - } - if (width > 0 && height > 0) { - return image.extract_area(left, top, width, height); - } - return image; - } - - /* - * Calculate (a * in + b) - */ - VImage Linear(VImage image, std::vector const a, std::vector const b) { - size_t const bands = static_cast(image.bands()); - if (a.size() > bands) { - throw VError("Band expansion using linear is unsupported"); - } - bool const uchar = !Is16Bit(image.interpretation()); - if (HasAlpha(image) && a.size() != bands && (a.size() == 1 || a.size() == bands - 1 || bands - 1 == 1)) { - // Separate alpha channel - VImage alpha = image[bands - 1]; - return RemoveAlpha(image).linear(a, b, VImage::option()->set("uchar", uchar)).bandjoin(alpha); - } else { - return image.linear(a, b, VImage::option()->set("uchar", uchar)); - } - } - - /* - * Unflatten - */ - VImage Unflatten(VImage image) { - if (HasAlpha(image)) { - VImage alpha = image[image.bands() - 1]; - VImage noAlpha = RemoveAlpha(image); - return noAlpha.bandjoin(alpha & (noAlpha.colourspace(VIPS_INTERPRETATION_B_W) < 255)); - } else { - return image.bandjoin(image.colourspace(VIPS_INTERPRETATION_B_W) < 255); - } - } - - /* - * Ensure the image is in a given colourspace - */ - VImage EnsureColourspace(VImage image, VipsInterpretation colourspace) { - if (colourspace != VIPS_INTERPRETATION_LAST && image.interpretation() != colourspace) { - image = image.colourspace(colourspace, - VImage::option()->set("source_space", image.interpretation())); - } - return image; - } - - /* - * Split and crop each frame, reassemble, and update pageHeight. - */ - VImage CropMultiPage(VImage image, int left, int top, int width, int height, - int nPages, int *pageHeight) { - if (top == 0 && height == *pageHeight) { - // Fast path; no need to adjust the height of the multi-page image - return image.extract_area(left, 0, width, image.height()); - } else { - std::vector pages; - pages.reserve(nPages); - - // Split the image into cropped frames - image = StaySequential(image, VIPS_ACCESS_SEQUENTIAL); - for (int i = 0; i < nPages; i++) { - pages.push_back( - image.extract_area(left, *pageHeight * i + top, width, height)); - } - - // Reassemble the frames into a tall, thin image - VImage assembled = VImage::arrayjoin(pages, - VImage::option()->set("across", 1)); - - // Update the page height - *pageHeight = height; - - return assembled; - } - } - - /* - * Split into frames, embed each frame, reassemble, and update pageHeight. - */ - VImage EmbedMultiPage(VImage image, int left, int top, int width, int height, - VipsExtend extendWith, std::vector background, int nPages, int *pageHeight) { - if (top == 0 && height == *pageHeight) { - // Fast path; no need to adjust the height of the multi-page image - return image.embed(left, 0, width, image.height(), VImage::option() - ->set("extend", extendWith) - ->set("background", background)); - } else if (left == 0 && width == image.width()) { - // Fast path; no need to adjust the width of the multi-page image - std::vector pages; - pages.reserve(nPages); - - // Rearrange the tall image into a vertical grid - image = image.grid(*pageHeight, nPages, 1); - - // Do the embed on the wide image - image = image.embed(0, top, image.width(), height, VImage::option() - ->set("extend", extendWith) - ->set("background", background)); - - // Split the wide image into frames - for (int i = 0; i < nPages; i++) { - pages.push_back( - image.extract_area(width * i, 0, width, height)); - } - - // Reassemble the frames into a tall, thin image - VImage assembled = VImage::arrayjoin(pages, - VImage::option()->set("across", 1)); - - // Update the page height - *pageHeight = height; - - return assembled; - } else { - std::vector pages; - pages.reserve(nPages); - - // Split the image into frames - for (int i = 0; i < nPages; i++) { - pages.push_back( - image.extract_area(0, *pageHeight * i, image.width(), *pageHeight)); - } - - // Embed each frame in the target size - for (int i = 0; i < nPages; i++) { - pages[i] = pages[i].embed(left, top, width, height, VImage::option() - ->set("extend", extendWith) - ->set("background", background)); - } - - // Reassemble the frames into a tall, thin image - VImage assembled = VImage::arrayjoin(pages, - VImage::option()->set("across", 1)); - - // Update the page height - *pageHeight = height; - - return assembled; - } - } - -} // namespace sharp diff --git a/node_modules/sharp/src/operations.h b/node_modules/sharp/src/operations.h deleted file mode 100644 index f2d73704..00000000 --- a/node_modules/sharp/src/operations.h +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -#ifndef SRC_OPERATIONS_H_ -#define SRC_OPERATIONS_H_ - -#include -#include -#include -#include -#include - -using vips::VImage; - -namespace sharp { - - /* - * Tint an image using the provided RGB. - */ - VImage Tint(VImage image, std::vector const tint); - - /* - * Stretch luminance to cover full dynamic range. - */ - VImage Normalise(VImage image, int const lower, int const upper); - - /* - * Contrast limiting adapative histogram equalization (CLAHE) - */ - VImage Clahe(VImage image, int const width, int const height, int const maxSlope); - - /* - * Gamma encoding/decoding - */ - VImage Gamma(VImage image, double const exponent); - - /* - * Flatten image to remove alpha channel - */ - VImage Flatten(VImage image, std::vector flattenBackground); - - /* - * Produce the "negative" of the image. - */ - VImage Negate(VImage image, bool const negateAlpha); - - /* - * Gaussian blur. Use sigma of -1.0 for fast blur. - */ - VImage Blur(VImage image, double const sigma); - - /* - * Convolution with a kernel. - */ - VImage Convolve(VImage image, int const width, int const height, - double const scale, double const offset, std::unique_ptr const &kernel_v); - - /* - * Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen. - */ - VImage Sharpen(VImage image, double const sigma, double const m1, double const m2, - double const x1, double const y2, double const y3); - - /* - Threshold an image - */ - VImage Threshold(VImage image, double const threshold, bool const thresholdColor); - - /* - Perform boolean/bitwise operation on image color channels - results in one channel image - */ - VImage Bandbool(VImage image, VipsOperationBoolean const boolean); - - /* - Perform bitwise boolean operation between images - */ - VImage Boolean(VImage image, VImage imageR, VipsOperationBoolean const boolean); - - /* - Trim an image - */ - VImage Trim(VImage image, std::vector background, double threshold, bool const lineArt); - - /* - * Linear adjustment (a * in + b) - */ - VImage Linear(VImage image, std::vector const a, std::vector const b); - - /* - * Unflatten - */ - VImage Unflatten(VImage image); - - /* - * Recomb with a Matrix of the given bands/channel size. - * Eg. RGB will be a 3x3 matrix. - */ - VImage Recomb(VImage image, std::unique_ptr const &matrix); - - /* - * Modulate brightness, saturation, hue and lightness - */ - VImage Modulate(VImage image, double const brightness, double const saturation, - int const hue, double const lightness); - - /* - * Ensure the image is in a given colourspace - */ - VImage EnsureColourspace(VImage image, VipsInterpretation colourspace); - - /* - * Split and crop each frame, reassemble, and update pageHeight. - */ - VImage CropMultiPage(VImage image, int left, int top, int width, int height, - int nPages, int *pageHeight); - - /* - * Split into frames, embed each frame, reassemble, and update pageHeight. - */ - VImage EmbedMultiPage(VImage image, int left, int top, int width, int height, - VipsExtend extendWith, std::vector background, int nPages, int *pageHeight); - -} // namespace sharp - -#endif // SRC_OPERATIONS_H_ diff --git a/node_modules/sharp/src/pipeline.cc b/node_modules/sharp/src/pipeline.cc deleted file mode 100644 index a9c68f12..00000000 --- a/node_modules/sharp/src/pipeline.cc +++ /dev/null @@ -1,1743 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "common.h" -#include "operations.h" -#include "pipeline.h" - -#ifdef _WIN32 -#define STAT64_STRUCT __stat64 -#define STAT64_FUNCTION _stat64 -#elif defined(_LARGEFILE64_SOURCE) -#define STAT64_STRUCT stat64 -#define STAT64_FUNCTION stat64 -#else -#define STAT64_STRUCT stat -#define STAT64_FUNCTION stat -#endif - -class PipelineWorker : public Napi::AsyncWorker { - public: - PipelineWorker(Napi::Function callback, PipelineBaton *baton, - Napi::Function debuglog, Napi::Function queueListener) : - Napi::AsyncWorker(callback), - baton(baton), - debuglog(Napi::Persistent(debuglog)), - queueListener(Napi::Persistent(queueListener)) {} - ~PipelineWorker() {} - - // libuv worker - void Execute() { - // Decrement queued task counter - sharp::counterQueue--; - // Increment processing task counter - sharp::counterProcess++; - - try { - // Open input - vips::VImage image; - sharp::ImageType inputImageType; - std::tie(image, inputImageType) = sharp::OpenInput(baton->input); - VipsAccess access = baton->input->access; - image = sharp::EnsureColourspace(image, baton->colourspacePipeline); - - int nPages = baton->input->pages; - if (nPages == -1) { - // Resolve the number of pages if we need to render until the end of the document - nPages = image.get_typeof(VIPS_META_N_PAGES) != 0 - ? image.get_int(VIPS_META_N_PAGES) - baton->input->page - : 1; - } - - // Get pre-resize page height - int pageHeight = sharp::GetPageHeight(image); - - // Calculate angle of rotation - VipsAngle rotation = VIPS_ANGLE_D0; - VipsAngle autoRotation = VIPS_ANGLE_D0; - bool autoFlip = FALSE; - bool autoFlop = FALSE; - - if (baton->useExifOrientation) { - // Rotate and flip image according to Exif orientation - std::tie(autoRotation, autoFlip, autoFlop) = CalculateExifRotationAndFlip(sharp::ExifOrientation(image)); - image = sharp::RemoveExifOrientation(image); - } else { - rotation = CalculateAngleRotation(baton->angle); - } - - // Rotate pre-extract - bool const shouldRotateBefore = baton->rotateBeforePreExtract && - (rotation != VIPS_ANGLE_D0 || autoRotation != VIPS_ANGLE_D0 || - autoFlip || baton->flip || autoFlop || baton->flop || - baton->rotationAngle != 0.0); - - if (shouldRotateBefore) { - image = sharp::StaySequential(image, access, - rotation != VIPS_ANGLE_D0 || - autoRotation != VIPS_ANGLE_D0 || - autoFlip || - baton->flip || - baton->rotationAngle != 0.0); - - if (autoRotation != VIPS_ANGLE_D0) { - if (autoRotation != VIPS_ANGLE_D180) { - MultiPageUnsupported(nPages, "Rotate"); - } - image = image.rot(autoRotation); - autoRotation = VIPS_ANGLE_D0; - } - if (autoFlip) { - image = image.flip(VIPS_DIRECTION_VERTICAL); - autoFlip = FALSE; - } else if (baton->flip) { - image = image.flip(VIPS_DIRECTION_VERTICAL); - baton->flip = FALSE; - } - if (autoFlop) { - image = image.flip(VIPS_DIRECTION_HORIZONTAL); - autoFlop = FALSE; - } else if (baton->flop) { - image = image.flip(VIPS_DIRECTION_HORIZONTAL); - baton->flop = FALSE; - } - if (rotation != VIPS_ANGLE_D0) { - if (rotation != VIPS_ANGLE_D180) { - MultiPageUnsupported(nPages, "Rotate"); - } - image = image.rot(rotation); - rotation = VIPS_ANGLE_D0; - } - if (baton->rotationAngle != 0.0) { - MultiPageUnsupported(nPages, "Rotate"); - std::vector background; - std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, FALSE); - image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background)).copy_memory(); - } - } - - // Trim - if (baton->trimThreshold >= 0.0) { - MultiPageUnsupported(nPages, "Trim"); - image = sharp::StaySequential(image, access); - image = sharp::Trim(image, baton->trimBackground, baton->trimThreshold, baton->trimLineArt); - baton->trimOffsetLeft = image.xoffset(); - baton->trimOffsetTop = image.yoffset(); - } - - // Pre extraction - if (baton->topOffsetPre != -1) { - image = nPages > 1 - ? sharp::CropMultiPage(image, - baton->leftOffsetPre, baton->topOffsetPre, baton->widthPre, baton->heightPre, nPages, &pageHeight) - : image.extract_area(baton->leftOffsetPre, baton->topOffsetPre, baton->widthPre, baton->heightPre); - } - - // Get pre-resize image width and height - int inputWidth = image.width(); - int inputHeight = image.height(); - - // Is there just one page? Shrink to inputHeight instead - if (nPages == 1) { - pageHeight = inputHeight; - } - - // Scaling calculations - double hshrink; - double vshrink; - int targetResizeWidth = baton->width; - int targetResizeHeight = baton->height; - - // When auto-rotating by 90 or 270 degrees, swap the target width and - // height to ensure the behavior aligns with how it would have been if - // the rotation had taken place *before* resizing. - if (!baton->rotateBeforePreExtract && - (autoRotation == VIPS_ANGLE_D90 || autoRotation == VIPS_ANGLE_D270)) { - std::swap(targetResizeWidth, targetResizeHeight); - } - - // Shrink to pageHeight, so we work for multi-page images - std::tie(hshrink, vshrink) = sharp::ResolveShrink( - inputWidth, pageHeight, targetResizeWidth, targetResizeHeight, - baton->canvas, baton->withoutEnlargement, baton->withoutReduction); - - // The jpeg preload shrink. - int jpegShrinkOnLoad = 1; - - // WebP, PDF, SVG scale - double scale = 1.0; - - // Try to reload input using shrink-on-load for JPEG, WebP, SVG and PDF, when: - // - the width or height parameters are specified; - // - gamma correction doesn't need to be applied; - // - trimming or pre-resize extract isn't required; - // - input colourspace is not specified; - bool const shouldPreShrink = (targetResizeWidth > 0 || targetResizeHeight > 0) && - baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold < 0.0 && - baton->colourspacePipeline == VIPS_INTERPRETATION_LAST && !shouldRotateBefore; - - if (shouldPreShrink) { - // The common part of the shrink: the bit by which both axes must be shrunk - double shrink = std::min(hshrink, vshrink); - - if (inputImageType == sharp::ImageType::JPEG) { - // Leave at least a factor of two for the final resize step, when fastShrinkOnLoad: false - // for more consistent results and to avoid extra sharpness to the image - int factor = baton->fastShrinkOnLoad ? 1 : 2; - if (shrink >= 8 * factor) { - jpegShrinkOnLoad = 8; - } else if (shrink >= 4 * factor) { - jpegShrinkOnLoad = 4; - } else if (shrink >= 2 * factor) { - jpegShrinkOnLoad = 2; - } - // Lower shrink-on-load for known libjpeg rounding errors - if (jpegShrinkOnLoad > 1 && static_cast(shrink) == jpegShrinkOnLoad) { - jpegShrinkOnLoad /= 2; - } - } else if (inputImageType == sharp::ImageType::WEBP && baton->fastShrinkOnLoad && shrink > 1.0) { - // Avoid upscaling via webp - scale = 1.0 / shrink; - } else if (inputImageType == sharp::ImageType::SVG || - inputImageType == sharp::ImageType::PDF) { - scale = 1.0 / shrink; - } - } - - // Reload input using shrink-on-load, it'll be an integer shrink - // factor for jpegload*, a double scale factor for webpload*, - // pdfload* and svgload* - if (jpegShrinkOnLoad > 1) { - vips::VOption *option = VImage::option() - ->set("access", access) - ->set("shrink", jpegShrinkOnLoad) - ->set("unlimited", baton->input->unlimited) - ->set("fail_on", baton->input->failOn); - if (baton->input->buffer != nullptr) { - // Reload JPEG buffer - VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); - image = VImage::jpegload_buffer(blob, option); - vips_area_unref(reinterpret_cast(blob)); - } else { - // Reload JPEG file - image = VImage::jpegload(const_cast(baton->input->file.data()), option); - } - } else if (scale != 1.0) { - vips::VOption *option = VImage::option() - ->set("access", access) - ->set("scale", scale) - ->set("fail_on", baton->input->failOn); - if (inputImageType == sharp::ImageType::WEBP) { - option->set("n", baton->input->pages); - option->set("page", baton->input->page); - - if (baton->input->buffer != nullptr) { - // Reload WebP buffer - VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); - image = VImage::webpload_buffer(blob, option); - vips_area_unref(reinterpret_cast(blob)); - } else { - // Reload WebP file - image = VImage::webpload(const_cast(baton->input->file.data()), option); - } - } else if (inputImageType == sharp::ImageType::SVG) { - option->set("unlimited", baton->input->unlimited); - option->set("dpi", baton->input->density); - - if (baton->input->buffer != nullptr) { - // Reload SVG buffer - VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); - image = VImage::svgload_buffer(blob, option); - vips_area_unref(reinterpret_cast(blob)); - } else { - // Reload SVG file - image = VImage::svgload(const_cast(baton->input->file.data()), option); - } - sharp::SetDensity(image, baton->input->density); - if (image.width() > 32767 || image.height() > 32767) { - throw vips::VError("Input SVG image will exceed 32767x32767 pixel limit when scaled"); - } - } else if (inputImageType == sharp::ImageType::PDF) { - option->set("n", baton->input->pages); - option->set("page", baton->input->page); - option->set("dpi", baton->input->density); - - if (baton->input->buffer != nullptr) { - // Reload PDF buffer - VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); - image = VImage::pdfload_buffer(blob, option); - vips_area_unref(reinterpret_cast(blob)); - } else { - // Reload PDF file - image = VImage::pdfload(const_cast(baton->input->file.data()), option); - } - - sharp::SetDensity(image, baton->input->density); - } - } else { - if (inputImageType == sharp::ImageType::SVG && (image.width() > 32767 || image.height() > 32767)) { - throw vips::VError("Input SVG image exceeds 32767x32767 pixel limit"); - } - } - - // Any pre-shrinking may already have been done - inputWidth = image.width(); - inputHeight = image.height(); - - // After pre-shrink, but before the main shrink stage - // Reuse the initial pageHeight if we didn't pre-shrink - if (shouldPreShrink) { - pageHeight = sharp::GetPageHeight(image); - } - - // Shrink to pageHeight, so we work for multi-page images - std::tie(hshrink, vshrink) = sharp::ResolveShrink( - inputWidth, pageHeight, targetResizeWidth, targetResizeHeight, - baton->canvas, baton->withoutEnlargement, baton->withoutReduction); - - int targetHeight = static_cast(std::rint(static_cast(pageHeight) / vshrink)); - int targetPageHeight = targetHeight; - - // In toilet-roll mode, we must adjust vshrink so that we exactly hit - // pageHeight or we'll have pixels straddling pixel boundaries - if (inputHeight > pageHeight) { - targetHeight *= nPages; - vshrink = static_cast(inputHeight) / targetHeight; - } - - // Ensure we're using a device-independent colour space - std::pair inputProfile(nullptr, 0); - if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) && baton->withIccProfile.empty()) { - // Cache input profile for use with output - inputProfile = sharp::GetProfile(image); - } - char const *processingProfile = image.interpretation() == VIPS_INTERPRETATION_RGB16 ? "p3" : "srgb"; - if ( - sharp::HasProfile(image) && - image.interpretation() != VIPS_INTERPRETATION_LABS && - image.interpretation() != VIPS_INTERPRETATION_GREY16 && - baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK && - !baton->input->ignoreIcc - ) { - // Convert to sRGB/P3 using embedded profile - try { - image = image.icc_transform(processingProfile, VImage::option() - ->set("embedded", TRUE) - ->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8) - ->set("intent", VIPS_INTENT_PERCEPTUAL)); - } catch(...) { - sharp::VipsWarningCallback(nullptr, G_LOG_LEVEL_WARNING, "Invalid embedded profile", nullptr); - } - } else if ( - image.interpretation() == VIPS_INTERPRETATION_CMYK && - baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK - ) { - image = image.icc_transform(processingProfile, VImage::option() - ->set("input_profile", "cmyk") - ->set("intent", VIPS_INTENT_PERCEPTUAL)); - } - - // Flatten image to remove alpha channel - if (baton->flatten && sharp::HasAlpha(image)) { - image = sharp::Flatten(image, baton->flattenBackground); - } - - // Negate the colours in the image - if (baton->negate) { - image = sharp::Negate(image, baton->negateAlpha); - } - - // Gamma encoding (darken) - if (baton->gamma >= 1 && baton->gamma <= 3) { - image = sharp::Gamma(image, 1.0 / baton->gamma); - } - - // Convert to greyscale (linear, therefore after gamma encoding, if any) - if (baton->greyscale) { - image = image.colourspace(VIPS_INTERPRETATION_B_W); - } - - bool const shouldResize = hshrink != 1.0 || vshrink != 1.0; - bool const shouldBlur = baton->blurSigma != 0.0; - bool const shouldConv = baton->convKernelWidth * baton->convKernelHeight > 0; - bool const shouldSharpen = baton->sharpenSigma != 0.0; - bool const shouldComposite = !baton->composite.empty(); - - if (shouldComposite && !sharp::HasAlpha(image)) { - image = sharp::EnsureAlpha(image, 1); - } - - VipsBandFormat premultiplyFormat = image.format(); - bool const shouldPremultiplyAlpha = sharp::HasAlpha(image) && - (shouldResize || shouldBlur || shouldConv || shouldSharpen); - - if (shouldPremultiplyAlpha) { - image = image.premultiply().cast(premultiplyFormat); - } - - // Resize - if (shouldResize) { - image = image.resize(1.0 / hshrink, VImage::option() - ->set("vscale", 1.0 / vshrink) - ->set("kernel", baton->kernel)); - } - - image = sharp::StaySequential(image, access, - autoRotation != VIPS_ANGLE_D0 || - baton->flip || - autoFlip || - rotation != VIPS_ANGLE_D0); - // Auto-rotate post-extract - if (autoRotation != VIPS_ANGLE_D0) { - if (autoRotation != VIPS_ANGLE_D180) { - MultiPageUnsupported(nPages, "Rotate"); - } - image = image.rot(autoRotation); - } - // Mirror vertically (up-down) about the x-axis - if (baton->flip || autoFlip) { - image = image.flip(VIPS_DIRECTION_VERTICAL); - } - // Mirror horizontally (left-right) about the y-axis - if (baton->flop || autoFlop) { - image = image.flip(VIPS_DIRECTION_HORIZONTAL); - } - // Rotate post-extract 90-angle - if (rotation != VIPS_ANGLE_D0) { - if (rotation != VIPS_ANGLE_D180) { - MultiPageUnsupported(nPages, "Rotate"); - } - image = image.rot(rotation); - } - - // Join additional color channels to the image - if (!baton->joinChannelIn.empty()) { - VImage joinImage; - sharp::ImageType joinImageType = sharp::ImageType::UNKNOWN; - - for (unsigned int i = 0; i < baton->joinChannelIn.size(); i++) { - baton->joinChannelIn[i]->access = access; - std::tie(joinImage, joinImageType) = sharp::OpenInput(baton->joinChannelIn[i]); - joinImage = sharp::EnsureColourspace(joinImage, baton->colourspacePipeline); - image = image.bandjoin(joinImage); - } - image = image.copy(VImage::option()->set("interpretation", baton->colourspace)); - image = sharp::RemoveGifPalette(image); - } - - inputWidth = image.width(); - inputHeight = nPages > 1 ? targetPageHeight : image.height(); - - // Resolve dimensions - if (baton->width <= 0) { - baton->width = inputWidth; - } - if (baton->height <= 0) { - baton->height = inputHeight; - } - - // Crop/embed - if (inputWidth != baton->width || inputHeight != baton->height) { - if (baton->canvas == sharp::Canvas::EMBED) { - std::vector background; - std::tie(image, background) = sharp::ApplyAlpha(image, baton->resizeBackground, shouldPremultiplyAlpha); - - // Embed - int left; - int top; - std::tie(left, top) = sharp::CalculateEmbedPosition( - inputWidth, inputHeight, baton->width, baton->height, baton->position); - int width = std::max(inputWidth, baton->width); - int height = std::max(inputHeight, baton->height); - - image = nPages > 1 - ? sharp::EmbedMultiPage(image, - left, top, width, height, VIPS_EXTEND_BACKGROUND, background, nPages, &targetPageHeight) - : image.embed(left, top, width, height, VImage::option() - ->set("extend", VIPS_EXTEND_BACKGROUND) - ->set("background", background)); - } else if (baton->canvas == sharp::Canvas::CROP) { - if (baton->width > inputWidth) { - baton->width = inputWidth; - } - if (baton->height > inputHeight) { - baton->height = inputHeight; - } - - // Crop - if (baton->position < 9) { - // Gravity-based crop - int left; - int top; - - std::tie(left, top) = sharp::CalculateCrop( - inputWidth, inputHeight, baton->width, baton->height, baton->position); - int width = std::min(inputWidth, baton->width); - int height = std::min(inputHeight, baton->height); - - image = nPages > 1 - ? sharp::CropMultiPage(image, - left, top, width, height, nPages, &targetPageHeight) - : image.extract_area(left, top, width, height); - } else { - int attention_x; - int attention_y; - - // Attention-based or Entropy-based crop - MultiPageUnsupported(nPages, "Resize strategy"); - image = sharp::StaySequential(image, access); - image = image.smartcrop(baton->width, baton->height, VImage::option() - ->set("interesting", baton->position == 16 ? VIPS_INTERESTING_ENTROPY : VIPS_INTERESTING_ATTENTION) - ->set("premultiplied", shouldPremultiplyAlpha) - ->set("attention_x", &attention_x) - ->set("attention_y", &attention_y)); - baton->hasCropOffset = true; - baton->cropOffsetLeft = static_cast(image.xoffset()); - baton->cropOffsetTop = static_cast(image.yoffset()); - baton->hasAttentionCenter = true; - baton->attentionX = static_cast(attention_x * jpegShrinkOnLoad / scale); - baton->attentionY = static_cast(attention_y * jpegShrinkOnLoad / scale); - } - } - } - - // Rotate post-extract non-90 angle - if (!baton->rotateBeforePreExtract && baton->rotationAngle != 0.0) { - MultiPageUnsupported(nPages, "Rotate"); - image = sharp::StaySequential(image, access); - std::vector background; - std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, shouldPremultiplyAlpha); - image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background)); - } - - // Post extraction - if (baton->topOffsetPost != -1) { - if (nPages > 1) { - image = sharp::CropMultiPage(image, - baton->leftOffsetPost, baton->topOffsetPost, baton->widthPost, baton->heightPost, - nPages, &targetPageHeight); - - // heightPost is used in the info object, so update to reflect the number of pages - baton->heightPost *= nPages; - } else { - image = image.extract_area( - baton->leftOffsetPost, baton->topOffsetPost, baton->widthPost, baton->heightPost); - } - } - - // Affine transform - if (!baton->affineMatrix.empty()) { - MultiPageUnsupported(nPages, "Affine"); - image = sharp::StaySequential(image, access); - std::vector background; - std::tie(image, background) = sharp::ApplyAlpha(image, baton->affineBackground, shouldPremultiplyAlpha); - vips::VInterpolate interp = vips::VInterpolate::new_from_name( - const_cast(baton->affineInterpolator.data())); - image = image.affine(baton->affineMatrix, VImage::option()->set("background", background) - ->set("idx", baton->affineIdx) - ->set("idy", baton->affineIdy) - ->set("odx", baton->affineOdx) - ->set("ody", baton->affineOdy) - ->set("interpolate", interp)); - } - - // Extend edges - if (baton->extendTop > 0 || baton->extendBottom > 0 || baton->extendLeft > 0 || baton->extendRight > 0) { - // Embed - baton->width = image.width() + baton->extendLeft + baton->extendRight; - baton->height = (nPages > 1 ? targetPageHeight : image.height()) + baton->extendTop + baton->extendBottom; - - if (baton->extendWith == VIPS_EXTEND_BACKGROUND) { - std::vector background; - std::tie(image, background) = sharp::ApplyAlpha(image, baton->extendBackground, shouldPremultiplyAlpha); - - image = nPages > 1 - ? sharp::EmbedMultiPage(image, - baton->extendLeft, baton->extendTop, baton->width, baton->height, - baton->extendWith, background, nPages, &targetPageHeight) - : image.embed(baton->extendLeft, baton->extendTop, baton->width, baton->height, - VImage::option()->set("extend", baton->extendWith)->set("background", background)); - } else { - std::vector ignoredBackground(1); - image = sharp::StaySequential(image, baton->input->access); - image = nPages > 1 - ? sharp::EmbedMultiPage(image, - baton->extendLeft, baton->extendTop, baton->width, baton->height, - baton->extendWith, ignoredBackground, nPages, &targetPageHeight) - : image.embed(baton->extendLeft, baton->extendTop, baton->width, baton->height, - VImage::option()->set("extend", baton->extendWith)); - } - } - // Median - must happen before blurring, due to the utility of blurring after thresholding - if (baton->medianSize > 0) { - image = image.median(baton->medianSize); - } - - // Threshold - must happen before blurring, due to the utility of blurring after thresholding - // Threshold - must happen before unflatten to enable non-white unflattening - if (baton->threshold != 0) { - image = sharp::Threshold(image, baton->threshold, baton->thresholdGrayscale); - } - - // Blur - if (shouldBlur) { - image = sharp::Blur(image, baton->blurSigma); - } - - // Unflatten the image - if (baton->unflatten) { - image = sharp::Unflatten(image); - } - - // Convolve - if (shouldConv) { - image = sharp::Convolve(image, - baton->convKernelWidth, baton->convKernelHeight, - baton->convKernelScale, baton->convKernelOffset, - baton->convKernel); - } - - // Recomb - if (baton->recombMatrix != NULL) { - image = sharp::Recomb(image, baton->recombMatrix); - } - - // Modulate - if (baton->brightness != 1.0 || baton->saturation != 1.0 || baton->hue != 0.0 || baton->lightness != 0.0) { - image = sharp::Modulate(image, baton->brightness, baton->saturation, baton->hue, baton->lightness); - } - - // Sharpen - if (shouldSharpen) { - image = sharp::Sharpen(image, baton->sharpenSigma, baton->sharpenM1, baton->sharpenM2, - baton->sharpenX1, baton->sharpenY2, baton->sharpenY3); - } - - // Reverse premultiplication after all transformations - if (shouldPremultiplyAlpha) { - image = image.unpremultiply().cast(premultiplyFormat); - } - baton->premultiplied = shouldPremultiplyAlpha; - - // Composite - if (shouldComposite) { - std::vector images = { image }; - std::vector modes, xs, ys; - for (Composite *composite : baton->composite) { - VImage compositeImage; - sharp::ImageType compositeImageType = sharp::ImageType::UNKNOWN; - composite->input->access = access; - std::tie(compositeImage, compositeImageType) = sharp::OpenInput(composite->input); - compositeImage = sharp::EnsureColourspace(compositeImage, baton->colourspacePipeline); - // Verify within current dimensions - if (compositeImage.width() > image.width() || compositeImage.height() > image.height()) { - throw vips::VError("Image to composite must have same dimensions or smaller"); - } - // Check if overlay is tiled - if (composite->tile) { - int across = 0; - int down = 0; - // Use gravity in overlay - if (compositeImage.width() <= image.width()) { - across = static_cast(ceil(static_cast(image.width()) / compositeImage.width())); - // Ensure odd number of tiles across when gravity is centre, north or south - if (composite->gravity == 0 || composite->gravity == 1 || composite->gravity == 3) { - across |= 1; - } - } - if (compositeImage.height() <= image.height()) { - down = static_cast(ceil(static_cast(image.height()) / compositeImage.height())); - // Ensure odd number of tiles down when gravity is centre, east or west - if (composite->gravity == 0 || composite->gravity == 2 || composite->gravity == 4) { - down |= 1; - } - } - if (across != 0 || down != 0) { - int left; - int top; - compositeImage = sharp::StaySequential(compositeImage, access).replicate(across, down); - if (composite->hasOffset) { - std::tie(left, top) = sharp::CalculateCrop( - compositeImage.width(), compositeImage.height(), image.width(), image.height(), - composite->left, composite->top); - } else { - std::tie(left, top) = sharp::CalculateCrop( - compositeImage.width(), compositeImage.height(), image.width(), image.height(), composite->gravity); - } - compositeImage = compositeImage.extract_area(left, top, image.width(), image.height()); - } - // gravity was used for extract_area, set it back to its default value of 0 - composite->gravity = 0; - } - // Ensure image to composite is sRGB with unpremultiplied alpha - compositeImage = compositeImage.colourspace(VIPS_INTERPRETATION_sRGB); - if (!sharp::HasAlpha(compositeImage)) { - compositeImage = sharp::EnsureAlpha(compositeImage, 1); - } - if (composite->premultiplied) compositeImage = compositeImage.unpremultiply(); - // Calculate position - int left; - int top; - if (composite->hasOffset) { - // Composite image at given offsets - if (composite->tile) { - std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(), - compositeImage.width(), compositeImage.height(), composite->left, composite->top); - } else { - left = composite->left; - top = composite->top; - } - } else { - // Composite image with given gravity - std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(), - compositeImage.width(), compositeImage.height(), composite->gravity); - } - images.push_back(compositeImage); - modes.push_back(composite->mode); - xs.push_back(left); - ys.push_back(top); - } - image = VImage::composite(images, modes, VImage::option()->set("x", xs)->set("y", ys)); - image = sharp::RemoveGifPalette(image); - } - - // Gamma decoding (brighten) - if (baton->gammaOut >= 1 && baton->gammaOut <= 3) { - image = sharp::Gamma(image, baton->gammaOut); - } - - // Linear adjustment (a * in + b) - if (!baton->linearA.empty()) { - image = sharp::Linear(image, baton->linearA, baton->linearB); - } - - // Apply normalisation - stretch luminance to cover full dynamic range - if (baton->normalise) { - image = sharp::StaySequential(image, access); - image = sharp::Normalise(image, baton->normaliseLower, baton->normaliseUpper); - } - - // Apply contrast limiting adaptive histogram equalization (CLAHE) - if (baton->claheWidth != 0 && baton->claheHeight != 0) { - image = sharp::StaySequential(image, access); - image = sharp::Clahe(image, baton->claheWidth, baton->claheHeight, baton->claheMaxSlope); - } - - // Apply bitwise boolean operation between images - if (baton->boolean != nullptr) { - VImage booleanImage; - sharp::ImageType booleanImageType = sharp::ImageType::UNKNOWN; - baton->boolean->access = access; - std::tie(booleanImage, booleanImageType) = sharp::OpenInput(baton->boolean); - booleanImage = sharp::EnsureColourspace(booleanImage, baton->colourspacePipeline); - image = sharp::Boolean(image, booleanImage, baton->booleanOp); - image = sharp::RemoveGifPalette(image); - } - - // Apply per-channel Bandbool bitwise operations after all other operations - if (baton->bandBoolOp >= VIPS_OPERATION_BOOLEAN_AND && baton->bandBoolOp < VIPS_OPERATION_BOOLEAN_LAST) { - image = sharp::Bandbool(image, baton->bandBoolOp); - } - - // Tint the image - if (baton->tint[0] >= 0.0) { - image = sharp::Tint(image, baton->tint); - } - - // Remove alpha channel, if any - if (baton->removeAlpha) { - image = sharp::RemoveAlpha(image); - } - - // Ensure alpha channel, if missing - if (baton->ensureAlpha != -1) { - image = sharp::EnsureAlpha(image, baton->ensureAlpha); - } - - // Convert image to sRGB, if not already - if (sharp::Is16Bit(image.interpretation())) { - image = image.cast(VIPS_FORMAT_USHORT); - } - if (image.interpretation() != baton->colourspace) { - // Convert colourspace, pass the current known interpretation so libvips doesn't have to guess - image = image.colourspace(baton->colourspace, VImage::option()->set("source_space", image.interpretation())); - // Transform colours from embedded profile to output profile - if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) && baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK && - baton->withIccProfile.empty() && sharp::HasProfile(image)) { - image = image.icc_transform(processingProfile, VImage::option() - ->set("embedded", TRUE) - ->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8) - ->set("intent", VIPS_INTENT_PERCEPTUAL)); - } - } - - // Extract channel - if (baton->extractChannel > -1) { - if (baton->extractChannel >= image.bands()) { - if (baton->extractChannel == 3 && sharp::HasAlpha(image)) { - baton->extractChannel = image.bands() - 1; - } else { - (baton->err) - .append("Cannot extract channel ").append(std::to_string(baton->extractChannel)) - .append(" from image with channels 0-").append(std::to_string(image.bands() - 1)); - return Error(); - } - } - VipsInterpretation colourspace = sharp::Is16Bit(image.interpretation()) - ? VIPS_INTERPRETATION_GREY16 - : VIPS_INTERPRETATION_B_W; - image = image - .extract_band(baton->extractChannel) - .copy(VImage::option()->set("interpretation", colourspace)); - } - - // Apply output ICC profile - if (!baton->withIccProfile.empty()) { - try { - image = image.icc_transform(const_cast(baton->withIccProfile.data()), VImage::option() - ->set("input_profile", processingProfile) - ->set("embedded", TRUE) - ->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8) - ->set("intent", VIPS_INTENT_PERCEPTUAL)); - } catch(...) { - sharp::VipsWarningCallback(nullptr, G_LOG_LEVEL_WARNING, "Invalid profile", nullptr); - } - } else if (baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) { - image = sharp::SetProfile(image, inputProfile); - } - // Override EXIF Orientation tag - if (baton->withMetadataOrientation != -1) { - image = sharp::SetExifOrientation(image, baton->withMetadataOrientation); - } - // Override pixel density - if (baton->withMetadataDensity > 0) { - image = sharp::SetDensity(image, baton->withMetadataDensity); - } - // EXIF key/value pairs - if (baton->keepMetadata & VIPS_FOREIGN_KEEP_EXIF) { - image = image.copy(); - if (!baton->withExifMerge) { - image = sharp::RemoveExif(image); - } - for (const auto& s : baton->withExif) { - image.set(s.first.data(), s.second.data()); - } - } - - // Number of channels used in output image - baton->channels = image.bands(); - baton->width = image.width(); - baton->height = image.height(); - - image = sharp::SetAnimationProperties( - image, nPages, targetPageHeight, baton->delay, baton->loop); - - // Output - sharp::SetTimeout(image, baton->timeoutSeconds); - if (baton->fileOut.empty()) { - // Buffer output - if (baton->formatOut == "jpeg" || (baton->formatOut == "input" && inputImageType == sharp::ImageType::JPEG)) { - // Write JPEG to buffer - sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG); - VipsArea *area = reinterpret_cast(image.jpegsave_buffer(VImage::option() - ->set("keep", baton->keepMetadata) - ->set("Q", baton->jpegQuality) - ->set("interlace", baton->jpegProgressive) - ->set("subsample_mode", baton->jpegChromaSubsampling == "4:4:4" - ? VIPS_FOREIGN_SUBSAMPLE_OFF - : VIPS_FOREIGN_SUBSAMPLE_ON) - ->set("trellis_quant", baton->jpegTrellisQuantisation) - ->set("quant_table", baton->jpegQuantisationTable) - ->set("overshoot_deringing", baton->jpegOvershootDeringing) - ->set("optimize_scans", baton->jpegOptimiseScans) - ->set("optimize_coding", baton->jpegOptimiseCoding))); - baton->bufferOut = static_cast(area->data); - baton->bufferOutLength = area->length; - area->free_fn = nullptr; - vips_area_unref(area); - baton->formatOut = "jpeg"; - if (baton->colourspace == VIPS_INTERPRETATION_CMYK) { - baton->channels = std::min(baton->channels, 4); - } else { - baton->channels = std::min(baton->channels, 3); - } - } else if (baton->formatOut == "jp2" || (baton->formatOut == "input" - && inputImageType == sharp::ImageType::JP2)) { - // Write JP2 to Buffer - sharp::AssertImageTypeDimensions(image, sharp::ImageType::JP2); - VipsArea *area = reinterpret_cast(image.jp2ksave_buffer(VImage::option() - ->set("Q", baton->jp2Quality) - ->set("lossless", baton->jp2Lossless) - ->set("subsample_mode", baton->jp2ChromaSubsampling == "4:4:4" - ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) - ->set("tile_height", baton->jp2TileHeight) - ->set("tile_width", baton->jp2TileWidth))); - baton->bufferOut = static_cast(area->data); - baton->bufferOutLength = area->length; - area->free_fn = nullptr; - vips_area_unref(area); - baton->formatOut = "jp2"; - } else if (baton->formatOut == "png" || (baton->formatOut == "input" && - (inputImageType == sharp::ImageType::PNG || inputImageType == sharp::ImageType::SVG))) { - // Write PNG to buffer - sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG); - VipsArea *area = reinterpret_cast(image.pngsave_buffer(VImage::option() - ->set("keep", baton->keepMetadata) - ->set("interlace", baton->pngProgressive) - ->set("compression", baton->pngCompressionLevel) - ->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE) - ->set("palette", baton->pngPalette) - ->set("Q", baton->pngQuality) - ->set("effort", baton->pngEffort) - ->set("bitdepth", sharp::Is16Bit(image.interpretation()) ? 16 : baton->pngBitdepth) - ->set("dither", baton->pngDither))); - baton->bufferOut = static_cast(area->data); - baton->bufferOutLength = area->length; - area->free_fn = nullptr; - vips_area_unref(area); - baton->formatOut = "png"; - } else if (baton->formatOut == "webp" || - (baton->formatOut == "input" && inputImageType == sharp::ImageType::WEBP)) { - // Write WEBP to buffer - sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP); - VipsArea *area = reinterpret_cast(image.webpsave_buffer(VImage::option() - ->set("keep", baton->keepMetadata) - ->set("Q", baton->webpQuality) - ->set("lossless", baton->webpLossless) - ->set("near_lossless", baton->webpNearLossless) - ->set("smart_subsample", baton->webpSmartSubsample) - ->set("preset", baton->webpPreset) - ->set("effort", baton->webpEffort) - ->set("min_size", baton->webpMinSize) - ->set("mixed", baton->webpMixed) - ->set("alpha_q", baton->webpAlphaQuality))); - baton->bufferOut = static_cast(area->data); - baton->bufferOutLength = area->length; - area->free_fn = nullptr; - vips_area_unref(area); - baton->formatOut = "webp"; - } else if (baton->formatOut == "gif" || - (baton->formatOut == "input" && inputImageType == sharp::ImageType::GIF)) { - // Write GIF to buffer - sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF); - VipsArea *area = reinterpret_cast(image.gifsave_buffer(VImage::option() - ->set("keep", baton->keepMetadata) - ->set("bitdepth", baton->gifBitdepth) - ->set("effort", baton->gifEffort) - ->set("reuse", baton->gifReuse) - ->set("interlace", baton->gifProgressive) - ->set("interframe_maxerror", baton->gifInterFrameMaxError) - ->set("interpalette_maxerror", baton->gifInterPaletteMaxError) - ->set("dither", baton->gifDither))); - baton->bufferOut = static_cast(area->data); - baton->bufferOutLength = area->length; - area->free_fn = nullptr; - vips_area_unref(area); - baton->formatOut = "gif"; - } else if (baton->formatOut == "tiff" || - (baton->formatOut == "input" && inputImageType == sharp::ImageType::TIFF)) { - // Write TIFF to buffer - if (baton->tiffCompression == VIPS_FOREIGN_TIFF_COMPRESSION_JPEG) { - sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG); - baton->channels = std::min(baton->channels, 3); - } - // Cast pixel values to float, if required - if (baton->tiffPredictor == VIPS_FOREIGN_TIFF_PREDICTOR_FLOAT) { - image = image.cast(VIPS_FORMAT_FLOAT); - } - VipsArea *area = reinterpret_cast(image.tiffsave_buffer(VImage::option() - ->set("keep", baton->keepMetadata) - ->set("Q", baton->tiffQuality) - ->set("bitdepth", baton->tiffBitdepth) - ->set("compression", baton->tiffCompression) - ->set("miniswhite", baton->tiffMiniswhite) - ->set("predictor", baton->tiffPredictor) - ->set("pyramid", baton->tiffPyramid) - ->set("tile", baton->tiffTile) - ->set("tile_height", baton->tiffTileHeight) - ->set("tile_width", baton->tiffTileWidth) - ->set("xres", baton->tiffXres) - ->set("yres", baton->tiffYres) - ->set("resunit", baton->tiffResolutionUnit))); - baton->bufferOut = static_cast(area->data); - baton->bufferOutLength = area->length; - area->free_fn = nullptr; - vips_area_unref(area); - baton->formatOut = "tiff"; - } else if (baton->formatOut == "heif" || - (baton->formatOut == "input" && inputImageType == sharp::ImageType::HEIF)) { - // Write HEIF to buffer - sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF); - image = sharp::RemoveAnimationProperties(image).cast(VIPS_FORMAT_UCHAR); - VipsArea *area = reinterpret_cast(image.heifsave_buffer(VImage::option() - ->set("keep", baton->keepMetadata) - ->set("Q", baton->heifQuality) - ->set("compression", baton->heifCompression) - ->set("effort", baton->heifEffort) - ->set("bitdepth", baton->heifBitdepth) - ->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4" - ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) - ->set("lossless", baton->heifLossless))); - baton->bufferOut = static_cast(area->data); - baton->bufferOutLength = area->length; - area->free_fn = nullptr; - vips_area_unref(area); - baton->formatOut = "heif"; - } else if (baton->formatOut == "dz") { - // Write DZ to buffer - baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP; - if (!sharp::HasAlpha(image)) { - baton->tileBackground.pop_back(); - } - image = sharp::StaySequential(image, access, baton->tileAngle != 0); - vips::VOption *options = BuildOptionsDZ(baton); - VipsArea *area = reinterpret_cast(image.dzsave_buffer(options)); - baton->bufferOut = static_cast(area->data); - baton->bufferOutLength = area->length; - area->free_fn = nullptr; - vips_area_unref(area); - baton->formatOut = "dz"; - } else if (baton->formatOut == "jxl" || - (baton->formatOut == "input" && inputImageType == sharp::ImageType::JXL)) { - // Write JXL to buffer - image = sharp::RemoveAnimationProperties(image); - VipsArea *area = reinterpret_cast(image.jxlsave_buffer(VImage::option() - ->set("keep", baton->keepMetadata) - ->set("distance", baton->jxlDistance) - ->set("tier", baton->jxlDecodingTier) - ->set("effort", baton->jxlEffort) - ->set("lossless", baton->jxlLossless))); - baton->bufferOut = static_cast(area->data); - baton->bufferOutLength = area->length; - area->free_fn = nullptr; - vips_area_unref(area); - baton->formatOut = "jxl"; - } else if (baton->formatOut == "raw" || - (baton->formatOut == "input" && inputImageType == sharp::ImageType::RAW)) { - // Write raw, uncompressed image data to buffer - if (baton->greyscale || image.interpretation() == VIPS_INTERPRETATION_B_W) { - // Extract first band for greyscale image - image = image[0]; - baton->channels = 1; - } - if (image.format() != baton->rawDepth) { - // Cast pixels to requested format - image = image.cast(baton->rawDepth); - } - // Get raw image data - baton->bufferOut = static_cast(image.write_to_memory(&baton->bufferOutLength)); - if (baton->bufferOut == nullptr) { - (baton->err).append("Could not allocate enough memory for raw output"); - return Error(); - } - baton->formatOut = "raw"; - } else { - // Unsupported output format - (baton->err).append("Unsupported output format "); - if (baton->formatOut == "input") { - (baton->err).append(ImageTypeId(inputImageType)); - } else { - (baton->err).append(baton->formatOut); - } - return Error(); - } - } else { - // File output - bool const isJpeg = sharp::IsJpeg(baton->fileOut); - bool const isPng = sharp::IsPng(baton->fileOut); - bool const isWebp = sharp::IsWebp(baton->fileOut); - bool const isGif = sharp::IsGif(baton->fileOut); - bool const isTiff = sharp::IsTiff(baton->fileOut); - bool const isJp2 = sharp::IsJp2(baton->fileOut); - bool const isHeif = sharp::IsHeif(baton->fileOut); - bool const isJxl = sharp::IsJxl(baton->fileOut); - bool const isDz = sharp::IsDz(baton->fileOut); - bool const isDzZip = sharp::IsDzZip(baton->fileOut); - bool const isV = sharp::IsV(baton->fileOut); - bool const mightMatchInput = baton->formatOut == "input"; - bool const willMatchInput = mightMatchInput && - !(isJpeg || isPng || isWebp || isGif || isTiff || isJp2 || isHeif || isDz || isDzZip || isV); - - if (baton->formatOut == "jpeg" || (mightMatchInput && isJpeg) || - (willMatchInput && inputImageType == sharp::ImageType::JPEG)) { - // Write JPEG to file - sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG); - image.jpegsave(const_cast(baton->fileOut.data()), VImage::option() - ->set("keep", baton->keepMetadata) - ->set("Q", baton->jpegQuality) - ->set("interlace", baton->jpegProgressive) - ->set("subsample_mode", baton->jpegChromaSubsampling == "4:4:4" - ? VIPS_FOREIGN_SUBSAMPLE_OFF - : VIPS_FOREIGN_SUBSAMPLE_ON) - ->set("trellis_quant", baton->jpegTrellisQuantisation) - ->set("quant_table", baton->jpegQuantisationTable) - ->set("overshoot_deringing", baton->jpegOvershootDeringing) - ->set("optimize_scans", baton->jpegOptimiseScans) - ->set("optimize_coding", baton->jpegOptimiseCoding)); - baton->formatOut = "jpeg"; - baton->channels = std::min(baton->channels, 3); - } else if (baton->formatOut == "jp2" || (mightMatchInput && isJp2) || - (willMatchInput && (inputImageType == sharp::ImageType::JP2))) { - // Write JP2 to file - sharp::AssertImageTypeDimensions(image, sharp::ImageType::JP2); - image.jp2ksave(const_cast(baton->fileOut.data()), VImage::option() - ->set("Q", baton->jp2Quality) - ->set("lossless", baton->jp2Lossless) - ->set("subsample_mode", baton->jp2ChromaSubsampling == "4:4:4" - ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) - ->set("tile_height", baton->jp2TileHeight) - ->set("tile_width", baton->jp2TileWidth)); - baton->formatOut = "jp2"; - } else if (baton->formatOut == "png" || (mightMatchInput && isPng) || (willMatchInput && - (inputImageType == sharp::ImageType::PNG || inputImageType == sharp::ImageType::SVG))) { - // Write PNG to file - sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG); - image.pngsave(const_cast(baton->fileOut.data()), VImage::option() - ->set("keep", baton->keepMetadata) - ->set("interlace", baton->pngProgressive) - ->set("compression", baton->pngCompressionLevel) - ->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE) - ->set("palette", baton->pngPalette) - ->set("Q", baton->pngQuality) - ->set("bitdepth", sharp::Is16Bit(image.interpretation()) ? 16 : baton->pngBitdepth) - ->set("effort", baton->pngEffort) - ->set("dither", baton->pngDither)); - baton->formatOut = "png"; - } else if (baton->formatOut == "webp" || (mightMatchInput && isWebp) || - (willMatchInput && inputImageType == sharp::ImageType::WEBP)) { - // Write WEBP to file - sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP); - image.webpsave(const_cast(baton->fileOut.data()), VImage::option() - ->set("keep", baton->keepMetadata) - ->set("Q", baton->webpQuality) - ->set("lossless", baton->webpLossless) - ->set("near_lossless", baton->webpNearLossless) - ->set("smart_subsample", baton->webpSmartSubsample) - ->set("preset", baton->webpPreset) - ->set("effort", baton->webpEffort) - ->set("min_size", baton->webpMinSize) - ->set("mixed", baton->webpMixed) - ->set("alpha_q", baton->webpAlphaQuality)); - baton->formatOut = "webp"; - } else if (baton->formatOut == "gif" || (mightMatchInput && isGif) || - (willMatchInput && inputImageType == sharp::ImageType::GIF)) { - // Write GIF to file - sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF); - image.gifsave(const_cast(baton->fileOut.data()), VImage::option() - ->set("keep", baton->keepMetadata) - ->set("bitdepth", baton->gifBitdepth) - ->set("effort", baton->gifEffort) - ->set("reuse", baton->gifReuse) - ->set("interlace", baton->gifProgressive) - ->set("dither", baton->gifDither)); - baton->formatOut = "gif"; - } else if (baton->formatOut == "tiff" || (mightMatchInput && isTiff) || - (willMatchInput && inputImageType == sharp::ImageType::TIFF)) { - // Write TIFF to file - if (baton->tiffCompression == VIPS_FOREIGN_TIFF_COMPRESSION_JPEG) { - sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG); - baton->channels = std::min(baton->channels, 3); - } - // Cast pixel values to float, if required - if (baton->tiffPredictor == VIPS_FOREIGN_TIFF_PREDICTOR_FLOAT) { - image = image.cast(VIPS_FORMAT_FLOAT); - } - image.tiffsave(const_cast(baton->fileOut.data()), VImage::option() - ->set("keep", baton->keepMetadata) - ->set("Q", baton->tiffQuality) - ->set("bitdepth", baton->tiffBitdepth) - ->set("compression", baton->tiffCompression) - ->set("miniswhite", baton->tiffMiniswhite) - ->set("predictor", baton->tiffPredictor) - ->set("pyramid", baton->tiffPyramid) - ->set("tile", baton->tiffTile) - ->set("tile_height", baton->tiffTileHeight) - ->set("tile_width", baton->tiffTileWidth) - ->set("xres", baton->tiffXres) - ->set("yres", baton->tiffYres) - ->set("resunit", baton->tiffResolutionUnit)); - baton->formatOut = "tiff"; - } else if (baton->formatOut == "heif" || (mightMatchInput && isHeif) || - (willMatchInput && inputImageType == sharp::ImageType::HEIF)) { - // Write HEIF to file - sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF); - image = sharp::RemoveAnimationProperties(image).cast(VIPS_FORMAT_UCHAR); - image.heifsave(const_cast(baton->fileOut.data()), VImage::option() - ->set("keep", baton->keepMetadata) - ->set("Q", baton->heifQuality) - ->set("compression", baton->heifCompression) - ->set("effort", baton->heifEffort) - ->set("bitdepth", baton->heifBitdepth) - ->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4" - ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) - ->set("lossless", baton->heifLossless)); - baton->formatOut = "heif"; - } else if (baton->formatOut == "jxl" || (mightMatchInput && isJxl) || - (willMatchInput && inputImageType == sharp::ImageType::JXL)) { - // Write JXL to file - image = sharp::RemoveAnimationProperties(image); - image.jxlsave(const_cast(baton->fileOut.data()), VImage::option() - ->set("keep", baton->keepMetadata) - ->set("distance", baton->jxlDistance) - ->set("tier", baton->jxlDecodingTier) - ->set("effort", baton->jxlEffort) - ->set("lossless", baton->jxlLossless)); - baton->formatOut = "jxl"; - } else if (baton->formatOut == "dz" || isDz || isDzZip) { - // Write DZ to file - if (isDzZip) { - baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP; - } - if (!sharp::HasAlpha(image)) { - baton->tileBackground.pop_back(); - } - image = sharp::StaySequential(image, access, baton->tileAngle != 0); - vips::VOption *options = BuildOptionsDZ(baton); - image.dzsave(const_cast(baton->fileOut.data()), options); - baton->formatOut = "dz"; - } else if (baton->formatOut == "v" || (mightMatchInput && isV) || - (willMatchInput && inputImageType == sharp::ImageType::VIPS)) { - // Write V to file - image.vipssave(const_cast(baton->fileOut.data()), VImage::option() - ->set("keep", baton->keepMetadata)); - baton->formatOut = "v"; - } else { - // Unsupported output format - (baton->err).append("Unsupported output format " + baton->fileOut); - return Error(); - } - } - } catch (vips::VError const &err) { - char const *what = err.what(); - if (what && what[0]) { - (baton->err).append(what); - } else { - (baton->err).append("Unknown error"); - } - } - // Clean up libvips' per-request data and threads - vips_error_clear(); - vips_thread_shutdown(); - } - - void OnOK() { - Napi::Env env = Env(); - Napi::HandleScope scope(env); - - // Handle warnings - std::string warning = sharp::VipsWarningPop(); - while (!warning.empty()) { - debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) }); - warning = sharp::VipsWarningPop(); - } - - if (baton->err.empty()) { - int width = baton->width; - int height = baton->height; - if (baton->topOffsetPre != -1 && (baton->width == -1 || baton->height == -1)) { - width = baton->widthPre; - height = baton->heightPre; - } - if (baton->topOffsetPost != -1) { - width = baton->widthPost; - height = baton->heightPost; - } - // Info Object - Napi::Object info = Napi::Object::New(env); - info.Set("format", baton->formatOut); - info.Set("width", static_cast(width)); - info.Set("height", static_cast(height)); - info.Set("channels", static_cast(baton->channels)); - if (baton->formatOut == "raw") { - info.Set("depth", vips_enum_nick(VIPS_TYPE_BAND_FORMAT, baton->rawDepth)); - } - info.Set("premultiplied", baton->premultiplied); - if (baton->hasCropOffset) { - info.Set("cropOffsetLeft", static_cast(baton->cropOffsetLeft)); - info.Set("cropOffsetTop", static_cast(baton->cropOffsetTop)); - } - if (baton->hasAttentionCenter) { - info.Set("attentionX", static_cast(baton->attentionX)); - info.Set("attentionY", static_cast(baton->attentionY)); - } - if (baton->trimThreshold >= 0.0) { - info.Set("trimOffsetLeft", static_cast(baton->trimOffsetLeft)); - info.Set("trimOffsetTop", static_cast(baton->trimOffsetTop)); - } - if (baton->input->textAutofitDpi) { - info.Set("textAutofitDpi", static_cast(baton->input->textAutofitDpi)); - } - - if (baton->bufferOutLength > 0) { - // Add buffer size to info - info.Set("size", static_cast(baton->bufferOutLength)); - // Pass ownership of output data to Buffer instance - Napi::Buffer data = Napi::Buffer::NewOrCopy(env, static_cast(baton->bufferOut), - baton->bufferOutLength, sharp::FreeCallback); - Callback().Call(Receiver().Value(), { env.Null(), data, info }); - } else { - // Add file size to info - struct STAT64_STRUCT st; - if (STAT64_FUNCTION(baton->fileOut.data(), &st) == 0) { - info.Set("size", static_cast(st.st_size)); - } - Callback().Call(Receiver().Value(), { env.Null(), info }); - } - } else { - Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() }); - } - - // Delete baton - delete baton->input; - delete baton->boolean; - for (Composite *composite : baton->composite) { - delete composite->input; - delete composite; - } - for (sharp::InputDescriptor *input : baton->joinChannelIn) { - delete input; - } - delete baton; - - // Decrement processing task counter - sharp::counterProcess--; - Napi::Number queueLength = Napi::Number::New(env, static_cast(sharp::counterQueue)); - queueListener.Call(Receiver().Value(), { queueLength }); - } - - private: - PipelineBaton *baton; - Napi::FunctionReference debuglog; - Napi::FunctionReference queueListener; - - void MultiPageUnsupported(int const pages, std::string op) { - if (pages > 1) { - throw vips::VError(op + " is not supported for multi-page images"); - } - } - - /* - Calculate the angle of rotation and need-to-flip for the given Exif orientation - By default, returns zero, i.e. no rotation. - */ - std::tuple - CalculateExifRotationAndFlip(int const exifOrientation) { - VipsAngle rotate = VIPS_ANGLE_D0; - bool flip = FALSE; - bool flop = FALSE; - switch (exifOrientation) { - case 6: rotate = VIPS_ANGLE_D90; break; - case 3: rotate = VIPS_ANGLE_D180; break; - case 8: rotate = VIPS_ANGLE_D270; break; - case 2: flop = TRUE; break; // flop 1 - case 7: flip = TRUE; rotate = VIPS_ANGLE_D90; break; // flip 6 - case 4: flop = TRUE; rotate = VIPS_ANGLE_D180; break; // flop 3 - case 5: flip = TRUE; rotate = VIPS_ANGLE_D270; break; // flip 8 - } - return std::make_tuple(rotate, flip, flop); - } - - /* - Calculate the rotation for the given angle. - Supports any positive or negative angle that is a multiple of 90. - */ - VipsAngle - CalculateAngleRotation(int angle) { - angle = angle % 360; - if (angle < 0) - angle = 360 + angle; - switch (angle) { - case 90: return VIPS_ANGLE_D90; - case 180: return VIPS_ANGLE_D180; - case 270: return VIPS_ANGLE_D270; - } - return VIPS_ANGLE_D0; - } - - /* - Assemble the suffix argument to dzsave, which is the format (by extname) - alongside comma-separated arguments to the corresponding `formatsave` vips - action. - */ - std::string - AssembleSuffixString(std::string extname, std::vector> options) { - std::string argument; - for (auto const &option : options) { - if (!argument.empty()) { - argument += ","; - } - argument += option.first + "=" + option.second; - } - return extname + "[" + argument + "]"; - } - - /* - Build VOption for dzsave - */ - vips::VOption* - BuildOptionsDZ(PipelineBaton *baton) { - // Forward format options through suffix - std::string suffix; - if (baton->tileFormat == "png") { - std::vector> options { - {"interlace", baton->pngProgressive ? "TRUE" : "FALSE"}, - {"compression", std::to_string(baton->pngCompressionLevel)}, - {"filter", baton->pngAdaptiveFiltering ? "all" : "none"} - }; - suffix = AssembleSuffixString(".png", options); - } else if (baton->tileFormat == "webp") { - std::vector> options { - {"Q", std::to_string(baton->webpQuality)}, - {"alpha_q", std::to_string(baton->webpAlphaQuality)}, - {"lossless", baton->webpLossless ? "TRUE" : "FALSE"}, - {"near_lossless", baton->webpNearLossless ? "TRUE" : "FALSE"}, - {"smart_subsample", baton->webpSmartSubsample ? "TRUE" : "FALSE"}, - {"preset", vips_enum_nick(VIPS_TYPE_FOREIGN_WEBP_PRESET, baton->webpPreset)}, - {"min_size", baton->webpMinSize ? "TRUE" : "FALSE"}, - {"mixed", baton->webpMixed ? "TRUE" : "FALSE"}, - {"effort", std::to_string(baton->webpEffort)} - }; - suffix = AssembleSuffixString(".webp", options); - } else { - std::vector> options { - {"Q", std::to_string(baton->jpegQuality)}, - {"interlace", baton->jpegProgressive ? "TRUE" : "FALSE"}, - {"subsample_mode", baton->jpegChromaSubsampling == "4:4:4" ? "off" : "on"}, - {"trellis_quant", baton->jpegTrellisQuantisation ? "TRUE" : "FALSE"}, - {"quant_table", std::to_string(baton->jpegQuantisationTable)}, - {"overshoot_deringing", baton->jpegOvershootDeringing ? "TRUE": "FALSE"}, - {"optimize_scans", baton->jpegOptimiseScans ? "TRUE": "FALSE"}, - {"optimize_coding", baton->jpegOptimiseCoding ? "TRUE": "FALSE"} - }; - std::string extname = baton->tileLayout == VIPS_FOREIGN_DZ_LAYOUT_DZ ? ".jpeg" : ".jpg"; - suffix = AssembleSuffixString(extname, options); - } - vips::VOption *options = VImage::option() - ->set("keep", baton->keepMetadata) - ->set("tile_size", baton->tileSize) - ->set("overlap", baton->tileOverlap) - ->set("container", baton->tileContainer) - ->set("layout", baton->tileLayout) - ->set("suffix", const_cast(suffix.data())) - ->set("angle", CalculateAngleRotation(baton->tileAngle)) - ->set("background", baton->tileBackground) - ->set("centre", baton->tileCentre) - ->set("id", const_cast(baton->tileId.data())) - ->set("skip_blanks", baton->tileSkipBlanks); - if (baton->tileDepth < VIPS_FOREIGN_DZ_DEPTH_LAST) { - options->set("depth", baton->tileDepth); - } - if (!baton->tileBasename.empty()) { - options->set("basename", const_cast(baton->tileBasename.data())); - } - return options; - } - - /* - Clear all thread-local data. - */ - void Error() { - // Clean up libvips' per-request data and threads - vips_error_clear(); - vips_thread_shutdown(); - } -}; - -/* - pipeline(options, output, callback) -*/ -Napi::Value pipeline(const Napi::CallbackInfo& info) { - // V8 objects are converted to non-V8 types held in the baton struct - PipelineBaton *baton = new PipelineBaton; - Napi::Object options = info[size_t(0)].As(); - - // Input - baton->input = sharp::CreateInputDescriptor(options.Get("input").As()); - // Extract image options - baton->topOffsetPre = sharp::AttrAsInt32(options, "topOffsetPre"); - baton->leftOffsetPre = sharp::AttrAsInt32(options, "leftOffsetPre"); - baton->widthPre = sharp::AttrAsInt32(options, "widthPre"); - baton->heightPre = sharp::AttrAsInt32(options, "heightPre"); - baton->topOffsetPost = sharp::AttrAsInt32(options, "topOffsetPost"); - baton->leftOffsetPost = sharp::AttrAsInt32(options, "leftOffsetPost"); - baton->widthPost = sharp::AttrAsInt32(options, "widthPost"); - baton->heightPost = sharp::AttrAsInt32(options, "heightPost"); - // Output image dimensions - baton->width = sharp::AttrAsInt32(options, "width"); - baton->height = sharp::AttrAsInt32(options, "height"); - // Canvas option - std::string canvas = sharp::AttrAsStr(options, "canvas"); - if (canvas == "crop") { - baton->canvas = sharp::Canvas::CROP; - } else if (canvas == "embed") { - baton->canvas = sharp::Canvas::EMBED; - } else if (canvas == "max") { - baton->canvas = sharp::Canvas::MAX; - } else if (canvas == "min") { - baton->canvas = sharp::Canvas::MIN; - } else if (canvas == "ignore_aspect") { - baton->canvas = sharp::Canvas::IGNORE_ASPECT; - } - // Composite - Napi::Array compositeArray = options.Get("composite").As(); - for (unsigned int i = 0; i < compositeArray.Length(); i++) { - Napi::Object compositeObject = compositeArray.Get(i).As(); - Composite *composite = new Composite; - composite->input = sharp::CreateInputDescriptor(compositeObject.Get("input").As()); - composite->mode = sharp::AttrAsEnum(compositeObject, "blend", VIPS_TYPE_BLEND_MODE); - composite->gravity = sharp::AttrAsUint32(compositeObject, "gravity"); - composite->left = sharp::AttrAsInt32(compositeObject, "left"); - composite->top = sharp::AttrAsInt32(compositeObject, "top"); - composite->hasOffset = sharp::AttrAsBool(compositeObject, "hasOffset"); - composite->tile = sharp::AttrAsBool(compositeObject, "tile"); - composite->premultiplied = sharp::AttrAsBool(compositeObject, "premultiplied"); - baton->composite.push_back(composite); - } - // Resize options - baton->withoutEnlargement = sharp::AttrAsBool(options, "withoutEnlargement"); - baton->withoutReduction = sharp::AttrAsBool(options, "withoutReduction"); - baton->position = sharp::AttrAsInt32(options, "position"); - baton->resizeBackground = sharp::AttrAsVectorOfDouble(options, "resizeBackground"); - baton->kernel = sharp::AttrAsEnum(options, "kernel", VIPS_TYPE_KERNEL); - baton->fastShrinkOnLoad = sharp::AttrAsBool(options, "fastShrinkOnLoad"); - // Join Channel Options - if (options.Has("joinChannelIn")) { - Napi::Array joinChannelArray = options.Get("joinChannelIn").As(); - for (unsigned int i = 0; i < joinChannelArray.Length(); i++) { - baton->joinChannelIn.push_back( - sharp::CreateInputDescriptor(joinChannelArray.Get(i).As())); - } - } - // Operators - baton->flatten = sharp::AttrAsBool(options, "flatten"); - baton->flattenBackground = sharp::AttrAsVectorOfDouble(options, "flattenBackground"); - baton->unflatten = sharp::AttrAsBool(options, "unflatten"); - baton->negate = sharp::AttrAsBool(options, "negate"); - baton->negateAlpha = sharp::AttrAsBool(options, "negateAlpha"); - baton->blurSigma = sharp::AttrAsDouble(options, "blurSigma"); - baton->brightness = sharp::AttrAsDouble(options, "brightness"); - baton->saturation = sharp::AttrAsDouble(options, "saturation"); - baton->hue = sharp::AttrAsInt32(options, "hue"); - baton->lightness = sharp::AttrAsDouble(options, "lightness"); - baton->medianSize = sharp::AttrAsUint32(options, "medianSize"); - baton->sharpenSigma = sharp::AttrAsDouble(options, "sharpenSigma"); - baton->sharpenM1 = sharp::AttrAsDouble(options, "sharpenM1"); - baton->sharpenM2 = sharp::AttrAsDouble(options, "sharpenM2"); - baton->sharpenX1 = sharp::AttrAsDouble(options, "sharpenX1"); - baton->sharpenY2 = sharp::AttrAsDouble(options, "sharpenY2"); - baton->sharpenY3 = sharp::AttrAsDouble(options, "sharpenY3"); - baton->threshold = sharp::AttrAsInt32(options, "threshold"); - baton->thresholdGrayscale = sharp::AttrAsBool(options, "thresholdGrayscale"); - baton->trimBackground = sharp::AttrAsVectorOfDouble(options, "trimBackground"); - baton->trimThreshold = sharp::AttrAsDouble(options, "trimThreshold"); - baton->trimLineArt = sharp::AttrAsBool(options, "trimLineArt"); - baton->gamma = sharp::AttrAsDouble(options, "gamma"); - baton->gammaOut = sharp::AttrAsDouble(options, "gammaOut"); - baton->linearA = sharp::AttrAsVectorOfDouble(options, "linearA"); - baton->linearB = sharp::AttrAsVectorOfDouble(options, "linearB"); - baton->greyscale = sharp::AttrAsBool(options, "greyscale"); - baton->normalise = sharp::AttrAsBool(options, "normalise"); - baton->normaliseLower = sharp::AttrAsUint32(options, "normaliseLower"); - baton->normaliseUpper = sharp::AttrAsUint32(options, "normaliseUpper"); - baton->tint = sharp::AttrAsVectorOfDouble(options, "tint"); - baton->claheWidth = sharp::AttrAsUint32(options, "claheWidth"); - baton->claheHeight = sharp::AttrAsUint32(options, "claheHeight"); - baton->claheMaxSlope = sharp::AttrAsUint32(options, "claheMaxSlope"); - baton->useExifOrientation = sharp::AttrAsBool(options, "useExifOrientation"); - baton->angle = sharp::AttrAsInt32(options, "angle"); - baton->rotationAngle = sharp::AttrAsDouble(options, "rotationAngle"); - baton->rotationBackground = sharp::AttrAsVectorOfDouble(options, "rotationBackground"); - baton->rotateBeforePreExtract = sharp::AttrAsBool(options, "rotateBeforePreExtract"); - baton->flip = sharp::AttrAsBool(options, "flip"); - baton->flop = sharp::AttrAsBool(options, "flop"); - baton->extendTop = sharp::AttrAsInt32(options, "extendTop"); - baton->extendBottom = sharp::AttrAsInt32(options, "extendBottom"); - baton->extendLeft = sharp::AttrAsInt32(options, "extendLeft"); - baton->extendRight = sharp::AttrAsInt32(options, "extendRight"); - baton->extendBackground = sharp::AttrAsVectorOfDouble(options, "extendBackground"); - baton->extendWith = sharp::AttrAsEnum(options, "extendWith", VIPS_TYPE_EXTEND); - baton->extractChannel = sharp::AttrAsInt32(options, "extractChannel"); - baton->affineMatrix = sharp::AttrAsVectorOfDouble(options, "affineMatrix"); - baton->affineBackground = sharp::AttrAsVectorOfDouble(options, "affineBackground"); - baton->affineIdx = sharp::AttrAsDouble(options, "affineIdx"); - baton->affineIdy = sharp::AttrAsDouble(options, "affineIdy"); - baton->affineOdx = sharp::AttrAsDouble(options, "affineOdx"); - baton->affineOdy = sharp::AttrAsDouble(options, "affineOdy"); - baton->affineInterpolator = sharp::AttrAsStr(options, "affineInterpolator"); - baton->removeAlpha = sharp::AttrAsBool(options, "removeAlpha"); - baton->ensureAlpha = sharp::AttrAsDouble(options, "ensureAlpha"); - if (options.Has("boolean")) { - baton->boolean = sharp::CreateInputDescriptor(options.Get("boolean").As()); - baton->booleanOp = sharp::AttrAsEnum(options, "booleanOp", VIPS_TYPE_OPERATION_BOOLEAN); - } - if (options.Has("bandBoolOp")) { - baton->bandBoolOp = sharp::AttrAsEnum(options, "bandBoolOp", VIPS_TYPE_OPERATION_BOOLEAN); - } - if (options.Has("convKernel")) { - Napi::Object kernel = options.Get("convKernel").As(); - baton->convKernelWidth = sharp::AttrAsUint32(kernel, "width"); - baton->convKernelHeight = sharp::AttrAsUint32(kernel, "height"); - baton->convKernelScale = sharp::AttrAsDouble(kernel, "scale"); - baton->convKernelOffset = sharp::AttrAsDouble(kernel, "offset"); - size_t const kernelSize = static_cast(baton->convKernelWidth * baton->convKernelHeight); - baton->convKernel = std::unique_ptr(new double[kernelSize]); - Napi::Array kdata = kernel.Get("kernel").As(); - for (unsigned int i = 0; i < kernelSize; i++) { - baton->convKernel[i] = sharp::AttrAsDouble(kdata, i); - } - } - if (options.Has("recombMatrix")) { - baton->recombMatrix = std::unique_ptr(new double[9]); - Napi::Array recombMatrix = options.Get("recombMatrix").As(); - for (unsigned int i = 0; i < 9; i++) { - baton->recombMatrix[i] = sharp::AttrAsDouble(recombMatrix, i); - } - } - baton->colourspacePipeline = sharp::AttrAsEnum( - options, "colourspacePipeline", VIPS_TYPE_INTERPRETATION); - if (baton->colourspacePipeline == VIPS_INTERPRETATION_ERROR) { - baton->colourspacePipeline = VIPS_INTERPRETATION_LAST; - } - baton->colourspace = sharp::AttrAsEnum(options, "colourspace", VIPS_TYPE_INTERPRETATION); - if (baton->colourspace == VIPS_INTERPRETATION_ERROR) { - baton->colourspace = VIPS_INTERPRETATION_sRGB; - } - // Output - baton->formatOut = sharp::AttrAsStr(options, "formatOut"); - baton->fileOut = sharp::AttrAsStr(options, "fileOut"); - baton->keepMetadata = sharp::AttrAsUint32(options, "keepMetadata"); - baton->withMetadataOrientation = sharp::AttrAsUint32(options, "withMetadataOrientation"); - baton->withMetadataDensity = sharp::AttrAsDouble(options, "withMetadataDensity"); - baton->withIccProfile = sharp::AttrAsStr(options, "withIccProfile"); - Napi::Object withExif = options.Get("withExif").As(); - Napi::Array withExifKeys = withExif.GetPropertyNames(); - for (unsigned int i = 0; i < withExifKeys.Length(); i++) { - std::string k = sharp::AttrAsStr(withExifKeys, i); - if (withExif.HasOwnProperty(k)) { - baton->withExif.insert(std::make_pair(k, sharp::AttrAsStr(withExif, k))); - } - } - baton->withExifMerge = sharp::AttrAsBool(options, "withExifMerge"); - baton->timeoutSeconds = sharp::AttrAsUint32(options, "timeoutSeconds"); - // Format-specific - baton->jpegQuality = sharp::AttrAsUint32(options, "jpegQuality"); - baton->jpegProgressive = sharp::AttrAsBool(options, "jpegProgressive"); - baton->jpegChromaSubsampling = sharp::AttrAsStr(options, "jpegChromaSubsampling"); - baton->jpegTrellisQuantisation = sharp::AttrAsBool(options, "jpegTrellisQuantisation"); - baton->jpegQuantisationTable = sharp::AttrAsUint32(options, "jpegQuantisationTable"); - baton->jpegOvershootDeringing = sharp::AttrAsBool(options, "jpegOvershootDeringing"); - baton->jpegOptimiseScans = sharp::AttrAsBool(options, "jpegOptimiseScans"); - baton->jpegOptimiseCoding = sharp::AttrAsBool(options, "jpegOptimiseCoding"); - baton->pngProgressive = sharp::AttrAsBool(options, "pngProgressive"); - baton->pngCompressionLevel = sharp::AttrAsUint32(options, "pngCompressionLevel"); - baton->pngAdaptiveFiltering = sharp::AttrAsBool(options, "pngAdaptiveFiltering"); - baton->pngPalette = sharp::AttrAsBool(options, "pngPalette"); - baton->pngQuality = sharp::AttrAsUint32(options, "pngQuality"); - baton->pngEffort = sharp::AttrAsUint32(options, "pngEffort"); - baton->pngBitdepth = sharp::AttrAsUint32(options, "pngBitdepth"); - baton->pngDither = sharp::AttrAsDouble(options, "pngDither"); - baton->jp2Quality = sharp::AttrAsUint32(options, "jp2Quality"); - baton->jp2Lossless = sharp::AttrAsBool(options, "jp2Lossless"); - baton->jp2TileHeight = sharp::AttrAsUint32(options, "jp2TileHeight"); - baton->jp2TileWidth = sharp::AttrAsUint32(options, "jp2TileWidth"); - baton->jp2ChromaSubsampling = sharp::AttrAsStr(options, "jp2ChromaSubsampling"); - baton->webpQuality = sharp::AttrAsUint32(options, "webpQuality"); - baton->webpAlphaQuality = sharp::AttrAsUint32(options, "webpAlphaQuality"); - baton->webpLossless = sharp::AttrAsBool(options, "webpLossless"); - baton->webpNearLossless = sharp::AttrAsBool(options, "webpNearLossless"); - baton->webpSmartSubsample = sharp::AttrAsBool(options, "webpSmartSubsample"); - baton->webpPreset = sharp::AttrAsEnum(options, "webpPreset", VIPS_TYPE_FOREIGN_WEBP_PRESET); - baton->webpEffort = sharp::AttrAsUint32(options, "webpEffort"); - baton->webpMinSize = sharp::AttrAsBool(options, "webpMinSize"); - baton->webpMixed = sharp::AttrAsBool(options, "webpMixed"); - baton->gifBitdepth = sharp::AttrAsUint32(options, "gifBitdepth"); - baton->gifEffort = sharp::AttrAsUint32(options, "gifEffort"); - baton->gifDither = sharp::AttrAsDouble(options, "gifDither"); - baton->gifInterFrameMaxError = sharp::AttrAsDouble(options, "gifInterFrameMaxError"); - baton->gifInterPaletteMaxError = sharp::AttrAsDouble(options, "gifInterPaletteMaxError"); - baton->gifReuse = sharp::AttrAsBool(options, "gifReuse"); - baton->gifProgressive = sharp::AttrAsBool(options, "gifProgressive"); - baton->tiffQuality = sharp::AttrAsUint32(options, "tiffQuality"); - baton->tiffPyramid = sharp::AttrAsBool(options, "tiffPyramid"); - baton->tiffMiniswhite = sharp::AttrAsBool(options, "tiffMiniswhite"); - baton->tiffBitdepth = sharp::AttrAsUint32(options, "tiffBitdepth"); - baton->tiffTile = sharp::AttrAsBool(options, "tiffTile"); - baton->tiffTileWidth = sharp::AttrAsUint32(options, "tiffTileWidth"); - baton->tiffTileHeight = sharp::AttrAsUint32(options, "tiffTileHeight"); - baton->tiffXres = sharp::AttrAsDouble(options, "tiffXres"); - baton->tiffYres = sharp::AttrAsDouble(options, "tiffYres"); - if (baton->tiffXres == 1.0 && baton->tiffYres == 1.0 && baton->withMetadataDensity > 0) { - baton->tiffXres = baton->tiffYres = baton->withMetadataDensity / 25.4; - } - baton->tiffCompression = sharp::AttrAsEnum( - options, "tiffCompression", VIPS_TYPE_FOREIGN_TIFF_COMPRESSION); - baton->tiffPredictor = sharp::AttrAsEnum( - options, "tiffPredictor", VIPS_TYPE_FOREIGN_TIFF_PREDICTOR); - baton->tiffResolutionUnit = sharp::AttrAsEnum( - options, "tiffResolutionUnit", VIPS_TYPE_FOREIGN_TIFF_RESUNIT); - baton->heifQuality = sharp::AttrAsUint32(options, "heifQuality"); - baton->heifLossless = sharp::AttrAsBool(options, "heifLossless"); - baton->heifCompression = sharp::AttrAsEnum( - options, "heifCompression", VIPS_TYPE_FOREIGN_HEIF_COMPRESSION); - baton->heifEffort = sharp::AttrAsUint32(options, "heifEffort"); - baton->heifChromaSubsampling = sharp::AttrAsStr(options, "heifChromaSubsampling"); - baton->heifBitdepth = sharp::AttrAsUint32(options, "heifBitdepth"); - baton->jxlDistance = sharp::AttrAsDouble(options, "jxlDistance"); - baton->jxlDecodingTier = sharp::AttrAsUint32(options, "jxlDecodingTier"); - baton->jxlEffort = sharp::AttrAsUint32(options, "jxlEffort"); - baton->jxlLossless = sharp::AttrAsBool(options, "jxlLossless"); - baton->rawDepth = sharp::AttrAsEnum(options, "rawDepth", VIPS_TYPE_BAND_FORMAT); - // Animated output properties - if (sharp::HasAttr(options, "loop")) { - baton->loop = sharp::AttrAsUint32(options, "loop"); - } - if (sharp::HasAttr(options, "delay")) { - baton->delay = sharp::AttrAsInt32Vector(options, "delay"); - } - baton->tileSize = sharp::AttrAsUint32(options, "tileSize"); - baton->tileOverlap = sharp::AttrAsUint32(options, "tileOverlap"); - baton->tileAngle = sharp::AttrAsInt32(options, "tileAngle"); - baton->tileBackground = sharp::AttrAsVectorOfDouble(options, "tileBackground"); - baton->tileSkipBlanks = sharp::AttrAsInt32(options, "tileSkipBlanks"); - baton->tileContainer = sharp::AttrAsEnum( - options, "tileContainer", VIPS_TYPE_FOREIGN_DZ_CONTAINER); - baton->tileLayout = sharp::AttrAsEnum(options, "tileLayout", VIPS_TYPE_FOREIGN_DZ_LAYOUT); - baton->tileFormat = sharp::AttrAsStr(options, "tileFormat"); - baton->tileDepth = sharp::AttrAsEnum(options, "tileDepth", VIPS_TYPE_FOREIGN_DZ_DEPTH); - baton->tileCentre = sharp::AttrAsBool(options, "tileCentre"); - baton->tileId = sharp::AttrAsStr(options, "tileId"); - baton->tileBasename = sharp::AttrAsStr(options, "tileBasename"); - - // Function to notify of libvips warnings - Napi::Function debuglog = options.Get("debuglog").As(); - - // Function to notify of queue length changes - Napi::Function queueListener = options.Get("queueListener").As(); - - // Join queue for worker thread - Napi::Function callback = info[size_t(1)].As(); - PipelineWorker *worker = new PipelineWorker(callback, baton, debuglog, queueListener); - worker->Receiver().Set("options", options); - worker->Queue(); - - // Increment queued task counter - Napi::Number queueLength = Napi::Number::New(info.Env(), static_cast(++sharp::counterQueue)); - queueListener.Call(info.This(), { queueLength }); - - return info.Env().Undefined(); -} diff --git a/node_modules/sharp/src/pipeline.h b/node_modules/sharp/src/pipeline.h deleted file mode 100644 index 6ebf0e63..00000000 --- a/node_modules/sharp/src/pipeline.h +++ /dev/null @@ -1,387 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -#ifndef SRC_PIPELINE_H_ -#define SRC_PIPELINE_H_ - -#include -#include -#include -#include - -#include -#include - -#include "./common.h" - -Napi::Value pipeline(const Napi::CallbackInfo& info); - -struct Composite { - sharp::InputDescriptor *input; - VipsBlendMode mode; - int gravity; - int left; - int top; - bool hasOffset; - bool tile; - bool premultiplied; - - Composite(): - input(nullptr), - mode(VIPS_BLEND_MODE_OVER), - gravity(0), - left(0), - top(0), - hasOffset(false), - tile(false), - premultiplied(false) {} -}; - -struct PipelineBaton { - sharp::InputDescriptor *input; - std::string formatOut; - std::string fileOut; - void *bufferOut; - size_t bufferOutLength; - std::vector composite; - std::vector joinChannelIn; - int topOffsetPre; - int leftOffsetPre; - int widthPre; - int heightPre; - int topOffsetPost; - int leftOffsetPost; - int widthPost; - int heightPost; - int width; - int height; - int channels; - VipsKernel kernel; - sharp::Canvas canvas; - int position; - std::vector resizeBackground; - bool hasCropOffset; - int cropOffsetLeft; - int cropOffsetTop; - bool hasAttentionCenter; - int attentionX; - int attentionY; - bool premultiplied; - bool tileCentre; - bool fastShrinkOnLoad; - std::vector tint; - bool flatten; - std::vector flattenBackground; - bool unflatten; - bool negate; - bool negateAlpha; - double blurSigma; - double brightness; - double saturation; - int hue; - double lightness; - int medianSize; - double sharpenSigma; - double sharpenM1; - double sharpenM2; - double sharpenX1; - double sharpenY2; - double sharpenY3; - int threshold; - bool thresholdGrayscale; - std::vector trimBackground; - double trimThreshold; - bool trimLineArt; - int trimOffsetLeft; - int trimOffsetTop; - std::vector linearA; - std::vector linearB; - double gamma; - double gammaOut; - bool greyscale; - bool normalise; - int normaliseLower; - int normaliseUpper; - int claheWidth; - int claheHeight; - int claheMaxSlope; - bool useExifOrientation; - int angle; - double rotationAngle; - std::vector rotationBackground; - bool rotateBeforePreExtract; - bool flip; - bool flop; - int extendTop; - int extendBottom; - int extendLeft; - int extendRight; - std::vector extendBackground; - VipsExtend extendWith; - bool withoutEnlargement; - bool withoutReduction; - std::vector affineMatrix; - std::vector affineBackground; - double affineIdx; - double affineIdy; - double affineOdx; - double affineOdy; - std::string affineInterpolator; - int jpegQuality; - bool jpegProgressive; - std::string jpegChromaSubsampling; - bool jpegTrellisQuantisation; - int jpegQuantisationTable; - bool jpegOvershootDeringing; - bool jpegOptimiseScans; - bool jpegOptimiseCoding; - bool pngProgressive; - int pngCompressionLevel; - bool pngAdaptiveFiltering; - bool pngPalette; - int pngQuality; - int pngEffort; - int pngBitdepth; - double pngDither; - int jp2Quality; - bool jp2Lossless; - int jp2TileHeight; - int jp2TileWidth; - std::string jp2ChromaSubsampling; - int webpQuality; - int webpAlphaQuality; - bool webpNearLossless; - bool webpLossless; - bool webpSmartSubsample; - VipsForeignWebpPreset webpPreset; - int webpEffort; - bool webpMinSize; - bool webpMixed; - int gifBitdepth; - int gifEffort; - double gifDither; - double gifInterFrameMaxError; - double gifInterPaletteMaxError; - bool gifReuse; - bool gifProgressive; - int tiffQuality; - VipsForeignTiffCompression tiffCompression; - VipsForeignTiffPredictor tiffPredictor; - bool tiffPyramid; - int tiffBitdepth; - bool tiffMiniswhite; - bool tiffTile; - int tiffTileHeight; - int tiffTileWidth; - double tiffXres; - double tiffYres; - VipsForeignTiffResunit tiffResolutionUnit; - int heifQuality; - VipsForeignHeifCompression heifCompression; - int heifEffort; - std::string heifChromaSubsampling; - bool heifLossless; - int heifBitdepth; - double jxlDistance; - int jxlDecodingTier; - int jxlEffort; - bool jxlLossless; - VipsBandFormat rawDepth; - std::string err; - int keepMetadata; - int withMetadataOrientation; - double withMetadataDensity; - std::string withIccProfile; - std::unordered_map withExif; - bool withExifMerge; - int timeoutSeconds; - std::unique_ptr convKernel; - int convKernelWidth; - int convKernelHeight; - double convKernelScale; - double convKernelOffset; - sharp::InputDescriptor *boolean; - VipsOperationBoolean booleanOp; - VipsOperationBoolean bandBoolOp; - int extractChannel; - bool removeAlpha; - double ensureAlpha; - VipsInterpretation colourspacePipeline; - VipsInterpretation colourspace; - std::vector delay; - int loop; - int tileSize; - int tileOverlap; - VipsForeignDzContainer tileContainer; - VipsForeignDzLayout tileLayout; - std::string tileFormat; - int tileAngle; - std::vector tileBackground; - int tileSkipBlanks; - VipsForeignDzDepth tileDepth; - std::string tileId; - std::string tileBasename; - std::unique_ptr recombMatrix; - - PipelineBaton(): - input(nullptr), - bufferOutLength(0), - topOffsetPre(-1), - topOffsetPost(-1), - channels(0), - kernel(VIPS_KERNEL_LANCZOS3), - canvas(sharp::Canvas::CROP), - position(0), - resizeBackground{ 0.0, 0.0, 0.0, 255.0 }, - hasCropOffset(false), - cropOffsetLeft(0), - cropOffsetTop(0), - hasAttentionCenter(false), - attentionX(0), - attentionY(0), - premultiplied(false), - tint{ -1.0, 0.0, 0.0, 0.0 }, - flatten(false), - flattenBackground{ 0.0, 0.0, 0.0 }, - unflatten(false), - negate(false), - negateAlpha(true), - blurSigma(0.0), - brightness(1.0), - saturation(1.0), - hue(0), - lightness(0), - medianSize(0), - sharpenSigma(0.0), - sharpenM1(1.0), - sharpenM2(2.0), - sharpenX1(2.0), - sharpenY2(10.0), - sharpenY3(20.0), - threshold(0), - thresholdGrayscale(true), - trimBackground{}, - trimThreshold(-1.0), - trimLineArt(false), - trimOffsetLeft(0), - trimOffsetTop(0), - linearA{}, - linearB{}, - gamma(0.0), - greyscale(false), - normalise(false), - normaliseLower(1), - normaliseUpper(99), - claheWidth(0), - claheHeight(0), - claheMaxSlope(3), - useExifOrientation(false), - angle(0), - rotationAngle(0.0), - rotationBackground{ 0.0, 0.0, 0.0, 255.0 }, - flip(false), - flop(false), - extendTop(0), - extendBottom(0), - extendLeft(0), - extendRight(0), - extendBackground{ 0.0, 0.0, 0.0, 255.0 }, - extendWith(VIPS_EXTEND_BACKGROUND), - withoutEnlargement(false), - withoutReduction(false), - affineMatrix{ 1.0, 0.0, 0.0, 1.0 }, - affineBackground{ 0.0, 0.0, 0.0, 255.0 }, - affineIdx(0), - affineIdy(0), - affineOdx(0), - affineOdy(0), - affineInterpolator("bicubic"), - jpegQuality(80), - jpegProgressive(false), - jpegChromaSubsampling("4:2:0"), - jpegTrellisQuantisation(false), - jpegQuantisationTable(0), - jpegOvershootDeringing(false), - jpegOptimiseScans(false), - jpegOptimiseCoding(true), - pngProgressive(false), - pngCompressionLevel(6), - pngAdaptiveFiltering(false), - pngPalette(false), - pngQuality(100), - pngEffort(7), - pngBitdepth(8), - pngDither(1.0), - jp2Quality(80), - jp2Lossless(false), - jp2TileHeight(512), - jp2TileWidth(512), - jp2ChromaSubsampling("4:4:4"), - webpQuality(80), - webpAlphaQuality(100), - webpNearLossless(false), - webpLossless(false), - webpSmartSubsample(false), - webpPreset(VIPS_FOREIGN_WEBP_PRESET_DEFAULT), - webpEffort(4), - webpMinSize(false), - webpMixed(false), - gifBitdepth(8), - gifEffort(7), - gifDither(1.0), - gifInterFrameMaxError(0.0), - gifInterPaletteMaxError(3.0), - gifReuse(true), - gifProgressive(false), - tiffQuality(80), - tiffCompression(VIPS_FOREIGN_TIFF_COMPRESSION_JPEG), - tiffPredictor(VIPS_FOREIGN_TIFF_PREDICTOR_HORIZONTAL), - tiffPyramid(false), - tiffBitdepth(8), - tiffMiniswhite(false), - tiffTile(false), - tiffTileHeight(256), - tiffTileWidth(256), - tiffXres(1.0), - tiffYres(1.0), - tiffResolutionUnit(VIPS_FOREIGN_TIFF_RESUNIT_INCH), - heifQuality(50), - heifCompression(VIPS_FOREIGN_HEIF_COMPRESSION_AV1), - heifEffort(4), - heifChromaSubsampling("4:4:4"), - heifLossless(false), - heifBitdepth(8), - jxlDistance(1.0), - jxlDecodingTier(0), - jxlEffort(7), - jxlLossless(false), - rawDepth(VIPS_FORMAT_UCHAR), - keepMetadata(0), - withMetadataOrientation(-1), - withMetadataDensity(0.0), - withExifMerge(true), - timeoutSeconds(0), - convKernelWidth(0), - convKernelHeight(0), - convKernelScale(0.0), - convKernelOffset(0.0), - boolean(nullptr), - booleanOp(VIPS_OPERATION_BOOLEAN_LAST), - bandBoolOp(VIPS_OPERATION_BOOLEAN_LAST), - extractChannel(-1), - removeAlpha(false), - ensureAlpha(-1.0), - colourspacePipeline(VIPS_INTERPRETATION_LAST), - colourspace(VIPS_INTERPRETATION_LAST), - loop(-1), - tileSize(256), - tileOverlap(0), - tileContainer(VIPS_FOREIGN_DZ_CONTAINER_FS), - tileLayout(VIPS_FOREIGN_DZ_LAYOUT_DZ), - tileAngle(0), - tileBackground{ 255.0, 255.0, 255.0, 255.0 }, - tileSkipBlanks(-1), - tileDepth(VIPS_FOREIGN_DZ_DEPTH_LAST) {} -}; - -#endif // SRC_PIPELINE_H_ diff --git a/node_modules/sharp/src/sharp.cc b/node_modules/sharp/src/sharp.cc deleted file mode 100644 index e017b2f3..00000000 --- a/node_modules/sharp/src/sharp.cc +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -#include // NOLINT(build/c++11) - -#include -#include - -#include "common.h" -#include "metadata.h" -#include "pipeline.h" -#include "utilities.h" -#include "stats.h" - -Napi::Object init(Napi::Env env, Napi::Object exports) { - static std::once_flag sharp_vips_init_once; - std::call_once(sharp_vips_init_once, []() { - vips_init("sharp"); - }); - - g_log_set_handler("VIPS", static_cast(G_LOG_LEVEL_WARNING), - static_cast(sharp::VipsWarningCallback), nullptr); - - // Methods available to JavaScript - exports.Set("metadata", Napi::Function::New(env, metadata)); - exports.Set("pipeline", Napi::Function::New(env, pipeline)); - exports.Set("cache", Napi::Function::New(env, cache)); - exports.Set("concurrency", Napi::Function::New(env, concurrency)); - exports.Set("counters", Napi::Function::New(env, counters)); - exports.Set("simd", Napi::Function::New(env, simd)); - exports.Set("libvipsVersion", Napi::Function::New(env, libvipsVersion)); - exports.Set("format", Napi::Function::New(env, format)); - exports.Set("block", Napi::Function::New(env, block)); - exports.Set("_maxColourDistance", Napi::Function::New(env, _maxColourDistance)); - exports.Set("_isUsingJemalloc", Napi::Function::New(env, _isUsingJemalloc)); - exports.Set("stats", Napi::Function::New(env, stats)); - return exports; -} - -NODE_API_MODULE(sharp, init) diff --git a/node_modules/sharp/src/stats.cc b/node_modules/sharp/src/stats.cc deleted file mode 100644 index b06d3bb5..00000000 --- a/node_modules/sharp/src/stats.cc +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -#include -#include -#include - -#include -#include - -#include "common.h" -#include "stats.h" - -class StatsWorker : public Napi::AsyncWorker { - public: - StatsWorker(Napi::Function callback, StatsBaton *baton, Napi::Function debuglog) : - Napi::AsyncWorker(callback), baton(baton), debuglog(Napi::Persistent(debuglog)) {} - ~StatsWorker() {} - - const int STAT_MIN_INDEX = 0; - const int STAT_MAX_INDEX = 1; - const int STAT_SUM_INDEX = 2; - const int STAT_SQ_SUM_INDEX = 3; - const int STAT_MEAN_INDEX = 4; - const int STAT_STDEV_INDEX = 5; - const int STAT_MINX_INDEX = 6; - const int STAT_MINY_INDEX = 7; - const int STAT_MAXX_INDEX = 8; - const int STAT_MAXY_INDEX = 9; - - void Execute() { - // Decrement queued task counter - sharp::counterQueue--; - - vips::VImage image; - sharp::ImageType imageType = sharp::ImageType::UNKNOWN; - try { - std::tie(image, imageType) = OpenInput(baton->input); - } catch (vips::VError const &err) { - (baton->err).append(err.what()); - } - if (imageType != sharp::ImageType::UNKNOWN) { - try { - vips::VImage stats = image.stats(); - int const bands = image.bands(); - for (int b = 1; b <= bands; b++) { - ChannelStats cStats( - static_cast(stats.getpoint(STAT_MIN_INDEX, b).front()), - static_cast(stats.getpoint(STAT_MAX_INDEX, b).front()), - stats.getpoint(STAT_SUM_INDEX, b).front(), - stats.getpoint(STAT_SQ_SUM_INDEX, b).front(), - stats.getpoint(STAT_MEAN_INDEX, b).front(), - stats.getpoint(STAT_STDEV_INDEX, b).front(), - static_cast(stats.getpoint(STAT_MINX_INDEX, b).front()), - static_cast(stats.getpoint(STAT_MINY_INDEX, b).front()), - static_cast(stats.getpoint(STAT_MAXX_INDEX, b).front()), - static_cast(stats.getpoint(STAT_MAXY_INDEX, b).front())); - baton->channelStats.push_back(cStats); - } - // Image is not opaque when alpha layer is present and contains a non-mamixa value - if (sharp::HasAlpha(image)) { - double const minAlpha = static_cast(stats.getpoint(STAT_MIN_INDEX, bands).front()); - if (minAlpha != sharp::MaximumImageAlpha(image.interpretation())) { - baton->isOpaque = false; - } - } - // Convert to greyscale - vips::VImage greyscale = image.colourspace(VIPS_INTERPRETATION_B_W)[0]; - // Estimate entropy via histogram of greyscale value frequency - baton->entropy = std::abs(greyscale.hist_find().hist_entropy()); - // Estimate sharpness via standard deviation of greyscale laplacian - if (image.width() > 1 || image.height() > 1) { - VImage laplacian = VImage::new_matrixv(3, 3, - 0.0, 1.0, 0.0, - 1.0, -4.0, 1.0, - 0.0, 1.0, 0.0); - laplacian.set("scale", 9.0); - baton->sharpness = greyscale.conv(laplacian).deviate(); - } - // Most dominant sRGB colour via 4096-bin 3D histogram - vips::VImage hist = sharp::RemoveAlpha(image) - .colourspace(VIPS_INTERPRETATION_sRGB) - .hist_find_ndim(VImage::option()->set("bins", 16)); - std::complex maxpos = hist.maxpos(); - int const dx = static_cast(std::real(maxpos)); - int const dy = static_cast(std::imag(maxpos)); - std::vector pel = hist(dx, dy); - int const dz = std::distance(pel.begin(), std::find(pel.begin(), pel.end(), hist.max())); - baton->dominantRed = dx * 16 + 8; - baton->dominantGreen = dy * 16 + 8; - baton->dominantBlue = dz * 16 + 8; - } catch (vips::VError const &err) { - (baton->err).append(err.what()); - } - } - - // Clean up - vips_error_clear(); - vips_thread_shutdown(); - } - - void OnOK() { - Napi::Env env = Env(); - Napi::HandleScope scope(env); - - // Handle warnings - std::string warning = sharp::VipsWarningPop(); - while (!warning.empty()) { - debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) }); - warning = sharp::VipsWarningPop(); - } - - if (baton->err.empty()) { - // Stats Object - Napi::Object info = Napi::Object::New(env); - Napi::Array channels = Napi::Array::New(env); - - std::vector::iterator it; - int i = 0; - for (it = baton->channelStats.begin(); it < baton->channelStats.end(); it++, i++) { - Napi::Object channelStat = Napi::Object::New(env); - channelStat.Set("min", it->min); - channelStat.Set("max", it->max); - channelStat.Set("sum", it->sum); - channelStat.Set("squaresSum", it->squaresSum); - channelStat.Set("mean", it->mean); - channelStat.Set("stdev", it->stdev); - channelStat.Set("minX", it->minX); - channelStat.Set("minY", it->minY); - channelStat.Set("maxX", it->maxX); - channelStat.Set("maxY", it->maxY); - channels.Set(i, channelStat); - } - - info.Set("channels", channels); - info.Set("isOpaque", baton->isOpaque); - info.Set("entropy", baton->entropy); - info.Set("sharpness", baton->sharpness); - Napi::Object dominant = Napi::Object::New(env); - dominant.Set("r", baton->dominantRed); - dominant.Set("g", baton->dominantGreen); - dominant.Set("b", baton->dominantBlue); - info.Set("dominant", dominant); - Callback().Call(Receiver().Value(), { env.Null(), info }); - } else { - Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() }); - } - - delete baton->input; - delete baton; - } - - private: - StatsBaton* baton; - Napi::FunctionReference debuglog; -}; - -/* - stats(options, callback) -*/ -Napi::Value stats(const Napi::CallbackInfo& info) { - // V8 objects are converted to non-V8 types held in the baton struct - StatsBaton *baton = new StatsBaton; - Napi::Object options = info[size_t(0)].As(); - - // Input - baton->input = sharp::CreateInputDescriptor(options.Get("input").As()); - baton->input->access = VIPS_ACCESS_RANDOM; - - // Function to notify of libvips warnings - Napi::Function debuglog = options.Get("debuglog").As(); - - // Join queue for worker thread - Napi::Function callback = info[size_t(1)].As(); - StatsWorker *worker = new StatsWorker(callback, baton, debuglog); - worker->Receiver().Set("options", options); - worker->Queue(); - - // Increment queued task counter - sharp::counterQueue++; - - return info.Env().Undefined(); -} diff --git a/node_modules/sharp/src/stats.h b/node_modules/sharp/src/stats.h deleted file mode 100644 index c80e65fa..00000000 --- a/node_modules/sharp/src/stats.h +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -#ifndef SRC_STATS_H_ -#define SRC_STATS_H_ - -#include -#include - -#include "./common.h" - -struct ChannelStats { - // stats per channel - int min; - int max; - double sum; - double squaresSum; - double mean; - double stdev; - int minX; - int minY; - int maxX; - int maxY; - - ChannelStats(int minVal, int maxVal, double sumVal, double squaresSumVal, - double meanVal, double stdevVal, int minXVal, int minYVal, int maxXVal, int maxYVal): - min(minVal), max(maxVal), sum(sumVal), squaresSum(squaresSumVal), - mean(meanVal), stdev(stdevVal), minX(minXVal), minY(minYVal), maxX(maxXVal), maxY(maxYVal) {} -}; - -struct StatsBaton { - // Input - sharp::InputDescriptor *input; - - // Output - std::vector channelStats; - bool isOpaque; - double entropy; - double sharpness; - int dominantRed; - int dominantGreen; - int dominantBlue; - - std::string err; - - StatsBaton(): - input(nullptr), - isOpaque(true), - entropy(0.0), - sharpness(0.0), - dominantRed(0), - dominantGreen(0), - dominantBlue(0) - {} -}; - -Napi::Value stats(const Napi::CallbackInfo& info); - -#endif // SRC_STATS_H_ diff --git a/node_modules/sharp/src/utilities.cc b/node_modules/sharp/src/utilities.cc deleted file mode 100644 index 07037404..00000000 --- a/node_modules/sharp/src/utilities.cc +++ /dev/null @@ -1,269 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -#include -#include -#include - -#include -#include -#include - -#include "common.h" -#include "operations.h" -#include "utilities.h" - -/* - Get and set cache limits -*/ -Napi::Value cache(const Napi::CallbackInfo& info) { - Napi::Env env = info.Env(); - - // Set memory limit - if (info[size_t(0)].IsNumber()) { - vips_cache_set_max_mem(info[size_t(0)].As().Int32Value() * 1048576); - } - // Set file limit - if (info[size_t(1)].IsNumber()) { - vips_cache_set_max_files(info[size_t(1)].As().Int32Value()); - } - // Set items limit - if (info[size_t(2)].IsNumber()) { - vips_cache_set_max(info[size_t(2)].As().Int32Value()); - } - - // Get memory stats - Napi::Object memory = Napi::Object::New(env); - memory.Set("current", round(vips_tracked_get_mem() / 1048576)); - memory.Set("high", round(vips_tracked_get_mem_highwater() / 1048576)); - memory.Set("max", round(vips_cache_get_max_mem() / 1048576)); - // Get file stats - Napi::Object files = Napi::Object::New(env); - files.Set("current", vips_tracked_get_files()); - files.Set("max", vips_cache_get_max_files()); - - // Get item stats - Napi::Object items = Napi::Object::New(env); - items.Set("current", vips_cache_get_size()); - items.Set("max", vips_cache_get_max()); - - Napi::Object cache = Napi::Object::New(env); - cache.Set("memory", memory); - cache.Set("files", files); - cache.Set("items", items); - return cache; -} - -/* - Get and set size of thread pool -*/ -Napi::Value concurrency(const Napi::CallbackInfo& info) { - // Set concurrency - if (info[size_t(0)].IsNumber()) { - vips_concurrency_set(info[size_t(0)].As().Int32Value()); - } - // Get concurrency - return Napi::Number::New(info.Env(), vips_concurrency_get()); -} - -/* - Get internal counters (queued tasks, processing tasks) -*/ -Napi::Value counters(const Napi::CallbackInfo& info) { - Napi::Object counters = Napi::Object::New(info.Env()); - counters.Set("queue", static_cast(sharp::counterQueue)); - counters.Set("process", static_cast(sharp::counterProcess)); - return counters; -} - -/* - Get and set use of SIMD vector unit instructions -*/ -Napi::Value simd(const Napi::CallbackInfo& info) { - // Set state - if (info[size_t(0)].IsBoolean()) { - vips_vector_set_enabled(info[size_t(0)].As().Value()); - } - // Get state - return Napi::Boolean::New(info.Env(), vips_vector_isenabled()); -} - -/* - Get libvips version -*/ -Napi::Value libvipsVersion(const Napi::CallbackInfo& info) { - Napi::Env env = info.Env(); - Napi::Object version = Napi::Object::New(env); - - char semver[9]; - std::snprintf(semver, sizeof(semver), "%d.%d.%d", vips_version(0), vips_version(1), vips_version(2)); - version.Set("semver", Napi::String::New(env, semver)); -#ifdef SHARP_USE_GLOBAL_LIBVIPS - version.Set("isGlobal", Napi::Boolean::New(env, true)); -#else - version.Set("isGlobal", Napi::Boolean::New(env, false)); -#endif -#ifdef __EMSCRIPTEN__ - version.Set("isWasm", Napi::Boolean::New(env, true)); -#else - version.Set("isWasm", Napi::Boolean::New(env, false)); -#endif - return version; -} - -/* - Get available input/output file/buffer/stream formats -*/ -Napi::Value format(const Napi::CallbackInfo& info) { - Napi::Env env = info.Env(); - Napi::Object format = Napi::Object::New(env); - for (std::string const f : { - "jpeg", "png", "webp", "tiff", "magick", "openslide", "dz", - "ppm", "fits", "gif", "svg", "heif", "pdf", "vips", "jp2k", "jxl" - }) { - // Input - const VipsObjectClass *oc = vips_class_find("VipsOperation", (f + "load").c_str()); - Napi::Boolean hasInputFile = Napi::Boolean::New(env, oc); - Napi::Boolean hasInputBuffer = - Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "load_buffer").c_str())); - Napi::Object input = Napi::Object::New(env); - input.Set("file", hasInputFile); - input.Set("buffer", hasInputBuffer); - input.Set("stream", hasInputBuffer); - if (hasInputFile) { - const VipsForeignClass *fc = VIPS_FOREIGN_CLASS(oc); - if (fc->suffs) { - Napi::Array fileSuffix = Napi::Array::New(env); - const char **suffix = fc->suffs; - for (int i = 0; *suffix; i++, suffix++) { - fileSuffix.Set(i, Napi::String::New(env, *suffix)); - } - input.Set("fileSuffix", fileSuffix); - } - } - // Output - Napi::Boolean hasOutputFile = - Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "save").c_str())); - Napi::Boolean hasOutputBuffer = - Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "save_buffer").c_str())); - Napi::Object output = Napi::Object::New(env); - output.Set("file", hasOutputFile); - output.Set("buffer", hasOutputBuffer); - output.Set("stream", hasOutputBuffer); - // Other attributes - Napi::Object container = Napi::Object::New(env); - container.Set("id", f); - container.Set("input", input); - container.Set("output", output); - // Add to set of formats - format.Set(f, container); - } - - // Raw, uncompressed data - Napi::Boolean supported = Napi::Boolean::New(env, true); - Napi::Boolean unsupported = Napi::Boolean::New(env, false); - Napi::Object rawInput = Napi::Object::New(env); - rawInput.Set("file", unsupported); - rawInput.Set("buffer", supported); - rawInput.Set("stream", supported); - Napi::Object rawOutput = Napi::Object::New(env); - rawOutput.Set("file", unsupported); - rawOutput.Set("buffer", supported); - rawOutput.Set("stream", supported); - Napi::Object raw = Napi::Object::New(env); - raw.Set("id", "raw"); - raw.Set("input", rawInput); - raw.Set("output", rawOutput); - format.Set("raw", raw); - - return format; -} - -/* - (Un)block libvips operations at runtime. -*/ -void block(const Napi::CallbackInfo& info) { - Napi::Array ops = info[size_t(0)].As(); - bool const state = info[size_t(1)].As().Value(); - for (unsigned int i = 0; i < ops.Length(); i++) { - vips_operation_block_set(ops.Get(i).As().Utf8Value().c_str(), state); - } -} - -/* - Synchronous, internal-only method used by some of the functional tests. - Calculates the maximum colour distance using the DE2000 algorithm - between two images of the same dimensions and number of channels. -*/ -Napi::Value _maxColourDistance(const Napi::CallbackInfo& info) { - Napi::Env env = info.Env(); - - // Open input files - VImage image1; - sharp::ImageType imageType1 = sharp::DetermineImageType(info[size_t(0)].As().Utf8Value().data()); - if (imageType1 != sharp::ImageType::UNKNOWN) { - try { - image1 = VImage::new_from_file(info[size_t(0)].As().Utf8Value().c_str()); - } catch (...) { - throw Napi::Error::New(env, "Input file 1 has corrupt header"); - } - } else { - throw Napi::Error::New(env, "Input file 1 is of an unsupported image format"); - } - VImage image2; - sharp::ImageType imageType2 = sharp::DetermineImageType(info[size_t(1)].As().Utf8Value().data()); - if (imageType2 != sharp::ImageType::UNKNOWN) { - try { - image2 = VImage::new_from_file(info[size_t(1)].As().Utf8Value().c_str()); - } catch (...) { - throw Napi::Error::New(env, "Input file 2 has corrupt header"); - } - } else { - throw Napi::Error::New(env, "Input file 2 is of an unsupported image format"); - } - // Ensure same number of channels - if (image1.bands() != image2.bands()) { - throw Napi::Error::New(env, "mismatchedBands"); - } - // Ensure same dimensions - if (image1.width() != image2.width() || image1.height() != image2.height()) { - throw Napi::Error::New(env, "mismatchedDimensions"); - } - - double maxColourDistance; - try { - // Premultiply and remove alpha - if (sharp::HasAlpha(image1)) { - image1 = image1.premultiply().extract_band(1, VImage::option()->set("n", image1.bands() - 1)); - } - if (sharp::HasAlpha(image2)) { - image2 = image2.premultiply().extract_band(1, VImage::option()->set("n", image2.bands() - 1)); - } - // Calculate colour distance - maxColourDistance = image1.dE00(image2).max(); - } catch (vips::VError const &err) { - throw Napi::Error::New(env, err.what()); - } - - // Clean up libvips' per-request data and threads - vips_error_clear(); - vips_thread_shutdown(); - - return Napi::Number::New(env, maxColourDistance); -} - -#if defined(__GNUC__) -// mallctl will be resolved by the runtime linker when jemalloc is being used -extern "C" { - int mallctl(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen) __attribute__((weak)); -} -Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info) { - Napi::Env env = info.Env(); - return Napi::Boolean::New(env, mallctl != nullptr); -} -#else -Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info) { - Napi::Env env = info.Env(); - return Napi::Boolean::New(env, false); -} -#endif diff --git a/node_modules/sharp/src/utilities.h b/node_modules/sharp/src/utilities.h deleted file mode 100644 index 0f499ad3..00000000 --- a/node_modules/sharp/src/utilities.h +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2013 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -#ifndef SRC_UTILITIES_H_ -#define SRC_UTILITIES_H_ - -#include - -Napi::Value cache(const Napi::CallbackInfo& info); -Napi::Value concurrency(const Napi::CallbackInfo& info); -Napi::Value counters(const Napi::CallbackInfo& info); -Napi::Value simd(const Napi::CallbackInfo& info); -Napi::Value libvipsVersion(const Napi::CallbackInfo& info); -Napi::Value format(const Napi::CallbackInfo& info); -void block(const Napi::CallbackInfo& info); -Napi::Value _maxColourDistance(const Napi::CallbackInfo& info); -Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info); - -#endif // SRC_UTILITIES_H_ diff --git a/node_modules/simple-swizzle/LICENSE b/node_modules/simple-swizzle/LICENSE deleted file mode 100644 index 1b77e5be..00000000 --- a/node_modules/simple-swizzle/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Josh Junon - -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/simple-swizzle/README.md b/node_modules/simple-swizzle/README.md deleted file mode 100644 index 7624577b..00000000 --- a/node_modules/simple-swizzle/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# simple-swizzle [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-simple-swizzle.svg?style=flat-square)](https://travis-ci.org/Qix-/node-simple-swizzle) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-simple-swizzle.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-simple-swizzle) - -> [Swizzle](https://en.wikipedia.org/wiki/Swizzling_(computer_graphics)) your function arguments; pass in mixed arrays/values and get a clean array - -## Usage - -```js -var swizzle = require('simple-swizzle'); - -function myFunc() { - var args = swizzle(arguments); - // ... - return args; -} - -myFunc(1, [2, 3], 4); // [1, 2, 3, 4] -myFunc(1, 2, 3, 4); // [1, 2, 3, 4] -myFunc([1, 2, 3, 4]); // [1, 2, 3, 4] -``` - -Functions can also be wrapped to automatically swizzle arguments and be passed -the resulting array. - -```js -var swizzle = require('simple-swizzle'); - -var swizzledFn = swizzle.wrap(function (args) { - // ... - return args; -}); - -swizzledFn(1, [2, 3], 4); // [1, 2, 3, 4] -swizzledFn(1, 2, 3, 4); // [1, 2, 3, 4] -swizzledFn([1, 2, 3, 4]); // [1, 2, 3, 4] -``` - -## License -Licensed under the [MIT License](http://opensource.org/licenses/MIT). -You can find a copy of it in [LICENSE](LICENSE). diff --git a/node_modules/simple-swizzle/index.js b/node_modules/simple-swizzle/index.js deleted file mode 100644 index 4d6b8ff7..00000000 --- a/node_modules/simple-swizzle/index.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -var isArrayish = require('is-arrayish'); - -var concat = Array.prototype.concat; -var slice = Array.prototype.slice; - -var swizzle = module.exports = function swizzle(args) { - var results = []; - - for (var i = 0, len = args.length; i < len; i++) { - var arg = args[i]; - - if (isArrayish(arg)) { - // http://jsperf.com/javascript-array-concat-vs-push/98 - results = concat.call(results, slice.call(arg)); - } else { - results.push(arg); - } - } - - return results; -}; - -swizzle.wrap = function (fn) { - return function () { - return fn(swizzle(arguments)); - }; -}; diff --git a/node_modules/simple-swizzle/package.json b/node_modules/simple-swizzle/package.json deleted file mode 100644 index 795ae4cc..00000000 --- a/node_modules/simple-swizzle/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "simple-swizzle", - "description": "Simply swizzle your arguments", - "version": "0.2.2", - "author": "Qix (http://github.com/qix-)", - "keywords": [ - "argument", - "arguments", - "swizzle", - "swizzling", - "parameter", - "parameters", - "mixed", - "array" - ], - "license": "MIT", - "scripts": { - "pretest": "xo", - "test": "mocha --compilers coffee:coffee-script/register" - }, - "files": [ - "index.js" - ], - "repository": "qix-/node-simple-swizzle", - "devDependencies": { - "coffee-script": "^1.9.3", - "coveralls": "^2.11.2", - "istanbul": "^0.3.17", - "mocha": "^2.2.5", - "should": "^7.0.1", - "xo": "^0.7.1" - }, - "dependencies": { - "is-arrayish": "^0.3.1" - } -} diff --git a/package-lock.json b/package-lock.json index 8b8d8c37..6ee07a30 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "bg3-mod-helper", - "version": "2.1.34", + "version": "2.1.50", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "bg3-mod-helper", - "version": "2.1.34", + "version": "2.1.50", "license": "LGPL-3.0-or-later", "dependencies": { "@img/sharp-win32-x64": "^0.33.3", @@ -15,7 +15,6 @@ "node-api-dotnet": "^0.7.8", "node-fetch": "^3.3.2", "node-gyp": "^10.1.0", - "sharp": "^0.33.3", "uuid": "^9.0.1", "xmlbuilder": "^15.1.1" }, @@ -414,18 +413,6 @@ "node": ">=6" } }, - "node_modules/color": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", - "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", - "dependencies": { - "color-convert": "^2.0.1", - "color-string": "^1.9.0" - }, - "engines": { - "node": ">=12.5.0" - } - }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -442,15 +429,6 @@ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" }, - "node_modules/color-string": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", - "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", - "dependencies": { - "color-name": "^1.0.0", - "simple-swizzle": "^0.2.2" - } - }, "node_modules/color-support": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", @@ -842,11 +820,6 @@ "node": ">= 12" } }, - "node_modules/is-arrayish": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz", - "integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==" - }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -1508,45 +1481,6 @@ "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==" }, - "node_modules/sharp": { - "version": "0.33.3", - "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.3.tgz", - "integrity": "sha512-vHUeXJU1UvlO/BNwTpT0x/r53WkLUVxrmb5JTgW92fdFCFk0ispLMAeu/jPO2vjkXM1fYUi3K7/qcLF47pwM1A==", - "hasInstallScript": true, - "dependencies": { - "color": "^4.2.3", - "detect-libc": "^2.0.3", - "semver": "^7.6.0" - }, - "engines": { - "libvips": ">=8.15.2", - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-darwin-arm64": "0.33.3", - "@img/sharp-darwin-x64": "0.33.3", - "@img/sharp-libvips-darwin-arm64": "1.0.2", - "@img/sharp-libvips-darwin-x64": "1.0.2", - "@img/sharp-libvips-linux-arm": "1.0.2", - "@img/sharp-libvips-linux-arm64": "1.0.2", - "@img/sharp-libvips-linux-s390x": "1.0.2", - "@img/sharp-libvips-linux-x64": "1.0.2", - "@img/sharp-libvips-linuxmusl-arm64": "1.0.2", - "@img/sharp-libvips-linuxmusl-x64": "1.0.2", - "@img/sharp-linux-arm": "0.33.3", - "@img/sharp-linux-arm64": "0.33.3", - "@img/sharp-linux-s390x": "0.33.3", - "@img/sharp-linux-x64": "0.33.3", - "@img/sharp-linuxmusl-arm64": "0.33.3", - "@img/sharp-linuxmusl-x64": "0.33.3", - "@img/sharp-wasm32": "0.33.3", - "@img/sharp-win32-ia32": "0.33.3", - "@img/sharp-win32-x64": "0.33.3" - } - }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -1571,14 +1505,6 @@ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" }, - "node_modules/simple-swizzle": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz", - "integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==", - "dependencies": { - "is-arrayish": "^0.3.1" - } - }, "node_modules/smart-buffer": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", diff --git a/package.json b/package.json index 6213e1f0..7ea3a161 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "displayName": "bg3_mod_helper", "publisher": "ghostboats", "description": "This extension is designed to help you make mods in Baldur's Gate 3 by creating UUIDs and handles for you, as well as updating your .loca.xml files as well should they exist. And more to come in the future.", - "version": "2.1.34", + "version": "2.1.50", "icon": "media/marketplace_icon.png", "engines": { "vscode": "^1.86.0" @@ -252,7 +252,7 @@ } ], "menus": { - "view/title" : [ + "view/title": [ { "when": "view == bg3ModHelperView", "command": "bg3-mod-helper.packMod", @@ -405,7 +405,6 @@ "node-api-dotnet": "^0.7.8", "node-fetch": "^3.3.2", "node-gyp": "^10.1.0", - "sharp": "^0.33.3", "uuid": "^9.0.1", "xmlbuilder": "^15.1.1" }, diff --git a/support_files/scripts/python/DDS_to_PNG.py b/support_files/scripts/python/DDS_to_PNG.py deleted file mode 100644 index a36806d8..00000000 --- a/support_files/scripts/python/DDS_to_PNG.py +++ /dev/null @@ -1,115 +0,0 @@ -from pathlib import Path -from types import NoneType -from typing import List -import argparse -import wand.image -import re - - -parser = argparse.ArgumentParser(description='Batch convert image files') -parser.add_argument("-f", "--files", type=str, help='Selection of files to include, separated with ;') -parser.add_argument("-d", "--directory", type=str, help='The directory to process, if any.') -parser.add_argument("--outputdirectory", type=Path, help='If set, converted files will be placed here.') -parser.add_argument("-e", "--ext", nargs='+', help='If in directory mode, only include these file extensions.') -parser.add_argument("-r", "--recursive", default=False, type=bool, help='If in directory mode, whether to recursively search directories.') -parser.add_argument("-o", "--outputformat", default=".png", type=str, help='The output format.') -parser.add_argument("-q", "--quality", default=100, type=int, help='Output quality.') -parser.add_argument("--alpha", default=None, type=str, help='Force alpha or not (true or false works). See: https://docs.wand-py.org/en/latest/wand/image.html#wand.image.ALPHA_CHANNEL_TYPES for other values.') -parser.add_argument("--ddscompression", default=None, type=str, help='If outputformat is ".dds", this is the compression to use. [dxt1, dxt3, dxt5]') -parser.add_argument("--append", default="", type=str, help='Append text to the output filename.') -parser.add_argument("--size", type=str, metavar='width;height', help='Optional size to use in the output (ex: --size 64;64') -parser.add_argument("--srgb", action='store_true', help='Whether to enable SRGB.') - -args = parser.parse_args() - -alpha_pattern = re.compile(r"^.*_((\w\wa)|(nm))$", re.IGNORECASE | re.MULTILINE) - -if args.alpha: - match str.lower(args.alpha): - case "true" | "yes" | "1": - args.alpha = True - case "false" | "no" | "none" | "null" | "undefined" | "0": - args.alpha = False - -def name_has_alpha(name:str): - if alpha_pattern.search(name): - return True - return False - -def convert_image(f:Path): - file_path = str(f.absolute()) - output_path = f.with_name(f"{f.stem}{args.append or ''}").with_suffix(args.outputformat) - if args.outputdirectory: - if not args.outputdirectory.is_dir(): - args.outputdirectory = args.outputdirectory.parent - args.outputdirectory.mkdir(exist_ok = True, parents = True) - output_path = args.outputdirectory.joinpath(output_path.name) - output_path = str(output_path.absolute()) - - with wand.image.Image(filename=file_path) as img: - img.format = str.replace(args.outputformat, ".", "") - img.compression_quality = args.quality - if args.size is not None: - sizes = str.split(args.size, ";") - w = int(sizes[0]) - h = int(sizes[1]) or w - img.resize(w, h) - if args.alpha is not None: - img.alpha_channel = args.alpha - if args.srgb: - img.transform_colorspace("srgb") - - match args.outputformat: - case ".jpg" | ".jpeg": - img.compression = 'jpeg' - case ".dds": - if args.ddscompression == None and name_has_alpha(f.stem): - img.compression = "dxt5" - img.alpha_channel = True - else: - img.compression = args.ddscompression or "dxt1" - if args.alpha is None: - img.alpha_channel = args.ddscompression == "dxt5" # Probably should have alpha - case _: - pass - - img.save(filename=output_path) - -# def convert_image_pillow(f:Path): -# from PIL import Image -# output_format = str.replace(args.outputformat, ".", "").upper() -# im = Image.open(f) -# if args.outputformat == ".jpg" and im.mode in ("RGBA", "P"): im = im.convert("RGB") -# if args.size is not None: -# im.save(f.with_suffix(args.outputformat), quality=args.quality, format=output_format, sizes=[(args.size,args.size)]) -# else: -# im.save(f.with_suffix(args.outputformat), quality=args.quality, format=output_format) - -if args.files is not None: - files:List[Path] = [Path(s) for s in args.files.split(";")] - for f in files: - convert_image(f) -elif args.directory is not None: - files:List[Path] = None - dir_path = Path(args.directory) - if args.ext is not None: - anyFile = "*" in args.ext - if args.recursive: - files = [p for p in dir_path.rglob('*') if (anyFile or p.suffix in args.ext)] - else: - files = [p for p in dir_path.glob('*') if (anyFile or p.suffix in args.ext)] - else: - if args.recursive: - files = [p for p in dir_path.rglob('*') if p.is_file()] - else: - files = [p for p in dir_path.glob('*') if p.is_file()] - - if files is not None and len(files) > 0: - for f in files: - convert_image(f) - print("[convert_images] All done.") - else: - print("Failed to find any image files in directory. Skipping.") -else: - print("Failed to find any files. Skipping.") - parser.print_help() \ No newline at end of file diff --git a/support_files/scripts/python/PNG_to_DDS.py b/support_files/scripts/python/PNG_to_DDS.py deleted file mode 100644 index d5b176bb..00000000 --- a/support_files/scripts/python/PNG_to_DDS.py +++ /dev/null @@ -1,113 +0,0 @@ -from pathlib import Path -from typing import List -import argparse -import wand.image -import re - -parser = argparse.ArgumentParser(description='Batch convert image files') -parser.add_argument("-f", "--files", type=str, help='Selection of files to include, separated with ;') -parser.add_argument("-d", "--directory", type=str, help='The directory to process, if any.') -parser.add_argument("--outputdirectory", type=Path, help='If set, converted files will be placed here.') -parser.add_argument("-e", "--ext", nargs='+', help='If in directory mode, only include these file extensions.') -parser.add_argument("-r", "--recursive", default=False, type=bool, help='If in directory mode, whether to recursively search directories.') -parser.add_argument("-o", "--outputformat", default=".png", type=str, help='The output format.') -parser.add_argument("-q", "--quality", default=100, type=int, help='Output quality.') -parser.add_argument("--alpha", default=None, type=str, help='Force alpha or not (true or false works). See: https://docs.wand-py.org/en/latest/wand/image.html#wand.image.ALPHA_CHANNEL_TYPES for other values.') -parser.add_argument("--ddscompression", default=None, type=str, help='If outputformat is ".dds", this is the compression to use. [dxt1, dxt3, dxt5]') -parser.add_argument("--append", default="", type=str, help='Append text to the output filename.') -parser.add_argument("--size", type=str, metavar='width;height', help='Optional size to use in the output (ex: --size 64;64)') -parser.add_argument("--srgb", action='store_true', help='Whether to enable SRGB.') - -args = parser.parse_args() - -alpha_pattern = re.compile(r"^.*_((\w\wa)|(nm))$", re.IGNORECASE | re.MULTILINE) - -if args.alpha: - match str.lower(args.alpha): - case "true" | "yes" | "1": - args.alpha = True - case "false" | "no" | "none" | "null" | "undefined" | "0": - args.alpha = False - -def name_has_alpha(name:str): - if alpha_pattern.search(name): - return True - return False - -def convert_image(f:Path): - file_path = str(f.absolute()) - output_path = f.with_name(f"{f.stem}{args.append or ''}").with_suffix(args.outputformat) - if args.outputdirectory: - if not args.outputdirectory.is_dir(): - args.outputdirectory = args.outputdirectory.parent - args.outputdirectory.mkdir(exist_ok = True, parents = True) - output_path = args.outputdirectory.joinpath(output_path.name) - output_path = str(output_path.absolute()) - - with wand.image.Image(filename=file_path) as img: - img.format = str.replace(args.outputformat, ".", "") - img.compression_quality = args.quality - if args.size is not None: - sizes = str.split(args.size, ";") - w = int(sizes[0]) - h = int(sizes[1]) or w - img.resize(w, h) - if args.alpha is not None: - img.alpha_channel = args.alpha - if args.srgb: - img.transform_colorspace("srgb") - - match args.outputformat: - case ".jpg" | ".jpeg": - img.compression = 'jpeg' - case ".dds": - if args.ddscompression == None and name_has_alpha(f.stem): - img.compression = "dxt5" - img.alpha_channel = True - else: - img.compression = args.ddscompression or "dxt1" - if args.alpha is None: - img.alpha_channel = args.ddscompression == "dxt5" # Probably should have alpha - case _: - pass - - img.save(filename=output_path) - -# def convert_image_pillow(f:Path): -# from PIL import Image -# output_format = str.replace(args.outputformat, ".", "").upper() -# im = Image.open(f) -# if args.outputformat == ".jpg" and im.mode in ("RGBA", "P"): im = im.convert("RGB") -# if args.size is not None: -# im.save(f.with_suffix(args.outputformat), quality=args.quality, format=output_format, sizes=[(args.size,args.size)]) -# else: -# im.save(f.with_suffix(args.outputformat), quality=args.quality, format=output_format) - -if args.files is not None: - files:List[Path] = [Path(s) for s in args.files.split(";")] - for f in files: - convert_image(f) -elif args.directory is not None: - files:List[Path] = None - dir_path = Path(args.directory) - if args.ext is not None: - anyFile = "*" in args.ext - if args.recursive: - files = [p for p in dir_path.rglob('*') if (anyFile or p.suffix in args.ext)] - else: - files = [p for p in dir_path.glob('*') if (anyFile or p.suffix in args.ext)] - else: - if args.recursive: - files = [p for p in dir_path.rglob('*') if p.is_file()] - else: - files = [p for p in dir_path.glob('*') if p.is_file()] - - if files is not None and len(files) > 0: - for f in files: - convert_image(f) - print("[convert_images] All done.") - else: - print("Failed to find any image files in directory. Skipping.") -else: - print("Failed to find any files. Skipping.") - parser.print_help() \ No newline at end of file diff --git a/support_files/scripts/python/convert_lsf.py b/support_files/scripts/python/convert_lsf.py deleted file mode 100644 index 115b2bc0..00000000 --- a/support_files/scripts/python/convert_lsf.py +++ /dev/null @@ -1,72 +0,0 @@ -import os -from pathlib import Path -import argparse - -print('--convert_lsf.py--') -script_dir = Path(os.path.dirname(os.path.abspath(__file__))) -print('Script location(will change dir to it): '+str(script_dir)) -os.chdir(script_dir) - -parser = argparse.ArgumentParser() -parser.add_argument("-d", "--divine", type=Path, help="The path to divine.exe.") -parser.add_argument("-o", "--output", type=Path, help="The output file path.") -parser.add_argument("-f", "--file", type=Path, required=True, help="The file to convert.") -parser.add_argument("-b", "--batch", action='store_true', help="Batch convert an input directory instead.") -parser.add_argument("--ext", type=str, default=".lsf", help="If in batch mode, make this the input file type (defaults to .lsf).") -parser.add_argument("--outputext", type=str, default=".lsx", help="If in batch mode, make this the output file tyoe (defaults to .lsx).") - -args = parser.parse_args() - -input_file:Path = args.file -output_file:Path = args.output -lslib_dll:Path = args.divine.is_dir() and args.divine.joinpath("LSLib.dll") or args.divine.parent.joinpath("LSLib.dll") -batch:bool = args.batch == True -in_type:str = args.ext -out_type:str = args.outputext -import clr -if lslib_dll.exists(): - from System.Reflection import Assembly # type: ignore - Assembly.LoadFrom(str(lslib_dll.absolute())) - clr.AddReference("LSLib") # type: ignore - - from LSLib.LS import ResourceUtils, ResourceConversionParameters, ResourceLoadParameters # type: ignore - from LSLib.LS.Enums import Game, ResourceFormat # type: ignore - - load_params = ResourceLoadParameters.FromGameVersion(Game.BaldursGate3) - conversion_params = ResourceConversionParameters.FromGameVersion(Game.BaldursGate3) - - def process_file(input:Path, output:Path = None): - ext = input.suffix.lower() - - if output is None: - if ext != ".lsx": - output = input.with_suffix(".lsx") - else: - output = input.with_suffix(".lsf") - - input_str = str(input.absolute()) - output_str = str(output.absolute()) - - out_format = ResourceUtils.ExtensionToResourceFormat(output_str) - resource = ResourceUtils.LoadResource(input_str, load_params) - ResourceUtils.SaveResource(resource, output_str, out_format, conversion_params) - - if input_file.is_dir(): - - input_str = str(input_file.absolute()) - if output_file is None: - output_file = input_file - output_str = str(output_file.absolute()) - - input_format = ResourceUtils.ExtensionToResourceFormat(in_type) - out_format = ResourceUtils.ExtensionToResourceFormat(out_type) - - - utils = ResourceUtils() - - utils.ConvertResources(input_str, output_str, input_format, out_format, load_params, conversion_params); - elif input_file.exists(): - process_file(input_file, output_file) -else: - raise FileNotFoundError("Failed to find LSLib.dll", lslib_dll) -print('__convert_lsf.py__') \ No newline at end of file diff --git a/support_files/scripts/python/xml_to_loca.py b/support_files/scripts/python/xml_to_loca.py deleted file mode 100644 index 72a6b0b0..00000000 --- a/support_files/scripts/python/xml_to_loca.py +++ /dev/null @@ -1,62 +0,0 @@ -import os -from pathlib import Path -import argparse -#pip install --upgrade pythonnet - -print('--xml_to_loca.py--') -script_dir = Path(os.path.dirname(os.path.abspath(__file__))) -print('Script location(will change dir to it): '+str(script_dir)) -os.chdir(script_dir) - -parser = argparse.ArgumentParser() -parser.add_argument("-d", "--divine", type=Path) -parser.add_argument("-o", "--output", type=Path) -parser.add_argument("-f", "--file", type=Path) - -args = parser.parse_args() - -target_file:Path = args.file -output_file:Path = args.output -print('Target_file: '+str(target_file)+'\nOutput_File: '+str(output_file)) - -if target_file.exists(): - lslib_dll:Path = args.divine.is_dir() and args.divine.joinpath("LSLib.dll") or args.divine.parent.joinpath("LSLib.dll") - print('LSLib.dll at: '+str(lslib_dll)) - if lslib_dll.exists(): - import clr - from System.Reflection import Assembly # type: ignore - Assembly.LoadFrom(str(lslib_dll.absolute())) - clr.AddReference("LSLib") # type: ignore - clr.AddReference("System") # type: ignore - - from LSLib.LS import LocaUtils, LocaFormat # type: ignore - from System.IO import File, FileMode # type: ignore - - in_format = LocaFormat.Xml - out_format = LocaFormat.Loca - - ext = target_file.suffix.lower() - - if ext == ".xml": - in_format = LocaFormat.Xml - out_format = LocaFormat.Loca - elif ext == ".loca": - in_format = LocaFormat.Loca - out_format = LocaFormat.Xml - - if output_file is None: - if out_format == LocaFormat.Xml: - output_file = target_file.with_suffix(".xml") - elif out_format == LocaFormat.Loca: - output_file = target_file.with_suffix(".loca") - - fs = File.Open(str(target_file.absolute()), FileMode.Open) - resource = LocaUtils.Load(fs, in_format) - LocaUtils.Save(resource, str(output_file.absolute()), out_format) - fs.Dispose() - print(f"Converted {target_file} to {output_file}") - else: - raise FileNotFoundError("Failed to find LSLib.dll in the provided divine path.") -else: - raise FileNotFoundError("A valid path to a xml file is required.") -print('__xml_to_loca.py__') \ No newline at end of file