dimcode-windows-x64
Advanced tools
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| const { | ||
| useGlobalLibvips, | ||
| globalLibvipsVersion, | ||
| log, | ||
| spawnRebuild, | ||
| } = require('../lib/libvips'); | ||
| log('Attempting to build from source via node-gyp'); | ||
| log('See https://sharp.pixelplumbing.com/install#building-from-source'); | ||
| try { | ||
| const addonApi = require('node-addon-api'); | ||
| log(`Found node-addon-api ${addonApi.version || ''}`); | ||
| } catch (_err) { | ||
| log('Please add node-addon-api to your dependencies'); | ||
| process.exit(1); | ||
| } | ||
| try { | ||
| const gyp = require('node-gyp'); | ||
| log(`Found node-gyp ${gyp().version}`); | ||
| } catch (_err) { | ||
| log('Please add node-gyp to your dependencies'); | ||
| process.exit(1); | ||
| } | ||
| if (useGlobalLibvips(log)) { | ||
| log(`Detected globally-installed libvips v${globalLibvipsVersion()}`); | ||
| } | ||
| const status = spawnRebuild(); | ||
| if (status !== 0) { | ||
| process.exit(status); | ||
| } |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| try { | ||
| const { useGlobalLibvips } = require('../lib/libvips'); | ||
| if (useGlobalLibvips() || process.env.npm_config_build_from_source) { | ||
| process.exit(1); | ||
| } | ||
| } catch (err) { | ||
| const summary = err.message.split(/\n/).slice(0, 1); | ||
| console.log(`sharp: skipping install check: ${summary}`); | ||
| } |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| const is = require('./is'); | ||
| /** | ||
| * Boolean operations for bandbool. | ||
| * @private | ||
| */ | ||
| const bool = { | ||
| and: 'and', | ||
| or: 'or', | ||
| eor: 'eor' | ||
| }; | ||
| /** | ||
| * Remove alpha channels, 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. | ||
| * | ||
| * The output colourspace will be either `b-w` (8-bit) or `grey16` (16-bit). | ||
| * | ||
| * @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>|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. | ||
| * @module Sharp | ||
| * @private | ||
| */ | ||
| module.exports = (Sharp) => { | ||
| Object.assign(Sharp.prototype, { | ||
| // Public instance functions | ||
| removeAlpha, | ||
| ensureAlpha, | ||
| extractChannel, | ||
| joinChannel, | ||
| bandbool | ||
| }); | ||
| // Class attributes | ||
| Sharp.bool = bool; | ||
| }; |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| const color = require('../node_modules/@img/colour/index.cjs'); | ||
| 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) colour channels. | ||
| * This may be overridden by other sharp operations such as `toColourspace('b-w')`, | ||
| * which will produce an output image containing one colour 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}. | ||
| * | ||
| * @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://www.libvips.org/API/current/enum.Interpretation.html) | ||
| * @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://www.libvips.org/API/current/enum.Interpretation.html) | ||
| * @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); | ||
| } | ||
| /** | ||
| * Create a RGBA colour array from a given value. | ||
| * @private | ||
| * @param {string|Object} value | ||
| * @throws {Error} Invalid value | ||
| */ | ||
| function _getBackgroundColourOption (value) { | ||
| if ( | ||
| is.object(value) || | ||
| (is.string(value) && value.length >= 3 && value.length <= 200) | ||
| ) { | ||
| const colour = color(value); | ||
| return [ | ||
| colour.red(), | ||
| colour.green(), | ||
| colour.blue(), | ||
| Math.round(colour.alpha() * 255) | ||
| ]; | ||
| } else { | ||
| throw is.invalidParameterError('background', 'object or string', value); | ||
| } | ||
| } | ||
| /** | ||
| * 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)) { | ||
| this.options[key] = _getBackgroundColourOption(value); | ||
| } | ||
| } | ||
| /** | ||
| * Decorate the Sharp prototype with colour-related functions. | ||
| * @module Sharp | ||
| * @private | ||
| */ | ||
| module.exports = (Sharp) => { | ||
| Object.assign(Sharp.prototype, { | ||
| // Public | ||
| tint, | ||
| greyscale, | ||
| grayscale, | ||
| pipelineColourspace, | ||
| pipelineColorspace, | ||
| toColourspace, | ||
| toColorspace, | ||
| // Private | ||
| _getBackgroundColourOption, | ||
| _setBackgroundColourOption | ||
| }); | ||
| // Class attributes | ||
| Sharp.colourspace = colourspace; | ||
| Sharp.colorspace = colourspace; | ||
| }; |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| 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`. | ||
| * | ||
| * Other operations in the same processing pipeline (e.g. resize, rotate, flip, | ||
| * flop, extract) 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/enum.BlendMode.html | ||
| * 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 `<i>Le</i>Monde`. | ||
| * @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 `<span foreground="red">Red!</span>`. | ||
| * @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified. | ||
| * @param {Boolean} [images[].autoOrient=false] - set to true to use EXIF orientation data, if present, to orient the image. | ||
| * @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/ constructor parameters} | ||
| * @param {number|boolean} [images[].limitInputPixels=268402689] - @see {@link /api-constructor/ 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. | ||
| * @module Sharp | ||
| * @private | ||
| */ | ||
| module.exports = (Sharp) => { | ||
| Sharp.prototype.composite = composite; | ||
| Sharp.blend = blend; | ||
| }; |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| 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'); | ||
| const queueListener = (queueLength) => { | ||
| Sharp.queue.emit('change', queueLength); | ||
| }; | ||
| /** | ||
| * 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: '<span foreground="red">Red!</span><span background="cyan">blue</span>', | ||
| * font: 'sans', | ||
| * rgba: true, | ||
| * dpi: 300 | ||
| * } | ||
| * }).toFile('text_rgba.png'); | ||
| * | ||
| * @example | ||
| * // Join four input images as a 2x2 grid with a 4 pixel gutter | ||
| * const data = await sharp( | ||
| * [image1, image2, image3, image4], | ||
| * { join: { across: 2, shim: 4 } } | ||
| * ).toBuffer(); | ||
| * | ||
| * @example | ||
| * // Generate a two-frame animated image from emoji | ||
| * const images = ['😀', '😛'].map(text => ({ | ||
| * text: { text, width: 64, height: 64, channels: 4, rgba: true } | ||
| * })); | ||
| * await sharp(images, { join: { animated: true } }).toFile('out.gif'); | ||
| * | ||
| * @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string|Array)} [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. | ||
| * An array of inputs can be provided, and these will be joined together. | ||
| * 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.autoOrient=false] - Set this to `true` to rotate/flip the image to match EXIF `Orientation`, if any. | ||
| * @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 {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 {number} [options.raw.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `raw.height`. | ||
| * @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 {number} [options.create.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `create.height`. | ||
| * @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=128] - Mean value of pixels in the generated noise. | ||
| * @param {number} [options.create.noise.sigma=30] - Standard deviation of pixel values in the 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 `<i>Le</i>Monde`. | ||
| * @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 `<span foreground="red">Red!</span>`. | ||
| * @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'. | ||
| * @param {Object} [options.join] - describes how an array of input images should be joined. | ||
| * @param {number} [options.join.across=1] - number of images to join horizontally. | ||
| * @param {boolean} [options.join.animated=false] - set this to `true` to join the images as an animated image. | ||
| * @param {number} [options.join.shim=0] - number of pixels to insert between joined images. | ||
| * @param {string|Object} [options.join.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. | ||
| * @param {string} [options.join.halign='left'] - horizontal alignment style for images joined horizontally (`'left'`, `'centre'`, `'center'`, `'right'`). | ||
| * @param {string} [options.join.valign='top'] - vertical alignment style for images joined vertically (`'top'`, `'centre'`, `'center'`, `'bottom'`). | ||
| * @param {Object} [options.tiff] - Describes TIFF specific options. | ||
| * @param {number} [options.tiff.subifd=-1] - Sub Image File Directory to extract for OME-TIFF, defaults to main image. | ||
| * @param {Object} [options.svg] - Describes SVG specific options. | ||
| * @param {string} [options.svg.stylesheet] - Custom CSS for SVG input, applied with a User Origin during the CSS cascade. | ||
| * @param {boolean} [options.svg.highBitdepth=false] - Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA. | ||
| * @param {Object} [options.pdf] - Describes PDF specific options. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick. | ||
| * @param {string|Object} [options.pdf.background] - Background colour to use when PDF is partially transparent. Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. | ||
| * @param {Object} [options.openSlide] - Describes OpenSlide specific options. Requires the use of a globally-installed libvips compiled with support for OpenSlide. | ||
| * @param {number} [options.openSlide.level=0] - Level to extract from a multi-level input, zero based. | ||
| * @param {Object} [options.jp2] - Describes JPEG 2000 specific options. Requires the use of a globally-installed libvips compiled with support for OpenJPEG. | ||
| * @param {boolean} [options.jp2.oneshot=false] - Set to `true` to decode tiled JPEG 2000 images in a single operation, improving compatibility. | ||
| * @returns {Sharp} | ||
| * @throws {Error} Invalid parameters | ||
| */ | ||
| const Sharp = function (input, options) { | ||
| // biome-ignore lint/complexity/noArguments: constructor factory | ||
| 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], | ||
| angle: 0, | ||
| rotationAngle: 0, | ||
| rotationBackground: [0, 0, 0, 255], | ||
| rotateBefore: false, | ||
| orientBefore: 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, | ||
| precision: 'integer', | ||
| minAmpl: 0.2, | ||
| sharpenSigma: 0, | ||
| sharpenM1: 1, | ||
| sharpenM2: 2, | ||
| sharpenX1: 2, | ||
| sharpenY2: 10, | ||
| sharpenY3: 20, | ||
| threshold: 0, | ||
| thresholdGrayscale: true, | ||
| trimBackground: [], | ||
| trimThreshold: -1, | ||
| trimLineArt: false, | ||
| dilateWidth: 0, | ||
| erodeWidth: 0, | ||
| 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, | ||
| withXmp: '', | ||
| resolveWithObject: false, | ||
| loop: -1, | ||
| delay: [], | ||
| // 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, | ||
| webpSmartDeblock: false, | ||
| webpPreset: 'default', | ||
| webpEffort: 4, | ||
| webpMinSize: false, | ||
| webpMixed: false, | ||
| gifBitdepth: 8, | ||
| gifEffort: 7, | ||
| gifDither: 1, | ||
| gifInterFrameMaxError: 0, | ||
| gifInterPaletteMaxError: 3, | ||
| gifKeepDuplicateFrames: false, | ||
| gifReuse: true, | ||
| gifProgressive: false, | ||
| tiffQuality: 80, | ||
| tiffCompression: 'jpeg', | ||
| tiffBigtiff: false, | ||
| 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: [], | ||
| pdfBackground: [255, 255, 255, 255], | ||
| // Function to notify of libvips warnings | ||
| debuglog: warning => { | ||
| this.emit('warning', warning); | ||
| debuglog(warning); | ||
| }, | ||
| // Function to notify of queue length changes | ||
| queueListener | ||
| }; | ||
| 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. | ||
| * @module Sharp | ||
| * @private | ||
| */ | ||
| module.exports = Sharp; |
Sorry, the diff of this file is too big to display
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| 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; |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| const is = require('./is'); | ||
| const sharp = require('./sharp'); | ||
| /** | ||
| * Justification alignment | ||
| * @member | ||
| * @private | ||
| */ | ||
| const align = { | ||
| left: 'low', | ||
| top: 'low', | ||
| low: 'low', | ||
| center: 'centre', | ||
| centre: 'centre', | ||
| right: 'high', | ||
| bottom: 'high', | ||
| high: 'high' | ||
| }; | ||
| const inputStreamParameters = [ | ||
| // Limits and error handling | ||
| 'failOn', 'limitInputPixels', 'unlimited', | ||
| // Format-generic | ||
| 'animated', 'autoOrient', 'density', 'ignoreIcc', 'page', 'pages', 'sequentialRead', | ||
| // Format-specific | ||
| 'jp2', 'openSlide', 'pdf', 'raw', 'svg', 'tiff', | ||
| // Deprecated | ||
| 'failOnError', 'openSlideLevel', 'pdfBackground', 'tiffSubifd' | ||
| ]; | ||
| /** | ||
| * Extract input options, if any, from an object. | ||
| * @private | ||
| */ | ||
| function _inputOptionsFromObject (obj) { | ||
| const params = inputStreamParameters | ||
| .filter(p => is.defined(obj[p])) | ||
| .map(p => ([p, obj[p]])); | ||
| return params.length | ||
| ? Object.fromEntries(params) | ||
| : undefined; | ||
| } | ||
| /** | ||
| * Create Object containing input and input-related options. | ||
| * @private | ||
| */ | ||
| function _createInputDescriptor (input, inputOptions, containerOptions) { | ||
| const inputDescriptor = { | ||
| autoOrient: false, | ||
| failOn: 'warning', | ||
| limitInputPixels: 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 if (Array.isArray(input)) { | ||
| if (input.length > 1) { | ||
| // Join images together | ||
| if (!this.options.joining) { | ||
| this.options.joining = true; | ||
| this.options.join = input.map(i => this._createInputDescriptor(i)); | ||
| } else { | ||
| throw new Error('Recursive join is unsupported'); | ||
| } | ||
| } else { | ||
| throw new Error('Expected at least two images to join'); | ||
| } | ||
| } 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); | ||
| } | ||
| } | ||
| // autoOrient | ||
| if (is.defined(inputOptions.autoOrient)) { | ||
| if (is.bool(inputOptions.autoOrient)) { | ||
| inputDescriptor.autoOrient = inputOptions.autoOrient; | ||
| } else { | ||
| throw is.invalidParameterError('autoOrient', 'boolean', inputOptions.autoOrient); | ||
| } | ||
| } | ||
| // 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 | ||
| ? 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; | ||
| 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'); | ||
| } | ||
| inputDescriptor.rawPremultiplied = false; | ||
| if (is.defined(inputOptions.raw.premultiplied)) { | ||
| if (is.bool(inputOptions.raw.premultiplied)) { | ||
| inputDescriptor.rawPremultiplied = inputOptions.raw.premultiplied; | ||
| } else { | ||
| throw is.invalidParameterError('raw.premultiplied', 'boolean', inputOptions.raw.premultiplied); | ||
| } | ||
| } | ||
| inputDescriptor.rawPageHeight = 0; | ||
| if (is.defined(inputOptions.raw.pageHeight)) { | ||
| if (is.integer(inputOptions.raw.pageHeight) && inputOptions.raw.pageHeight > 0 && inputOptions.raw.pageHeight <= inputOptions.raw.height) { | ||
| if (inputOptions.raw.height % inputOptions.raw.pageHeight !== 0) { | ||
| throw new Error(`Expected raw.height ${inputOptions.raw.height} to be a multiple of raw.pageHeight ${inputOptions.raw.pageHeight}`); | ||
| } | ||
| inputDescriptor.rawPageHeight = inputOptions.raw.pageHeight; | ||
| } else { | ||
| throw is.invalidParameterError('raw.pageHeight', 'positive integer', inputOptions.raw.pageHeight); | ||
| } | ||
| } | ||
| } | ||
| // 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); | ||
| } | ||
| } | ||
| // OpenSlide specific options | ||
| if (is.object(inputOptions.openSlide) && is.defined(inputOptions.openSlide.level)) { | ||
| if (is.integer(inputOptions.openSlide.level) && is.inRange(inputOptions.openSlide.level, 0, 256)) { | ||
| inputDescriptor.openSlideLevel = inputOptions.openSlide.level; | ||
| } else { | ||
| throw is.invalidParameterError('openSlide.level', 'integer between 0 and 256', inputOptions.openSlide.level); | ||
| } | ||
| } else if (is.defined(inputOptions.level)) { | ||
| // Deprecated | ||
| if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) { | ||
| inputDescriptor.openSlideLevel = inputOptions.level; | ||
| } else { | ||
| throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level); | ||
| } | ||
| } | ||
| // TIFF specific options | ||
| if (is.object(inputOptions.tiff) && is.defined(inputOptions.tiff.subifd)) { | ||
| if (is.integer(inputOptions.tiff.subifd) && is.inRange(inputOptions.tiff.subifd, -1, 100000)) { | ||
| inputDescriptor.tiffSubifd = inputOptions.tiff.subifd; | ||
| } else { | ||
| throw is.invalidParameterError('tiff.subifd', 'integer between -1 and 100000', inputOptions.tiff.subifd); | ||
| } | ||
| } else if (is.defined(inputOptions.subifd)) { | ||
| // Deprecated | ||
| if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) { | ||
| inputDescriptor.tiffSubifd = inputOptions.subifd; | ||
| } else { | ||
| throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd); | ||
| } | ||
| } | ||
| // SVG specific options | ||
| if (is.object(inputOptions.svg)) { | ||
| if (is.defined(inputOptions.svg.stylesheet)) { | ||
| if (is.string(inputOptions.svg.stylesheet)) { | ||
| inputDescriptor.svgStylesheet = inputOptions.svg.stylesheet; | ||
| } else { | ||
| throw is.invalidParameterError('svg.stylesheet', 'string', inputOptions.svg.stylesheet); | ||
| } | ||
| } | ||
| if (is.defined(inputOptions.svg.highBitdepth)) { | ||
| if (is.bool(inputOptions.svg.highBitdepth)) { | ||
| inputDescriptor.svgHighBitdepth = inputOptions.svg.highBitdepth; | ||
| } else { | ||
| throw is.invalidParameterError('svg.highBitdepth', 'boolean', inputOptions.svg.highBitdepth); | ||
| } | ||
| } | ||
| } | ||
| // PDF specific options | ||
| if (is.object(inputOptions.pdf) && is.defined(inputOptions.pdf.background)) { | ||
| inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdf.background); | ||
| } else if (is.defined(inputOptions.pdfBackground)) { | ||
| // Deprecated | ||
| inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdfBackground); | ||
| } | ||
| // JPEG 2000 specific options | ||
| if (is.object(inputOptions.jp2) && is.defined(inputOptions.jp2.oneshot)) { | ||
| if (is.bool(inputOptions.jp2.oneshot)) { | ||
| inputDescriptor.jp2Oneshot = inputOptions.jp2.oneshot; | ||
| } else { | ||
| throw is.invalidParameterError('jp2.oneshot', 'boolean', inputOptions.jp2.oneshot); | ||
| } | ||
| } | ||
| // 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; | ||
| inputDescriptor.createPageHeight = 0; | ||
| if (is.defined(inputOptions.create.pageHeight)) { | ||
| if (is.integer(inputOptions.create.pageHeight) && inputOptions.create.pageHeight > 0 && inputOptions.create.pageHeight <= inputOptions.create.height) { | ||
| if (inputOptions.create.height % inputOptions.create.pageHeight !== 0) { | ||
| throw new Error(`Expected create.height ${inputOptions.create.height} to be a multiple of create.pageHeight ${inputOptions.create.pageHeight}`); | ||
| } | ||
| inputDescriptor.createPageHeight = inputOptions.create.pageHeight; | ||
| } else { | ||
| throw is.invalidParameterError('create.pageHeight', 'positive integer', inputOptions.create.pageHeight); | ||
| } | ||
| } | ||
| // Noise | ||
| if (is.defined(inputOptions.create.noise)) { | ||
| if (!is.object(inputOptions.create.noise)) { | ||
| throw new Error('Expected noise to be an object'); | ||
| } | ||
| if (inputOptions.create.noise.type !== 'gaussian') { | ||
| throw new Error('Only gaussian noise is supported at the moment'); | ||
| } | ||
| inputDescriptor.createNoiseType = inputOptions.create.noise.type; | ||
| if (!is.inRange(inputOptions.create.channels, 1, 4)) { | ||
| throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels); | ||
| } | ||
| inputDescriptor.createNoiseMean = 128; | ||
| if (is.defined(inputOptions.create.noise.mean)) { | ||
| 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); | ||
| } | ||
| } | ||
| inputDescriptor.createNoiseSigma = 30; | ||
| if (is.defined(inputOptions.create.noise.sigma)) { | ||
| 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); | ||
| } | ||
| inputDescriptor.createBackground = this._getBackgroundColourOption(inputOptions.create.background); | ||
| } 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.integer(inputOptions.text.width) && inputOptions.text.width > 0) { | ||
| inputDescriptor.textWidth = inputOptions.text.width; | ||
| } else { | ||
| throw is.invalidParameterError('text.width', 'positive integer', inputOptions.text.width); | ||
| } | ||
| } | ||
| if (is.defined(inputOptions.text.height)) { | ||
| if (is.integer(inputOptions.text.height) && inputOptions.text.height > 0) { | ||
| inputDescriptor.textHeight = inputOptions.text.height; | ||
| } else { | ||
| throw is.invalidParameterError('text.height', 'positive integer', 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.integer(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 1000000)) { | ||
| inputDescriptor.textDpi = inputOptions.text.dpi; | ||
| } else { | ||
| throw is.invalidParameterError('text.dpi', 'integer between 1 and 1000000', 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.integer(inputOptions.text.spacing) && is.inRange(inputOptions.text.spacing, -1000000, 1000000)) { | ||
| inputDescriptor.textSpacing = inputOptions.text.spacing; | ||
| } else { | ||
| throw is.invalidParameterError('text.spacing', 'integer between -1000000 and 1000000', 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.'); | ||
| } | ||
| } | ||
| // Join images together | ||
| if (is.defined(inputOptions.join)) { | ||
| if (is.defined(this.options.join)) { | ||
| if (is.defined(inputOptions.join.animated)) { | ||
| if (is.bool(inputOptions.join.animated)) { | ||
| inputDescriptor.joinAnimated = inputOptions.join.animated; | ||
| } else { | ||
| throw is.invalidParameterError('join.animated', 'boolean', inputOptions.join.animated); | ||
| } | ||
| } | ||
| if (is.defined(inputOptions.join.across)) { | ||
| if (is.integer(inputOptions.join.across) && is.inRange(inputOptions.join.across, 1, 1000000)) { | ||
| inputDescriptor.joinAcross = inputOptions.join.across; | ||
| } else { | ||
| throw is.invalidParameterError('join.across', 'integer between 1 and 100000', inputOptions.join.across); | ||
| } | ||
| } | ||
| if (is.defined(inputOptions.join.shim)) { | ||
| if (is.integer(inputOptions.join.shim) && is.inRange(inputOptions.join.shim, 0, 1000000)) { | ||
| inputDescriptor.joinShim = inputOptions.join.shim; | ||
| } else { | ||
| throw is.invalidParameterError('join.shim', 'integer between 0 and 100000', inputOptions.join.shim); | ||
| } | ||
| } | ||
| if (is.defined(inputOptions.join.background)) { | ||
| inputDescriptor.joinBackground = this._getBackgroundColourOption(inputOptions.join.background); | ||
| } | ||
| if (is.defined(inputOptions.join.halign)) { | ||
| if (is.string(inputOptions.join.halign) && is.string(this.constructor.align[inputOptions.join.halign])) { | ||
| inputDescriptor.joinHalign = this.constructor.align[inputOptions.join.halign]; | ||
| } else { | ||
| throw is.invalidParameterError('join.halign', 'valid alignment', inputOptions.join.halign); | ||
| } | ||
| } | ||
| if (is.defined(inputOptions.join.valign)) { | ||
| if (is.string(inputOptions.join.valign) && is.string(this.constructor.align[inputOptions.join.valign])) { | ||
| inputDescriptor.joinValign = this.constructor.align[inputOptions.join.valign]; | ||
| } else { | ||
| throw is.invalidParameterError('join.valign', 'valid alignment', inputOptions.join.valign); | ||
| } | ||
| } | ||
| } else { | ||
| throw new Error('Expected input to be an array of images to join'); | ||
| } | ||
| } | ||
| } 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) { | ||
| if (Array.isArray(this.options.input.buffer)) { | ||
| 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/ 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/enum.Interpretation.html) | ||
| * - `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/enum.BandFormat.html) | ||
| * - `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 | ||
| * - `isPalette`: Boolean indicating whether the image is palette-based (GIF, PNG). | ||
| * - `bitsPerSample`: Number of bits per sample for each channel (GIF, PNG, HEIF). | ||
| * - `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. | ||
| * - `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 | ||
| * - `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 | ||
| * - `xmpAsString`: String containing XMP data, if valid UTF-8. | ||
| * - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present | ||
| * - `formatMagick`: String containing format for images loaded via *magick | ||
| * - `comments`: Array of keyword/text pairs representing PNG text blocks, if present. | ||
| * | ||
| * @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 | ||
| * // Get dimensions taking EXIF Orientation into account. | ||
| * const { autoOrient } = await sharp(input).metadata(); | ||
| * const { width, height } = autoOrient; | ||
| * | ||
| * @param {Function} [callback] - called with the arguments `(err, metadata)` | ||
| * @returns {Promise<Object>|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<Object>} | ||
| */ | ||
| 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. | ||
| * @module Sharp | ||
| * @private | ||
| */ | ||
| module.exports = (Sharp) => { | ||
| Object.assign(Sharp.prototype, { | ||
| // Private | ||
| _inputOptionsFromObject, | ||
| _createInputDescriptor, | ||
| _write, | ||
| _flattenBufferIn, | ||
| _isStreamInput, | ||
| // Public | ||
| metadata, | ||
| stats | ||
| }); | ||
| // Class attributes | ||
| Sharp.align = align; | ||
| }; |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| /** | ||
| * Is this value defined and not null? | ||
| * @private | ||
| */ | ||
| const defined = (val) => typeof val !== 'undefined' && val !== null; | ||
| /** | ||
| * Is this value an object? | ||
| * @private | ||
| */ | ||
| const object = (val) => typeof val === 'object'; | ||
| /** | ||
| * Is this value a plain object? | ||
| * @private | ||
| */ | ||
| const plainObject = (val) => Object.prototype.toString.call(val) === '[object Object]'; | ||
| /** | ||
| * Is this value a function? | ||
| * @private | ||
| */ | ||
| const fn = (val) => typeof val === 'function'; | ||
| /** | ||
| * Is this value a boolean? | ||
| * @private | ||
| */ | ||
| const bool = (val) => typeof val === 'boolean'; | ||
| /** | ||
| * Is this value a Buffer object? | ||
| * @private | ||
| */ | ||
| const buffer = (val) => val instanceof Buffer; | ||
| /** | ||
| * Is this value a typed array object?. E.g. Uint8Array or Uint8ClampedArray? | ||
| * @private | ||
| */ | ||
| const typedArray = (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 = (val) => val instanceof ArrayBuffer; | ||
| /** | ||
| * Is this value a non-empty string? | ||
| * @private | ||
| */ | ||
| const string = (val) => typeof val === 'string' && val.length > 0; | ||
| /** | ||
| * Is this value a real number? | ||
| * @private | ||
| */ | ||
| const number = (val) => typeof val === 'number' && !Number.isNaN(val); | ||
| /** | ||
| * Is this value an integer? | ||
| * @private | ||
| */ | ||
| const integer = (val) => Number.isInteger(val); | ||
| /** | ||
| * Is this value within an inclusive given range? | ||
| * @private | ||
| */ | ||
| const inRange = (val, min, max) => val >= min && val <= max; | ||
| /** | ||
| * Is this value within the elements of an array? | ||
| * @private | ||
| */ | ||
| const inArray = (val, list) => 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 = (name, expected, actual) => 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 = (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 | ||
| }; |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| const { spawnSync } = require('node:child_process'); | ||
| const { createHash } = require('node:crypto'); | ||
| const semverCoerce = require('../node_modules/semver/functions/coerce.js'); | ||
| const semverGreaterThanOrEqualTo = require('../node_modules/semver/functions/gte.js'); | ||
| const semverSatisfies = require('../node_modules/semver/functions/satisfies.js'); | ||
| const detectLibc = require('../node_modules/detect-libc/lib/detect-libc.js'); | ||
| const { config, engines, optionalDependencies } = require('../package.json'); | ||
| /* node:coverage ignore next */ | ||
| const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || config.libvips; | ||
| const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version; | ||
| const prebuiltPlatforms = [ | ||
| 'darwin-arm64', 'darwin-x64', | ||
| 'linux-arm', 'linux-arm64', 'linux-ppc64', 'linux-riscv64', 'linux-s390x', 'linux-x64', | ||
| 'linuxmusl-arm64', 'linuxmusl-x64', | ||
| 'win32-arm64', '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}`); | ||
| } | ||
| }; | ||
| /* node:coverage ignore next */ | ||
| const runtimeLibc = () => detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : ''; | ||
| const runtimePlatformArch = () => `${process.platform}${runtimeLibc()}-${process.arch}`; | ||
| const buildPlatformArch = () => { | ||
| /* node:coverage ignore next 3 */ | ||
| if (isEmscripten()) { | ||
| return 'wasm32'; | ||
| } | ||
| 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(`../node_modules/@img/sharp-libvips-dev-${buildPlatformArch()}/include`); | ||
| } catch { | ||
| /* node:coverage ignore next 5 */ | ||
| try { | ||
| return require('../node_modules/@img/sharp-libvips-dev/include'); | ||
| } catch {} | ||
| } | ||
| return ''; | ||
| }; | ||
| const buildSharpLibvipsCPlusPlusDir = () => { | ||
| /* node:coverage ignore next 4 */ | ||
| try { | ||
| return require('../node_modules/@img/sharp-libvips-dev/cplusplus'); | ||
| } catch {} | ||
| return ''; | ||
| }; | ||
| const buildSharpLibvipsLibDir = () => { | ||
| try { | ||
| return require(`../node_modules/@img/sharp-libvips-dev-${buildPlatformArch()}/lib`); | ||
| } catch { | ||
| /* node:coverage ignore next 5 */ | ||
| try { | ||
| return require(`../node_modules/@img/sharp-libvips-${buildPlatformArch()}/lib/index.js`); | ||
| } catch {} | ||
| } | ||
| return ''; | ||
| }; | ||
| /* node:coverage disable */ | ||
| const isUnsupportedNodeRuntime = () => { | ||
| if (process.release?.name === 'node' && process.versions) { | ||
| if (!semverSatisfies(process.versions.node, engines.node)) { | ||
| return { found: process.versions.node, expected: engines.node }; | ||
| } | ||
| } | ||
| }; | ||
| const isEmscripten = () => { | ||
| const { CC } = process.env; | ||
| return Boolean(CC?.endsWith('/emcc')); | ||
| }; | ||
| const isRosetta = () => { | ||
| 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; | ||
| }; | ||
| /* node:coverage enable */ | ||
| 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()}`], { | ||
| includePrerelease: true | ||
| }).version; | ||
| return sha512(`${identHash}npm:${npmVersion}`).slice(0, 10); | ||
| } catch {} | ||
| return ''; | ||
| }; | ||
| /* node:coverage disable */ | ||
| 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; | ||
| return (globalLibvipsVersion || '').trim(); | ||
| } else { | ||
| return ''; | ||
| } | ||
| }; | ||
| /* node:coverage enable */ | ||
| const pkgConfigPath = () => { | ||
| if (process.platform !== 'win32') { | ||
| /* node:coverage ignore next 4 */ | ||
| 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 skipSearch = (status, reason, logger) => { | ||
| if (logger) { | ||
| logger(`Detected ${reason}, skipping search for globally-installed libvips`); | ||
| } | ||
| return status; | ||
| }; | ||
| const useGlobalLibvips = (logger) => { | ||
| if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) { | ||
| return skipSearch(false, 'SHARP_IGNORE_GLOBAL_LIBVIPS', logger); | ||
| } | ||
| if (Boolean(process.env.SHARP_FORCE_GLOBAL_LIBVIPS) === true) { | ||
| return skipSearch(true, 'SHARP_FORCE_GLOBAL_LIBVIPS', logger); | ||
| } | ||
| /* node:coverage ignore next 3 */ | ||
| if (isRosetta()) { | ||
| return skipSearch(false, 'Rosetta', logger); | ||
| } | ||
| const globalVipsVersion = globalLibvipsVersion(); | ||
| /* node:coverage ignore next */ | ||
| return !!globalVipsVersion && semverGreaterThanOrEqualTo(globalVipsVersion, minimumLibvipsVersion); | ||
| }; | ||
| module.exports = { | ||
| minimumLibvipsVersion, | ||
| prebuiltPlatforms, | ||
| buildPlatformArch, | ||
| buildSharpLibvipsIncludeDir, | ||
| buildSharpLibvipsCPlusPlusDir, | ||
| buildSharpLibvipsLibDir, | ||
| isUnsupportedNodeRuntime, | ||
| runtimePlatformArch, | ||
| log, | ||
| yarnLocator, | ||
| spawnRebuild, | ||
| globalLibvipsVersion, | ||
| pkgConfigPath, | ||
| useGlobalLibvips | ||
| }; |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| const is = require('./is'); | ||
| /** | ||
| * How accurate an operation should be. | ||
| * @member | ||
| * @private | ||
| */ | ||
| const vipsPrecision = { | ||
| integer: 'integer', | ||
| float: 'float', | ||
| approximate: 'approximate' | ||
| }; | ||
| /** | ||
| * Rotate the output image. | ||
| * | ||
| * The provided angle 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. | ||
| * | ||
| * For backwards compatibility, if no angle is provided, `.autoOrient()` will be called. | ||
| * | ||
| * Only one rotation can occur per pipeline (aside from an initial call without | ||
| * arguments to orient via EXIF data). 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 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 (!is.defined(angle)) { | ||
| return this.autoOrient(); | ||
| } | ||
| if (this.options.angle || this.options.rotationAngle) { | ||
| this.options.debuglog('ignoring previous rotate options'); | ||
| this.options.angle = 0; | ||
| this.options.rotationAngle = 0; | ||
| } | ||
| 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) { | ||
| this._setBackgroundColourOption('rotationBackground', options.background); | ||
| } | ||
| } else { | ||
| throw is.invalidParameterError('angle', 'numeric', angle); | ||
| } | ||
| return this; | ||
| } | ||
| /** | ||
| * Auto-orient based on the EXIF `Orientation` tag, then remove the tag. | ||
| * Mirroring is supported and may infer the use of a flip operation. | ||
| * | ||
| * Previous or subsequent use of `rotate(angle)` and either `flip()` or `flop()` | ||
| * will logically occur after auto-orientation, regardless of call order. | ||
| * | ||
| * @example | ||
| * const output = await sharp(input).autoOrient().toBuffer(); | ||
| * | ||
| * @example | ||
| * const pipeline = sharp() | ||
| * .autoOrient() | ||
| * .resize(null, 200) | ||
| * .toBuffer(function (err, outputBuffer, info) { | ||
| * // outputBuffer contains 200px high JPEG image data, | ||
| * // auto-oriented using EXIF Orientation tag | ||
| * // info.width and info.height contain the dimensions of the resized image | ||
| * }); | ||
| * readableStream.pipe(pipeline); | ||
| * | ||
| * @returns {Sharp} | ||
| */ | ||
| function autoOrient () { | ||
| this.options.input.autoOrient = true; | ||
| 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 colour 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<number>>|Array<number>} 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/method.Image.sharpen.html 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 {Object|number|Boolean} [options] | ||
| * @param {number} [options.sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. | ||
| * @param {string} [options.precision='integer'] How accurate the operation should be, one of: integer, float, approximate. | ||
| * @param {number} [options.minAmplitude=0.2] A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask. | ||
| * @returns {Sharp} | ||
| * @throws {Error} Invalid parameters | ||
| */ | ||
| function blur (options) { | ||
| let sigma; | ||
| if (is.number(options)) { | ||
| sigma = options; | ||
| } else if (is.plainObject(options)) { | ||
| if (!is.number(options.sigma)) { | ||
| throw is.invalidParameterError('options.sigma', 'number between 0.3 and 1000', sigma); | ||
| } | ||
| sigma = options.sigma; | ||
| if ('precision' in options) { | ||
| if (is.string(vipsPrecision[options.precision])) { | ||
| this.options.precision = vipsPrecision[options.precision]; | ||
| } else { | ||
| throw is.invalidParameterError('precision', 'one of: integer, float, approximate', options.precision); | ||
| } | ||
| } | ||
| if ('minAmplitude' in options) { | ||
| if (is.number(options.minAmplitude) && is.inRange(options.minAmplitude, 0.001, 1)) { | ||
| this.options.minAmpl = options.minAmplitude; | ||
| } else { | ||
| throw is.invalidParameterError('minAmplitude', 'number between 0.001 and 1', options.minAmplitude); | ||
| } | ||
| } | ||
| } | ||
| if (!is.defined(options)) { | ||
| // No arguments: default to mild blur | ||
| this.options.blurSigma = -1; | ||
| } else if (is.bool(options)) { | ||
| // Boolean argument: apply mild blur? | ||
| this.options.blurSigma = options ? -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; | ||
| } | ||
| /** | ||
| * Expand foreground objects using the dilate morphological operator. | ||
| * | ||
| * @example | ||
| * const output = await sharp(input) | ||
| * .dilate() | ||
| * .toBuffer(); | ||
| * | ||
| * @param {Number} [width=1] dilation width in pixels. | ||
| * @returns {Sharp} | ||
| * @throws {Error} Invalid parameters | ||
| */ | ||
| function dilate (width) { | ||
| if (!is.defined(width)) { | ||
| this.options.dilateWidth = 1; | ||
| } else if (is.integer(width) && width > 0) { | ||
| this.options.dilateWidth = width; | ||
| } else { | ||
| throw is.invalidParameterError('dilate', 'positive integer', dilate); | ||
| } | ||
| return this; | ||
| } | ||
| /** | ||
| * Shrink foreground objects using the erode morphological operator. | ||
| * | ||
| * @example | ||
| * const output = await sharp(input) | ||
| * .erode() | ||
| * .toBuffer(); | ||
| * | ||
| * @param {Number} [width=1] erosion width in pixels. | ||
| * @returns {Sharp} | ||
| * @throws {Error} Invalid parameters | ||
| */ | ||
| function erode (width) { | ||
| if (!is.defined(width)) { | ||
| this.options.erodeWidth = 1; | ||
| } else if (is.integer(width) && width > 0) { | ||
| this.options.erodeWidth = width; | ||
| } else { | ||
| throw is.invalidParameterError('erode', 'positive integer', erode); | ||
| } | ||
| 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<number>} 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((a, b) => 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<Array<number>>} inputMatrix - 3x3 or 4x4 Recombination matrix | ||
| * @returns {Sharp} | ||
| * @throws {Error} Invalid parameters | ||
| */ | ||
| function recomb (inputMatrix) { | ||
| if (!Array.isArray(inputMatrix)) { | ||
| throw is.invalidParameterError('inputMatrix', 'array', inputMatrix); | ||
| } | ||
| if (inputMatrix.length !== 3 && inputMatrix.length !== 4) { | ||
| throw is.invalidParameterError('inputMatrix', '3x3 or 4x4 array', inputMatrix.length); | ||
| } | ||
| const recombMatrix = inputMatrix.flat().map(Number); | ||
| if (recombMatrix.length !== 9 && recombMatrix.length !== 16) { | ||
| throw is.invalidParameterError('inputMatrix', 'cardinality of 9 or 16', recombMatrix.length); | ||
| } | ||
| this.options.recombMatrix = recombMatrix; | ||
| 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. | ||
| * @module Sharp | ||
| * @private | ||
| */ | ||
| module.exports = (Sharp) => { | ||
| Object.assign(Sharp.prototype, { | ||
| autoOrient, | ||
| rotate, | ||
| flip, | ||
| flop, | ||
| affine, | ||
| sharpen, | ||
| erode, | ||
| dilate, | ||
| median, | ||
| blur, | ||
| flatten, | ||
| unflatten, | ||
| gamma, | ||
| negate, | ||
| normalise, | ||
| normalize, | ||
| clahe, | ||
| convolve, | ||
| threshold, | ||
| boolean, | ||
| linear, | ||
| recomb, | ||
| modulate | ||
| }); | ||
| }; |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| 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. | ||
| * Animated output will also contain `pageHeight` and `pages`. | ||
| * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. | ||
| * @returns {Promise<Object>} - 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 jpeg}, {@link #png 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`. | ||
| * Animated output will also contain `pageHeight` and `pages`. | ||
| * 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<Buffer>} - 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<string, Object<string, string>>} 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<string, Object<string, string>>} 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. | ||
| * | ||
| * When input and output colour spaces differ, use with {@link /api-colour/#tocolourspace toColourspace} and optionally {@link /api-colour/#pipelinecolourspace pipelineColourspace}. | ||
| * | ||
| * @since 0.33.0 | ||
| * | ||
| * @example | ||
| * const outputWithIccProfile = await sharp(inputWithIccProfile) | ||
| * .keepIccProfile() | ||
| * .toBuffer(); | ||
| * | ||
| * @example | ||
| * const cmykOutputWithIccProfile = await sharp(cmykInputWithIccProfile) | ||
| * .pipelineColourspace('cmyk') | ||
| * .toColourspace('cmyk') | ||
| * .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 XMP metadata from the input image in the output image. | ||
| * | ||
| * @since 0.34.3 | ||
| * | ||
| * @example | ||
| * const outputWithXmp = await sharp(inputWithXmp) | ||
| * .keepXmp() | ||
| * .toBuffer(); | ||
| * | ||
| * @returns {Sharp} | ||
| */ | ||
| function keepXmp () { | ||
| this.options.keepMetadata |= 0b00010; | ||
| return this; | ||
| } | ||
| /** | ||
| * Set XMP metadata in the output image. | ||
| * | ||
| * Supported by PNG, JPEG, WebP, and TIFF output. | ||
| * | ||
| * @since 0.34.3 | ||
| * | ||
| * @example | ||
| * const xmpString = ` | ||
| * <?xml version="1.0"?> | ||
| * <x:xmpmeta xmlns:x="adobe:ns:meta/"> | ||
| * <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> | ||
| * <rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/"> | ||
| * <dc:creator><rdf:Seq><rdf:li>John Doe</rdf:li></rdf:Seq></dc:creator> | ||
| * </rdf:Description> | ||
| * </rdf:RDF> | ||
| * </x:xmpmeta>`; | ||
| * | ||
| * const data = await sharp(input) | ||
| * .withXmp(xmpString) | ||
| * .toBuffer(); | ||
| * | ||
| * @param {string} xmp String containing XMP metadata to be embedded in the output image. | ||
| * @returns {Sharp} | ||
| * @throws {Error} Invalid parameters | ||
| */ | ||
| function withXmp (xmp) { | ||
| if (is.string(xmp) && xmp.length > 0) { | ||
| this.options.withXmp = xmp; | ||
| this.options.keepMetadata |= 0b00010; | ||
| } else { | ||
| throw is.invalidParameterError('xmp', 'non-empty string', xmp); | ||
| } | ||
| 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 {boolean} [options.smartDeblock=false] - auto-adjust the deblocking filter, can improve low contrast edges (slow) | ||
| * @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.smartDeblock)) { | ||
| this._setBooleanOption('webpSmartDeblock', options.smartDeblock); | ||
| } | ||
| 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 {boolean} [options.keepDuplicateFrames=false] - keep duplicate frames in the output instead of combining them | ||
| * @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); | ||
| } | ||
| } | ||
| if (is.defined(options.keepDuplicateFrames)) { | ||
| if (is.bool(options.keepDuplicateFrames)) { | ||
| this._setBooleanOption('gifKeepDuplicateFrames', options.keepDuplicateFrames); | ||
| } else { | ||
| throw is.invalidParameterError('keepDuplicateFrames', 'boolean', options.keepDuplicateFrames); | ||
| } | ||
| } | ||
| } | ||
| trySetAnimationOptions(options, this.options); | ||
| return this._updateFormatOut('gif', options); | ||
| } | ||
| /** | ||
| * Use these JP2 options for output image. | ||
| * | ||
| * Requires libvips compiled with support for OpenJPEG. | ||
| * The prebuilt binaries do not include this - see | ||
| * {@link /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) { | ||
| /* node:coverage ignore next 41 */ | ||
| 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 {boolean} [options.bigtiff=false] - use BigTIFF variant (has no effect when compression is none) | ||
| * @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); | ||
| } | ||
| } | ||
| // bigtiff | ||
| if (is.defined(options.bigtiff)) { | ||
| this._setBooleanOption('tiffBigtiff', options.bigtiff); | ||
| } | ||
| // 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. | ||
| * | ||
| * This feature is experimental on the Windows ARM64 platform | ||
| * and requires a CPU with ARM64v8.4 or later. | ||
| * | ||
| * @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 /install/#custom-libvips installing a custom libvips}. | ||
| * | ||
| * @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 1 (fastest) and 9 (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) | ||
| * @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, 1, 9)) { | ||
| this.options.jxlEffort = options.effort; | ||
| } else { | ||
| throw is.invalidParameterError('effort', 'integer between 1 and 9', options.effort); | ||
| } | ||
| } | ||
| } | ||
| trySetAnimationOptions(options, this.options); | ||
| 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`. | ||
| * | ||
| * @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 () { | ||
| 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. | ||
| * @module Sharp | ||
| * @private | ||
| */ | ||
| module.exports = (Sharp) => { | ||
| Object.assign(Sharp.prototype, { | ||
| // Public | ||
| toFile, | ||
| toBuffer, | ||
| keepExif, | ||
| withExif, | ||
| withExifMerge, | ||
| keepIccProfile, | ||
| withIccProfile, | ||
| keepXmp, | ||
| withXmp, | ||
| keepMetadata, | ||
| withMetadata, | ||
| toFormat, | ||
| jpeg, | ||
| jp2, | ||
| png, | ||
| webp, | ||
| tiff, | ||
| avif, | ||
| heif, | ||
| jxl, | ||
| gif, | ||
| raw, | ||
| tile, | ||
| timeout, | ||
| // Private | ||
| _updateFormatOut, | ||
| _setBooleanOption, | ||
| _read, | ||
| _pipeline | ||
| }); | ||
| }; |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| 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', | ||
| linear: 'linear', | ||
| cubic: 'cubic', | ||
| mitchell: 'mitchell', | ||
| lanczos2: 'lanczos2', | ||
| lanczos3: 'lanczos3', | ||
| mks2013: 'mks2013', | ||
| mks2021: 'mks2021' | ||
| }; | ||
| /** | ||
| * 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.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. | ||
| * | ||
| * <img alt="Examples of various values for the fit property when resizing" width="100%" style="aspect-ratio: 998/243" src="/api-resize-fit.svg"> | ||
| * | ||
| * 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 strategy-based approach initially 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 downsizing kernels are: | ||
| * - `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). | ||
| * - `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function). | ||
| * - `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). | ||
| * - `mks2013`: Use a [Magic Kernel Sharp](https://johncostella.com/magic/mks.pdf) 2013 kernel, as adopted by Facebook. | ||
| * - `mks2021`: Use a Magic Kernel Sharp 2021 kernel, with more accurate (reduced) sharpening than the 2013 version. | ||
| * | ||
| * When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators. | ||
| * Downsampling kernels without a matching upsampling interpolator map to `cubic`. | ||
| * | ||
| * 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 and the inferred interpolator to use for upsampling. 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.rotateBefore = 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.rotateBefore = true; | ||
| } | ||
| } | ||
| if (this.options.input.autoOrient) { | ||
| this.options.orientBefore = 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.rotateBefore = true; | ||
| } | ||
| return this; | ||
| } | ||
| /** | ||
| * Decorate the Sharp prototype with resize-related functions. | ||
| * @module Sharp | ||
| * @private | ||
| */ | ||
| module.exports = (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; | ||
| }; |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| // Inspects the runtime environment and exports the relevant sharp.node binary | ||
| const { familySync, versionSync } = require('../node_modules/detect-libc/lib/detect-libc.js'); | ||
| const { runtimePlatformArch, isUnsupportedNodeRuntime, prebuiltPlatforms, minimumLibvipsVersion } = require('./libvips'); | ||
| const runtimePlatform = runtimePlatformArch(); | ||
| const paths = [ | ||
| `../src/build/Release/sharp-${runtimePlatform}.node`, | ||
| '../src/build/Release/sharp-wasm32.node', | ||
| `../node_modules/@img/sharp-${runtimePlatform}/lib/sharp-${runtimePlatform}.node`, | ||
| '../node_modules/@img/sharp-wasm32/lib/sharp-wasm32.node' | ||
| ]; | ||
| /* node:coverage disable */ | ||
| let path, sharp; | ||
| const errors = []; | ||
| for (path of paths) { | ||
| try { | ||
| sharp = require(path); | ||
| break; | ||
| } catch (err) { | ||
| errors.push(err); | ||
| } | ||
| } | ||
| if (sharp && path.includes('@img/sharp-linux-x64') && !sharp._isUsingX64V2()) { | ||
| const err = new Error('Prebuilt binaries for linux-x64 require v2 microarchitecture'); | ||
| err.code = 'Unsupported CPU'; | ||
| errors.push(err); | ||
| sharp = null; | ||
| } | ||
| 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', | ||
| '- 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 { config } = require(`../node_modules/@img/sharp-libvips-${runtimePlatform}/package.json`); | ||
| const libcFound = `${familySync()} ${versionSync()}`; | ||
| const libcRequires = `${config.musl ? 'musl' : 'glibc'} ${config.musl || config.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')); | ||
| } |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| const events = require('node:events'); | ||
| const detectLibc = require('../node_modules/detect-libc/lib/detect-libc.js'); | ||
| 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 | ||
| }; | ||
| /* node:coverage ignore next 15 */ | ||
| if (!libvipsVersion.isGlobal) { | ||
| if (!libvipsVersion.isWasm) { | ||
| try { | ||
| versions = require(`../node_modules/@img/sharp-${runtimePlatform}/versions.json`); | ||
| } catch (_) { | ||
| try { | ||
| versions = require(`../node_modules/@img/sharp-libvips-${runtimePlatform}/versions.json`); | ||
| } catch (_) {} | ||
| } | ||
| } else { | ||
| try { | ||
| versions = require('../node_modules/@img/sharp-wasm32/versions.json'); | ||
| } catch (_) {} | ||
| } | ||
| } | ||
| versions.sharp = require('../package.json').version; | ||
| /* node:coverage ignore next 5 */ | ||
| if (versions.heif && format.heif) { | ||
| // Prebuilt binaries provide AV1 | ||
| format.heif.input.fileSuffix = ['.avif']; | ||
| format.heif.output.alias = ['avif']; | ||
| } | ||
| /** | ||
| * 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. | ||
| * | ||
| * :::note | ||
| * Further {@link /performance/ control over performance} is available. | ||
| * ::: | ||
| * | ||
| * @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); | ||
| } | ||
| /* node:coverage ignore next 7 */ | ||
| if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) { | ||
| // Reduce default concurrency to 1 when using glibc memory allocator | ||
| sharp.concurrency(1); | ||
| } else if (detectLibc.familySync() === detectLibc.MUSL && sharp.concurrency() === 1024) { | ||
| // Reduce default concurrency when musl thread over-subscription detected | ||
| sharp.concurrency(require('node:os').availableParallelism()); | ||
| } | ||
| /** | ||
| * 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 <caption>Block all TIFF input.</caption> | ||
| * sharp.block({ | ||
| * operation: ['VipsForeignLoadTiff'] | ||
| * }); | ||
| * | ||
| * @param {Object} options | ||
| * @param {Array<string>} 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<string>', 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 <caption>Block all input except WebP from the filesystem.</caption> | ||
| * sharp.block({ | ||
| * operation: ['VipsForeignLoad'] | ||
| * }); | ||
| * sharp.unblock({ | ||
| * operation: ['VipsForeignLoadWebpFile'] | ||
| * }); | ||
| * | ||
| * @example <caption>Block all input except JPEG and PNG from a Buffer or Stream.</caption> | ||
| * sharp.block({ | ||
| * operation: ['VipsForeignLoad'] | ||
| * }); | ||
| * sharp.unblock({ | ||
| * operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer'] | ||
| * }); | ||
| * | ||
| * @param {Object} options | ||
| * @param {Array<string>} 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<string>', options.operation); | ||
| } | ||
| } else { | ||
| throw is.invalidParameterError('options', 'object', options); | ||
| } | ||
| } | ||
| /** | ||
| * Decorate the Sharp class with utility-related functions. | ||
| * @module Sharp | ||
| * @private | ||
| */ | ||
| module.exports = (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; | ||
| }; |
| 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. |
Sorry, the diff of this file is not supported yet
| var __defProp = Object.defineProperty; | ||
| var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
| var __getOwnPropNames = Object.getOwnPropertyNames; | ||
| var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
| var __export = (target, all) => { | ||
| for (var name in all) | ||
| __defProp(target, name, { get: all[name], enumerable: true }); | ||
| }; | ||
| var __copyProps = (to, from, except, desc) => { | ||
| if (from && typeof from === "object" || typeof from === "function") { | ||
| for (let key of __getOwnPropNames(from)) | ||
| if (!__hasOwnProp.call(to, key) && key !== except) | ||
| __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
| } | ||
| return to; | ||
| }; | ||
| var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
| // node_modules/color/index.js | ||
| var index_exports = {}; | ||
| __export(index_exports, { | ||
| default: () => index_default | ||
| }); | ||
| module.exports = __toCommonJS(index_exports); | ||
| // node_modules/color-name/index.js | ||
| var colors = { | ||
| aliceblue: [240, 248, 255], | ||
| antiquewhite: [250, 235, 215], | ||
| aqua: [0, 255, 255], | ||
| aquamarine: [127, 255, 212], | ||
| azure: [240, 255, 255], | ||
| beige: [245, 245, 220], | ||
| bisque: [255, 228, 196], | ||
| black: [0, 0, 0], | ||
| blanchedalmond: [255, 235, 205], | ||
| blue: [0, 0, 255], | ||
| blueviolet: [138, 43, 226], | ||
| brown: [165, 42, 42], | ||
| burlywood: [222, 184, 135], | ||
| cadetblue: [95, 158, 160], | ||
| chartreuse: [127, 255, 0], | ||
| chocolate: [210, 105, 30], | ||
| coral: [255, 127, 80], | ||
| cornflowerblue: [100, 149, 237], | ||
| cornsilk: [255, 248, 220], | ||
| crimson: [220, 20, 60], | ||
| cyan: [0, 255, 255], | ||
| darkblue: [0, 0, 139], | ||
| darkcyan: [0, 139, 139], | ||
| darkgoldenrod: [184, 134, 11], | ||
| darkgray: [169, 169, 169], | ||
| darkgreen: [0, 100, 0], | ||
| darkgrey: [169, 169, 169], | ||
| darkkhaki: [189, 183, 107], | ||
| darkmagenta: [139, 0, 139], | ||
| darkolivegreen: [85, 107, 47], | ||
| darkorange: [255, 140, 0], | ||
| darkorchid: [153, 50, 204], | ||
| darkred: [139, 0, 0], | ||
| darksalmon: [233, 150, 122], | ||
| darkseagreen: [143, 188, 143], | ||
| darkslateblue: [72, 61, 139], | ||
| darkslategray: [47, 79, 79], | ||
| darkslategrey: [47, 79, 79], | ||
| darkturquoise: [0, 206, 209], | ||
| darkviolet: [148, 0, 211], | ||
| deeppink: [255, 20, 147], | ||
| deepskyblue: [0, 191, 255], | ||
| dimgray: [105, 105, 105], | ||
| dimgrey: [105, 105, 105], | ||
| dodgerblue: [30, 144, 255], | ||
| firebrick: [178, 34, 34], | ||
| floralwhite: [255, 250, 240], | ||
| forestgreen: [34, 139, 34], | ||
| fuchsia: [255, 0, 255], | ||
| gainsboro: [220, 220, 220], | ||
| ghostwhite: [248, 248, 255], | ||
| gold: [255, 215, 0], | ||
| goldenrod: [218, 165, 32], | ||
| gray: [128, 128, 128], | ||
| green: [0, 128, 0], | ||
| greenyellow: [173, 255, 47], | ||
| grey: [128, 128, 128], | ||
| honeydew: [240, 255, 240], | ||
| hotpink: [255, 105, 180], | ||
| indianred: [205, 92, 92], | ||
| indigo: [75, 0, 130], | ||
| ivory: [255, 255, 240], | ||
| khaki: [240, 230, 140], | ||
| lavender: [230, 230, 250], | ||
| lavenderblush: [255, 240, 245], | ||
| lawngreen: [124, 252, 0], | ||
| lemonchiffon: [255, 250, 205], | ||
| lightblue: [173, 216, 230], | ||
| lightcoral: [240, 128, 128], | ||
| lightcyan: [224, 255, 255], | ||
| lightgoldenrodyellow: [250, 250, 210], | ||
| lightgray: [211, 211, 211], | ||
| lightgreen: [144, 238, 144], | ||
| lightgrey: [211, 211, 211], | ||
| lightpink: [255, 182, 193], | ||
| lightsalmon: [255, 160, 122], | ||
| lightseagreen: [32, 178, 170], | ||
| lightskyblue: [135, 206, 250], | ||
| lightslategray: [119, 136, 153], | ||
| lightslategrey: [119, 136, 153], | ||
| lightsteelblue: [176, 196, 222], | ||
| lightyellow: [255, 255, 224], | ||
| lime: [0, 255, 0], | ||
| limegreen: [50, 205, 50], | ||
| linen: [250, 240, 230], | ||
| magenta: [255, 0, 255], | ||
| maroon: [128, 0, 0], | ||
| mediumaquamarine: [102, 205, 170], | ||
| mediumblue: [0, 0, 205], | ||
| mediumorchid: [186, 85, 211], | ||
| mediumpurple: [147, 112, 219], | ||
| mediumseagreen: [60, 179, 113], | ||
| mediumslateblue: [123, 104, 238], | ||
| mediumspringgreen: [0, 250, 154], | ||
| mediumturquoise: [72, 209, 204], | ||
| mediumvioletred: [199, 21, 133], | ||
| midnightblue: [25, 25, 112], | ||
| mintcream: [245, 255, 250], | ||
| mistyrose: [255, 228, 225], | ||
| moccasin: [255, 228, 181], | ||
| navajowhite: [255, 222, 173], | ||
| navy: [0, 0, 128], | ||
| oldlace: [253, 245, 230], | ||
| olive: [128, 128, 0], | ||
| olivedrab: [107, 142, 35], | ||
| orange: [255, 165, 0], | ||
| orangered: [255, 69, 0], | ||
| orchid: [218, 112, 214], | ||
| palegoldenrod: [238, 232, 170], | ||
| palegreen: [152, 251, 152], | ||
| paleturquoise: [175, 238, 238], | ||
| palevioletred: [219, 112, 147], | ||
| papayawhip: [255, 239, 213], | ||
| peachpuff: [255, 218, 185], | ||
| peru: [205, 133, 63], | ||
| pink: [255, 192, 203], | ||
| plum: [221, 160, 221], | ||
| powderblue: [176, 224, 230], | ||
| purple: [128, 0, 128], | ||
| rebeccapurple: [102, 51, 153], | ||
| red: [255, 0, 0], | ||
| rosybrown: [188, 143, 143], | ||
| royalblue: [65, 105, 225], | ||
| saddlebrown: [139, 69, 19], | ||
| salmon: [250, 128, 114], | ||
| sandybrown: [244, 164, 96], | ||
| seagreen: [46, 139, 87], | ||
| seashell: [255, 245, 238], | ||
| sienna: [160, 82, 45], | ||
| silver: [192, 192, 192], | ||
| skyblue: [135, 206, 235], | ||
| slateblue: [106, 90, 205], | ||
| slategray: [112, 128, 144], | ||
| slategrey: [112, 128, 144], | ||
| snow: [255, 250, 250], | ||
| springgreen: [0, 255, 127], | ||
| steelblue: [70, 130, 180], | ||
| tan: [210, 180, 140], | ||
| teal: [0, 128, 128], | ||
| thistle: [216, 191, 216], | ||
| tomato: [255, 99, 71], | ||
| turquoise: [64, 224, 208], | ||
| violet: [238, 130, 238], | ||
| wheat: [245, 222, 179], | ||
| white: [255, 255, 255], | ||
| whitesmoke: [245, 245, 245], | ||
| yellow: [255, 255, 0], | ||
| yellowgreen: [154, 205, 50] | ||
| }; | ||
| for (const key in colors) Object.freeze(colors[key]); | ||
| var color_name_default = Object.freeze(colors); | ||
| // node_modules/color-string/index.js | ||
| var reverseNames = /* @__PURE__ */ Object.create(null); | ||
| for (const name in color_name_default) { | ||
| if (Object.hasOwn(color_name_default, name)) { | ||
| reverseNames[color_name_default[name]] = name; | ||
| } | ||
| } | ||
| var cs = { | ||
| to: {}, | ||
| get: {} | ||
| }; | ||
| cs.get = function(string) { | ||
| const prefix = string.slice(0, 3).toLowerCase(); | ||
| let value; | ||
| let model; | ||
| switch (prefix) { | ||
| case "hsl": { | ||
| value = cs.get.hsl(string); | ||
| model = "hsl"; | ||
| break; | ||
| } | ||
| case "hwb": { | ||
| value = cs.get.hwb(string); | ||
| model = "hwb"; | ||
| break; | ||
| } | ||
| default: { | ||
| value = cs.get.rgb(string); | ||
| model = "rgb"; | ||
| break; | ||
| } | ||
| } | ||
| if (!value) { | ||
| return null; | ||
| } | ||
| return { model, value }; | ||
| }; | ||
| cs.get.rgb = function(string) { | ||
| if (!string) { | ||
| return null; | ||
| } | ||
| const abbr = /^#([a-f\d]{3,4})$/i; | ||
| const hex = /^#([a-f\d]{6})([a-f\d]{2})?$/i; | ||
| const rgba = /^rgba?\(\s*([+-]?(?:\d*\.)?\d+(?:e\d+)?)(?=[\s,])\s*(?:,\s*)?([+-]?(?:\d*\.)?\d+(?:e\d+)?)(?=[\s,])\s*(?:,\s*)?([+-]?(?:\d*\.)?\d+(?:e\d+)?)\s*(?:[\s,|/]\s*([+-]?(?:\d*\.)?\d+(?:e\d+)?)(%?)\s*)?\)$/i; | ||
| const per = /^rgba?\(\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/i; | ||
| const keyword = /^(\w+)$/; | ||
| let rgb = [0, 0, 0, 1]; | ||
| let match; | ||
| let i; | ||
| let hexAlpha; | ||
| if (match = string.match(hex)) { | ||
| hexAlpha = match[2]; | ||
| match = match[1]; | ||
| for (i = 0; i < 3; i++) { | ||
| const i2 = i * 2; | ||
| rgb[i] = Number.parseInt(match.slice(i2, i2 + 2), 16); | ||
| } | ||
| if (hexAlpha) { | ||
| rgb[3] = Number.parseInt(hexAlpha, 16) / 255; | ||
| } | ||
| } else if (match = string.match(abbr)) { | ||
| match = match[1]; | ||
| hexAlpha = match[3]; | ||
| for (i = 0; i < 3; i++) { | ||
| rgb[i] = Number.parseInt(match[i] + match[i], 16); | ||
| } | ||
| if (hexAlpha) { | ||
| rgb[3] = Number.parseInt(hexAlpha + hexAlpha, 16) / 255; | ||
| } | ||
| } else if (match = string.match(rgba)) { | ||
| for (i = 0; i < 3; i++) { | ||
| rgb[i] = Number.parseFloat(match[i + 1]); | ||
| } | ||
| if (match[4]) { | ||
| rgb[3] = match[5] ? Number.parseFloat(match[4]) * 0.01 : Number.parseFloat(match[4]); | ||
| } | ||
| } else if (match = string.match(per)) { | ||
| for (i = 0; i < 3; i++) { | ||
| rgb[i] = Math.round(Number.parseFloat(match[i + 1]) * 2.55); | ||
| } | ||
| if (match[4]) { | ||
| rgb[3] = match[5] ? Number.parseFloat(match[4]) * 0.01 : Number.parseFloat(match[4]); | ||
| } | ||
| } else if (match = string.toLowerCase().match(keyword)) { | ||
| if (match[1] === "transparent") { | ||
| return [0, 0, 0, 0]; | ||
| } | ||
| if (!Object.hasOwn(color_name_default, match[1])) { | ||
| return null; | ||
| } | ||
| rgb = color_name_default[match[1]].slice(); | ||
| 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; | ||
| } | ||
| const hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[,|/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:e[+-]?\d+)?)\s*)?\)$/i; | ||
| const match = string.match(hsl); | ||
| if (match) { | ||
| const alpha = Number.parseFloat(match[4]); | ||
| const h = (Number.parseFloat(match[1]) % 360 + 360) % 360; | ||
| const s = clamp(Number.parseFloat(match[2]), 0, 100); | ||
| const l = clamp(Number.parseFloat(match[3]), 0, 100); | ||
| const a = clamp(Number.isNaN(alpha) ? 1 : alpha, 0, 1); | ||
| return [h, s, l, a]; | ||
| } | ||
| return null; | ||
| }; | ||
| cs.get.hwb = function(string) { | ||
| if (!string) { | ||
| return null; | ||
| } | ||
| const hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*[\s,]\s*([+-]?[\d.]+)%\s*[\s,]\s*([+-]?[\d.]+)%\s*(?:[\s,]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:e[+-]?\d+)?)\s*)?\)$/i; | ||
| const match = string.match(hwb); | ||
| if (match) { | ||
| const alpha = Number.parseFloat(match[4]); | ||
| const h = (Number.parseFloat(match[1]) % 360 + 360) % 360; | ||
| const w = clamp(Number.parseFloat(match[2]), 0, 100); | ||
| const b = clamp(Number.parseFloat(match[3]), 0, 100); | ||
| const a = clamp(Number.isNaN(alpha) ? 1 : alpha, 0, 1); | ||
| return [h, w, b, a]; | ||
| } | ||
| return null; | ||
| }; | ||
| cs.to.hex = function(...rgba) { | ||
| return "#" + hexDouble(rgba[0]) + hexDouble(rgba[1]) + hexDouble(rgba[2]) + (rgba[3] < 1 ? hexDouble(Math.round(rgba[3] * 255)) : ""); | ||
| }; | ||
| cs.to.rgb = function(...rgba) { | ||
| 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(...rgba) { | ||
| const r = Math.round(rgba[0] / 255 * 100); | ||
| const g = Math.round(rgba[1] / 255 * 100); | ||
| const 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(...hsla) { | ||
| return hsla.length < 4 || hsla[3] === 1 ? "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)" : "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, " + hsla[3] + ")"; | ||
| }; | ||
| cs.to.hwb = function(...hwba) { | ||
| let 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)]; | ||
| }; | ||
| function clamp(number_, min, max) { | ||
| return Math.min(Math.max(min, number_), max); | ||
| } | ||
| function hexDouble(number_) { | ||
| const string_ = Math.round(number_).toString(16).toUpperCase(); | ||
| return string_.length < 2 ? "0" + string_ : string_; | ||
| } | ||
| var color_string_default = cs; | ||
| // node_modules/color-convert/conversions.js | ||
| var reverseKeywords = {}; | ||
| for (const key of Object.keys(color_name_default)) { | ||
| reverseKeywords[color_name_default[key]] = key; | ||
| } | ||
| var convert = { | ||
| rgb: { channels: 3, labels: "rgb" }, | ||
| hsl: { channels: 3, labels: "hsl" }, | ||
| hsv: { channels: 3, labels: "hsv" }, | ||
| hwb: { channels: 3, labels: "hwb" }, | ||
| cmyk: { channels: 4, labels: "cmyk" }, | ||
| xyz: { channels: 3, labels: "xyz" }, | ||
| lab: { channels: 3, labels: "lab" }, | ||
| oklab: { channels: 3, labels: ["okl", "oka", "okb"] }, | ||
| lch: { channels: 3, labels: "lch" }, | ||
| oklch: { channels: 3, labels: ["okl", "okc", "okh"] }, | ||
| hex: { channels: 1, labels: ["hex"] }, | ||
| keyword: { channels: 1, labels: ["keyword"] }, | ||
| ansi16: { channels: 1, labels: ["ansi16"] }, | ||
| ansi256: { channels: 1, labels: ["ansi256"] }, | ||
| hcg: { channels: 3, labels: ["h", "c", "g"] }, | ||
| apple: { channels: 3, labels: ["r16", "g16", "b16"] }, | ||
| gray: { channels: 1, labels: ["gray"] } | ||
| }; | ||
| var conversions_default = convert; | ||
| var LAB_FT = (6 / 29) ** 3; | ||
| function srgbNonlinearTransform(c) { | ||
| const cc = c > 31308e-7 ? 1.055 * c ** (1 / 2.4) - 0.055 : c * 12.92; | ||
| return Math.min(Math.max(0, cc), 1); | ||
| } | ||
| function srgbNonlinearTransformInv(c) { | ||
| return c > 0.04045 ? ((c + 0.055) / 1.055) ** 2.4 : c / 12.92; | ||
| } | ||
| for (const model of Object.keys(convert)) { | ||
| if (!("channels" in convert[model])) { | ||
| throw new Error("missing channels property: " + model); | ||
| } | ||
| if (!("labels" in convert[model])) { | ||
| throw new Error("missing channel labels property: " + model); | ||
| } | ||
| if (convert[model].labels.length !== convert[model].channels) { | ||
| throw new Error("channel and label counts mismatch: " + model); | ||
| } | ||
| const { channels, labels } = convert[model]; | ||
| delete convert[model].channels; | ||
| delete convert[model].labels; | ||
| Object.defineProperty(convert[model], "channels", { value: channels }); | ||
| Object.defineProperty(convert[model], "labels", { value: labels }); | ||
| } | ||
| convert.rgb.hsl = function(rgb) { | ||
| const r = rgb[0] / 255; | ||
| const g = rgb[1] / 255; | ||
| const b = rgb[2] / 255; | ||
| const min = Math.min(r, g, b); | ||
| const max = Math.max(r, g, b); | ||
| const delta = max - min; | ||
| let h; | ||
| let s; | ||
| switch (max) { | ||
| case min: { | ||
| h = 0; | ||
| break; | ||
| } | ||
| case r: { | ||
| h = (g - b) / delta; | ||
| break; | ||
| } | ||
| case g: { | ||
| h = 2 + (b - r) / delta; | ||
| break; | ||
| } | ||
| case b: { | ||
| h = 4 + (r - g) / delta; | ||
| break; | ||
| } | ||
| } | ||
| h = Math.min(h * 60, 360); | ||
| if (h < 0) { | ||
| h += 360; | ||
| } | ||
| const l = (min + max) / 2; | ||
| if (max === min) { | ||
| s = 0; | ||
| } else if (l <= 0.5) { | ||
| s = delta / (max + min); | ||
| } else { | ||
| s = delta / (2 - max - min); | ||
| } | ||
| return [h, s * 100, l * 100]; | ||
| }; | ||
| convert.rgb.hsv = function(rgb) { | ||
| let rdif; | ||
| let gdif; | ||
| let bdif; | ||
| let h; | ||
| let s; | ||
| const r = rgb[0] / 255; | ||
| const g = rgb[1] / 255; | ||
| const b = rgb[2] / 255; | ||
| const v = Math.max(r, g, b); | ||
| const diff = v - Math.min(r, g, b); | ||
| const diffc = function(c) { | ||
| return (v - c) / 6 / diff + 1 / 2; | ||
| }; | ||
| if (diff === 0) { | ||
| h = 0; | ||
| s = 0; | ||
| } else { | ||
| s = diff / v; | ||
| rdif = diffc(r); | ||
| gdif = diffc(g); | ||
| bdif = diffc(b); | ||
| switch (v) { | ||
| case r: { | ||
| h = bdif - gdif; | ||
| break; | ||
| } | ||
| case g: { | ||
| h = 1 / 3 + rdif - bdif; | ||
| break; | ||
| } | ||
| case b: { | ||
| h = 2 / 3 + gdif - rdif; | ||
| break; | ||
| } | ||
| } | ||
| if (h < 0) { | ||
| h += 1; | ||
| } else if (h > 1) { | ||
| h -= 1; | ||
| } | ||
| } | ||
| return [ | ||
| h * 360, | ||
| s * 100, | ||
| v * 100 | ||
| ]; | ||
| }; | ||
| convert.rgb.hwb = function(rgb) { | ||
| const r = rgb[0]; | ||
| const g = rgb[1]; | ||
| let b = rgb[2]; | ||
| const h = convert.rgb.hsl(rgb)[0]; | ||
| const w = 1 / 255 * Math.min(r, Math.min(g, b)); | ||
| b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); | ||
| return [h, w * 100, b * 100]; | ||
| }; | ||
| convert.rgb.oklab = function(rgb) { | ||
| const r = srgbNonlinearTransformInv(rgb[0] / 255); | ||
| const g = srgbNonlinearTransformInv(rgb[1] / 255); | ||
| const b = srgbNonlinearTransformInv(rgb[2] / 255); | ||
| const lp = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); | ||
| const mp = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); | ||
| const sp = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); | ||
| const l = 0.2104542553 * lp + 0.793617785 * mp - 0.0040720468 * sp; | ||
| const aa = 1.9779984951 * lp - 2.428592205 * mp + 0.4505937099 * sp; | ||
| const bb = 0.0259040371 * lp + 0.7827717662 * mp - 0.808675766 * sp; | ||
| return [l * 100, aa * 100, bb * 100]; | ||
| }; | ||
| convert.rgb.cmyk = function(rgb) { | ||
| const r = rgb[0] / 255; | ||
| const g = rgb[1] / 255; | ||
| const b = rgb[2] / 255; | ||
| const k = Math.min(1 - r, 1 - g, 1 - b); | ||
| const c = (1 - r - k) / (1 - k) || 0; | ||
| const m = (1 - g - k) / (1 - k) || 0; | ||
| const y = (1 - b - k) / (1 - k) || 0; | ||
| return [c * 100, m * 100, y * 100, k * 100]; | ||
| }; | ||
| function comparativeDistance(x, y) { | ||
| return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2; | ||
| } | ||
| convert.rgb.keyword = function(rgb) { | ||
| const reversed = reverseKeywords[rgb]; | ||
| if (reversed) { | ||
| return reversed; | ||
| } | ||
| let currentClosestDistance = Number.POSITIVE_INFINITY; | ||
| let currentClosestKeyword; | ||
| for (const keyword of Object.keys(color_name_default)) { | ||
| const value = color_name_default[keyword]; | ||
| const distance = comparativeDistance(rgb, value); | ||
| if (distance < currentClosestDistance) { | ||
| currentClosestDistance = distance; | ||
| currentClosestKeyword = keyword; | ||
| } | ||
| } | ||
| return currentClosestKeyword; | ||
| }; | ||
| convert.keyword.rgb = function(keyword) { | ||
| return [...color_name_default[keyword]]; | ||
| }; | ||
| convert.rgb.xyz = function(rgb) { | ||
| const r = srgbNonlinearTransformInv(rgb[0] / 255); | ||
| const g = srgbNonlinearTransformInv(rgb[1] / 255); | ||
| const b = srgbNonlinearTransformInv(rgb[2] / 255); | ||
| const x = r * 0.4124564 + g * 0.3575761 + b * 0.1804375; | ||
| const y = r * 0.2126729 + g * 0.7151522 + b * 0.072175; | ||
| const z = r * 0.0193339 + g * 0.119192 + b * 0.9503041; | ||
| return [x * 100, y * 100, z * 100]; | ||
| }; | ||
| convert.rgb.lab = function(rgb) { | ||
| const xyz = convert.rgb.xyz(rgb); | ||
| let x = xyz[0]; | ||
| let y = xyz[1]; | ||
| let z = xyz[2]; | ||
| x /= 95.047; | ||
| y /= 100; | ||
| z /= 108.883; | ||
| x = x > LAB_FT ? x ** (1 / 3) : 7.787 * x + 16 / 116; | ||
| y = y > LAB_FT ? y ** (1 / 3) : 7.787 * y + 16 / 116; | ||
| z = z > LAB_FT ? z ** (1 / 3) : 7.787 * z + 16 / 116; | ||
| const l = 116 * y - 16; | ||
| const a = 500 * (x - y); | ||
| const b = 200 * (y - z); | ||
| return [l, a, b]; | ||
| }; | ||
| convert.hsl.rgb = function(hsl) { | ||
| const h = hsl[0] / 360; | ||
| const s = hsl[1] / 100; | ||
| const l = hsl[2] / 100; | ||
| let t3; | ||
| let value; | ||
| if (s === 0) { | ||
| value = l * 255; | ||
| return [value, value, value]; | ||
| } | ||
| const t2 = l < 0.5 ? l * (1 + s) : l + s - l * s; | ||
| const t1 = 2 * l - t2; | ||
| const rgb = [0, 0, 0]; | ||
| for (let i = 0; i < 3; i++) { | ||
| t3 = h + 1 / 3 * -(i - 1); | ||
| if (t3 < 0) { | ||
| t3++; | ||
| } | ||
| if (t3 > 1) { | ||
| t3--; | ||
| } | ||
| if (6 * t3 < 1) { | ||
| value = t1 + (t2 - t1) * 6 * t3; | ||
| } else if (2 * t3 < 1) { | ||
| value = t2; | ||
| } else if (3 * t3 < 2) { | ||
| value = t1 + (t2 - t1) * (2 / 3 - t3) * 6; | ||
| } else { | ||
| value = t1; | ||
| } | ||
| rgb[i] = value * 255; | ||
| } | ||
| return rgb; | ||
| }; | ||
| convert.hsl.hsv = function(hsl) { | ||
| const h = hsl[0]; | ||
| let s = hsl[1] / 100; | ||
| let l = hsl[2] / 100; | ||
| let smin = s; | ||
| const lmin = Math.max(l, 0.01); | ||
| l *= 2; | ||
| s *= l <= 1 ? l : 2 - l; | ||
| smin *= lmin <= 1 ? lmin : 2 - lmin; | ||
| const v = (l + s) / 2; | ||
| const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); | ||
| return [h, sv * 100, v * 100]; | ||
| }; | ||
| convert.hsv.rgb = function(hsv) { | ||
| const h = hsv[0] / 60; | ||
| const s = hsv[1] / 100; | ||
| let v = hsv[2] / 100; | ||
| const hi = Math.floor(h) % 6; | ||
| const f = h - Math.floor(h); | ||
| const p = 255 * v * (1 - s); | ||
| const q = 255 * v * (1 - s * f); | ||
| const t = 255 * v * (1 - s * (1 - f)); | ||
| v *= 255; | ||
| switch (hi) { | ||
| case 0: { | ||
| return [v, t, p]; | ||
| } | ||
| case 1: { | ||
| return [q, v, p]; | ||
| } | ||
| case 2: { | ||
| return [p, v, t]; | ||
| } | ||
| case 3: { | ||
| return [p, q, v]; | ||
| } | ||
| case 4: { | ||
| return [t, p, v]; | ||
| } | ||
| case 5: { | ||
| return [v, p, q]; | ||
| } | ||
| } | ||
| }; | ||
| convert.hsv.hsl = function(hsv) { | ||
| const h = hsv[0]; | ||
| const s = hsv[1] / 100; | ||
| const v = hsv[2] / 100; | ||
| const vmin = Math.max(v, 0.01); | ||
| let sl; | ||
| let l; | ||
| l = (2 - s) * v; | ||
| const lmin = (2 - s) * vmin; | ||
| sl = s * vmin; | ||
| sl /= lmin <= 1 ? lmin : 2 - lmin; | ||
| sl = sl || 0; | ||
| l /= 2; | ||
| return [h, sl * 100, l * 100]; | ||
| }; | ||
| convert.hwb.rgb = function(hwb) { | ||
| const h = hwb[0] / 360; | ||
| let wh = hwb[1] / 100; | ||
| let bl = hwb[2] / 100; | ||
| const ratio = wh + bl; | ||
| let f; | ||
| if (ratio > 1) { | ||
| wh /= ratio; | ||
| bl /= ratio; | ||
| } | ||
| const i = Math.floor(6 * h); | ||
| const v = 1 - bl; | ||
| f = 6 * h - i; | ||
| if ((i & 1) !== 0) { | ||
| f = 1 - f; | ||
| } | ||
| const n = wh + f * (v - wh); | ||
| let r; | ||
| let g; | ||
| let b; | ||
| switch (i) { | ||
| default: | ||
| case 6: | ||
| case 0: { | ||
| r = v; | ||
| g = n; | ||
| b = wh; | ||
| break; | ||
| } | ||
| case 1: { | ||
| r = n; | ||
| g = v; | ||
| b = wh; | ||
| break; | ||
| } | ||
| case 2: { | ||
| r = wh; | ||
| g = v; | ||
| b = n; | ||
| break; | ||
| } | ||
| case 3: { | ||
| r = wh; | ||
| g = n; | ||
| b = v; | ||
| break; | ||
| } | ||
| case 4: { | ||
| r = n; | ||
| g = wh; | ||
| b = v; | ||
| break; | ||
| } | ||
| case 5: { | ||
| r = v; | ||
| g = wh; | ||
| b = n; | ||
| break; | ||
| } | ||
| } | ||
| return [r * 255, g * 255, b * 255]; | ||
| }; | ||
| convert.cmyk.rgb = function(cmyk) { | ||
| const c = cmyk[0] / 100; | ||
| const m = cmyk[1] / 100; | ||
| const y = cmyk[2] / 100; | ||
| const k = cmyk[3] / 100; | ||
| const r = 1 - Math.min(1, c * (1 - k) + k); | ||
| const g = 1 - Math.min(1, m * (1 - k) + k); | ||
| const b = 1 - Math.min(1, y * (1 - k) + k); | ||
| return [r * 255, g * 255, b * 255]; | ||
| }; | ||
| convert.xyz.rgb = function(xyz) { | ||
| const x = xyz[0] / 100; | ||
| const y = xyz[1] / 100; | ||
| const z = xyz[2] / 100; | ||
| let r; | ||
| let g; | ||
| let b; | ||
| r = x * 3.2404542 + y * -1.5371385 + z * -0.4985314; | ||
| g = x * -0.969266 + y * 1.8760108 + z * 0.041556; | ||
| b = x * 0.0556434 + y * -0.2040259 + z * 1.0572252; | ||
| r = srgbNonlinearTransform(r); | ||
| g = srgbNonlinearTransform(g); | ||
| b = srgbNonlinearTransform(b); | ||
| return [r * 255, g * 255, b * 255]; | ||
| }; | ||
| convert.xyz.lab = function(xyz) { | ||
| let x = xyz[0]; | ||
| let y = xyz[1]; | ||
| let z = xyz[2]; | ||
| x /= 95.047; | ||
| y /= 100; | ||
| z /= 108.883; | ||
| x = x > LAB_FT ? x ** (1 / 3) : 7.787 * x + 16 / 116; | ||
| y = y > LAB_FT ? y ** (1 / 3) : 7.787 * y + 16 / 116; | ||
| z = z > LAB_FT ? z ** (1 / 3) : 7.787 * z + 16 / 116; | ||
| const l = 116 * y - 16; | ||
| const a = 500 * (x - y); | ||
| const b = 200 * (y - z); | ||
| return [l, a, b]; | ||
| }; | ||
| convert.xyz.oklab = function(xyz) { | ||
| const x = xyz[0] / 100; | ||
| const y = xyz[1] / 100; | ||
| const z = xyz[2] / 100; | ||
| const lp = Math.cbrt(0.8189330101 * x + 0.3618667424 * y - 0.1288597137 * z); | ||
| const mp = Math.cbrt(0.0329845436 * x + 0.9293118715 * y + 0.0361456387 * z); | ||
| const sp = Math.cbrt(0.0482003018 * x + 0.2643662691 * y + 0.633851707 * z); | ||
| const l = 0.2104542553 * lp + 0.793617785 * mp - 0.0040720468 * sp; | ||
| const a = 1.9779984951 * lp - 2.428592205 * mp + 0.4505937099 * sp; | ||
| const b = 0.0259040371 * lp + 0.7827717662 * mp - 0.808675766 * sp; | ||
| return [l * 100, a * 100, b * 100]; | ||
| }; | ||
| convert.oklab.oklch = function(oklab) { | ||
| return convert.lab.lch(oklab); | ||
| }; | ||
| convert.oklab.xyz = function(oklab) { | ||
| const ll = oklab[0] / 100; | ||
| const a = oklab[1] / 100; | ||
| const b = oklab[2] / 100; | ||
| const l = (0.999999998 * ll + 0.396337792 * a + 0.215803758 * b) ** 3; | ||
| const m = (1.000000008 * ll - 0.105561342 * a - 0.063854175 * b) ** 3; | ||
| const s = (1.000000055 * ll - 0.089484182 * a - 1.291485538 * b) ** 3; | ||
| const x = 1.227013851 * l - 0.55779998 * m + 0.281256149 * s; | ||
| const y = -0.040580178 * l + 1.11225687 * m - 0.071676679 * s; | ||
| const z = -0.076381285 * l - 0.421481978 * m + 1.58616322 * s; | ||
| return [x * 100, y * 100, z * 100]; | ||
| }; | ||
| convert.oklab.rgb = function(oklab) { | ||
| const ll = oklab[0] / 100; | ||
| const aa = oklab[1] / 100; | ||
| const bb = oklab[2] / 100; | ||
| const l = (ll + 0.3963377774 * aa + 0.2158037573 * bb) ** 3; | ||
| const m = (ll - 0.1055613458 * aa - 0.0638541728 * bb) ** 3; | ||
| const s = (ll - 0.0894841775 * aa - 1.291485548 * bb) ** 3; | ||
| const r = srgbNonlinearTransform(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s); | ||
| const g = srgbNonlinearTransform(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s); | ||
| const b = srgbNonlinearTransform(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s); | ||
| return [r * 255, g * 255, b * 255]; | ||
| }; | ||
| convert.oklch.oklab = function(oklch) { | ||
| return convert.lch.lab(oklch); | ||
| }; | ||
| convert.lab.xyz = function(lab) { | ||
| const l = lab[0]; | ||
| const a = lab[1]; | ||
| const b = lab[2]; | ||
| let x; | ||
| let y; | ||
| let z; | ||
| y = (l + 16) / 116; | ||
| x = a / 500 + y; | ||
| z = y - b / 200; | ||
| const y2 = y ** 3; | ||
| const x2 = x ** 3; | ||
| const z2 = z ** 3; | ||
| y = y2 > LAB_FT ? y2 : (y - 16 / 116) / 7.787; | ||
| x = x2 > LAB_FT ? x2 : (x - 16 / 116) / 7.787; | ||
| z = z2 > LAB_FT ? z2 : (z - 16 / 116) / 7.787; | ||
| x *= 95.047; | ||
| y *= 100; | ||
| z *= 108.883; | ||
| return [x, y, z]; | ||
| }; | ||
| convert.lab.lch = function(lab) { | ||
| const l = lab[0]; | ||
| const a = lab[1]; | ||
| const b = lab[2]; | ||
| let h; | ||
| const hr = Math.atan2(b, a); | ||
| h = hr * 360 / 2 / Math.PI; | ||
| if (h < 0) { | ||
| h += 360; | ||
| } | ||
| const c = Math.sqrt(a * a + b * b); | ||
| return [l, c, h]; | ||
| }; | ||
| convert.lch.lab = function(lch) { | ||
| const l = lch[0]; | ||
| const c = lch[1]; | ||
| const h = lch[2]; | ||
| const hr = h / 360 * 2 * Math.PI; | ||
| const a = c * Math.cos(hr); | ||
| const b = c * Math.sin(hr); | ||
| return [l, a, b]; | ||
| }; | ||
| convert.rgb.ansi16 = function(args, saturation = null) { | ||
| const [r, g, b] = args; | ||
| let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; | ||
| value = Math.round(value / 50); | ||
| if (value === 0) { | ||
| return 30; | ||
| } | ||
| let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); | ||
| if (value === 2) { | ||
| ansi += 60; | ||
| } | ||
| return ansi; | ||
| }; | ||
| convert.hsv.ansi16 = function(args) { | ||
| return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); | ||
| }; | ||
| convert.rgb.ansi256 = function(args) { | ||
| const r = args[0]; | ||
| const g = args[1]; | ||
| const b = args[2]; | ||
| if (r >> 4 === g >> 4 && g >> 4 === b >> 4) { | ||
| if (r < 8) { | ||
| return 16; | ||
| } | ||
| if (r > 248) { | ||
| return 231; | ||
| } | ||
| return Math.round((r - 8) / 247 * 24) + 232; | ||
| } | ||
| const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); | ||
| return ansi; | ||
| }; | ||
| convert.ansi16.rgb = function(args) { | ||
| args = args[0]; | ||
| let color = args % 10; | ||
| if (color === 0 || color === 7) { | ||
| if (args > 50) { | ||
| color += 3.5; | ||
| } | ||
| color = color / 10.5 * 255; | ||
| return [color, color, color]; | ||
| } | ||
| const mult = (Math.trunc(args > 50) + 1) * 0.5; | ||
| const r = (color & 1) * mult * 255; | ||
| const g = (color >> 1 & 1) * mult * 255; | ||
| const b = (color >> 2 & 1) * mult * 255; | ||
| return [r, g, b]; | ||
| }; | ||
| convert.ansi256.rgb = function(args) { | ||
| args = args[0]; | ||
| if (args >= 232) { | ||
| const c = (args - 232) * 10 + 8; | ||
| return [c, c, c]; | ||
| } | ||
| args -= 16; | ||
| let rem; | ||
| const r = Math.floor(args / 36) / 5 * 255; | ||
| const g = Math.floor((rem = args % 36) / 6) / 5 * 255; | ||
| const b = rem % 6 / 5 * 255; | ||
| return [r, g, b]; | ||
| }; | ||
| convert.rgb.hex = function(args) { | ||
| const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255); | ||
| const string = integer.toString(16).toUpperCase(); | ||
| return "000000".slice(string.length) + string; | ||
| }; | ||
| convert.hex.rgb = function(args) { | ||
| const match = args.toString(16).match(/[a-f\d]{6}|[a-f\d]{3}/i); | ||
| if (!match) { | ||
| return [0, 0, 0]; | ||
| } | ||
| let colorString = match[0]; | ||
| if (match[0].length === 3) { | ||
| colorString = [...colorString].map((char) => char + char).join(""); | ||
| } | ||
| const integer = Number.parseInt(colorString, 16); | ||
| const r = integer >> 16 & 255; | ||
| const g = integer >> 8 & 255; | ||
| const b = integer & 255; | ||
| return [r, g, b]; | ||
| }; | ||
| convert.rgb.hcg = function(rgb) { | ||
| const r = rgb[0] / 255; | ||
| const g = rgb[1] / 255; | ||
| const b = rgb[2] / 255; | ||
| const max = Math.max(Math.max(r, g), b); | ||
| const min = Math.min(Math.min(r, g), b); | ||
| const chroma = max - min; | ||
| let hue; | ||
| const grayscale = chroma < 1 ? min / (1 - chroma) : 0; | ||
| if (chroma <= 0) { | ||
| hue = 0; | ||
| } else if (max === r) { | ||
| hue = (g - b) / chroma % 6; | ||
| } else if (max === g) { | ||
| hue = 2 + (b - r) / chroma; | ||
| } else { | ||
| hue = 4 + (r - g) / chroma; | ||
| } | ||
| hue /= 6; | ||
| hue %= 1; | ||
| return [hue * 360, chroma * 100, grayscale * 100]; | ||
| }; | ||
| convert.hsl.hcg = function(hsl) { | ||
| const s = hsl[1] / 100; | ||
| const l = hsl[2] / 100; | ||
| const c = l < 0.5 ? 2 * s * l : 2 * s * (1 - l); | ||
| let f = 0; | ||
| if (c < 1) { | ||
| f = (l - 0.5 * c) / (1 - c); | ||
| } | ||
| return [hsl[0], c * 100, f * 100]; | ||
| }; | ||
| convert.hsv.hcg = function(hsv) { | ||
| const s = hsv[1] / 100; | ||
| const v = hsv[2] / 100; | ||
| const c = s * v; | ||
| let f = 0; | ||
| if (c < 1) { | ||
| f = (v - c) / (1 - c); | ||
| } | ||
| return [hsv[0], c * 100, f * 100]; | ||
| }; | ||
| convert.hcg.rgb = function(hcg) { | ||
| const h = hcg[0] / 360; | ||
| const c = hcg[1] / 100; | ||
| const g = hcg[2] / 100; | ||
| if (c === 0) { | ||
| return [g * 255, g * 255, g * 255]; | ||
| } | ||
| const pure = [0, 0, 0]; | ||
| const hi = h % 1 * 6; | ||
| const v = hi % 1; | ||
| const w = 1 - v; | ||
| let mg = 0; | ||
| switch (Math.floor(hi)) { | ||
| case 0: { | ||
| pure[0] = 1; | ||
| pure[1] = v; | ||
| pure[2] = 0; | ||
| break; | ||
| } | ||
| case 1: { | ||
| pure[0] = w; | ||
| pure[1] = 1; | ||
| pure[2] = 0; | ||
| break; | ||
| } | ||
| case 2: { | ||
| pure[0] = 0; | ||
| pure[1] = 1; | ||
| pure[2] = v; | ||
| break; | ||
| } | ||
| case 3: { | ||
| pure[0] = 0; | ||
| pure[1] = w; | ||
| pure[2] = 1; | ||
| break; | ||
| } | ||
| case 4: { | ||
| pure[0] = v; | ||
| pure[1] = 0; | ||
| pure[2] = 1; | ||
| break; | ||
| } | ||
| default: { | ||
| pure[0] = 1; | ||
| pure[1] = 0; | ||
| pure[2] = w; | ||
| } | ||
| } | ||
| mg = (1 - c) * g; | ||
| return [ | ||
| (c * pure[0] + mg) * 255, | ||
| (c * pure[1] + mg) * 255, | ||
| (c * pure[2] + mg) * 255 | ||
| ]; | ||
| }; | ||
| convert.hcg.hsv = function(hcg) { | ||
| const c = hcg[1] / 100; | ||
| const g = hcg[2] / 100; | ||
| const v = c + g * (1 - c); | ||
| let f = 0; | ||
| if (v > 0) { | ||
| f = c / v; | ||
| } | ||
| return [hcg[0], f * 100, v * 100]; | ||
| }; | ||
| convert.hcg.hsl = function(hcg) { | ||
| const c = hcg[1] / 100; | ||
| const g = hcg[2] / 100; | ||
| const l = g * (1 - c) + 0.5 * c; | ||
| let s = 0; | ||
| if (l > 0 && l < 0.5) { | ||
| s = c / (2 * l); | ||
| } else if (l >= 0.5 && l < 1) { | ||
| s = c / (2 * (1 - l)); | ||
| } | ||
| return [hcg[0], s * 100, l * 100]; | ||
| }; | ||
| convert.hcg.hwb = function(hcg) { | ||
| const c = hcg[1] / 100; | ||
| const g = hcg[2] / 100; | ||
| const v = c + g * (1 - c); | ||
| return [hcg[0], (v - c) * 100, (1 - v) * 100]; | ||
| }; | ||
| convert.hwb.hcg = function(hwb) { | ||
| const w = hwb[1] / 100; | ||
| const b = hwb[2] / 100; | ||
| const v = 1 - b; | ||
| const c = v - w; | ||
| let g = 0; | ||
| if (c < 1) { | ||
| g = (v - c) / (1 - c); | ||
| } | ||
| return [hwb[0], c * 100, g * 100]; | ||
| }; | ||
| convert.apple.rgb = function(apple) { | ||
| return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; | ||
| }; | ||
| convert.rgb.apple = function(rgb) { | ||
| return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; | ||
| }; | ||
| convert.gray.rgb = function(args) { | ||
| return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; | ||
| }; | ||
| convert.gray.hsl = function(args) { | ||
| return [0, 0, args[0]]; | ||
| }; | ||
| convert.gray.hsv = convert.gray.hsl; | ||
| convert.gray.hwb = function(gray) { | ||
| return [0, 100, gray[0]]; | ||
| }; | ||
| convert.gray.cmyk = function(gray) { | ||
| return [0, 0, 0, gray[0]]; | ||
| }; | ||
| convert.gray.lab = function(gray) { | ||
| return [gray[0], 0, 0]; | ||
| }; | ||
| convert.gray.hex = function(gray) { | ||
| const value = Math.round(gray[0] / 100 * 255) & 255; | ||
| const integer = (value << 16) + (value << 8) + value; | ||
| const string = integer.toString(16).toUpperCase(); | ||
| return "000000".slice(string.length) + string; | ||
| }; | ||
| convert.rgb.gray = function(rgb) { | ||
| const value = (rgb[0] + rgb[1] + rgb[2]) / 3; | ||
| return [value / 255 * 100]; | ||
| }; | ||
| // node_modules/color-convert/route.js | ||
| function buildGraph() { | ||
| const graph = {}; | ||
| const models2 = Object.keys(conversions_default); | ||
| for (let { length } = models2, i = 0; i < length; i++) { | ||
| graph[models2[i]] = { | ||
| // http://jsperf.com/1-vs-infinity | ||
| // micro-opt, but this is simple. | ||
| distance: -1, | ||
| parent: null | ||
| }; | ||
| } | ||
| return graph; | ||
| } | ||
| function deriveBFS(fromModel) { | ||
| const graph = buildGraph(); | ||
| const queue = [fromModel]; | ||
| graph[fromModel].distance = 0; | ||
| while (queue.length > 0) { | ||
| const current = queue.pop(); | ||
| const adjacents = Object.keys(conversions_default[current]); | ||
| for (let { length } = adjacents, i = 0; i < length; i++) { | ||
| const adjacent = adjacents[i]; | ||
| const node = graph[adjacent]; | ||
| if (node.distance === -1) { | ||
| node.distance = graph[current].distance + 1; | ||
| node.parent = current; | ||
| queue.unshift(adjacent); | ||
| } | ||
| } | ||
| } | ||
| return graph; | ||
| } | ||
| function link(from, to) { | ||
| return function(args) { | ||
| return to(from(args)); | ||
| }; | ||
| } | ||
| function wrapConversion(toModel, graph) { | ||
| const path = [graph[toModel].parent, toModel]; | ||
| let fn = conversions_default[graph[toModel].parent][toModel]; | ||
| let cur = graph[toModel].parent; | ||
| while (graph[cur].parent) { | ||
| path.unshift(graph[cur].parent); | ||
| fn = link(conversions_default[graph[cur].parent][cur], fn); | ||
| cur = graph[cur].parent; | ||
| } | ||
| fn.conversion = path; | ||
| return fn; | ||
| } | ||
| function route(fromModel) { | ||
| const graph = deriveBFS(fromModel); | ||
| const conversion = {}; | ||
| const models2 = Object.keys(graph); | ||
| for (let { length } = models2, i = 0; i < length; i++) { | ||
| const toModel = models2[i]; | ||
| const node = graph[toModel]; | ||
| if (node.parent === null) { | ||
| continue; | ||
| } | ||
| conversion[toModel] = wrapConversion(toModel, graph); | ||
| } | ||
| return conversion; | ||
| } | ||
| var route_default = route; | ||
| // node_modules/color-convert/index.js | ||
| var convert2 = {}; | ||
| var models = Object.keys(conversions_default); | ||
| function wrapRaw(fn) { | ||
| const wrappedFn = function(...args) { | ||
| const arg0 = args[0]; | ||
| if (arg0 === void 0 || arg0 === null) { | ||
| return arg0; | ||
| } | ||
| if (arg0.length > 1) { | ||
| args = arg0; | ||
| } | ||
| return fn(args); | ||
| }; | ||
| if ("conversion" in fn) { | ||
| wrappedFn.conversion = fn.conversion; | ||
| } | ||
| return wrappedFn; | ||
| } | ||
| function wrapRounded(fn) { | ||
| const wrappedFn = function(...args) { | ||
| const arg0 = args[0]; | ||
| if (arg0 === void 0 || arg0 === null) { | ||
| return arg0; | ||
| } | ||
| if (arg0.length > 1) { | ||
| args = arg0; | ||
| } | ||
| const result = fn(args); | ||
| if (typeof result === "object") { | ||
| for (let { length } = result, i = 0; i < length; i++) { | ||
| result[i] = Math.round(result[i]); | ||
| } | ||
| } | ||
| return result; | ||
| }; | ||
| if ("conversion" in fn) { | ||
| wrappedFn.conversion = fn.conversion; | ||
| } | ||
| return wrappedFn; | ||
| } | ||
| for (const fromModel of models) { | ||
| convert2[fromModel] = {}; | ||
| Object.defineProperty(convert2[fromModel], "channels", { value: conversions_default[fromModel].channels }); | ||
| Object.defineProperty(convert2[fromModel], "labels", { value: conversions_default[fromModel].labels }); | ||
| const routes = route_default(fromModel); | ||
| const routeModels = Object.keys(routes); | ||
| for (const toModel of routeModels) { | ||
| const fn = routes[toModel]; | ||
| convert2[fromModel][toModel] = wrapRounded(fn); | ||
| convert2[fromModel][toModel].raw = wrapRaw(fn); | ||
| } | ||
| } | ||
| var color_convert_default = convert2; | ||
| // node_modules/color/index.js | ||
| var 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" | ||
| ]; | ||
| var hashedModelKeys = {}; | ||
| for (const model of Object.keys(color_convert_default)) { | ||
| hashedModelKeys[[...color_convert_default[model].labels].sort().join("")] = model; | ||
| } | ||
| var 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 color_convert_default)) { | ||
| throw new Error("Unknown model: " + model); | ||
| } | ||
| let i; | ||
| let channels; | ||
| if (object == null) { | ||
| 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 = color_string_default.get(object); | ||
| if (result === null) { | ||
| throw new Error("Unable to parse color from string: " + object); | ||
| } | ||
| this.model = result.model; | ||
| channels = color_convert_default[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 = color_convert_default[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.model = "rgb"; | ||
| this.color = [ | ||
| object >> 16 & 255, | ||
| object >> 8 & 255, | ||
| object & 255 | ||
| ]; | ||
| 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 } = color_convert_default[this.model]; | ||
| const color = []; | ||
| for (i = 0; i < labels.length; i++) { | ||
| color.push(object[labels[i]]); | ||
| } | ||
| this.color = zeroArray(color); | ||
| } | ||
| if (limiters[this.model]) { | ||
| channels = color_convert_default[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 color_string_default.to ? this : this.rgb(); | ||
| self = self.round(typeof places === "number" ? places : 1); | ||
| const arguments_ = self.valpha === 1 ? self.color : [...self.color, this.valpha]; | ||
| return color_string_default.to[self.model](...arguments_); | ||
| }, | ||
| percentString(places) { | ||
| const self = this.rgb().round(typeof places === "number" ? places : 1); | ||
| const arguments_ = self.valpha === 1 ? self.color : [...self.color, this.valpha]; | ||
| return color_string_default.to.rgb.percent(...arguments_); | ||
| }, | ||
| array() { | ||
| return this.valpha === 1 ? [...this.color] : [...this.color, this.valpha]; | ||
| }, | ||
| object() { | ||
| const result = {}; | ||
| const { channels } = color_convert_default[this.model]; | ||
| const { labels } = color_convert_default[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 !== void 0) { | ||
| 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 !== void 0) { | ||
| return new Color(value); | ||
| } | ||
| return color_convert_default[this.model].keyword(this.color); | ||
| }, | ||
| hex(value) { | ||
| if (value !== void 0) { | ||
| return new Color(value); | ||
| } | ||
| return color_string_default.to.hex(...this.rgb().round().color); | ||
| }, | ||
| hexa(value) { | ||
| if (value !== void 0) { | ||
| 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 color_string_default.to.hex(...rgbArray) + alphaHex; | ||
| }, | ||
| rgbNumber() { | ||
| const rgb = this.rgb().color; | ||
| return (rgb[0] & 255) << 16 | (rgb[1] & 255) << 8 | rgb[2] & 255; | ||
| }, | ||
| luminosity() { | ||
| 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) { | ||
| 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) { | ||
| const contrastRatio = this.contrast(color2); | ||
| if (contrastRatio >= 7) { | ||
| return "AAA"; | ||
| } | ||
| return contrastRatio >= 4.5 ? "AA" : ""; | ||
| }, | ||
| isDark() { | ||
| const rgb = this.rgb().color; | ||
| const yiq = (rgb[0] * 2126 + rgb[1] * 7152 + rgb[2] * 722) / 1e4; | ||
| 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() { | ||
| 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) { | ||
| 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 === void 0 ? 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) | ||
| ); | ||
| } | ||
| }; | ||
| for (const model of Object.keys(color_convert_default)) { | ||
| if (skippedModels.includes(model)) { | ||
| continue; | ||
| } | ||
| const { channels } = color_convert_default[model]; | ||
| Color.prototype[model] = function(...arguments_) { | ||
| if (this.model === model) { | ||
| return new Color(this); | ||
| } | ||
| if (arguments_.length > 0) { | ||
| return new Color(arguments_, model); | ||
| } | ||
| return new Color([...assertArray(color_convert_default[this.model][model].raw(this.color)), this.valpha], model); | ||
| }; | ||
| Color[model] = function(...arguments_) { | ||
| let color = arguments_[0]; | ||
| if (typeof color === "number") { | ||
| color = zeroArray(arguments_, 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] ||= [])[channel] = modifier; | ||
| } | ||
| model = model[0]; | ||
| return function(value) { | ||
| let result; | ||
| if (value !== void 0) { | ||
| 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; | ||
| } | ||
| var index_default = Color; |
| module.exports = require("./color.cjs").default; |
| // Generated by dts-bundle-generator v9.5.1 | ||
| type Channels = number; | ||
| type RGB = [ | ||
| r: number, | ||
| g: number, | ||
| b: number | ||
| ]; | ||
| type HSL = [ | ||
| h: number, | ||
| s: number, | ||
| l: number | ||
| ]; | ||
| type HSV = [ | ||
| h: number, | ||
| s: number, | ||
| v: number | ||
| ]; | ||
| type CMYK = [ | ||
| c: number, | ||
| m: number, | ||
| y: number, | ||
| k: number | ||
| ]; | ||
| type LAB = [ | ||
| l: number, | ||
| a: number, | ||
| b: number | ||
| ]; | ||
| type LCH = [ | ||
| l: number, | ||
| c: number, | ||
| h: number | ||
| ]; | ||
| type HCG = [ | ||
| h: number, | ||
| c: number, | ||
| g: number | ||
| ]; | ||
| type HWB = [ | ||
| h: number, | ||
| w: number, | ||
| b: number | ||
| ]; | ||
| type XYZ = [ | ||
| x: number, | ||
| y: number, | ||
| z: number | ||
| ]; | ||
| type Apple = [ | ||
| r16: number, | ||
| g16: number, | ||
| b16: number | ||
| ]; | ||
| type Gray = [ | ||
| gray: number | ||
| ]; | ||
| type ANSI16 = number; | ||
| type ANSI256 = number; | ||
| type Keyword = string; | ||
| type HEX = string; | ||
| declare namespace route { | ||
| type rgb = { | ||
| hsl(from: RGB): HSL; | ||
| hsl(...from: RGB): HSL; | ||
| hsl(from: RGB): HSL; | ||
| hsl(...from: RGB): HSL; | ||
| hsv(from: RGB): HSV; | ||
| hsv(...from: RGB): HSV; | ||
| hwb(from: RGB): HWB; | ||
| hwb(...from: RGB): HWB; | ||
| cmyk(from: RGB): CMYK; | ||
| cmyk(...from: RGB): CMYK; | ||
| xyz(from: RGB): XYZ; | ||
| xyz(...from: RGB): XYZ; | ||
| lab(from: RGB): LAB; | ||
| lab(...from: RGB): LAB; | ||
| lch(from: RGB): LCH; | ||
| lch(...from: RGB): LCH; | ||
| hex(from: RGB): HEX; | ||
| hex(...from: RGB): HEX; | ||
| keyword(from: RGB): Keyword; | ||
| keyword(...from: RGB): Keyword; | ||
| ansi16(from: RGB): ANSI16; | ||
| ansi16(...from: RGB): ANSI16; | ||
| ansi256(from: RGB): ANSI256; | ||
| ansi256(...from: RGB): ANSI256; | ||
| hcg(from: RGB): HCG; | ||
| hcg(...from: RGB): HCG; | ||
| apple(from: RGB): Apple; | ||
| apple(...from: RGB): Apple; | ||
| gray(from: RGB): Gray; | ||
| gray(...from: RGB): Gray; | ||
| }; | ||
| type hsl = { | ||
| rgb(from: HSL): RGB; | ||
| rgb(...from: HSL): RGB; | ||
| hsv(from: HSL): HSV; | ||
| hsv(...from: HSL): HSV; | ||
| hwb(from: HSL): HWB; | ||
| hwb(...from: HSL): HWB; | ||
| cmyk(from: HSL): CMYK; | ||
| cmyk(...from: HSL): CMYK; | ||
| xyz(from: HSL): XYZ; | ||
| xyz(...from: HSL): XYZ; | ||
| lab(from: HSL): LAB; | ||
| lab(...from: HSL): LAB; | ||
| lch(from: HSL): LCH; | ||
| lch(...from: HSL): LCH; | ||
| hex(from: HSL): HEX; | ||
| hex(...from: HSL): HEX; | ||
| keyword(from: HSL): Keyword; | ||
| keyword(...from: HSL): Keyword; | ||
| ansi16(from: HSL): ANSI16; | ||
| ansi16(...from: HSL): ANSI16; | ||
| ansi256(from: HSL): ANSI256; | ||
| ansi256(...from: HSL): ANSI256; | ||
| hcg(from: HSL): HCG; | ||
| hcg(...from: HSL): HCG; | ||
| apple(from: HSL): Apple; | ||
| apple(...from: HSL): Apple; | ||
| gray(from: HSL): Gray; | ||
| gray(...from: HSL): Gray; | ||
| }; | ||
| type hsv = { | ||
| rgb(from: HSV): RGB; | ||
| rgb(...from: HSV): RGB; | ||
| hsl(from: HSV): HSL; | ||
| hsl(...from: HSV): HSL; | ||
| hwb(from: HSV): HWB; | ||
| hwb(...from: HSV): HWB; | ||
| cmyk(from: HSV): CMYK; | ||
| cmyk(...from: HSV): CMYK; | ||
| xyz(from: HSV): XYZ; | ||
| xyz(...from: HSV): XYZ; | ||
| lab(from: HSV): LAB; | ||
| lab(...from: HSV): LAB; | ||
| lch(from: HSV): LCH; | ||
| lch(...from: HSV): LCH; | ||
| hex(from: HSV): HEX; | ||
| hex(...from: HSV): HEX; | ||
| keyword(from: HSV): Keyword; | ||
| keyword(...from: HSV): Keyword; | ||
| ansi16(from: HSV): ANSI16; | ||
| ansi16(...from: HSV): ANSI16; | ||
| ansi256(from: HSV): ANSI256; | ||
| ansi256(...from: HSV): ANSI256; | ||
| hcg(from: HSV): HCG; | ||
| hcg(...from: HSV): HCG; | ||
| apple(from: HSV): Apple; | ||
| apple(...from: HSV): Apple; | ||
| gray(from: HSV): Gray; | ||
| gray(...from: HSV): Gray; | ||
| }; | ||
| type hwb = { | ||
| rgb(from: HWB): RGB; | ||
| rgb(...from: HWB): RGB; | ||
| hsl(from: HWB): HSL; | ||
| hsl(...from: HWB): HSL; | ||
| hsv(from: HWB): HSV; | ||
| hsv(...from: HWB): HSV; | ||
| cmyk(from: HWB): CMYK; | ||
| cmyk(...from: HWB): CMYK; | ||
| xyz(from: HWB): XYZ; | ||
| xyz(...from: HWB): XYZ; | ||
| lab(from: HWB): LAB; | ||
| lab(...from: HWB): LAB; | ||
| lch(from: HWB): LCH; | ||
| lch(...from: HWB): LCH; | ||
| hex(from: HWB): HEX; | ||
| hex(...from: HWB): HEX; | ||
| keyword(from: HWB): Keyword; | ||
| keyword(...from: HWB): Keyword; | ||
| ansi16(from: HWB): ANSI16; | ||
| ansi16(...from: HWB): ANSI16; | ||
| ansi256(from: HWB): ANSI256; | ||
| ansi256(...from: HWB): ANSI256; | ||
| hcg(from: HWB): HCG; | ||
| hcg(...from: HWB): HCG; | ||
| apple(from: HWB): Apple; | ||
| apple(...from: HWB): Apple; | ||
| gray(from: HWB): Gray; | ||
| gray(...from: HWB): Gray; | ||
| }; | ||
| type cmyk = { | ||
| rgb(from: CMYK): RGB; | ||
| rgb(...from: CMYK): RGB; | ||
| hsl(from: CMYK): HSL; | ||
| hsl(...from: CMYK): HSL; | ||
| hsv(from: CMYK): HSV; | ||
| hsv(...from: CMYK): HSV; | ||
| hwb(from: CMYK): HWB; | ||
| hwb(...from: CMYK): HWB; | ||
| xyz(from: CMYK): XYZ; | ||
| xyz(...from: CMYK): XYZ; | ||
| lab(from: CMYK): LAB; | ||
| lab(...from: CMYK): LAB; | ||
| lch(from: CMYK): LCH; | ||
| lch(...from: CMYK): LCH; | ||
| hex(from: CMYK): HEX; | ||
| hex(...from: CMYK): HEX; | ||
| keyword(from: CMYK): Keyword; | ||
| keyword(...from: CMYK): Keyword; | ||
| ansi16(from: CMYK): ANSI16; | ||
| ansi16(...from: CMYK): ANSI16; | ||
| ansi256(from: CMYK): ANSI256; | ||
| ansi256(...from: CMYK): ANSI256; | ||
| hcg(from: CMYK): HCG; | ||
| hcg(...from: CMYK): HCG; | ||
| apple(from: CMYK): Apple; | ||
| apple(...from: CMYK): Apple; | ||
| gray(from: CMYK): Gray; | ||
| gray(...from: CMYK): Gray; | ||
| }; | ||
| type xyz = { | ||
| rgb(from: XYZ): RGB; | ||
| rgb(...from: XYZ): RGB; | ||
| hsl(from: XYZ): HSL; | ||
| hsl(...from: XYZ): HSL; | ||
| hsv(from: XYZ): HSV; | ||
| hsv(...from: XYZ): HSV; | ||
| hwb(from: XYZ): HWB; | ||
| hwb(...from: XYZ): HWB; | ||
| cmyk(from: XYZ): CMYK; | ||
| cmyk(...from: XYZ): CMYK; | ||
| lab(from: XYZ): LAB; | ||
| lab(...from: XYZ): LAB; | ||
| lch(from: XYZ): LCH; | ||
| lch(...from: XYZ): LCH; | ||
| hex(from: XYZ): HEX; | ||
| hex(...from: XYZ): HEX; | ||
| keyword(from: XYZ): Keyword; | ||
| keyword(...from: XYZ): Keyword; | ||
| ansi16(from: XYZ): ANSI16; | ||
| ansi16(...from: XYZ): ANSI16; | ||
| ansi256(from: XYZ): ANSI256; | ||
| ansi256(...from: XYZ): ANSI256; | ||
| hcg(from: XYZ): HCG; | ||
| hcg(...from: XYZ): HCG; | ||
| apple(from: XYZ): Apple; | ||
| apple(...from: XYZ): Apple; | ||
| gray(from: XYZ): Gray; | ||
| gray(...from: XYZ): Gray; | ||
| }; | ||
| type lab = { | ||
| rgb(from: LAB): RGB; | ||
| rgb(...from: LAB): RGB; | ||
| hsl(from: LAB): HSL; | ||
| hsl(...from: LAB): HSL; | ||
| hsv(from: LAB): HSV; | ||
| hsv(...from: LAB): HSV; | ||
| hwb(from: LAB): HWB; | ||
| hwb(...from: LAB): HWB; | ||
| cmyk(from: LAB): CMYK; | ||
| cmyk(...from: LAB): CMYK; | ||
| xyz(from: LAB): XYZ; | ||
| xyz(...from: LAB): XYZ; | ||
| lch(from: LAB): LCH; | ||
| lch(...from: LAB): LCH; | ||
| hex(from: LAB): HEX; | ||
| hex(...from: LAB): HEX; | ||
| keyword(from: LAB): Keyword; | ||
| keyword(...from: LAB): Keyword; | ||
| ansi16(from: LAB): ANSI16; | ||
| ansi16(...from: LAB): ANSI16; | ||
| ansi256(from: LAB): ANSI256; | ||
| ansi256(...from: LAB): ANSI256; | ||
| hcg(from: LAB): HCG; | ||
| hcg(...from: LAB): HCG; | ||
| apple(from: LAB): Apple; | ||
| apple(...from: LAB): Apple; | ||
| gray(from: LAB): Gray; | ||
| gray(...from: LAB): Gray; | ||
| }; | ||
| type lch = { | ||
| rgb(from: LCH): RGB; | ||
| rgb(...from: LCH): RGB; | ||
| hsl(from: LCH): HSL; | ||
| hsl(...from: LCH): HSL; | ||
| hsv(from: LCH): HSV; | ||
| hsv(...from: LCH): HSV; | ||
| hwb(from: LCH): HWB; | ||
| hwb(...from: LCH): HWB; | ||
| cmyk(from: LCH): CMYK; | ||
| cmyk(...from: LCH): CMYK; | ||
| xyz(from: LCH): XYZ; | ||
| xyz(...from: LCH): XYZ; | ||
| lab(from: LCH): LAB; | ||
| lab(...from: LCH): LAB; | ||
| hex(from: LCH): HEX; | ||
| hex(...from: LCH): HEX; | ||
| keyword(from: LCH): Keyword; | ||
| keyword(...from: LCH): Keyword; | ||
| ansi16(from: LCH): ANSI16; | ||
| ansi16(...from: LCH): ANSI16; | ||
| ansi256(from: LCH): ANSI256; | ||
| ansi256(...from: LCH): ANSI256; | ||
| hcg(from: LCH): HCG; | ||
| hcg(...from: LCH): HCG; | ||
| apple(from: LCH): Apple; | ||
| apple(...from: LCH): Apple; | ||
| gray(from: LCH): Gray; | ||
| gray(...from: LCH): Gray; | ||
| }; | ||
| type hex = { | ||
| rgb(from: HEX): RGB; | ||
| hsl(from: HEX): HSL; | ||
| hsv(from: HEX): HSV; | ||
| hwb(from: HEX): HWB; | ||
| cmyk(from: HEX): CMYK; | ||
| xyz(from: HEX): XYZ; | ||
| lab(from: HEX): LAB; | ||
| lch(from: HEX): LCH; | ||
| keyword(from: HEX): Keyword; | ||
| ansi16(from: HEX): ANSI16; | ||
| ansi256(from: HEX): ANSI256; | ||
| hcg(from: HEX): HCG; | ||
| apple(from: HEX): Apple; | ||
| gray(from: HEX): Gray; | ||
| }; | ||
| type keyword = { | ||
| rgb(from: Keyword): RGB; | ||
| hsl(from: Keyword): HSL; | ||
| hsv(from: Keyword): HSV; | ||
| hwb(from: Keyword): HWB; | ||
| cmyk(from: Keyword): CMYK; | ||
| xyz(from: Keyword): XYZ; | ||
| lab(from: Keyword): LAB; | ||
| lch(from: Keyword): LCH; | ||
| hex(from: Keyword): HEX; | ||
| ansi16(from: Keyword): ANSI16; | ||
| ansi256(from: Keyword): ANSI256; | ||
| hcg(from: Keyword): HCG; | ||
| apple(from: Keyword): Apple; | ||
| gray(from: Keyword): Gray; | ||
| }; | ||
| type ansi16 = { | ||
| rgb(from: ANSI16): RGB; | ||
| hsl(from: ANSI16): HSL; | ||
| hsv(from: ANSI16): HSV; | ||
| hwb(from: ANSI16): HWB; | ||
| cmyk(from: ANSI16): CMYK; | ||
| xyz(from: ANSI16): XYZ; | ||
| lab(from: ANSI16): LAB; | ||
| lch(from: ANSI16): LCH; | ||
| hex(from: ANSI16): HEX; | ||
| keyword(from: ANSI16): Keyword; | ||
| ansi256(from: ANSI16): ANSI256; | ||
| hcg(from: ANSI16): HCG; | ||
| apple(from: ANSI16): Apple; | ||
| gray(from: ANSI16): Gray; | ||
| }; | ||
| type ansi256 = { | ||
| rgb(from: ANSI256): RGB; | ||
| hsl(from: ANSI256): HSL; | ||
| hsv(from: ANSI256): HSV; | ||
| hwb(from: ANSI256): HWB; | ||
| cmyk(from: ANSI256): CMYK; | ||
| xyz(from: ANSI256): XYZ; | ||
| lab(from: ANSI256): LAB; | ||
| lch(from: ANSI256): LCH; | ||
| hex(from: ANSI256): HEX; | ||
| keyword(from: ANSI256): Keyword; | ||
| ansi16(from: ANSI256): ANSI16; | ||
| hcg(from: ANSI256): HCG; | ||
| apple(from: ANSI256): Apple; | ||
| gray(from: ANSI256): Gray; | ||
| }; | ||
| type hcg = { | ||
| rgb(from: HCG): RGB; | ||
| rgb(...from: HCG): RGB; | ||
| hsl(from: HCG): HSL; | ||
| hsl(...from: HCG): HSL; | ||
| hsv(from: HCG): HSV; | ||
| hsv(...from: HCG): HSV; | ||
| hwb(from: HCG): HWB; | ||
| hwb(...from: HCG): HWB; | ||
| cmyk(from: HCG): CMYK; | ||
| cmyk(...from: HCG): CMYK; | ||
| xyz(from: HCG): XYZ; | ||
| xyz(...from: HCG): XYZ; | ||
| lab(from: HCG): LAB; | ||
| lab(...from: HCG): LAB; | ||
| lch(from: HCG): LCH; | ||
| lch(...from: HCG): LCH; | ||
| hex(from: HCG): HEX; | ||
| hex(...from: HCG): HEX; | ||
| keyword(from: HCG): Keyword; | ||
| keyword(...from: HCG): Keyword; | ||
| ansi16(from: HCG): ANSI16; | ||
| ansi16(...from: HCG): ANSI16; | ||
| ansi256(from: HCG): ANSI256; | ||
| ansi256(...from: HCG): ANSI256; | ||
| apple(from: HCG): Apple; | ||
| apple(...from: HCG): Apple; | ||
| gray(from: HCG): Gray; | ||
| gray(...from: HCG): Gray; | ||
| }; | ||
| type apple = { | ||
| rgb(from: Apple): RGB; | ||
| rgb(...from: Apple): RGB; | ||
| hsl(from: Apple): HSL; | ||
| hsl(...from: Apple): HSL; | ||
| hsv(from: Apple): HSV; | ||
| hsv(...from: Apple): HSV; | ||
| hwb(from: Apple): HWB; | ||
| hwb(...from: Apple): HWB; | ||
| cmyk(from: Apple): CMYK; | ||
| cmyk(...from: Apple): CMYK; | ||
| xyz(from: Apple): XYZ; | ||
| xyz(...from: Apple): XYZ; | ||
| lab(from: Apple): LAB; | ||
| lab(...from: Apple): LAB; | ||
| lch(from: Apple): LCH; | ||
| lch(...from: Apple): LCH; | ||
| hex(from: Apple): HEX; | ||
| hex(...from: Apple): HEX; | ||
| keyword(from: Apple): Keyword; | ||
| keyword(...from: Apple): Keyword; | ||
| ansi16(from: Apple): ANSI16; | ||
| ansi16(...from: Apple): ANSI16; | ||
| ansi256(from: Apple): ANSI256; | ||
| ansi256(...from: Apple): ANSI256; | ||
| hcg(from: Apple): HCG; | ||
| hcg(...from: Apple): HCG; | ||
| gray(from: Apple): Gray; | ||
| gray(...from: Apple): Gray; | ||
| }; | ||
| type gray = { | ||
| rgb(from: Gray): RGB; | ||
| rgb(...from: Gray): RGB; | ||
| hsl(from: Gray): HSL; | ||
| hsl(...from: Gray): HSL; | ||
| hsv(from: Gray): HSV; | ||
| hsv(...from: Gray): HSV; | ||
| hwb(from: Gray): HWB; | ||
| hwb(...from: Gray): HWB; | ||
| cmyk(from: Gray): CMYK; | ||
| cmyk(...from: Gray): CMYK; | ||
| xyz(from: Gray): XYZ; | ||
| xyz(...from: Gray): XYZ; | ||
| lab(from: Gray): LAB; | ||
| lab(...from: Gray): LAB; | ||
| lch(from: Gray): LCH; | ||
| lch(...from: Gray): LCH; | ||
| hex(from: Gray): HEX; | ||
| hex(...from: Gray): HEX; | ||
| keyword(from: Gray): Keyword; | ||
| keyword(...from: Gray): Keyword; | ||
| ansi16(from: Gray): ANSI16; | ||
| ansi16(...from: Gray): ANSI16; | ||
| ansi256(from: Gray): ANSI256; | ||
| ansi256(...from: Gray): ANSI256; | ||
| hcg(from: Gray): HCG; | ||
| hcg(...from: Gray): HCG; | ||
| apple(from: Gray): Apple; | ||
| apple(...from: Gray): Apple; | ||
| }; | ||
| } | ||
| declare function route(fromModel: "rgb"): route.rgb; | ||
| declare function route(fromModel: "hsl"): route.hsl; | ||
| declare function route(fromModel: "hsv"): route.hsv; | ||
| declare function route(fromModel: "hwb"): route.hwb; | ||
| declare function route(fromModel: "cmyk"): route.cmyk; | ||
| declare function route(fromModel: "xyz"): route.xyz; | ||
| declare function route(fromModel: "lab"): route.lab; | ||
| declare function route(fromModel: "lch"): route.lch; | ||
| declare function route(fromModel: "hex"): route.hex; | ||
| declare function route(fromModel: "keyword"): route.keyword; | ||
| declare function route(fromModel: "ansi16"): route.ansi16; | ||
| declare function route(fromModel: "ansi256"): route.ansi256; | ||
| declare function route(fromModel: "hcg"): route.hcg; | ||
| declare function route(fromModel: "apple"): route.apple; | ||
| declare function route(fromModel: "gray"): route.gray; | ||
| type Convert = { | ||
| rgb: { | ||
| channels: Channels; | ||
| labels: "rgb"; | ||
| hsl: { | ||
| (...rgb: RGB): HSL; | ||
| raw: (...rgb: RGB) => HSL; | ||
| }; | ||
| hsv: { | ||
| (...rgb: RGB): HSV; | ||
| raw: (...rgb: RGB) => HSV; | ||
| }; | ||
| hwb: { | ||
| (...rgb: RGB): HWB; | ||
| raw: (...rgb: RGB) => HWB; | ||
| }; | ||
| hcg: { | ||
| (...rgb: RGB): HCG; | ||
| raw: (...rgb: RGB) => HCG; | ||
| }; | ||
| cmyk: { | ||
| (...rgb: RGB): CMYK; | ||
| raw: (...rgb: RGB) => CMYK; | ||
| }; | ||
| keyword: { | ||
| (...rgb: RGB): Keyword; | ||
| raw: (...rgb: RGB) => Keyword; | ||
| }; | ||
| ansi16: { | ||
| (...rgb: RGB): ANSI16; | ||
| raw: (...rgb: RGB) => ANSI16; | ||
| }; | ||
| ansi256: { | ||
| (...rgb: RGB): ANSI256; | ||
| raw: (...rgb: RGB) => ANSI256; | ||
| }; | ||
| apple: { | ||
| (...rgb: RGB): Apple; | ||
| raw: (...rgb: RGB) => Apple; | ||
| }; | ||
| hex: { | ||
| (...rgb: RGB): HEX; | ||
| raw: (...rgb: RGB) => HEX; | ||
| }; | ||
| gray: { | ||
| (...rgb: RGB): Gray; | ||
| raw: (...rgb: RGB) => Gray; | ||
| }; | ||
| } & route.rgb & { | ||
| [F in keyof route.rgb]: { | ||
| raw: route.rgb[F]; | ||
| }; | ||
| }; | ||
| keyword: { | ||
| channels: Channels; | ||
| rgb: { | ||
| (keyword: Keyword): RGB; | ||
| raw: (keyword: Keyword) => RGB; | ||
| }; | ||
| } & route.keyword & { | ||
| [F in keyof route.keyword]: { | ||
| raw: route.keyword[F]; | ||
| }; | ||
| }; | ||
| hsl: { | ||
| channels: Channels; | ||
| labels: "hsl"; | ||
| rgb: { | ||
| (...hsl: HSL): RGB; | ||
| raw: (...hsl: HSL) => RGB; | ||
| }; | ||
| hsv: { | ||
| (...hsl: HSL): HSV; | ||
| raw: (...hsl: HSL) => HSV; | ||
| }; | ||
| hcg: { | ||
| (...hsl: HSL): HCG; | ||
| raw: (...hsl: HSL) => HCG; | ||
| }; | ||
| } & route.hsl & { | ||
| [F in keyof route.hsl]: { | ||
| raw: route.hsl[F]; | ||
| }; | ||
| }; | ||
| hsv: { | ||
| channels: Channels; | ||
| labels: "hsv"; | ||
| hcg: { | ||
| (...hsv: HSV): HCG; | ||
| raw: (...hsv: HSV) => HCG; | ||
| }; | ||
| rgb: { | ||
| (...hsv: HSV): RGB; | ||
| raw: (...hsv: HSV) => RGB; | ||
| }; | ||
| hsv: { | ||
| (...hsv: HSV): HSV; | ||
| raw: (...hsv: HSV) => HSV; | ||
| }; | ||
| hsl: { | ||
| (...hsv: HSV): HSL; | ||
| raw: (...hsv: HSV) => HSL; | ||
| }; | ||
| hwb: { | ||
| (...hsv: HSV): HWB; | ||
| raw: (...hsv: HSV) => HWB; | ||
| }; | ||
| ansi16: { | ||
| (...hsv: HSV): ANSI16; | ||
| raw: (...hsv: HSV) => ANSI16; | ||
| }; | ||
| } & route.hsv & { | ||
| [F in keyof route.hsv]: { | ||
| raw: route.hsv[F]; | ||
| }; | ||
| }; | ||
| hwb: { | ||
| channels: Channels; | ||
| labels: "hwb"; | ||
| hcg: { | ||
| (...hwb: HWB): HCG; | ||
| raw: (...hwb: HWB) => HCG; | ||
| }; | ||
| rgb: { | ||
| (...hwb: HWB): RGB; | ||
| raw: (...hwb: HWB) => RGB; | ||
| }; | ||
| } & route.hwb & { | ||
| [F in keyof route.hwb]: { | ||
| raw: route.hwb[F]; | ||
| }; | ||
| }; | ||
| cmyk: { | ||
| channels: Channels; | ||
| labels: "cmyk"; | ||
| rgb: { | ||
| (...cmyk: CMYK): RGB; | ||
| raw: (...cmyk: CMYK) => RGB; | ||
| }; | ||
| } & route.cmyk & { | ||
| [F in keyof route.cmyk]: { | ||
| raw: route.cmyk[F]; | ||
| }; | ||
| }; | ||
| xyz: { | ||
| channels: Channels; | ||
| labels: "xyz"; | ||
| rgb: { | ||
| (...xyz: XYZ): RGB; | ||
| raw: (...xyz: XYZ) => RGB; | ||
| }; | ||
| lab: { | ||
| (...xyz: XYZ): LAB; | ||
| raw: (...xyz: XYZ) => LAB; | ||
| }; | ||
| } & route.xyz & { | ||
| [F in keyof route.xyz]: { | ||
| raw: route.xyz[F]; | ||
| }; | ||
| }; | ||
| lab: { | ||
| channels: Channels; | ||
| labels: "lab"; | ||
| xyz: { | ||
| (...lab: LAB): XYZ; | ||
| raw: (...lab: LAB) => XYZ; | ||
| }; | ||
| lch: { | ||
| (...lab: LAB): LCH; | ||
| raw: (...lab: LAB) => LCH; | ||
| }; | ||
| } & route.lab & { | ||
| [F in keyof route.lab]: { | ||
| raw: route.lab[F]; | ||
| }; | ||
| }; | ||
| lch: { | ||
| channels: Channels; | ||
| labels: "lch"; | ||
| lab: { | ||
| (...lch: LCH): LAB; | ||
| raw: (...lch: LCH) => LAB; | ||
| }; | ||
| } & route.lch & { | ||
| [F in keyof route.lch]: { | ||
| raw: route.lch[F]; | ||
| }; | ||
| }; | ||
| hex: { | ||
| channels: Channels; | ||
| labels: [ | ||
| "hex" | ||
| ]; | ||
| rgb: { | ||
| (hex: HEX): RGB; | ||
| raw: (hex: HEX) => RGB; | ||
| }; | ||
| } & route.hex & { | ||
| [F in keyof route.hex]: { | ||
| raw: route.hex[F]; | ||
| }; | ||
| }; | ||
| ansi16: { | ||
| channels: Channels; | ||
| labels: [ | ||
| "ansi16" | ||
| ]; | ||
| rgb: { | ||
| (ansi16: ANSI16): RGB; | ||
| raw: (ansi16: ANSI16) => RGB; | ||
| }; | ||
| } & route.ansi16 & { | ||
| [F in keyof route.ansi16]: { | ||
| raw: route.ansi16[F]; | ||
| }; | ||
| }; | ||
| ansi256: { | ||
| channels: Channels; | ||
| labels: [ | ||
| "ansi256" | ||
| ]; | ||
| rgb: { | ||
| (ansi256: ANSI256): RGB; | ||
| raw: (ansi256: ANSI256) => RGB; | ||
| }; | ||
| } & route.ansi256 & { | ||
| [F in keyof route.ansi256]: { | ||
| raw: route.ansi256[F]; | ||
| }; | ||
| }; | ||
| hcg: { | ||
| channels: Channels; | ||
| labels: [ | ||
| "h", | ||
| "c", | ||
| "g" | ||
| ]; | ||
| rgb: { | ||
| (...hcg: HCG): RGB; | ||
| raw: (...hcg: HCG) => RGB; | ||
| }; | ||
| hsv: { | ||
| (...hcg: HCG): HSV; | ||
| raw: (...hcg: HCG) => HSV; | ||
| }; | ||
| hwb: { | ||
| (...hcg: HCG): HWB; | ||
| raw: (...hcg: HCG) => HWB; | ||
| }; | ||
| } & route.hcg & { | ||
| [F in keyof route.hcg]: { | ||
| raw: route.hcg[F]; | ||
| }; | ||
| }; | ||
| apple: { | ||
| channels: Channels; | ||
| labels: [ | ||
| "r16", | ||
| "g16", | ||
| "b16" | ||
| ]; | ||
| rgb: { | ||
| (...apple: Apple): RGB; | ||
| raw: (...apple: Apple) => RGB; | ||
| }; | ||
| } & route.apple & { | ||
| [F in keyof route.apple]: { | ||
| raw: route.apple[F]; | ||
| }; | ||
| }; | ||
| gray: { | ||
| channels: Channels; | ||
| labels: [ | ||
| "gray" | ||
| ]; | ||
| rgb: { | ||
| (...gray: Gray): RGB; | ||
| raw: (...gray: Gray) => RGB; | ||
| }; | ||
| hsl: { | ||
| (...gray: Gray): HSL; | ||
| raw: (...gray: Gray) => HSL; | ||
| }; | ||
| hsv: { | ||
| (...gray: Gray): HSV; | ||
| raw: (...gray: Gray) => HSV; | ||
| }; | ||
| hwb: { | ||
| (...gray: Gray): HWB; | ||
| raw: (...gray: Gray) => HWB; | ||
| }; | ||
| cmyk: { | ||
| (...gray: Gray): CMYK; | ||
| raw: (...gray: Gray) => CMYK; | ||
| }; | ||
| lab: { | ||
| (...gray: Gray): LAB; | ||
| raw: (...gray: Gray) => LAB; | ||
| }; | ||
| hex: { | ||
| (...gray: Gray): HEX; | ||
| raw: (...gray: Gray) => HEX; | ||
| }; | ||
| } & route.gray & { | ||
| [F in keyof route.gray]: { | ||
| raw: route.gray[F]; | ||
| }; | ||
| }; | ||
| }; | ||
| declare const convert: Convert; | ||
| export type ColorLike = ColorInstance | string | ArrayLike<number> | number | Record<string, any>; | ||
| export type ColorJson = { | ||
| model: string; | ||
| color: number[]; | ||
| valpha: number; | ||
| }; | ||
| export type ColorObject = { | ||
| alpha?: number | undefined; | ||
| } & Record<string, number>; | ||
| // eslint-disable-next-line @typescript-eslint/consistent-type-definitions | ||
| export interface ColorInstance { | ||
| toString(): string; | ||
| // eslint-disable-next-line @typescript-eslint/naming-convention | ||
| toJSON(): ColorJson; | ||
| string(places?: number): string; | ||
| percentString(places?: number): string; | ||
| array(): number[]; | ||
| object(): ColorObject; | ||
| unitArray(): number[]; | ||
| unitObject(): { | ||
| r: number; | ||
| g: number; | ||
| b: number; | ||
| alpha?: number | undefined; | ||
| }; | ||
| round(places?: number): ColorInstance; | ||
| alpha(): number; | ||
| alpha(value: number): ColorInstance; | ||
| red(): number; | ||
| red(value: number): ColorInstance; | ||
| green(): number; | ||
| green(value: number): ColorInstance; | ||
| blue(): number; | ||
| blue(value: number): ColorInstance; | ||
| hue(): number; | ||
| hue(value: number): ColorInstance; | ||
| saturationl(): number; | ||
| saturationl(value: number): ColorInstance; | ||
| lightness(): number; | ||
| lightness(value: number): ColorInstance; | ||
| saturationv(): number; | ||
| saturationv(value: number): ColorInstance; | ||
| value(): number; | ||
| value(value: number): ColorInstance; | ||
| chroma(): number; | ||
| chroma(value: number): ColorInstance; | ||
| gray(): number; | ||
| gray(value: number): ColorInstance; | ||
| white(): number; | ||
| white(value: number): ColorInstance; | ||
| wblack(): number; | ||
| wblack(value: number): ColorInstance; | ||
| cyan(): number; | ||
| cyan(value: number): ColorInstance; | ||
| magenta(): number; | ||
| magenta(value: number): ColorInstance; | ||
| yellow(): number; | ||
| yellow(value: number): ColorInstance; | ||
| black(): number; | ||
| black(value: number): ColorInstance; | ||
| x(): number; | ||
| x(value: number): ColorInstance; | ||
| y(): number; | ||
| y(value: number): ColorInstance; | ||
| z(): number; | ||
| z(value: number): ColorInstance; | ||
| l(): number; | ||
| l(value: number): ColorInstance; | ||
| a(): number; | ||
| a(value: number): ColorInstance; | ||
| b(): number; | ||
| b(value: number): ColorInstance; | ||
| keyword(): string; | ||
| keyword<V extends string>(value: V): ColorInstance; | ||
| hex(): string; | ||
| hex<V extends string>(value: V): ColorInstance; | ||
| hexa(): string; | ||
| hexa<V extends string>(value: V): ColorInstance; | ||
| rgbNumber(): number; | ||
| luminosity(): number; | ||
| contrast(color2: ColorInstance): number; | ||
| level(color2: ColorInstance): "AAA" | "AA" | ""; | ||
| isDark(): boolean; | ||
| isLight(): boolean; | ||
| negate(): ColorInstance; | ||
| lighten(ratio: number): ColorInstance; | ||
| darken(ratio: number): ColorInstance; | ||
| saturate(ratio: number): ColorInstance; | ||
| desaturate(ratio: number): ColorInstance; | ||
| whiten(ratio: number): ColorInstance; | ||
| blacken(ratio: number): ColorInstance; | ||
| grayscale(): ColorInstance; | ||
| fade(ratio: number): ColorInstance; | ||
| opaquer(ratio: number): ColorInstance; | ||
| rotate(degrees: number): ColorInstance; | ||
| mix(mixinColor: ColorInstance, weight?: number): ColorInstance; | ||
| rgb(...arguments_: number[]): ColorInstance; | ||
| hsl(...arguments_: number[]): ColorInstance; | ||
| hsv(...arguments_: number[]): ColorInstance; | ||
| hwb(...arguments_: number[]): ColorInstance; | ||
| cmyk(...arguments_: number[]): ColorInstance; | ||
| xyz(...arguments_: number[]): ColorInstance; | ||
| lab(...arguments_: number[]): ColorInstance; | ||
| lch(...arguments_: number[]): ColorInstance; | ||
| ansi16(...arguments_: number[]): ColorInstance; | ||
| ansi256(...arguments_: number[]): ColorInstance; | ||
| hcg(...arguments_: number[]): ColorInstance; | ||
| apple(...arguments_: number[]): ColorInstance; | ||
| } | ||
| export type ColorConstructor = { | ||
| (object?: ColorLike, model?: keyof (typeof convert)): ColorInstance; | ||
| new (object?: ColorLike, model?: keyof (typeof convert)): ColorInstance; | ||
| rgb(...value: number[]): ColorInstance; | ||
| rgb(color: ColorLike): ColorInstance; | ||
| hsl(...value: number[]): ColorInstance; | ||
| hsl(color: ColorLike): ColorInstance; | ||
| hsv(...value: number[]): ColorInstance; | ||
| hsv(color: ColorLike): ColorInstance; | ||
| hwb(...value: number[]): ColorInstance; | ||
| hwb(color: ColorLike): ColorInstance; | ||
| cmyk(...value: number[]): ColorInstance; | ||
| cmyk(color: ColorLike): ColorInstance; | ||
| xyz(...value: number[]): ColorInstance; | ||
| xyz(color: ColorLike): ColorInstance; | ||
| lab(...value: number[]): ColorInstance; | ||
| lab(color: ColorLike): ColorInstance; | ||
| lch(...value: number[]): ColorInstance; | ||
| lch(color: ColorLike): ColorInstance; | ||
| ansi16(...value: number[]): ColorInstance; | ||
| ansi16(color: ColorLike): ColorInstance; | ||
| ansi256(...value: number[]): ColorInstance; | ||
| ansi256(color: ColorLike): ColorInstance; | ||
| hcg(...value: number[]): ColorInstance; | ||
| hcg(color: ColorLike): ColorInstance; | ||
| apple(...value: number[]): ColorInstance; | ||
| apple(color: ColorLike): ColorInstance; | ||
| }; | ||
| // eslint-disable-next-line @typescript-eslint/naming-convention | ||
| declare const Color: ColorConstructor; | ||
| export { | ||
| Color as default, | ||
| }; | ||
| export {}; |
| # Licensing | ||
| ## color | ||
| 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. | ||
| ## color-convert | ||
| Copyright (c) 2011-2016 Heather Arthur <fayearthur@gmail.com>. | ||
| Copyright (c) 2016-2021 Josh Junon <josh@junon.me>. | ||
| 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. | ||
| ## color-string | ||
| Copyright (c) 2011 Heather Arthur <fayearthur@gmail.com> | ||
| Permission is hereby granted, free of charge, to any person obtaining | ||
| a copy of this software and associated documentation files (the | ||
| "Software"), to deal in the Software without restriction, including | ||
| without limitation the rights to use, copy, modify, merge, publish, | ||
| distribute, sublicense, and/or sell copies of the Software, and to | ||
| permit persons to whom the Software is furnished to do so, subject to | ||
| the following conditions: | ||
| The above copyright notice and this permission notice shall be | ||
| included in all copies or substantial portions of the Software. | ||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
| EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
| MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | ||
| NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE | ||
| LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | ||
| OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | ||
| WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
| ## color-name | ||
| The MIT License (MIT) | ||
| Copyright (c) 2015 Dmitry Ivanov | ||
| 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. |
| { | ||
| "name": "@img/colour", | ||
| "version": "1.1.0", | ||
| "description": "The ESM-only 'color' package made compatible for use with CommonJS runtimes", | ||
| "license": "MIT", | ||
| "main": "index.cjs", | ||
| "types": "index.d.ts", | ||
| "exports": { | ||
| ".": { | ||
| "types": "./index.d.ts", | ||
| "require": "./index.cjs", | ||
| "default": "./index.cjs" | ||
| }, | ||
| "./package.json": "./package.json" | ||
| }, | ||
| "authors": [ | ||
| "Heather Arthur <fayearthur@gmail.com>", | ||
| "Josh Junon <josh@junon.me>", | ||
| "Maxime Thirouin", | ||
| "Dyma Ywanov <dfcreative@gmail.com>", | ||
| "LitoMore (https://github.com/LitoMore)" | ||
| ], | ||
| "engines": { | ||
| "node": ">=18" | ||
| }, | ||
| "files": [ | ||
| "color.cjs", | ||
| "index.d.ts" | ||
| ], | ||
| "publishConfig": { | ||
| "access": "public" | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/lovell/colour.git" | ||
| }, | ||
| "type": "commonjs", | ||
| "keywords": [ | ||
| "color", | ||
| "colour", | ||
| "cjs", | ||
| "commonjs" | ||
| ], | ||
| "scripts": { | ||
| "build:cjs": "esbuild node_modules/color/index.js --bundle --platform=node --outfile=color.cjs", | ||
| "build:dts": "dts-bundle-generator ./dts-src.ts -o index.d.ts --project tsconfig.build.json --external-inlines color --external-inlines color-convert --export-referenced-types=false", | ||
| "build": "npm run build:cjs && npm run build:dts", | ||
| "test": "node --test" | ||
| }, | ||
| "devDependencies": { | ||
| "color": "5.0.3", | ||
| "color-convert": "3.1.3", | ||
| "color-name": "2.1.0", | ||
| "color-string": "2.1.4", | ||
| "dts-bundle-generator": "^9.5.1", | ||
| "esbuild": "^0.27.3" | ||
| } | ||
| } |
| # `@img/colour` | ||
| The latest version of the | ||
| [color](https://www.npmjs.com/package/color) | ||
| package is now ESM-only, | ||
| however some JavaScript runtimes do not yet support this, | ||
| which includes versions of Node.js prior to 20.19.0. | ||
| This package converts the `color` package and its dependencies, | ||
| all of which are MIT-licensed, to CommonJS. | ||
| - [color](https://www.npmjs.com/package/color) | ||
| - [color-convert](https://www.npmjs.com/package/color-convert) | ||
| - [color-string](https://www.npmjs.com/package/color-string) | ||
| - [color-name](https://www.npmjs.com/package/color-name) |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
| 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. |
| { | ||
| "name": "@img/sharp-win32-x64", | ||
| "version": "0.34.5", | ||
| "description": "Prebuilt sharp for use with Windows x64", | ||
| "author": "Lovell Fuller <npm@lovell.info>", | ||
| "homepage": "https://sharp.pixelplumbing.com", | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/lovell/sharp.git", | ||
| "directory": "npm/win32-x64" | ||
| }, | ||
| "license": "Apache-2.0 AND LGPL-3.0-or-later", | ||
| "funding": { | ||
| "url": "https://opencollective.com/libvips" | ||
| }, | ||
| "preferUnplugged": true, | ||
| "files": [ | ||
| "lib", | ||
| "versions.json" | ||
| ], | ||
| "publishConfig": { | ||
| "access": "public" | ||
| }, | ||
| "type": "commonjs", | ||
| "exports": { | ||
| "./sharp.node": "./lib/sharp-win32-x64.node", | ||
| "./package": "./package.json", | ||
| "./versions": "./versions.json" | ||
| }, | ||
| "engines": { | ||
| "node": "^18.17.0 || ^20.3.0 || >=21.0.0" | ||
| }, | ||
| "os": [ | ||
| "win32" | ||
| ], | ||
| "cpu": [ | ||
| "x64" | ||
| ] | ||
| } |
| # `@img/sharp-win32-x64` | ||
| Prebuilt sharp for use with Windows x64. | ||
| ## 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. | ||
| This software contains third-party libraries | ||
| used under the terms of the following licences: | ||
| | Library | Used under the terms of | | ||
| |---------------|-----------------------------------------------------------------------------------------------------------| | ||
| | aom | BSD 2-Clause + [Alliance for Open Media Patent License 1.0](https://aomedia.org/license/patent-license/) | | ||
| | cairo | Mozilla Public License 2.0 | | ||
| | cgif | MIT Licence | | ||
| | expat | MIT Licence | | ||
| | fontconfig | [fontconfig Licence](https://gitlab.freedesktop.org/fontconfig/fontconfig/blob/main/COPYING) (BSD-like) | | ||
| | freetype | [freetype Licence](https://git.savannah.gnu.org/cgit/freetype/freetype2.git/tree/docs/FTL.TXT) (BSD-like) | | ||
| | fribidi | LGPLv3 | | ||
| | glib | LGPLv3 | | ||
| | harfbuzz | MIT Licence | | ||
| | highway | Apache-2.0 License, BSD 3-Clause | | ||
| | lcms | MIT Licence | | ||
| | libarchive | BSD 2-Clause | | ||
| | libexif | LGPLv3 | | ||
| | libffi | MIT Licence | | ||
| | libheif | LGPLv3 | | ||
| | libimagequant | [BSD 2-Clause](https://github.com/lovell/libimagequant/blob/main/COPYRIGHT) | | ||
| | libnsgif | MIT Licence | | ||
| | libpng | [libpng License](https://github.com/pnggroup/libpng/blob/master/LICENSE) | | ||
| | librsvg | LGPLv3 | | ||
| | libspng | [BSD 2-Clause, libpng License](https://github.com/randy408/libspng/blob/master/LICENSE) | | ||
| | libtiff | [libtiff License](https://gitlab.com/libtiff/libtiff/blob/master/LICENSE.md) (BSD-like) | | ||
| | libvips | LGPLv3 | | ||
| | libwebp | New BSD License | | ||
| | libxml2 | MIT Licence | | ||
| | mozjpeg | [zlib License, IJG License, BSD-3-Clause](https://github.com/mozilla/mozjpeg/blob/master/LICENSE.md) | | ||
| | pango | LGPLv3 | | ||
| | pixman | MIT Licence | | ||
| | proxy-libintl | LGPLv3 | | ||
| | zlib-ng | [zlib Licence](https://github.com/zlib-ng/zlib-ng/blob/develop/LICENSE.md) | | ||
| Use of libraries under the terms of the LGPLv3 is via the | ||
| "any later version" clause of the LGPLv2 or LGPLv2.1. | ||
| Please report any errors or omissions via | ||
| https://github.com/lovell/sharp-libvips/issues/new |
| { | ||
| "aom": "3.13.1", | ||
| "archive": "3.8.2", | ||
| "cairo": "1.18.4", | ||
| "cgif": "0.5.0", | ||
| "exif": "0.6.25", | ||
| "expat": "2.7.3", | ||
| "ffi": "3.5.2", | ||
| "fontconfig": "2.17.1", | ||
| "freetype": "2.14.1", | ||
| "fribidi": "1.0.16", | ||
| "glib": "2.86.1", | ||
| "harfbuzz": "12.1.0", | ||
| "heif": "1.20.2", | ||
| "highway": "1.3.0", | ||
| "imagequant": "2.4.1", | ||
| "lcms": "2.17", | ||
| "mozjpeg": "0826579", | ||
| "pango": "1.57.0", | ||
| "pixman": "0.46.4", | ||
| "png": "1.6.50", | ||
| "proxy-libintl": "0.5", | ||
| "rsvg": "2.61.2", | ||
| "spng": "0.7.4", | ||
| "tiff": "4.7.1", | ||
| "vips": "8.17.3", | ||
| "webp": "1.6.0", | ||
| "xml2": "2.15.1", | ||
| "zlib-ng": "2.2.5" | ||
| } |
| // Copyright 2017 Lovell Fuller and others. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| export const GLIBC: 'glibc'; | ||
| export const MUSL: 'musl'; | ||
| export function family(): Promise<string | null>; | ||
| export function familySync(): string | null; | ||
| export function isNonGlibcLinux(): Promise<boolean>; | ||
| export function isNonGlibcLinuxSync(): boolean; | ||
| export function version(): Promise<string | null>; | ||
| export function versionSync(): string | null; |
| // Copyright 2017 Lovell Fuller and others. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| 'use strict'; | ||
| const childProcess = require('child_process'); | ||
| const { isLinux, getReport } = require('./process'); | ||
| const { LDD_PATH, SELF_PATH, readFile, readFileSync } = require('./filesystem'); | ||
| const { interpreterPath } = require('./elf'); | ||
| let cachedFamilyInterpreter; | ||
| let cachedFamilyFilesystem; | ||
| let cachedVersionFilesystem; | ||
| const command = 'getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true'; | ||
| let commandOut = ''; | ||
| const safeCommand = () => { | ||
| if (!commandOut) { | ||
| return new Promise((resolve) => { | ||
| childProcess.exec(command, (err, out) => { | ||
| commandOut = err ? ' ' : out; | ||
| resolve(commandOut); | ||
| }); | ||
| }); | ||
| } | ||
| return commandOut; | ||
| }; | ||
| const safeCommandSync = () => { | ||
| if (!commandOut) { | ||
| try { | ||
| commandOut = childProcess.execSync(command, { encoding: 'utf8' }); | ||
| } catch (_err) { | ||
| commandOut = ' '; | ||
| } | ||
| } | ||
| return commandOut; | ||
| }; | ||
| /** | ||
| * A String constant containing the value `glibc`. | ||
| * @type {string} | ||
| * @public | ||
| */ | ||
| const GLIBC = 'glibc'; | ||
| /** | ||
| * A Regexp constant to get the GLIBC Version. | ||
| * @type {string} | ||
| */ | ||
| const RE_GLIBC_VERSION = /LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i; | ||
| /** | ||
| * A String constant containing the value `musl`. | ||
| * @type {string} | ||
| * @public | ||
| */ | ||
| const MUSL = 'musl'; | ||
| const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-'); | ||
| const familyFromReport = () => { | ||
| const report = getReport(); | ||
| if (report.header && report.header.glibcVersionRuntime) { | ||
| return GLIBC; | ||
| } | ||
| if (Array.isArray(report.sharedObjects)) { | ||
| if (report.sharedObjects.some(isFileMusl)) { | ||
| return MUSL; | ||
| } | ||
| } | ||
| return null; | ||
| }; | ||
| const familyFromCommand = (out) => { | ||
| const [getconf, ldd1] = out.split(/[\r\n]+/); | ||
| if (getconf && getconf.includes(GLIBC)) { | ||
| return GLIBC; | ||
| } | ||
| if (ldd1 && ldd1.includes(MUSL)) { | ||
| return MUSL; | ||
| } | ||
| return null; | ||
| }; | ||
| const familyFromInterpreterPath = (path) => { | ||
| if (path) { | ||
| if (path.includes('/ld-musl-')) { | ||
| return MUSL; | ||
| } else if (path.includes('/ld-linux-')) { | ||
| return GLIBC; | ||
| } | ||
| } | ||
| return null; | ||
| }; | ||
| const getFamilyFromLddContent = (content) => { | ||
| content = content.toString(); | ||
| if (content.includes('musl')) { | ||
| return MUSL; | ||
| } | ||
| if (content.includes('GNU C Library')) { | ||
| return GLIBC; | ||
| } | ||
| return null; | ||
| }; | ||
| const familyFromFilesystem = async () => { | ||
| if (cachedFamilyFilesystem !== undefined) { | ||
| return cachedFamilyFilesystem; | ||
| } | ||
| cachedFamilyFilesystem = null; | ||
| try { | ||
| const lddContent = await readFile(LDD_PATH); | ||
| cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); | ||
| } catch (e) {} | ||
| return cachedFamilyFilesystem; | ||
| }; | ||
| const familyFromFilesystemSync = () => { | ||
| if (cachedFamilyFilesystem !== undefined) { | ||
| return cachedFamilyFilesystem; | ||
| } | ||
| cachedFamilyFilesystem = null; | ||
| try { | ||
| const lddContent = readFileSync(LDD_PATH); | ||
| cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); | ||
| } catch (e) {} | ||
| return cachedFamilyFilesystem; | ||
| }; | ||
| const familyFromInterpreter = async () => { | ||
| if (cachedFamilyInterpreter !== undefined) { | ||
| return cachedFamilyInterpreter; | ||
| } | ||
| cachedFamilyInterpreter = null; | ||
| try { | ||
| const selfContent = await readFile(SELF_PATH); | ||
| const path = interpreterPath(selfContent); | ||
| cachedFamilyInterpreter = familyFromInterpreterPath(path); | ||
| } catch (e) {} | ||
| return cachedFamilyInterpreter; | ||
| }; | ||
| const familyFromInterpreterSync = () => { | ||
| if (cachedFamilyInterpreter !== undefined) { | ||
| return cachedFamilyInterpreter; | ||
| } | ||
| cachedFamilyInterpreter = null; | ||
| try { | ||
| const selfContent = readFileSync(SELF_PATH); | ||
| const path = interpreterPath(selfContent); | ||
| cachedFamilyInterpreter = familyFromInterpreterPath(path); | ||
| } catch (e) {} | ||
| return cachedFamilyInterpreter; | ||
| }; | ||
| /** | ||
| * Resolves with the libc family when it can be determined, `null` otherwise. | ||
| * @returns {Promise<?string>} | ||
| */ | ||
| const family = async () => { | ||
| let family = null; | ||
| if (isLinux()) { | ||
| family = await familyFromInterpreter(); | ||
| if (!family) { | ||
| family = await familyFromFilesystem(); | ||
| if (!family) { | ||
| family = familyFromReport(); | ||
| } | ||
| if (!family) { | ||
| const out = await safeCommand(); | ||
| family = familyFromCommand(out); | ||
| } | ||
| } | ||
| } | ||
| return family; | ||
| }; | ||
| /** | ||
| * Returns the libc family when it can be determined, `null` otherwise. | ||
| * @returns {?string} | ||
| */ | ||
| const familySync = () => { | ||
| let family = null; | ||
| if (isLinux()) { | ||
| family = familyFromInterpreterSync(); | ||
| if (!family) { | ||
| family = familyFromFilesystemSync(); | ||
| if (!family) { | ||
| family = familyFromReport(); | ||
| } | ||
| if (!family) { | ||
| const out = safeCommandSync(); | ||
| family = familyFromCommand(out); | ||
| } | ||
| } | ||
| } | ||
| return family; | ||
| }; | ||
| /** | ||
| * Resolves `true` only when the platform is Linux and the libc family is not `glibc`. | ||
| * @returns {Promise<boolean>} | ||
| */ | ||
| const isNonGlibcLinux = async () => isLinux() && await family() !== GLIBC; | ||
| /** | ||
| * Returns `true` only when the platform is Linux and the libc family is not `glibc`. | ||
| * @returns {boolean} | ||
| */ | ||
| const isNonGlibcLinuxSync = () => isLinux() && familySync() !== GLIBC; | ||
| const versionFromFilesystem = async () => { | ||
| if (cachedVersionFilesystem !== undefined) { | ||
| return cachedVersionFilesystem; | ||
| } | ||
| cachedVersionFilesystem = null; | ||
| try { | ||
| const lddContent = await readFile(LDD_PATH); | ||
| const versionMatch = lddContent.match(RE_GLIBC_VERSION); | ||
| if (versionMatch) { | ||
| cachedVersionFilesystem = versionMatch[1]; | ||
| } | ||
| } catch (e) {} | ||
| return cachedVersionFilesystem; | ||
| }; | ||
| const versionFromFilesystemSync = () => { | ||
| if (cachedVersionFilesystem !== undefined) { | ||
| return cachedVersionFilesystem; | ||
| } | ||
| cachedVersionFilesystem = null; | ||
| try { | ||
| const lddContent = readFileSync(LDD_PATH); | ||
| const versionMatch = lddContent.match(RE_GLIBC_VERSION); | ||
| if (versionMatch) { | ||
| cachedVersionFilesystem = versionMatch[1]; | ||
| } | ||
| } catch (e) {} | ||
| return cachedVersionFilesystem; | ||
| }; | ||
| const versionFromReport = () => { | ||
| const report = getReport(); | ||
| if (report.header && report.header.glibcVersionRuntime) { | ||
| return report.header.glibcVersionRuntime; | ||
| } | ||
| return null; | ||
| }; | ||
| const versionSuffix = (s) => s.trim().split(/\s+/)[1]; | ||
| const versionFromCommand = (out) => { | ||
| const [getconf, ldd1, ldd2] = out.split(/[\r\n]+/); | ||
| if (getconf && getconf.includes(GLIBC)) { | ||
| return versionSuffix(getconf); | ||
| } | ||
| if (ldd1 && ldd2 && ldd1.includes(MUSL)) { | ||
| return versionSuffix(ldd2); | ||
| } | ||
| return null; | ||
| }; | ||
| /** | ||
| * Resolves with the libc version when it can be determined, `null` otherwise. | ||
| * @returns {Promise<?string>} | ||
| */ | ||
| const version = async () => { | ||
| let version = null; | ||
| if (isLinux()) { | ||
| version = await versionFromFilesystem(); | ||
| if (!version) { | ||
| version = versionFromReport(); | ||
| } | ||
| if (!version) { | ||
| const out = await safeCommand(); | ||
| version = versionFromCommand(out); | ||
| } | ||
| } | ||
| return version; | ||
| }; | ||
| /** | ||
| * Returns the libc version when it can be determined, `null` otherwise. | ||
| * @returns {?string} | ||
| */ | ||
| const versionSync = () => { | ||
| let version = null; | ||
| if (isLinux()) { | ||
| version = versionFromFilesystemSync(); | ||
| if (!version) { | ||
| version = versionFromReport(); | ||
| } | ||
| if (!version) { | ||
| const out = safeCommandSync(); | ||
| version = versionFromCommand(out); | ||
| } | ||
| } | ||
| return version; | ||
| }; | ||
| module.exports = { | ||
| GLIBC, | ||
| MUSL, | ||
| family, | ||
| familySync, | ||
| isNonGlibcLinux, | ||
| isNonGlibcLinuxSync, | ||
| version, | ||
| versionSync | ||
| }; |
| // Copyright 2017 Lovell Fuller and others. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| 'use strict'; | ||
| const interpreterPath = (elf) => { | ||
| if (elf.length < 64) { | ||
| return null; | ||
| } | ||
| if (elf.readUInt32BE(0) !== 0x7F454C46) { | ||
| // Unexpected magic bytes | ||
| return null; | ||
| } | ||
| if (elf.readUInt8(4) !== 2) { | ||
| // Not a 64-bit ELF | ||
| return null; | ||
| } | ||
| if (elf.readUInt8(5) !== 1) { | ||
| // Not little-endian | ||
| return null; | ||
| } | ||
| const offset = elf.readUInt32LE(32); | ||
| const size = elf.readUInt16LE(54); | ||
| const count = elf.readUInt16LE(56); | ||
| for (let i = 0; i < count; i++) { | ||
| const headerOffset = offset + (i * size); | ||
| const type = elf.readUInt32LE(headerOffset); | ||
| if (type === 3) { | ||
| const fileOffset = elf.readUInt32LE(headerOffset + 8); | ||
| const fileSize = elf.readUInt32LE(headerOffset + 32); | ||
| return elf.subarray(fileOffset, fileOffset + fileSize).toString().replace(/\0.*$/g, ''); | ||
| } | ||
| } | ||
| return null; | ||
| }; | ||
| module.exports = { | ||
| interpreterPath | ||
| }; |
| // Copyright 2017 Lovell Fuller and others. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| 'use strict'; | ||
| const fs = require('fs'); | ||
| const LDD_PATH = '/usr/bin/ldd'; | ||
| const SELF_PATH = '/proc/self/exe'; | ||
| const MAX_LENGTH = 2048; | ||
| /** | ||
| * Read the content of a file synchronous | ||
| * | ||
| * @param {string} path | ||
| * @returns {Buffer} | ||
| */ | ||
| const readFileSync = (path) => { | ||
| const fd = fs.openSync(path, 'r'); | ||
| const buffer = Buffer.alloc(MAX_LENGTH); | ||
| const bytesRead = fs.readSync(fd, buffer, 0, MAX_LENGTH, 0); | ||
| fs.close(fd, () => {}); | ||
| return buffer.subarray(0, bytesRead); | ||
| }; | ||
| /** | ||
| * Read the content of a file | ||
| * | ||
| * @param {string} path | ||
| * @returns {Promise<Buffer>} | ||
| */ | ||
| const readFile = (path) => new Promise((resolve, reject) => { | ||
| fs.open(path, 'r', (err, fd) => { | ||
| if (err) { | ||
| reject(err); | ||
| } else { | ||
| const buffer = Buffer.alloc(MAX_LENGTH); | ||
| fs.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => { | ||
| resolve(buffer.subarray(0, bytesRead)); | ||
| fs.close(fd, () => {}); | ||
| }); | ||
| } | ||
| }); | ||
| }); | ||
| module.exports = { | ||
| LDD_PATH, | ||
| SELF_PATH, | ||
| readFileSync, | ||
| readFile | ||
| }; |
| // Copyright 2017 Lovell Fuller and others. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| 'use strict'; | ||
| const isLinux = () => process.platform === 'linux'; | ||
| let report = null; | ||
| const getReport = () => { | ||
| if (!report) { | ||
| /* istanbul ignore next */ | ||
| if (isLinux() && process.report) { | ||
| const orig = process.report.excludeNetwork; | ||
| process.report.excludeNetwork = true; | ||
| report = process.report.getReport(); | ||
| process.report.excludeNetwork = orig; | ||
| } else { | ||
| report = {}; | ||
| } | ||
| } | ||
| return report; | ||
| }; | ||
| module.exports = { isLinux, getReport }; |
| 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: | ||
| (a) You must give any other recipients of the Work or | ||
| Derivative Works a copy of this License; and | ||
| (b) You must cause any modified files to carry prominent notices | ||
| stating that You changed the files; and | ||
| (c) 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 | ||
| (d) 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. |
| { | ||
| "name": "detect-libc", | ||
| "version": "2.1.2", | ||
| "description": "Node.js module to detect the C standard library (libc) implementation family and version", | ||
| "main": "lib/detect-libc.js", | ||
| "files": [ | ||
| "lib/", | ||
| "index.d.ts" | ||
| ], | ||
| "scripts": { | ||
| "test": "semistandard && nyc --reporter=text --check-coverage --branches=100 ava test/unit.js", | ||
| "changelog": "conventional-changelog -i CHANGELOG.md -s", | ||
| "bench": "node benchmark/detect-libc", | ||
| "bench:calls": "node benchmark/call-familySync.js && sleep 1 && node benchmark/call-isNonGlibcLinuxSync.js && sleep 1 && node benchmark/call-versionSync.js" | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git://github.com/lovell/detect-libc.git" | ||
| }, | ||
| "keywords": [ | ||
| "libc", | ||
| "glibc", | ||
| "musl" | ||
| ], | ||
| "author": "Lovell Fuller <npm@lovell.info>", | ||
| "contributors": [ | ||
| "Niklas Salmoukas <niklas@salmoukas.com>", | ||
| "Vinícius Lourenço <vinyygamerlol@gmail.com>" | ||
| ], | ||
| "license": "Apache-2.0", | ||
| "devDependencies": { | ||
| "ava": "^2.4.0", | ||
| "benchmark": "^2.1.4", | ||
| "conventional-changelog-cli": "^5.0.0", | ||
| "eslint-config-standard": "^13.0.1", | ||
| "nyc": "^15.1.0", | ||
| "proxyquire": "^2.1.3", | ||
| "semistandard": "^14.2.3" | ||
| }, | ||
| "engines": { | ||
| "node": ">=8" | ||
| }, | ||
| "types": "index.d.ts" | ||
| } |
| # detect-libc | ||
| Node.js module to detect details of the C standard library (libc) | ||
| implementation provided by a given Linux system. | ||
| Currently supports detection of GNU glibc and MUSL libc. | ||
| Provides asychronous and synchronous functions for the | ||
| family (e.g. `glibc`, `musl`) and version (e.g. `1.23`, `1.2.3`). | ||
| The version numbers of libc implementations | ||
| are not guaranteed to be semver-compliant. | ||
| For previous v1.x releases, please see the | ||
| [v1](https://github.com/lovell/detect-libc/tree/v1) branch. | ||
| ## Install | ||
| ```sh | ||
| npm install detect-libc | ||
| ``` | ||
| ## API | ||
| ### GLIBC | ||
| ```ts | ||
| const GLIBC: string = 'glibc'; | ||
| ``` | ||
| A String constant containing the value `glibc`. | ||
| ### MUSL | ||
| ```ts | ||
| const MUSL: string = 'musl'; | ||
| ``` | ||
| A String constant containing the value `musl`. | ||
| ### family | ||
| ```ts | ||
| function family(): Promise<string | null>; | ||
| ``` | ||
| Resolves asychronously with: | ||
| * `glibc` or `musl` when the libc family can be determined | ||
| * `null` when the libc family cannot be determined | ||
| * `null` when run on a non-Linux platform | ||
| ```js | ||
| const { family, GLIBC, MUSL } = require('detect-libc'); | ||
| switch (await family()) { | ||
| case GLIBC: ... | ||
| case MUSL: ... | ||
| case null: ... | ||
| } | ||
| ``` | ||
| ### familySync | ||
| ```ts | ||
| function familySync(): string | null; | ||
| ``` | ||
| Synchronous version of `family()`. | ||
| ```js | ||
| const { familySync, GLIBC, MUSL } = require('detect-libc'); | ||
| switch (familySync()) { | ||
| case GLIBC: ... | ||
| case MUSL: ... | ||
| case null: ... | ||
| } | ||
| ``` | ||
| ### version | ||
| ```ts | ||
| function version(): Promise<string | null>; | ||
| ``` | ||
| Resolves asychronously with: | ||
| * The version when it can be determined | ||
| * `null` when the libc family cannot be determined | ||
| * `null` when run on a non-Linux platform | ||
| ```js | ||
| const { version } = require('detect-libc'); | ||
| const v = await version(); | ||
| if (v) { | ||
| const [major, minor, patch] = v.split('.'); | ||
| } | ||
| ``` | ||
| ### versionSync | ||
| ```ts | ||
| function versionSync(): string | null; | ||
| ``` | ||
| Synchronous version of `version()`. | ||
| ```js | ||
| const { versionSync } = require('detect-libc'); | ||
| const v = versionSync(); | ||
| if (v) { | ||
| const [major, minor, patch] = v.split('.'); | ||
| } | ||
| ``` | ||
| ### isNonGlibcLinux | ||
| ```ts | ||
| function isNonGlibcLinux(): Promise<boolean>; | ||
| ``` | ||
| Resolves asychronously with: | ||
| * `false` when the libc family is `glibc` | ||
| * `true` when the libc family is not `glibc` | ||
| * `false` when run on a non-Linux platform | ||
| ```js | ||
| const { isNonGlibcLinux } = require('detect-libc'); | ||
| if (await isNonGlibcLinux()) { ... } | ||
| ``` | ||
| ### isNonGlibcLinuxSync | ||
| ```ts | ||
| function isNonGlibcLinuxSync(): boolean; | ||
| ``` | ||
| Synchronous version of `isNonGlibcLinux()`. | ||
| ```js | ||
| const { isNonGlibcLinuxSync } = require('detect-libc'); | ||
| if (isNonGlibcLinuxSync()) { ... } | ||
| ``` | ||
| ## Licensing | ||
| Copyright 2017 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 [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0.html) | ||
| 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. |
| #!/usr/bin/env node | ||
| // Standalone semver comparison program. | ||
| // Exits successfully and prints matching version(s) if | ||
| // any supplied version is valid and passes all tests. | ||
| 'use strict' | ||
| const argv = process.argv.slice(2) | ||
| let versions = [] | ||
| const range = [] | ||
| let inc = null | ||
| const version = require('../package.json').version | ||
| let loose = false | ||
| let includePrerelease = false | ||
| let coerce = false | ||
| let rtl = false | ||
| let identifier | ||
| let identifierBase | ||
| const semver = require('../') | ||
| const parseOptions = require('../internal/parse-options') | ||
| let reverse = false | ||
| let options = {} | ||
| const main = () => { | ||
| if (!argv.length) { | ||
| return help() | ||
| } | ||
| while (argv.length) { | ||
| let a = argv.shift() | ||
| const indexOfEqualSign = a.indexOf('=') | ||
| if (indexOfEqualSign !== -1) { | ||
| const value = a.slice(indexOfEqualSign + 1) | ||
| a = a.slice(0, indexOfEqualSign) | ||
| argv.unshift(value) | ||
| } | ||
| switch (a) { | ||
| case '-rv': case '-rev': case '--rev': case '--reverse': | ||
| reverse = true | ||
| break | ||
| case '-l': case '--loose': | ||
| loose = true | ||
| break | ||
| case '-p': case '--include-prerelease': | ||
| includePrerelease = true | ||
| break | ||
| case '-v': case '--version': | ||
| versions.push(argv.shift()) | ||
| break | ||
| case '-i': case '--inc': case '--increment': | ||
| if (semver.RELEASE_TYPES.includes(argv[0]) || (argv[0] === 'release')) { | ||
| inc = { value: argv.shift(), maybeErrantValue: null, option: a } | ||
| } else { | ||
| inc = { value: 'patch', maybeErrantValue: argv[0], option: a } | ||
| } | ||
| break | ||
| case '--preid': | ||
| identifier = argv.shift() | ||
| break | ||
| case '-r': case '--range': | ||
| range.push(argv.shift()) | ||
| break | ||
| case '-n': | ||
| identifierBase = argv.shift() | ||
| if (identifierBase === 'false') { | ||
| identifierBase = false | ||
| } | ||
| break | ||
| case '-c': case '--coerce': | ||
| coerce = true | ||
| break | ||
| case '--rtl': | ||
| rtl = true | ||
| break | ||
| case '--ltr': | ||
| rtl = false | ||
| break | ||
| case '-h': case '--help': case '-?': | ||
| return help() | ||
| default: | ||
| versions.push(a) | ||
| break | ||
| } | ||
| } | ||
| options = parseOptions({ loose, includePrerelease, rtl }) | ||
| if ( | ||
| inc && | ||
| versions.includes(inc.maybeErrantValue) && | ||
| !semver.valid(inc.maybeErrantValue, options) | ||
| ) { | ||
| console.warn(`Invalid value for ${inc.option}; defaulting to 'patch'. This may become a failure in future major versions.`) | ||
| } | ||
| versions = versions.map((v) => { | ||
| return coerce ? (semver.coerce(v, options) || { version: v }).version : v | ||
| }).filter((v) => { | ||
| return semver.valid(v, options) | ||
| }) | ||
| if (!versions.length) { | ||
| return fail() | ||
| } | ||
| if (inc && (versions.length !== 1 || range.length)) { | ||
| return failInc() | ||
| } | ||
| for (let i = 0, l = range.length; i < l; i++) { | ||
| versions = versions.filter((v) => { | ||
| return semver.satisfies(v, range[i], options) | ||
| }) | ||
| if (!versions.length) { | ||
| return fail() | ||
| } | ||
| } | ||
| versions | ||
| .sort((a, b) => semver[reverse ? 'rcompare' : 'compare'](a, b, options)) | ||
| .map(v => semver.clean(v, options)) | ||
| .map(v => inc ? semver.inc(v, inc.value, options, identifier, identifierBase) : v) | ||
| .forEach(v => console.log(v)) | ||
| } | ||
| const failInc = () => { | ||
| console.error('--inc can only be used on a single version with no range') | ||
| fail() | ||
| } | ||
| const fail = () => process.exit(1) | ||
| const help = () => console.log( | ||
| `SemVer ${version} | ||
| A JavaScript implementation of the https://semver.org/ specification | ||
| Copyright Isaac Z. Schlueter | ||
| Usage: semver [options] <version> [<version> [...]] | ||
| Prints valid versions sorted by SemVer precedence | ||
| Options: | ||
| -r --range <range> | ||
| Print versions that match the specified range. | ||
| -i --increment [<level>] | ||
| Increment a version by the specified level. Level can | ||
| be one of: major, minor, patch, premajor, preminor, | ||
| prepatch, prerelease, or release. Default level is 'patch'. | ||
| Only one version may be specified. | ||
| --preid <identifier> | ||
| Identifier to be used to prefix premajor, preminor, | ||
| prepatch or prerelease version increments. | ||
| -l --loose | ||
| Interpret versions and ranges loosely | ||
| -p --include-prerelease | ||
| Always include prerelease versions in range matching | ||
| -c --coerce | ||
| Coerce a string into SemVer if possible | ||
| (does not imply --loose) | ||
| --rtl | ||
| Coerce version strings right to left | ||
| --ltr | ||
| Coerce version strings left to right (default) | ||
| -n <base> | ||
| Base number to be used for the prerelease identifier. | ||
| Can be either 0 or 1, or false to omit the number altogether. | ||
| Defaults to 0. | ||
| Program exits successfully if any valid version satisfies | ||
| all supplied ranges, and prints all satisfying versions. | ||
| If no satisfying versions are found, then exits failure. | ||
| Versions are printed in ascending order, so supplying | ||
| multiple versions to the utility will just sort them.`) | ||
| main() |
| 'use strict' | ||
| const ANY = Symbol('SemVer ANY') | ||
| // hoisted class for cyclic dependency | ||
| class Comparator { | ||
| static get ANY () { | ||
| return ANY | ||
| } | ||
| constructor (comp, options) { | ||
| options = parseOptions(options) | ||
| if (comp instanceof Comparator) { | ||
| if (comp.loose === !!options.loose) { | ||
| return comp | ||
| } else { | ||
| comp = comp.value | ||
| } | ||
| } | ||
| comp = comp.trim().split(/\s+/).join(' ') | ||
| debug('comparator', comp, options) | ||
| this.options = options | ||
| this.loose = !!options.loose | ||
| this.parse(comp) | ||
| if (this.semver === ANY) { | ||
| this.value = '' | ||
| } else { | ||
| this.value = this.operator + this.semver.version | ||
| } | ||
| debug('comp', this) | ||
| } | ||
| parse (comp) { | ||
| const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] | ||
| const m = comp.match(r) | ||
| if (!m) { | ||
| throw new TypeError(`Invalid comparator: ${comp}`) | ||
| } | ||
| this.operator = m[1] !== undefined ? m[1] : '' | ||
| if (this.operator === '=') { | ||
| this.operator = '' | ||
| } | ||
| // if it literally is just '>' or '' then allow anything. | ||
| if (!m[2]) { | ||
| this.semver = ANY | ||
| } else { | ||
| this.semver = new SemVer(m[2], this.options.loose) | ||
| } | ||
| } | ||
| toString () { | ||
| return this.value | ||
| } | ||
| test (version) { | ||
| debug('Comparator.test', version, this.options.loose) | ||
| if (this.semver === ANY || version === ANY) { | ||
| return true | ||
| } | ||
| if (typeof version === 'string') { | ||
| try { | ||
| version = new SemVer(version, this.options) | ||
| } catch (er) { | ||
| return false | ||
| } | ||
| } | ||
| return cmp(version, this.operator, this.semver, this.options) | ||
| } | ||
| intersects (comp, options) { | ||
| if (!(comp instanceof Comparator)) { | ||
| throw new TypeError('a Comparator is required') | ||
| } | ||
| if (this.operator === '') { | ||
| if (this.value === '') { | ||
| return true | ||
| } | ||
| return new Range(comp.value, options).test(this.value) | ||
| } else if (comp.operator === '') { | ||
| if (comp.value === '') { | ||
| return true | ||
| } | ||
| return new Range(this.value, options).test(comp.semver) | ||
| } | ||
| options = parseOptions(options) | ||
| // Special cases where nothing can possibly be lower | ||
| if (options.includePrerelease && | ||
| (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { | ||
| return false | ||
| } | ||
| if (!options.includePrerelease && | ||
| (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { | ||
| return false | ||
| } | ||
| // Same direction increasing (> or >=) | ||
| if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { | ||
| return true | ||
| } | ||
| // Same direction decreasing (< or <=) | ||
| if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { | ||
| return true | ||
| } | ||
| // same SemVer and both sides are inclusive (<= or >=) | ||
| if ( | ||
| (this.semver.version === comp.semver.version) && | ||
| this.operator.includes('=') && comp.operator.includes('=')) { | ||
| return true | ||
| } | ||
| // opposite directions less than | ||
| if (cmp(this.semver, '<', comp.semver, options) && | ||
| this.operator.startsWith('>') && comp.operator.startsWith('<')) { | ||
| return true | ||
| } | ||
| // opposite directions greater than | ||
| if (cmp(this.semver, '>', comp.semver, options) && | ||
| this.operator.startsWith('<') && comp.operator.startsWith('>')) { | ||
| return true | ||
| } | ||
| return false | ||
| } | ||
| } | ||
| module.exports = Comparator | ||
| const parseOptions = require('../internal/parse-options') | ||
| const { safeRe: re, t } = require('../internal/re') | ||
| const cmp = require('../functions/cmp') | ||
| const debug = require('../internal/debug') | ||
| const SemVer = require('./semver') | ||
| const Range = require('./range') |
| 'use strict' | ||
| module.exports = { | ||
| SemVer: require('./semver.js'), | ||
| Range: require('./range.js'), | ||
| Comparator: require('./comparator.js'), | ||
| } |
| 'use strict' | ||
| const SPACE_CHARACTERS = /\s+/g | ||
| // hoisted class for cyclic dependency | ||
| class Range { | ||
| constructor (range, options) { | ||
| options = parseOptions(options) | ||
| if (range instanceof Range) { | ||
| if ( | ||
| range.loose === !!options.loose && | ||
| range.includePrerelease === !!options.includePrerelease | ||
| ) { | ||
| return range | ||
| } else { | ||
| return new Range(range.raw, options) | ||
| } | ||
| } | ||
| if (range instanceof Comparator) { | ||
| // just put it in the set and return | ||
| this.raw = range.value | ||
| this.set = [[range]] | ||
| this.formatted = undefined | ||
| return this | ||
| } | ||
| this.options = options | ||
| this.loose = !!options.loose | ||
| this.includePrerelease = !!options.includePrerelease | ||
| // First reduce all whitespace as much as possible so we do not have to rely | ||
| // on potentially slow regexes like \s*. This is then stored and used for | ||
| // future error messages as well. | ||
| this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') | ||
| // First, split on || | ||
| this.set = this.raw | ||
| .split('||') | ||
| // map the range to a 2d array of comparators | ||
| .map(r => this.parseRange(r.trim())) | ||
| // throw out any comparator lists that are empty | ||
| // this generally means that it was not a valid range, which is allowed | ||
| // in loose mode, but will still throw if the WHOLE range is invalid. | ||
| .filter(c => c.length) | ||
| if (!this.set.length) { | ||
| throw new TypeError(`Invalid SemVer Range: ${this.raw}`) | ||
| } | ||
| // if we have any that are not the null set, throw out null sets. | ||
| if (this.set.length > 1) { | ||
| // keep the first one, in case they're all null sets | ||
| const first = this.set[0] | ||
| this.set = this.set.filter(c => !isNullSet(c[0])) | ||
| if (this.set.length === 0) { | ||
| this.set = [first] | ||
| } else if (this.set.length > 1) { | ||
| // if we have any that are *, then the range is just * | ||
| for (const c of this.set) { | ||
| if (c.length === 1 && isAny(c[0])) { | ||
| this.set = [c] | ||
| break | ||
| } | ||
| } | ||
| } | ||
| } | ||
| this.formatted = undefined | ||
| } | ||
| get range () { | ||
| if (this.formatted === undefined) { | ||
| this.formatted = '' | ||
| for (let i = 0; i < this.set.length; i++) { | ||
| if (i > 0) { | ||
| this.formatted += '||' | ||
| } | ||
| const comps = this.set[i] | ||
| for (let k = 0; k < comps.length; k++) { | ||
| if (k > 0) { | ||
| this.formatted += ' ' | ||
| } | ||
| this.formatted += comps[k].toString().trim() | ||
| } | ||
| } | ||
| } | ||
| return this.formatted | ||
| } | ||
| format () { | ||
| return this.range | ||
| } | ||
| toString () { | ||
| return this.range | ||
| } | ||
| parseRange (range) { | ||
| // strip build metadata so it can't bleed into the version | ||
| range = range.replace(BUILDSTRIPRE, '') | ||
| // memoize range parsing for performance. | ||
| // this is a very hot path, and fully deterministic. | ||
| const memoOpts = | ||
| (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | | ||
| (this.options.loose && FLAG_LOOSE) | ||
| const memoKey = memoOpts + ':' + range | ||
| const cached = cache.get(memoKey) | ||
| if (cached) { | ||
| return cached | ||
| } | ||
| const loose = this.options.loose | ||
| // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` | ||
| const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] | ||
| range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) | ||
| debug('hyphen replace', range) | ||
| // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` | ||
| range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) | ||
| debug('comparator trim', range) | ||
| // `~ 1.2.3` => `~1.2.3` | ||
| range = range.replace(re[t.TILDETRIM], tildeTrimReplace) | ||
| debug('tilde trim', range) | ||
| // `^ 1.2.3` => `^1.2.3` | ||
| range = range.replace(re[t.CARETTRIM], caretTrimReplace) | ||
| debug('caret trim', range) | ||
| // At this point, the range is completely trimmed and | ||
| // ready to be split into comparators. | ||
| let rangeList = range | ||
| .split(' ') | ||
| .map(comp => parseComparator(comp, this.options)) | ||
| .join(' ') | ||
| .split(/\s+/) | ||
| // >=0.0.0 is equivalent to * | ||
| .map(comp => replaceGTE0(comp, this.options)) | ||
| if (loose) { | ||
| // in loose mode, throw out any that are not valid comparators | ||
| rangeList = rangeList.filter(comp => { | ||
| debug('loose invalid filter', comp, this.options) | ||
| return !!comp.match(re[t.COMPARATORLOOSE]) | ||
| }) | ||
| } | ||
| debug('range list', rangeList) | ||
| // if any comparators are the null set, then replace with JUST null set | ||
| // if more than one comparator, remove any * comparators | ||
| // also, don't include the same comparator more than once | ||
| const rangeMap = new Map() | ||
| const comparators = rangeList.map(comp => new Comparator(comp, this.options)) | ||
| for (const comp of comparators) { | ||
| if (isNullSet(comp)) { | ||
| return [comp] | ||
| } | ||
| rangeMap.set(comp.value, comp) | ||
| } | ||
| if (rangeMap.size > 1 && rangeMap.has('')) { | ||
| rangeMap.delete('') | ||
| } | ||
| const result = [...rangeMap.values()] | ||
| cache.set(memoKey, result) | ||
| return result | ||
| } | ||
| intersects (range, options) { | ||
| if (!(range instanceof Range)) { | ||
| throw new TypeError('a Range is required') | ||
| } | ||
| return this.set.some((thisComparators) => { | ||
| return ( | ||
| isSatisfiable(thisComparators, options) && | ||
| range.set.some((rangeComparators) => { | ||
| return ( | ||
| isSatisfiable(rangeComparators, options) && | ||
| thisComparators.every((thisComparator) => { | ||
| return rangeComparators.every((rangeComparator) => { | ||
| return thisComparator.intersects(rangeComparator, options) | ||
| }) | ||
| }) | ||
| ) | ||
| }) | ||
| ) | ||
| }) | ||
| } | ||
| // if ANY of the sets match ALL of its comparators, then pass | ||
| test (version) { | ||
| if (!version) { | ||
| return false | ||
| } | ||
| if (typeof version === 'string') { | ||
| try { | ||
| version = new SemVer(version, this.options) | ||
| } catch (er) { | ||
| return false | ||
| } | ||
| } | ||
| for (let i = 0; i < this.set.length; i++) { | ||
| if (testSet(this.set[i], version, this.options)) { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } | ||
| } | ||
| module.exports = Range | ||
| const LRU = require('../internal/lrucache') | ||
| const cache = new LRU() | ||
| const parseOptions = require('../internal/parse-options') | ||
| const Comparator = require('./comparator') | ||
| const debug = require('../internal/debug') | ||
| const SemVer = require('./semver') | ||
| const { | ||
| safeRe: re, | ||
| src, | ||
| t, | ||
| comparatorTrimReplace, | ||
| tildeTrimReplace, | ||
| caretTrimReplace, | ||
| } = require('../internal/re') | ||
| const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants') | ||
| // unbounded global build-metadata stripper used by parseRange | ||
| const BUILDSTRIPRE = new RegExp(src[t.BUILD], 'g') | ||
| const isNullSet = c => c.value === '<0.0.0-0' | ||
| const isAny = c => c.value === '' | ||
| // take a set of comparators and determine whether there | ||
| // exists a version which can satisfy it | ||
| const isSatisfiable = (comparators, options) => { | ||
| let result = true | ||
| const remainingComparators = comparators.slice() | ||
| let testComparator = remainingComparators.pop() | ||
| while (result && remainingComparators.length) { | ||
| result = remainingComparators.every((otherComparator) => { | ||
| return testComparator.intersects(otherComparator, options) | ||
| }) | ||
| testComparator = remainingComparators.pop() | ||
| } | ||
| return result | ||
| } | ||
| // comprised of xranges, tildes, stars, and gtlt's at this point. | ||
| // already replaced the hyphen ranges | ||
| // turn into a set of JUST comparators. | ||
| const parseComparator = (comp, options) => { | ||
| comp = comp.replace(re[t.BUILD], '') | ||
| debug('comp', comp, options) | ||
| comp = replaceCarets(comp, options) | ||
| debug('caret', comp) | ||
| comp = replaceTildes(comp, options) | ||
| debug('tildes', comp) | ||
| comp = replaceXRanges(comp, options) | ||
| debug('xrange', comp) | ||
| comp = replaceStars(comp, options) | ||
| debug('stars', comp) | ||
| return comp | ||
| } | ||
| const isX = id => !id || id.toLowerCase() === 'x' || id === '*' | ||
| const invalidXRangeOrder = (M, m, p) => ( | ||
| (isX(M) && !isX(m)) || | ||
| (isX(m) && p && !isX(p)) | ||
| ) | ||
| // ~, ~> --> * (any, kinda silly) | ||
| // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 | ||
| // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 | ||
| // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 | ||
| // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 | ||
| // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 | ||
| // ~0.0.1 --> >=0.0.1 <0.1.0-0 | ||
| const replaceTildes = (comp, options) => { | ||
| return comp | ||
| .trim() | ||
| .split(/\s+/) | ||
| .map((c) => replaceTilde(c, options)) | ||
| .join(' ') | ||
| } | ||
| const replaceTilde = (comp, options) => { | ||
| const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] | ||
| // if we're including prereleases in the match, then the lower bound is | ||
| // -0, the lowest possible prerelease value, just like x-ranges and carets. | ||
| // this keeps `~1.2` equivalent to the `1.2.x` x-range it's documented as. | ||
| const z = options.includePrerelease ? '-0' : '' | ||
| return comp.replace(r, (_, M, m, p, pr) => { | ||
| debug('tilde', comp, _, M, m, p, pr) | ||
| let ret | ||
| if (isX(M)) { | ||
| ret = '' | ||
| } else if (isX(m)) { | ||
| ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` | ||
| } else if (isX(p)) { | ||
| // ~1.2 == >=1.2.0 <1.3.0-0 | ||
| ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` | ||
| } else if (pr) { | ||
| debug('replaceTilde pr', pr) | ||
| ret = `>=${M}.${m}.${p}-${pr | ||
| } <${M}.${+m + 1}.0-0` | ||
| } else { | ||
| // ~1.2.3 == >=1.2.3 <1.3.0-0 | ||
| ret = `>=${M}.${m}.${p | ||
| } <${M}.${+m + 1}.0-0` | ||
| } | ||
| debug('tilde return', ret) | ||
| return ret | ||
| }) | ||
| } | ||
| // ^ --> * (any, kinda silly) | ||
| // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 | ||
| // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 | ||
| // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 | ||
| // ^1.2.3 --> >=1.2.3 <2.0.0-0 | ||
| // ^1.2.0 --> >=1.2.0 <2.0.0-0 | ||
| // ^0.0.1 --> >=0.0.1 <0.0.2-0 | ||
| // ^0.1.0 --> >=0.1.0 <0.2.0-0 | ||
| const replaceCarets = (comp, options) => { | ||
| return comp | ||
| .trim() | ||
| .split(/\s+/) | ||
| .map((c) => replaceCaret(c, options)) | ||
| .join(' ') | ||
| } | ||
| const replaceCaret = (comp, options) => { | ||
| debug('caret', comp, options) | ||
| const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] | ||
| const z = options.includePrerelease ? '-0' : '' | ||
| return comp.replace(r, (_, M, m, p, pr) => { | ||
| debug('caret', comp, _, M, m, p, pr) | ||
| let ret | ||
| if (isX(M)) { | ||
| ret = '' | ||
| } else if (isX(m)) { | ||
| ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` | ||
| } else if (isX(p)) { | ||
| if (M === '0') { | ||
| ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` | ||
| } else { | ||
| ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` | ||
| } | ||
| } else if (pr) { | ||
| debug('replaceCaret pr', pr) | ||
| if (M === '0') { | ||
| if (m === '0') { | ||
| ret = `>=${M}.${m}.${p}-${pr | ||
| } <${M}.${m}.${+p + 1}-0` | ||
| } else { | ||
| ret = `>=${M}.${m}.${p}-${pr | ||
| } <${M}.${+m + 1}.0-0` | ||
| } | ||
| } else { | ||
| ret = `>=${M}.${m}.${p}-${pr | ||
| } <${+M + 1}.0.0-0` | ||
| } | ||
| } else { | ||
| debug('no pr') | ||
| if (M === '0') { | ||
| if (m === '0') { | ||
| ret = `>=${M}.${m}.${p | ||
| } <${M}.${m}.${+p + 1}-0` | ||
| } else { | ||
| ret = `>=${M}.${m}.${p | ||
| } <${M}.${+m + 1}.0-0` | ||
| } | ||
| } else { | ||
| ret = `>=${M}.${m}.${p | ||
| } <${+M + 1}.0.0-0` | ||
| } | ||
| } | ||
| debug('caret return', ret) | ||
| return ret | ||
| }) | ||
| } | ||
| const replaceXRanges = (comp, options) => { | ||
| debug('replaceXRanges', comp, options) | ||
| return comp | ||
| .split(/\s+/) | ||
| .map((c) => replaceXRange(c, options)) | ||
| .join(' ') | ||
| } | ||
| const replaceXRange = (comp, options) => { | ||
| comp = comp.trim() | ||
| const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] | ||
| return comp.replace(r, (ret, gtlt, M, m, p, pr) => { | ||
| debug('xRange', comp, ret, gtlt, M, m, p, pr) | ||
| if (invalidXRangeOrder(M, m, p)) { | ||
| return comp | ||
| } | ||
| const xM = isX(M) | ||
| const xm = xM || isX(m) | ||
| const xp = xm || isX(p) | ||
| const anyX = xp | ||
| if (gtlt === '=' && anyX) { | ||
| gtlt = '' | ||
| } | ||
| // if we're including prereleases in the match, then we need | ||
| // to fix this to -0, the lowest possible prerelease value | ||
| pr = options.includePrerelease ? '-0' : '' | ||
| if (xM) { | ||
| if (gtlt === '>' || gtlt === '<') { | ||
| // nothing is allowed | ||
| ret = '<0.0.0-0' | ||
| } else { | ||
| // nothing is forbidden | ||
| ret = '*' | ||
| } | ||
| } else if (gtlt && anyX) { | ||
| // we know patch is an x, because we have any x at all. | ||
| // replace X with 0 | ||
| if (xm) { | ||
| m = 0 | ||
| } | ||
| p = 0 | ||
| if (gtlt === '>') { | ||
| // >1 => >=2.0.0 | ||
| // >1.2 => >=1.3.0 | ||
| gtlt = '>=' | ||
| if (xm) { | ||
| M = +M + 1 | ||
| m = 0 | ||
| p = 0 | ||
| } else { | ||
| m = +m + 1 | ||
| p = 0 | ||
| } | ||
| } else if (gtlt === '<=') { | ||
| // <=0.7.x is actually <0.8.0, since any 0.7.x should | ||
| // pass. Similarly, <=7.x is actually <8.0.0, etc. | ||
| gtlt = '<' | ||
| if (xm) { | ||
| M = +M + 1 | ||
| } else { | ||
| m = +m + 1 | ||
| } | ||
| } | ||
| if (gtlt === '<') { | ||
| pr = '-0' | ||
| } | ||
| ret = `${gtlt + M}.${m}.${p}${pr}` | ||
| } else if (xm) { | ||
| ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` | ||
| } else if (xp) { | ||
| ret = `>=${M}.${m}.0${pr | ||
| } <${M}.${+m + 1}.0-0` | ||
| } | ||
| debug('xRange return', ret) | ||
| return ret | ||
| }) | ||
| } | ||
| // Because * is AND-ed with everything else in the comparator, | ||
| // and '' means "any version", just remove the *s entirely. | ||
| const replaceStars = (comp, options) => { | ||
| debug('replaceStars', comp, options) | ||
| // Looseness is ignored here. star is always as loose as it gets! | ||
| return comp | ||
| .trim() | ||
| .replace(re[t.STAR], '') | ||
| } | ||
| const replaceGTE0 = (comp, options) => { | ||
| debug('replaceGTE0', comp, options) | ||
| return comp | ||
| .trim() | ||
| .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') | ||
| } | ||
| // This function is passed to string.replace(re[t.HYPHENRANGE]) | ||
| // M, m, patch, prerelease, build | ||
| // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 | ||
| // 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do | ||
| // 1.2 - 3.4 => >=1.2.0 <3.5.0-0 | ||
| // TODO build? | ||
| const hyphenReplace = incPr => ($0, | ||
| from, fM, fm, fp, fpr, fb, | ||
| to, tM, tm, tp, tpr) => { | ||
| if (isX(fM)) { | ||
| from = '' | ||
| } else if (isX(fm)) { | ||
| from = `>=${fM}.0.0${incPr ? '-0' : ''}` | ||
| } else if (isX(fp)) { | ||
| from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` | ||
| } else if (fpr) { | ||
| from = `>=${from}` | ||
| } else { | ||
| from = `>=${from}${incPr ? '-0' : ''}` | ||
| } | ||
| if (isX(tM)) { | ||
| to = '' | ||
| } else if (isX(tm)) { | ||
| to = `<${+tM + 1}.0.0-0` | ||
| } else if (isX(tp)) { | ||
| to = `<${tM}.${+tm + 1}.0-0` | ||
| } else if (tpr) { | ||
| to = `<=${tM}.${tm}.${tp}-${tpr}` | ||
| } else if (incPr) { | ||
| to = `<${tM}.${tm}.${+tp + 1}-0` | ||
| } else { | ||
| to = `<=${to}` | ||
| } | ||
| return `${from} ${to}`.trim() | ||
| } | ||
| const testSet = (set, version, options) => { | ||
| for (let i = 0; i < set.length; i++) { | ||
| if (!set[i].test(version)) { | ||
| return false | ||
| } | ||
| } | ||
| if (version.prerelease.length && !options.includePrerelease) { | ||
| // Find the set of versions that are allowed to have prereleases | ||
| // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 | ||
| // That should allow `1.2.3-pr.2` to pass. | ||
| // However, `1.2.4-alpha.notready` should NOT be allowed, | ||
| // even though it's within the range set by the comparators. | ||
| for (let i = 0; i < set.length; i++) { | ||
| debug(set[i].semver) | ||
| if (set[i].semver === Comparator.ANY) { | ||
| continue | ||
| } | ||
| if (set[i].semver.prerelease.length > 0) { | ||
| const allowed = set[i].semver | ||
| if (allowed.major === version.major && | ||
| allowed.minor === version.minor && | ||
| allowed.patch === version.patch) { | ||
| return true | ||
| } | ||
| } | ||
| } | ||
| // Version has a -pre, but it's not one of the ones we like. | ||
| return false | ||
| } | ||
| return true | ||
| } |
| 'use strict' | ||
| const debug = require('../internal/debug') | ||
| const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') | ||
| const { safeRe: re, t } = require('../internal/re') | ||
| const parseOptions = require('../internal/parse-options') | ||
| const { compareIdentifiers } = require('../internal/identifiers') | ||
| const isPrereleaseIdentifier = (prerelease, identifier) => { | ||
| const identifiers = identifier.split('.') | ||
| if (identifiers.length > prerelease.length) { | ||
| return false | ||
| } | ||
| for (let i = 0; i < identifiers.length; i++) { | ||
| if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) { | ||
| return false | ||
| } | ||
| } | ||
| return true | ||
| } | ||
| class SemVer { | ||
| constructor (version, options) { | ||
| options = parseOptions(options) | ||
| if (version instanceof SemVer) { | ||
| if (version.loose === !!options.loose && | ||
| version.includePrerelease === !!options.includePrerelease) { | ||
| return version | ||
| } else { | ||
| version = version.version | ||
| } | ||
| } else if (typeof version !== 'string') { | ||
| throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) | ||
| } | ||
| if (version.length > MAX_LENGTH) { | ||
| throw new TypeError( | ||
| `version is longer than ${MAX_LENGTH} characters` | ||
| ) | ||
| } | ||
| debug('SemVer', version, options) | ||
| this.options = options | ||
| this.loose = !!options.loose | ||
| // this isn't actually relevant for versions, but keep it so that we | ||
| // don't run into trouble passing this.options around. | ||
| this.includePrerelease = !!options.includePrerelease | ||
| const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) | ||
| if (!m) { | ||
| throw new TypeError(`Invalid Version: ${version}`) | ||
| } | ||
| this.raw = version | ||
| // these are actually numbers | ||
| this.major = +m[1] | ||
| this.minor = +m[2] | ||
| this.patch = +m[3] | ||
| if (this.major > MAX_SAFE_INTEGER || this.major < 0) { | ||
| throw new TypeError('Invalid major version') | ||
| } | ||
| if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { | ||
| throw new TypeError('Invalid minor version') | ||
| } | ||
| if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { | ||
| throw new TypeError('Invalid patch version') | ||
| } | ||
| // numberify any prerelease numeric ids | ||
| if (!m[4]) { | ||
| this.prerelease = [] | ||
| } else { | ||
| this.prerelease = m[4].split('.').map((id) => { | ||
| if (/^[0-9]+$/.test(id)) { | ||
| const num = +id | ||
| if (num >= 0 && num < MAX_SAFE_INTEGER) { | ||
| return num | ||
| } | ||
| } | ||
| return id | ||
| }) | ||
| } | ||
| this.build = m[5] ? m[5].split('.') : [] | ||
| this.format() | ||
| } | ||
| format () { | ||
| this.version = `${this.major}.${this.minor}.${this.patch}` | ||
| if (this.prerelease.length) { | ||
| this.version += `-${this.prerelease.join('.')}` | ||
| } | ||
| return this.version | ||
| } | ||
| toString () { | ||
| return this.version | ||
| } | ||
| compare (other) { | ||
| debug('SemVer.compare', this.version, this.options, other) | ||
| if (!(other instanceof SemVer)) { | ||
| if (typeof other === 'string' && other === this.version) { | ||
| return 0 | ||
| } | ||
| other = new SemVer(other, this.options) | ||
| } | ||
| if (other.version === this.version) { | ||
| return 0 | ||
| } | ||
| return this.compareMain(other) || this.comparePre(other) | ||
| } | ||
| compareMain (other) { | ||
| if (!(other instanceof SemVer)) { | ||
| other = new SemVer(other, this.options) | ||
| } | ||
| if (this.major < other.major) { | ||
| return -1 | ||
| } | ||
| if (this.major > other.major) { | ||
| return 1 | ||
| } | ||
| if (this.minor < other.minor) { | ||
| return -1 | ||
| } | ||
| if (this.minor > other.minor) { | ||
| return 1 | ||
| } | ||
| if (this.patch < other.patch) { | ||
| return -1 | ||
| } | ||
| if (this.patch > other.patch) { | ||
| return 1 | ||
| } | ||
| return 0 | ||
| } | ||
| comparePre (other) { | ||
| if (!(other instanceof SemVer)) { | ||
| other = new SemVer(other, this.options) | ||
| } | ||
| // NOT having a prerelease is > having one | ||
| if (this.prerelease.length && !other.prerelease.length) { | ||
| return -1 | ||
| } else if (!this.prerelease.length && other.prerelease.length) { | ||
| return 1 | ||
| } else if (!this.prerelease.length && !other.prerelease.length) { | ||
| return 0 | ||
| } | ||
| let i = 0 | ||
| do { | ||
| const a = this.prerelease[i] | ||
| const b = other.prerelease[i] | ||
| debug('prerelease compare', i, a, b) | ||
| if (a === undefined && b === undefined) { | ||
| return 0 | ||
| } else if (b === undefined) { | ||
| return 1 | ||
| } else if (a === undefined) { | ||
| return -1 | ||
| } else if (a === b) { | ||
| continue | ||
| } else { | ||
| return compareIdentifiers(a, b) | ||
| } | ||
| } while (++i) | ||
| } | ||
| compareBuild (other) { | ||
| if (!(other instanceof SemVer)) { | ||
| other = new SemVer(other, this.options) | ||
| } | ||
| let i = 0 | ||
| do { | ||
| const a = this.build[i] | ||
| const b = other.build[i] | ||
| debug('build compare', i, a, b) | ||
| if (a === undefined && b === undefined) { | ||
| return 0 | ||
| } else if (b === undefined) { | ||
| return 1 | ||
| } else if (a === undefined) { | ||
| return -1 | ||
| } else if (a === b) { | ||
| continue | ||
| } else { | ||
| return compareIdentifiers(a, b) | ||
| } | ||
| } while (++i) | ||
| } | ||
| // preminor will bump the version up to the next minor release, and immediately | ||
| // down to pre-release. premajor and prepatch work the same way. | ||
| inc (release, identifier, identifierBase) { | ||
| if (release.startsWith('pre')) { | ||
| if (!identifier && identifierBase === false) { | ||
| throw new Error('invalid increment argument: identifier is empty') | ||
| } | ||
| // Avoid an invalid semver results | ||
| if (identifier) { | ||
| const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]) | ||
| if (!match || match[1] !== identifier) { | ||
| throw new Error(`invalid identifier: ${identifier}`) | ||
| } | ||
| } | ||
| } | ||
| switch (release) { | ||
| case 'premajor': | ||
| this.prerelease.length = 0 | ||
| this.patch = 0 | ||
| this.minor = 0 | ||
| this.major++ | ||
| this.inc('pre', identifier, identifierBase) | ||
| break | ||
| case 'preminor': | ||
| this.prerelease.length = 0 | ||
| this.patch = 0 | ||
| this.minor++ | ||
| this.inc('pre', identifier, identifierBase) | ||
| break | ||
| case 'prepatch': | ||
| // If this is already a prerelease, it will bump to the next version | ||
| // drop any prereleases that might already exist, since they are not | ||
| // relevant at this point. | ||
| this.prerelease.length = 0 | ||
| this.inc('patch', identifier, identifierBase) | ||
| this.inc('pre', identifier, identifierBase) | ||
| break | ||
| // If the input is a non-prerelease version, this acts the same as | ||
| // prepatch. | ||
| case 'prerelease': | ||
| if (this.prerelease.length === 0) { | ||
| this.inc('patch', identifier, identifierBase) | ||
| } | ||
| this.inc('pre', identifier, identifierBase) | ||
| break | ||
| case 'release': | ||
| if (this.prerelease.length === 0) { | ||
| throw new Error(`version ${this.raw} is not a prerelease`) | ||
| } | ||
| this.prerelease.length = 0 | ||
| break | ||
| case 'major': | ||
| // If this is a pre-major version, bump up to the same major version. | ||
| // Otherwise increment major. | ||
| // 1.0.0-5 bumps to 1.0.0 | ||
| // 1.1.0 bumps to 2.0.0 | ||
| if ( | ||
| this.minor !== 0 || | ||
| this.patch !== 0 || | ||
| this.prerelease.length === 0 | ||
| ) { | ||
| this.major++ | ||
| } | ||
| this.minor = 0 | ||
| this.patch = 0 | ||
| this.prerelease = [] | ||
| break | ||
| case 'minor': | ||
| // If this is a pre-minor version, bump up to the same minor version. | ||
| // Otherwise increment minor. | ||
| // 1.2.0-5 bumps to 1.2.0 | ||
| // 1.2.1 bumps to 1.3.0 | ||
| if (this.patch !== 0 || this.prerelease.length === 0) { | ||
| this.minor++ | ||
| } | ||
| this.patch = 0 | ||
| this.prerelease = [] | ||
| break | ||
| case 'patch': | ||
| // If this is not a pre-release version, it will increment the patch. | ||
| // If it is a pre-release it will bump up to the same patch version. | ||
| // 1.2.0-5 patches to 1.2.0 | ||
| // 1.2.0 patches to 1.2.1 | ||
| if (this.prerelease.length === 0) { | ||
| this.patch++ | ||
| } | ||
| this.prerelease = [] | ||
| break | ||
| // This probably shouldn't be used publicly. | ||
| // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. | ||
| case 'pre': { | ||
| const base = Number(identifierBase) ? 1 : 0 | ||
| if (this.prerelease.length === 0) { | ||
| this.prerelease = [base] | ||
| } else { | ||
| let i = this.prerelease.length | ||
| while (--i >= 0) { | ||
| if (typeof this.prerelease[i] === 'number') { | ||
| this.prerelease[i]++ | ||
| i = -2 | ||
| } | ||
| } | ||
| if (i === -1) { | ||
| // didn't increment anything | ||
| if (identifier === this.prerelease.join('.') && identifierBase === false) { | ||
| throw new Error('invalid increment argument: identifier already exists') | ||
| } | ||
| this.prerelease.push(base) | ||
| } | ||
| } | ||
| if (identifier) { | ||
| // 1.2.0-beta.1 bumps to 1.2.0-beta.2, | ||
| // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 | ||
| let prerelease = [identifier, base] | ||
| if (identifierBase === false) { | ||
| prerelease = [identifier] | ||
| } | ||
| if (isPrereleaseIdentifier(this.prerelease, identifier)) { | ||
| const prereleaseBase = this.prerelease[identifier.split('.').length] | ||
| if (isNaN(prereleaseBase)) { | ||
| this.prerelease = prerelease | ||
| } | ||
| } else { | ||
| this.prerelease = prerelease | ||
| } | ||
| } | ||
| break | ||
| } | ||
| default: | ||
| throw new Error(`invalid increment argument: ${release}`) | ||
| } | ||
| this.raw = this.format() | ||
| if (this.build.length) { | ||
| this.raw += `+${this.build.join('.')}` | ||
| } | ||
| return this | ||
| } | ||
| } | ||
| module.exports = SemVer |
| 'use strict' | ||
| const parse = require('./parse') | ||
| const clean = (version, options) => { | ||
| const s = parse(version.trim().replace(/^[=v]+/, ''), options) | ||
| return s ? s.version : null | ||
| } | ||
| module.exports = clean |
| 'use strict' | ||
| const eq = require('./eq') | ||
| const neq = require('./neq') | ||
| const gt = require('./gt') | ||
| const gte = require('./gte') | ||
| const lt = require('./lt') | ||
| const lte = require('./lte') | ||
| const cmp = (a, op, b, loose) => { | ||
| switch (op) { | ||
| case '===': | ||
| if (typeof a === 'object') { | ||
| a = a.version | ||
| } | ||
| if (typeof b === 'object') { | ||
| b = b.version | ||
| } | ||
| return a === b | ||
| case '!==': | ||
| if (typeof a === 'object') { | ||
| a = a.version | ||
| } | ||
| if (typeof b === 'object') { | ||
| b = b.version | ||
| } | ||
| return a !== b | ||
| case '': | ||
| case '=': | ||
| case '==': | ||
| return eq(a, b, loose) | ||
| case '!=': | ||
| return neq(a, b, loose) | ||
| case '>': | ||
| return gt(a, b, loose) | ||
| case '>=': | ||
| return gte(a, b, loose) | ||
| case '<': | ||
| return lt(a, b, loose) | ||
| case '<=': | ||
| return lte(a, b, loose) | ||
| default: | ||
| throw new TypeError(`Invalid operator: ${op}`) | ||
| } | ||
| } | ||
| module.exports = cmp |
| 'use strict' | ||
| const SemVer = require('../classes/semver') | ||
| const parse = require('./parse') | ||
| const { safeRe: re, t } = require('../internal/re') | ||
| const coerce = (version, options) => { | ||
| if (version instanceof SemVer) { | ||
| return version | ||
| } | ||
| if (typeof version === 'number') { | ||
| version = String(version) | ||
| } | ||
| if (typeof version !== 'string') { | ||
| return null | ||
| } | ||
| options = options || {} | ||
| let match = null | ||
| if (!options.rtl) { | ||
| match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) | ||
| } else { | ||
| // Find the right-most coercible string that does not share | ||
| // a terminus with a more left-ward coercible string. | ||
| // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' | ||
| // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' | ||
| // | ||
| // Walk through the string checking with a /g regexp | ||
| // Manually set the index so as to pick up overlapping matches. | ||
| // Stop when we get a match that ends at the string end, since no | ||
| // coercible string can be more right-ward without the same terminus. | ||
| const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] | ||
| let next | ||
| while ((next = coerceRtlRegex.exec(version)) && | ||
| (!match || match.index + match[0].length !== version.length) | ||
| ) { | ||
| if (!match || | ||
| next.index + next[0].length !== match.index + match[0].length) { | ||
| match = next | ||
| } | ||
| coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length | ||
| } | ||
| // leave it in a clean state | ||
| coerceRtlRegex.lastIndex = -1 | ||
| } | ||
| if (match === null) { | ||
| return null | ||
| } | ||
| const major = match[2] | ||
| const minor = match[3] || '0' | ||
| const patch = match[4] || '0' | ||
| const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' | ||
| const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' | ||
| return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) | ||
| } | ||
| module.exports = coerce |
| 'use strict' | ||
| const SemVer = require('../classes/semver') | ||
| const compareBuild = (a, b, loose) => { | ||
| const versionA = new SemVer(a, loose) | ||
| const versionB = new SemVer(b, loose) | ||
| return versionA.compare(versionB) || versionA.compareBuild(versionB) | ||
| } | ||
| module.exports = compareBuild |
| 'use strict' | ||
| const compare = require('./compare') | ||
| const compareLoose = (a, b) => compare(a, b, true) | ||
| module.exports = compareLoose |
| 'use strict' | ||
| const SemVer = require('../classes/semver') | ||
| const compare = (a, b, loose) => | ||
| new SemVer(a, loose).compare(new SemVer(b, loose)) | ||
| module.exports = compare |
| 'use strict' | ||
| const parse = require('./parse.js') | ||
| const diff = (version1, version2) => { | ||
| const v1 = parse(version1, null, true) | ||
| const v2 = parse(version2, null, true) | ||
| const comparison = v1.compare(v2) | ||
| if (comparison === 0) { | ||
| return null | ||
| } | ||
| const v1Higher = comparison > 0 | ||
| const highVersion = v1Higher ? v1 : v2 | ||
| const lowVersion = v1Higher ? v2 : v1 | ||
| const highHasPre = !!highVersion.prerelease.length | ||
| const lowHasPre = !!lowVersion.prerelease.length | ||
| if (lowHasPre && !highHasPre) { | ||
| // Going from prerelease -> no prerelease requires some special casing | ||
| // If the low version has only a major, then it will always be a major | ||
| // Some examples: | ||
| // 1.0.0-1 -> 1.0.0 | ||
| // 1.0.0-1 -> 1.1.1 | ||
| // 1.0.0-1 -> 2.0.0 | ||
| if (!lowVersion.patch && !lowVersion.minor) { | ||
| return 'major' | ||
| } | ||
| // If the main part has no difference | ||
| if (lowVersion.compareMain(highVersion) === 0) { | ||
| if (lowVersion.minor && !lowVersion.patch) { | ||
| return 'minor' | ||
| } | ||
| return 'patch' | ||
| } | ||
| } | ||
| // add the `pre` prefix if we are going to a prerelease version | ||
| const prefix = highHasPre ? 'pre' : '' | ||
| if (v1.major !== v2.major) { | ||
| return prefix + 'major' | ||
| } | ||
| if (v1.minor !== v2.minor) { | ||
| return prefix + 'minor' | ||
| } | ||
| if (v1.patch !== v2.patch) { | ||
| return prefix + 'patch' | ||
| } | ||
| // high and low are prereleases | ||
| return 'prerelease' | ||
| } | ||
| module.exports = diff |
| 'use strict' | ||
| const compare = require('./compare') | ||
| const eq = (a, b, loose) => compare(a, b, loose) === 0 | ||
| module.exports = eq |
| 'use strict' | ||
| const compare = require('./compare') | ||
| const gt = (a, b, loose) => compare(a, b, loose) > 0 | ||
| module.exports = gt |
| 'use strict' | ||
| const compare = require('./compare') | ||
| const gte = (a, b, loose) => compare(a, b, loose) >= 0 | ||
| module.exports = gte |
| 'use strict' | ||
| const SemVer = require('../classes/semver') | ||
| const inc = (version, release, options, identifier, identifierBase) => { | ||
| if (typeof (options) === 'string') { | ||
| identifierBase = identifier | ||
| identifier = options | ||
| options = undefined | ||
| } | ||
| try { | ||
| return new SemVer( | ||
| version instanceof SemVer ? version.version : version, | ||
| options | ||
| ).inc(release, identifier, identifierBase).version | ||
| } catch (er) { | ||
| return null | ||
| } | ||
| } | ||
| module.exports = inc |
| 'use strict' | ||
| const compare = require('./compare') | ||
| const lt = (a, b, loose) => compare(a, b, loose) < 0 | ||
| module.exports = lt |
| 'use strict' | ||
| const compare = require('./compare') | ||
| const lte = (a, b, loose) => compare(a, b, loose) <= 0 | ||
| module.exports = lte |
| 'use strict' | ||
| const SemVer = require('../classes/semver') | ||
| const major = (a, loose) => new SemVer(a, loose).major | ||
| module.exports = major |
| 'use strict' | ||
| const SemVer = require('../classes/semver') | ||
| const minor = (a, loose) => new SemVer(a, loose).minor | ||
| module.exports = minor |
| 'use strict' | ||
| const compare = require('./compare') | ||
| const neq = (a, b, loose) => compare(a, b, loose) !== 0 | ||
| module.exports = neq |
| 'use strict' | ||
| const SemVer = require('../classes/semver') | ||
| const parse = (version, options, throwErrors = false) => { | ||
| if (version instanceof SemVer) { | ||
| return version | ||
| } | ||
| try { | ||
| return new SemVer(version, options) | ||
| } catch (er) { | ||
| if (!throwErrors) { | ||
| return null | ||
| } | ||
| throw er | ||
| } | ||
| } | ||
| module.exports = parse |
| 'use strict' | ||
| const SemVer = require('../classes/semver') | ||
| const patch = (a, loose) => new SemVer(a, loose).patch | ||
| module.exports = patch |
| 'use strict' | ||
| const parse = require('./parse') | ||
| const prerelease = (version, options) => { | ||
| const parsed = parse(version, options) | ||
| return (parsed && parsed.prerelease.length) ? parsed.prerelease : null | ||
| } | ||
| module.exports = prerelease |
| 'use strict' | ||
| const compare = require('./compare') | ||
| const rcompare = (a, b, loose) => compare(b, a, loose) | ||
| module.exports = rcompare |
| 'use strict' | ||
| const compareBuild = require('./compare-build') | ||
| const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) | ||
| module.exports = rsort |
| 'use strict' | ||
| const Range = require('../classes/range') | ||
| const satisfies = (version, range, options) => { | ||
| try { | ||
| range = new Range(range, options) | ||
| } catch (er) { | ||
| return false | ||
| } | ||
| return range.test(version) | ||
| } | ||
| module.exports = satisfies |
| 'use strict' | ||
| const compareBuild = require('./compare-build') | ||
| const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) | ||
| module.exports = sort |
| 'use strict' | ||
| const parse = require('./parse') | ||
| const constants = require('../internal/constants') | ||
| const SemVer = require('../classes/semver') | ||
| const truncate = (version, truncation, options) => { | ||
| if (!constants.RELEASE_TYPES.includes(truncation)) { | ||
| return null | ||
| } | ||
| const clonedVersion = cloneInputVersion(version, options) | ||
| return clonedVersion && doTruncation(clonedVersion, truncation) | ||
| } | ||
| const cloneInputVersion = (version, options) => { | ||
| const versionStringToParse = ( | ||
| version instanceof SemVer ? version.version : version | ||
| ) | ||
| return parse(versionStringToParse, options) | ||
| } | ||
| const doTruncation = (version, truncation) => { | ||
| if (isPrerelease(truncation)) { | ||
| return version.version | ||
| } | ||
| version.prerelease = [] | ||
| switch (truncation) { | ||
| case 'major': | ||
| version.minor = 0 | ||
| version.patch = 0 | ||
| break | ||
| case 'minor': | ||
| version.patch = 0 | ||
| break | ||
| } | ||
| return version.format() | ||
| } | ||
| const isPrerelease = (type) => { | ||
| return type.startsWith('pre') | ||
| } | ||
| module.exports = truncate |
| 'use strict' | ||
| const parse = require('./parse') | ||
| const valid = (version, options) => { | ||
| const v = parse(version, options) | ||
| return v ? v.version : null | ||
| } | ||
| module.exports = valid |
| 'use strict' | ||
| // just pre-load all the stuff that index.js lazily exports | ||
| const internalRe = require('./internal/re') | ||
| const constants = require('./internal/constants') | ||
| const SemVer = require('./classes/semver') | ||
| const identifiers = require('./internal/identifiers') | ||
| const parse = require('./functions/parse') | ||
| const valid = require('./functions/valid') | ||
| const clean = require('./functions/clean') | ||
| const inc = require('./functions/inc') | ||
| const diff = require('./functions/diff') | ||
| const major = require('./functions/major') | ||
| const minor = require('./functions/minor') | ||
| const patch = require('./functions/patch') | ||
| const prerelease = require('./functions/prerelease') | ||
| const compare = require('./functions/compare') | ||
| const rcompare = require('./functions/rcompare') | ||
| const compareLoose = require('./functions/compare-loose') | ||
| const compareBuild = require('./functions/compare-build') | ||
| const sort = require('./functions/sort') | ||
| const rsort = require('./functions/rsort') | ||
| const gt = require('./functions/gt') | ||
| const lt = require('./functions/lt') | ||
| const eq = require('./functions/eq') | ||
| const neq = require('./functions/neq') | ||
| const gte = require('./functions/gte') | ||
| const lte = require('./functions/lte') | ||
| const cmp = require('./functions/cmp') | ||
| const coerce = require('./functions/coerce') | ||
| const truncate = require('./functions/truncate') | ||
| const Comparator = require('./classes/comparator') | ||
| const Range = require('./classes/range') | ||
| const satisfies = require('./functions/satisfies') | ||
| const toComparators = require('./ranges/to-comparators') | ||
| const maxSatisfying = require('./ranges/max-satisfying') | ||
| const minSatisfying = require('./ranges/min-satisfying') | ||
| const minVersion = require('./ranges/min-version') | ||
| const validRange = require('./ranges/valid') | ||
| const outside = require('./ranges/outside') | ||
| const gtr = require('./ranges/gtr') | ||
| const ltr = require('./ranges/ltr') | ||
| const intersects = require('./ranges/intersects') | ||
| const simplifyRange = require('./ranges/simplify') | ||
| const subset = require('./ranges/subset') | ||
| module.exports = { | ||
| parse, | ||
| valid, | ||
| clean, | ||
| inc, | ||
| diff, | ||
| major, | ||
| minor, | ||
| patch, | ||
| prerelease, | ||
| compare, | ||
| rcompare, | ||
| compareLoose, | ||
| compareBuild, | ||
| sort, | ||
| rsort, | ||
| gt, | ||
| lt, | ||
| eq, | ||
| neq, | ||
| gte, | ||
| lte, | ||
| cmp, | ||
| coerce, | ||
| truncate, | ||
| Comparator, | ||
| Range, | ||
| satisfies, | ||
| toComparators, | ||
| maxSatisfying, | ||
| minSatisfying, | ||
| minVersion, | ||
| validRange, | ||
| outside, | ||
| gtr, | ||
| ltr, | ||
| intersects, | ||
| simplifyRange, | ||
| subset, | ||
| SemVer, | ||
| re: internalRe.re, | ||
| src: internalRe.src, | ||
| tokens: internalRe.t, | ||
| SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, | ||
| RELEASE_TYPES: constants.RELEASE_TYPES, | ||
| compareIdentifiers: identifiers.compareIdentifiers, | ||
| rcompareIdentifiers: identifiers.rcompareIdentifiers, | ||
| } |
| 'use strict' | ||
| // Note: this is the semver.org version of the spec that it implements | ||
| // Not necessarily the package version of this code. | ||
| const SEMVER_SPEC_VERSION = '2.0.0' | ||
| const MAX_LENGTH = 256 | ||
| const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || | ||
| /* istanbul ignore next */ 9007199254740991 | ||
| // Max safe segment length for coercion. | ||
| const MAX_SAFE_COMPONENT_LENGTH = 16 | ||
| // Max safe length for a build identifier. The max length minus 6 characters for | ||
| // the shortest version with a build 0.0.0+BUILD. | ||
| const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 | ||
| const RELEASE_TYPES = [ | ||
| 'major', | ||
| 'premajor', | ||
| 'minor', | ||
| 'preminor', | ||
| 'patch', | ||
| 'prepatch', | ||
| 'prerelease', | ||
| ] | ||
| module.exports = { | ||
| MAX_LENGTH, | ||
| MAX_SAFE_COMPONENT_LENGTH, | ||
| MAX_SAFE_BUILD_LENGTH, | ||
| MAX_SAFE_INTEGER, | ||
| RELEASE_TYPES, | ||
| SEMVER_SPEC_VERSION, | ||
| FLAG_INCLUDE_PRERELEASE: 0b001, | ||
| FLAG_LOOSE: 0b010, | ||
| } |
| 'use strict' | ||
| const debug = ( | ||
| typeof process === 'object' && | ||
| process.env && | ||
| process.env.NODE_DEBUG && | ||
| /\bsemver\b/i.test(process.env.NODE_DEBUG) | ||
| ) ? (...args) => console.error('SEMVER', ...args) | ||
| : () => {} | ||
| module.exports = debug |
| 'use strict' | ||
| const numeric = /^[0-9]+$/ | ||
| const compareIdentifiers = (a, b) => { | ||
| if (typeof a === 'number' && typeof b === 'number') { | ||
| return a === b ? 0 : a < b ? -1 : 1 | ||
| } | ||
| const anum = numeric.test(a) | ||
| const bnum = numeric.test(b) | ||
| if (anum && bnum) { | ||
| a = +a | ||
| b = +b | ||
| } | ||
| return a === b ? 0 | ||
| : (anum && !bnum) ? -1 | ||
| : (bnum && !anum) ? 1 | ||
| : a < b ? -1 | ||
| : 1 | ||
| } | ||
| const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) | ||
| module.exports = { | ||
| compareIdentifiers, | ||
| rcompareIdentifiers, | ||
| } |
| 'use strict' | ||
| class LRUCache { | ||
| constructor () { | ||
| this.max = 1000 | ||
| this.map = new Map() | ||
| } | ||
| get (key) { | ||
| const value = this.map.get(key) | ||
| if (value === undefined) { | ||
| return undefined | ||
| } else { | ||
| // Remove the key from the map and add it to the end | ||
| this.map.delete(key) | ||
| this.map.set(key, value) | ||
| return value | ||
| } | ||
| } | ||
| delete (key) { | ||
| return this.map.delete(key) | ||
| } | ||
| set (key, value) { | ||
| const deleted = this.delete(key) | ||
| if (!deleted && value !== undefined) { | ||
| // If cache is full, delete the least recently used item | ||
| if (this.map.size >= this.max) { | ||
| const firstKey = this.map.keys().next().value | ||
| this.delete(firstKey) | ||
| } | ||
| this.map.set(key, value) | ||
| } | ||
| return this | ||
| } | ||
| } | ||
| module.exports = LRUCache |
| 'use strict' | ||
| // parse out just the options we care about | ||
| const looseOption = Object.freeze({ loose: true }) | ||
| const emptyOpts = Object.freeze({ }) | ||
| const parseOptions = options => { | ||
| if (!options) { | ||
| return emptyOpts | ||
| } | ||
| if (typeof options !== 'object') { | ||
| return looseOption | ||
| } | ||
| return options | ||
| } | ||
| module.exports = parseOptions |
| 'use strict' | ||
| const { | ||
| MAX_SAFE_COMPONENT_LENGTH, | ||
| MAX_SAFE_BUILD_LENGTH, | ||
| MAX_LENGTH, | ||
| } = require('./constants') | ||
| const debug = require('./debug') | ||
| exports = module.exports = {} | ||
| // The actual regexps go on exports.re | ||
| const re = exports.re = [] | ||
| const safeRe = exports.safeRe = [] | ||
| const src = exports.src = [] | ||
| const safeSrc = exports.safeSrc = [] | ||
| const t = exports.t = {} | ||
| let R = 0 | ||
| const LETTERDASHNUMBER = '[a-zA-Z0-9-]' | ||
| // Replace some greedy regex tokens to prevent regex dos issues. These regex are | ||
| // used internally via the safeRe object since all inputs in this library get | ||
| // normalized first to trim and collapse all extra whitespace. The original | ||
| // regexes are exported for userland consumption and lower level usage. A | ||
| // future breaking change could export the safer regex only with a note that | ||
| // all input should have extra whitespace removed. | ||
| const safeRegexReplacements = [ | ||
| ['\\s', 1], | ||
| ['\\d', MAX_LENGTH], | ||
| [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], | ||
| ] | ||
| const makeSafeRegex = (value) => { | ||
| for (const [token, max] of safeRegexReplacements) { | ||
| value = value | ||
| .split(`${token}*`).join(`${token}{0,${max}}`) | ||
| .split(`${token}+`).join(`${token}{1,${max}}`) | ||
| } | ||
| return value | ||
| } | ||
| const createToken = (name, value, isGlobal) => { | ||
| const safe = makeSafeRegex(value) | ||
| const index = R++ | ||
| debug(name, index, value) | ||
| t[name] = index | ||
| src[index] = value | ||
| safeSrc[index] = safe | ||
| re[index] = new RegExp(value, isGlobal ? 'g' : undefined) | ||
| safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) | ||
| } | ||
| // The following Regular Expressions can be used for tokenizing, | ||
| // validating, and parsing SemVer version strings. | ||
| // ## Numeric Identifier | ||
| // A single `0`, or a non-zero digit followed by zero or more digits. | ||
| createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') | ||
| createToken('NUMERICIDENTIFIERLOOSE', '\\d+') | ||
| // ## Non-numeric Identifier | ||
| // Zero or more digits, followed by a letter or hyphen, and then zero or | ||
| // more letters, digits, or hyphens. | ||
| createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) | ||
| // ## Main Version | ||
| // Three dot-separated numeric identifiers. | ||
| createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + | ||
| `(${src[t.NUMERICIDENTIFIER]})\\.` + | ||
| `(${src[t.NUMERICIDENTIFIER]})`) | ||
| createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + | ||
| `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + | ||
| `(${src[t.NUMERICIDENTIFIERLOOSE]})`) | ||
| // ## Pre-release Version Identifier | ||
| // A numeric identifier, or a non-numeric identifier. | ||
| // Non-numeric identifiers include numeric identifiers but can be longer. | ||
| // Therefore non-numeric identifiers must go first. | ||
| createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER] | ||
| }|${src[t.NUMERICIDENTIFIER]})`) | ||
| createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER] | ||
| }|${src[t.NUMERICIDENTIFIERLOOSE]})`) | ||
| // ## Pre-release Version | ||
| // Hyphen, followed by one or more dot-separated pre-release version | ||
| // identifiers. | ||
| createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] | ||
| }(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) | ||
| createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] | ||
| }(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) | ||
| // ## Build Metadata Identifier | ||
| // Any combination of digits, letters, or hyphens. | ||
| createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) | ||
| // ## Build Metadata | ||
| // Plus sign, followed by one or more period-separated build metadata | ||
| // identifiers. | ||
| createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] | ||
| }(?:\\.${src[t.BUILDIDENTIFIER]})*))`) | ||
| // ## Full Version String | ||
| // A main version, followed optionally by a pre-release version and | ||
| // build metadata. | ||
| // Note that the only major, minor, patch, and pre-release sections of | ||
| // the version string are capturing groups. The build metadata is not a | ||
| // capturing group, because it should not ever be used in version | ||
| // comparison. | ||
| createToken('FULLPLAIN', `v?${src[t.MAINVERSION] | ||
| }${src[t.PRERELEASE]}?${ | ||
| src[t.BUILD]}?`) | ||
| createToken('FULL', `^${src[t.FULLPLAIN]}$`) | ||
| // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. | ||
| // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty | ||
| // common in the npm registry. | ||
| createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] | ||
| }${src[t.PRERELEASELOOSE]}?${ | ||
| src[t.BUILD]}?`) | ||
| createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) | ||
| createToken('GTLT', '((?:<|>)?=?)') | ||
| // Something like "2.*" or "1.2.x". | ||
| // Note that "x.x" is a valid xRange identifier, meaning "any version" | ||
| // Only the first item is strictly required. | ||
| createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) | ||
| createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) | ||
| createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + | ||
| `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + | ||
| `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + | ||
| `(?:${src[t.PRERELEASE]})?${ | ||
| src[t.BUILD]}?` + | ||
| `)?)?`) | ||
| createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + | ||
| `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + | ||
| `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + | ||
| `(?:${src[t.PRERELEASELOOSE]})?${ | ||
| src[t.BUILD]}?` + | ||
| `)?)?`) | ||
| createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) | ||
| createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) | ||
| // Coercion. | ||
| // Extract anything that could conceivably be a part of a valid semver | ||
| createToken('COERCEPLAIN', `${'(^|[^\\d])' + | ||
| '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + | ||
| `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + | ||
| `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) | ||
| createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) | ||
| createToken('COERCEFULL', src[t.COERCEPLAIN] + | ||
| `(?:${src[t.PRERELEASE]})?` + | ||
| `(?:${src[t.BUILD]})?` + | ||
| `(?:$|[^\\d])`) | ||
| createToken('COERCERTL', src[t.COERCE], true) | ||
| createToken('COERCERTLFULL', src[t.COERCEFULL], true) | ||
| // Tilde ranges. | ||
| // Meaning is "reasonably at or greater than" | ||
| createToken('LONETILDE', '(?:~>?)') | ||
| createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) | ||
| exports.tildeTrimReplace = '$1~' | ||
| createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) | ||
| createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) | ||
| // Caret ranges. | ||
| // Meaning is "at least and backwards compatible with" | ||
| createToken('LONECARET', '(?:\\^)') | ||
| createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) | ||
| exports.caretTrimReplace = '$1^' | ||
| createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) | ||
| createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) | ||
| // A simple gt/lt/eq thing, or just "" to indicate "any version" | ||
| createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) | ||
| createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) | ||
| // An expression to strip any whitespace between the gtlt and the thing | ||
| // it modifies, so that `> 1.2.3` ==> `>1.2.3` | ||
| createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] | ||
| }\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) | ||
| exports.comparatorTrimReplace = '$1$2$3' | ||
| // Something like `1.2.3 - 1.2.4` | ||
| // Note that these all use the loose form, because they'll be | ||
| // checked against either the strict or loose comparator form | ||
| // later. | ||
| createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + | ||
| `\\s+-\\s+` + | ||
| `(${src[t.XRANGEPLAIN]})` + | ||
| `\\s*$`) | ||
| createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + | ||
| `\\s+-\\s+` + | ||
| `(${src[t.XRANGEPLAINLOOSE]})` + | ||
| `\\s*$`) | ||
| // Star ranges basically just allow anything at all. | ||
| createToken('STAR', '(<|>)?=?\\s*\\*') | ||
| // >=0.0.0 is like a star | ||
| createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') | ||
| createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') |
| The ISC License | ||
| Copyright (c) Isaac Z. Schlueter and Contributors | ||
| Permission to use, copy, modify, and/or distribute this software for any | ||
| purpose with or without fee is hereby granted, provided that the above | ||
| copyright notice and this permission notice appear in all copies. | ||
| THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES | ||
| WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF | ||
| MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR | ||
| ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES | ||
| WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN | ||
| ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR | ||
| IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| { | ||
| "name": "semver", | ||
| "version": "7.8.5", | ||
| "description": "The semantic version parser used by npm.", | ||
| "main": "index.js", | ||
| "scripts": { | ||
| "test": "tap", | ||
| "snap": "tap", | ||
| "lint": "npm run eslint", | ||
| "postlint": "template-oss-check", | ||
| "lintfix": "npm run eslint -- --fix", | ||
| "posttest": "npm run lint", | ||
| "template-oss-apply": "template-oss-apply --force", | ||
| "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\"" | ||
| }, | ||
| "devDependencies": { | ||
| "@npmcli/eslint-config": "^7.0.0", | ||
| "@npmcli/template-oss": "5.0.0", | ||
| "benchmark": "^2.1.4", | ||
| "tap": "^16.0.0" | ||
| }, | ||
| "license": "ISC", | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/npm/node-semver.git" | ||
| }, | ||
| "bin": { | ||
| "semver": "bin/semver.js" | ||
| }, | ||
| "files": [ | ||
| "bin/", | ||
| "lib/", | ||
| "classes/", | ||
| "functions/", | ||
| "internal/", | ||
| "ranges/", | ||
| "index.js", | ||
| "preload.js", | ||
| "range.bnf" | ||
| ], | ||
| "tap": { | ||
| "timeout": 30, | ||
| "coverage-map": "map.js", | ||
| "nyc-arg": [ | ||
| "--exclude", | ||
| "tap-snapshots/**" | ||
| ] | ||
| }, | ||
| "engines": { | ||
| "node": ">=10" | ||
| }, | ||
| "author": "GitHub Inc.", | ||
| "templateOSS": { | ||
| "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", | ||
| "version": "5.0.0", | ||
| "engines": ">=10", | ||
| "distPaths": [ | ||
| "classes/", | ||
| "functions/", | ||
| "internal/", | ||
| "ranges/", | ||
| "index.js", | ||
| "preload.js", | ||
| "range.bnf" | ||
| ], | ||
| "allowPaths": [ | ||
| "/classes/", | ||
| "/functions/", | ||
| "/internal/", | ||
| "/ranges/", | ||
| "/index.js", | ||
| "/preload.js", | ||
| "/range.bnf", | ||
| "/benchmarks" | ||
| ], | ||
| "publish": "true" | ||
| } | ||
| } |
| 'use strict' | ||
| // XXX remove in v8 or beyond | ||
| module.exports = require('./index.js') |
Sorry, the diff of this file is not supported yet
| 'use strict' | ||
| // Determine if version is greater than all the versions possible in the range. | ||
| const outside = require('./outside') | ||
| const gtr = (version, range, options) => outside(version, range, '>', options) | ||
| module.exports = gtr |
| 'use strict' | ||
| const Range = require('../classes/range') | ||
| const intersects = (r1, r2, options) => { | ||
| r1 = new Range(r1, options) | ||
| r2 = new Range(r2, options) | ||
| return r1.intersects(r2, options) | ||
| } | ||
| module.exports = intersects |
| 'use strict' | ||
| const outside = require('./outside') | ||
| // Determine if version is less than all the versions possible in the range | ||
| const ltr = (version, range, options) => outside(version, range, '<', options) | ||
| module.exports = ltr |
| 'use strict' | ||
| const SemVer = require('../classes/semver') | ||
| const Range = require('../classes/range') | ||
| const maxSatisfying = (versions, range, options) => { | ||
| let max = null | ||
| let maxSV = null | ||
| let rangeObj = null | ||
| try { | ||
| rangeObj = new Range(range, options) | ||
| } catch (er) { | ||
| return null | ||
| } | ||
| versions.forEach((v) => { | ||
| if (rangeObj.test(v)) { | ||
| // satisfies(v, range, options) | ||
| if (!max || maxSV.compare(v) === -1) { | ||
| // compare(max, v, true) | ||
| max = v | ||
| maxSV = new SemVer(max, options) | ||
| } | ||
| } | ||
| }) | ||
| return max | ||
| } | ||
| module.exports = maxSatisfying |
| 'use strict' | ||
| const SemVer = require('../classes/semver') | ||
| const Range = require('../classes/range') | ||
| const minSatisfying = (versions, range, options) => { | ||
| let min = null | ||
| let minSV = null | ||
| let rangeObj = null | ||
| try { | ||
| rangeObj = new Range(range, options) | ||
| } catch (er) { | ||
| return null | ||
| } | ||
| versions.forEach((v) => { | ||
| if (rangeObj.test(v)) { | ||
| // satisfies(v, range, options) | ||
| if (!min || minSV.compare(v) === 1) { | ||
| // compare(min, v, true) | ||
| min = v | ||
| minSV = new SemVer(min, options) | ||
| } | ||
| } | ||
| }) | ||
| return min | ||
| } | ||
| module.exports = minSatisfying |
| 'use strict' | ||
| const SemVer = require('../classes/semver') | ||
| const Range = require('../classes/range') | ||
| const gt = require('../functions/gt') | ||
| const minVersion = (range, loose) => { | ||
| range = new Range(range, loose) | ||
| let minver = new SemVer('0.0.0') | ||
| if (range.test(minver)) { | ||
| return minver | ||
| } | ||
| minver = new SemVer('0.0.0-0') | ||
| if (range.test(minver)) { | ||
| return minver | ||
| } | ||
| minver = null | ||
| for (let i = 0; i < range.set.length; ++i) { | ||
| const comparators = range.set[i] | ||
| let setMin = null | ||
| comparators.forEach((comparator) => { | ||
| // Clone to avoid manipulating the comparator's semver object. | ||
| const compver = new SemVer(comparator.semver.version) | ||
| switch (comparator.operator) { | ||
| case '>': | ||
| if (compver.prerelease.length === 0) { | ||
| compver.patch++ | ||
| } else { | ||
| compver.prerelease.push(0) | ||
| } | ||
| compver.raw = compver.format() | ||
| /* fallthrough */ | ||
| case '': | ||
| case '>=': | ||
| if (!setMin || gt(compver, setMin)) { | ||
| setMin = compver | ||
| } | ||
| break | ||
| case '<': | ||
| case '<=': | ||
| /* Ignore maximum versions */ | ||
| break | ||
| /* istanbul ignore next */ | ||
| default: | ||
| throw new Error(`Unexpected operation: ${comparator.operator}`) | ||
| } | ||
| }) | ||
| if (setMin && (!minver || gt(minver, setMin))) { | ||
| minver = setMin | ||
| } | ||
| } | ||
| if (minver && range.test(minver)) { | ||
| return minver | ||
| } | ||
| return null | ||
| } | ||
| module.exports = minVersion |
| 'use strict' | ||
| const SemVer = require('../classes/semver') | ||
| const Comparator = require('../classes/comparator') | ||
| const { ANY } = Comparator | ||
| const Range = require('../classes/range') | ||
| const satisfies = require('../functions/satisfies') | ||
| const gt = require('../functions/gt') | ||
| const lt = require('../functions/lt') | ||
| const lte = require('../functions/lte') | ||
| const gte = require('../functions/gte') | ||
| const outside = (version, range, hilo, options) => { | ||
| version = new SemVer(version, options) | ||
| range = new Range(range, options) | ||
| let gtfn, ltefn, ltfn, comp, ecomp | ||
| switch (hilo) { | ||
| case '>': | ||
| gtfn = gt | ||
| ltefn = lte | ||
| ltfn = lt | ||
| comp = '>' | ||
| ecomp = '>=' | ||
| break | ||
| case '<': | ||
| gtfn = lt | ||
| ltefn = gte | ||
| ltfn = gt | ||
| comp = '<' | ||
| ecomp = '<=' | ||
| break | ||
| default: | ||
| throw new TypeError('Must provide a hilo val of "<" or ">"') | ||
| } | ||
| // If it satisfies the range it is not outside | ||
| if (satisfies(version, range, options)) { | ||
| return false | ||
| } | ||
| // From now on, variable terms are as if we're in "gtr" mode. | ||
| // but note that everything is flipped for the "ltr" function. | ||
| for (let i = 0; i < range.set.length; ++i) { | ||
| const comparators = range.set[i] | ||
| let high = null | ||
| let low = null | ||
| comparators.forEach((comparator) => { | ||
| if (comparator.semver === ANY) { | ||
| comparator = new Comparator('>=0.0.0') | ||
| } | ||
| high = high || comparator | ||
| low = low || comparator | ||
| if (gtfn(comparator.semver, high.semver, options)) { | ||
| high = comparator | ||
| } else if (ltfn(comparator.semver, low.semver, options)) { | ||
| low = comparator | ||
| } | ||
| }) | ||
| // If the edge version comparator has a operator then our version | ||
| // isn't outside it | ||
| if (high.operator === comp || high.operator === ecomp) { | ||
| return false | ||
| } | ||
| // If the lowest version comparator has an operator and our version | ||
| // is less than it then it isn't higher than the range | ||
| if ((!low.operator || low.operator === comp) && | ||
| ltefn(version, low.semver)) { | ||
| return false | ||
| } else if (low.operator === ecomp && ltfn(version, low.semver)) { | ||
| return false | ||
| } | ||
| } | ||
| return true | ||
| } | ||
| module.exports = outside |
| 'use strict' | ||
| // given a set of versions and a range, create a "simplified" range | ||
| // that includes the same versions that the original range does | ||
| // If the original range is shorter than the simplified one, return that. | ||
| const satisfies = require('../functions/satisfies.js') | ||
| const compare = require('../functions/compare.js') | ||
| module.exports = (versions, range, options) => { | ||
| const set = [] | ||
| let first = null | ||
| let prev = null | ||
| const v = versions.sort((a, b) => compare(a, b, options)) | ||
| for (const version of v) { | ||
| const included = satisfies(version, range, options) | ||
| if (included) { | ||
| prev = version | ||
| if (!first) { | ||
| first = version | ||
| } | ||
| } else { | ||
| if (prev) { | ||
| set.push([first, prev]) | ||
| } | ||
| prev = null | ||
| first = null | ||
| } | ||
| } | ||
| if (first) { | ||
| set.push([first, null]) | ||
| } | ||
| const ranges = [] | ||
| for (const [min, max] of set) { | ||
| if (min === max) { | ||
| ranges.push(min) | ||
| } else if (!max && min === v[0]) { | ||
| ranges.push('*') | ||
| } else if (!max) { | ||
| ranges.push(`>=${min}`) | ||
| } else if (min === v[0]) { | ||
| ranges.push(`<=${max}`) | ||
| } else { | ||
| ranges.push(`${min} - ${max}`) | ||
| } | ||
| } | ||
| const simplified = ranges.join(' || ') | ||
| const original = typeof range.raw === 'string' ? range.raw : String(range) | ||
| return simplified.length < original.length ? simplified : range | ||
| } |
| 'use strict' | ||
| const Range = require('../classes/range.js') | ||
| const Comparator = require('../classes/comparator.js') | ||
| const { ANY } = Comparator | ||
| const satisfies = require('../functions/satisfies.js') | ||
| const compare = require('../functions/compare.js') | ||
| // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: | ||
| // - Every simple range `r1, r2, ...` is a null set, OR | ||
| // - Every simple range `r1, r2, ...` which is not a null set is a subset of | ||
| // some `R1, R2, ...` | ||
| // | ||
| // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: | ||
| // - If c is only the ANY comparator | ||
| // - If C is only the ANY comparator, return true | ||
| // - Else if in prerelease mode, return false | ||
| // - else replace c with `[>=0.0.0]` | ||
| // - If C is only the ANY comparator | ||
| // - if in prerelease mode, return true | ||
| // - else replace C with `[>=0.0.0]` | ||
| // - Let EQ be the set of = comparators in c | ||
| // - If EQ is more than one, return true (null set) | ||
| // - Let GT be the highest > or >= comparator in c | ||
| // - Let LT be the lowest < or <= comparator in c | ||
| // - If GT and LT, and GT.semver > LT.semver, return true (null set) | ||
| // - If any C is a = range, and GT or LT are set, return false | ||
| // - If EQ | ||
| // - If GT, and EQ does not satisfy GT, return true (null set) | ||
| // - If LT, and EQ does not satisfy LT, return true (null set) | ||
| // - If EQ satisfies every C, return true | ||
| // - Else return false | ||
| // - If GT | ||
| // - If GT.semver is lower than any > or >= comp in C, return false | ||
| // - If GT is >=, and GT.semver does not satisfy every C, return false | ||
| // - If GT.semver has a prerelease, and not in prerelease mode | ||
| // - If no C has a prerelease and the GT.semver tuple, return false | ||
| // - If LT | ||
| // - If LT.semver is greater than any < or <= comp in C, return false | ||
| // - If LT is <=, and LT.semver does not satisfy every C, return false | ||
| // - If LT.semver has a prerelease, and not in prerelease mode | ||
| // - If no C has a prerelease and the LT.semver tuple, return false | ||
| // - Else return true | ||
| const subset = (sub, dom, options = {}) => { | ||
| if (sub === dom) { | ||
| return true | ||
| } | ||
| sub = new Range(sub, options) | ||
| dom = new Range(dom, options) | ||
| let sawNonNull = false | ||
| OUTER: for (const simpleSub of sub.set) { | ||
| for (const simpleDom of dom.set) { | ||
| const isSub = simpleSubset(simpleSub, simpleDom, options) | ||
| sawNonNull = sawNonNull || isSub !== null | ||
| if (isSub) { | ||
| continue OUTER | ||
| } | ||
| } | ||
| // the null set is a subset of everything, but null simple ranges in | ||
| // a complex range should be ignored. so if we saw a non-null range, | ||
| // then we know this isn't a subset, but if EVERY simple range was null, | ||
| // then it is a subset. | ||
| if (sawNonNull) { | ||
| return false | ||
| } | ||
| } | ||
| return true | ||
| } | ||
| const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] | ||
| const minimumVersion = [new Comparator('>=0.0.0')] | ||
| const simpleSubset = (sub, dom, options) => { | ||
| if (sub === dom) { | ||
| return true | ||
| } | ||
| if (sub.length === 1 && sub[0].semver === ANY) { | ||
| if (dom.length === 1 && dom[0].semver === ANY) { | ||
| return true | ||
| } else if (options.includePrerelease) { | ||
| sub = minimumVersionWithPreRelease | ||
| } else { | ||
| sub = minimumVersion | ||
| } | ||
| } | ||
| if (dom.length === 1 && dom[0].semver === ANY) { | ||
| if (options.includePrerelease) { | ||
| return true | ||
| } else { | ||
| dom = minimumVersion | ||
| } | ||
| } | ||
| const eqSet = new Set() | ||
| let gt, lt | ||
| for (const c of sub) { | ||
| if (c.operator === '>' || c.operator === '>=') { | ||
| gt = higherGT(gt, c, options) | ||
| } else if (c.operator === '<' || c.operator === '<=') { | ||
| lt = lowerLT(lt, c, options) | ||
| } else { | ||
| eqSet.add(c.semver) | ||
| } | ||
| } | ||
| if (eqSet.size > 1) { | ||
| return null | ||
| } | ||
| let gtltComp | ||
| if (gt && lt) { | ||
| gtltComp = compare(gt.semver, lt.semver, options) | ||
| if (gtltComp > 0) { | ||
| return null | ||
| } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { | ||
| return null | ||
| } | ||
| } | ||
| // will iterate one or zero times | ||
| for (const eq of eqSet) { | ||
| if (gt && !satisfies(eq, String(gt), options)) { | ||
| return null | ||
| } | ||
| if (lt && !satisfies(eq, String(lt), options)) { | ||
| return null | ||
| } | ||
| for (const c of dom) { | ||
| if (!satisfies(eq, String(c), options)) { | ||
| return false | ||
| } | ||
| } | ||
| return true | ||
| } | ||
| let higher, lower | ||
| let hasDomLT, hasDomGT | ||
| // if the subset has a prerelease, we need a comparator in the superset | ||
| // with the same tuple and a prerelease, or it's not a subset | ||
| let needDomLTPre = lt && | ||
| !options.includePrerelease && | ||
| lt.semver.prerelease.length ? lt.semver : false | ||
| let needDomGTPre = gt && | ||
| !options.includePrerelease && | ||
| gt.semver.prerelease.length ? gt.semver : false | ||
| // exception: <1.2.3-0 is the same as <1.2.3 | ||
| if (needDomLTPre && needDomLTPre.prerelease.length === 1 && | ||
| lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { | ||
| needDomLTPre = false | ||
| } | ||
| for (const c of dom) { | ||
| hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' | ||
| hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' | ||
| if (gt) { | ||
| if (needDomGTPre) { | ||
| if (c.semver.prerelease && c.semver.prerelease.length && | ||
| c.semver.major === needDomGTPre.major && | ||
| c.semver.minor === needDomGTPre.minor && | ||
| c.semver.patch === needDomGTPre.patch) { | ||
| needDomGTPre = false | ||
| } | ||
| } | ||
| if (c.operator === '>' || c.operator === '>=') { | ||
| higher = higherGT(gt, c, options) | ||
| if (higher === c && higher !== gt) { | ||
| return false | ||
| } | ||
| } else if (gt.operator === '>=' && !c.test(gt.semver)) { | ||
| return false | ||
| } | ||
| } | ||
| if (lt) { | ||
| if (needDomLTPre) { | ||
| if (c.semver.prerelease && c.semver.prerelease.length && | ||
| c.semver.major === needDomLTPre.major && | ||
| c.semver.minor === needDomLTPre.minor && | ||
| c.semver.patch === needDomLTPre.patch) { | ||
| needDomLTPre = false | ||
| } | ||
| } | ||
| if (c.operator === '<' || c.operator === '<=') { | ||
| lower = lowerLT(lt, c, options) | ||
| if (lower === c && lower !== lt) { | ||
| return false | ||
| } | ||
| } else if (lt.operator === '<=' && !c.test(lt.semver)) { | ||
| return false | ||
| } | ||
| } | ||
| if (!c.operator && (lt || gt) && gtltComp !== 0) { | ||
| return false | ||
| } | ||
| } | ||
| // if there was a < or >, and nothing in the dom, then must be false | ||
| // UNLESS it was limited by another range in the other direction. | ||
| // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 | ||
| if (gt && hasDomLT && !lt && gtltComp !== 0) { | ||
| return false | ||
| } | ||
| if (lt && hasDomGT && !gt && gtltComp !== 0) { | ||
| return false | ||
| } | ||
| // we needed a prerelease range in a specific tuple, but didn't get one | ||
| // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, | ||
| // because it includes prereleases in the 1.2.3 tuple | ||
| if (needDomGTPre || needDomLTPre) { | ||
| return false | ||
| } | ||
| return true | ||
| } | ||
| // >=1.2.3 is lower than >1.2.3 | ||
| const higherGT = (a, b, options) => { | ||
| if (!a) { | ||
| return b | ||
| } | ||
| const comp = compare(a.semver, b.semver, options) | ||
| return comp > 0 ? a | ||
| : comp < 0 ? b | ||
| : b.operator === '>' && a.operator === '>=' ? b | ||
| : a | ||
| } | ||
| // <=1.2.3 is higher than <1.2.3 | ||
| const lowerLT = (a, b, options) => { | ||
| if (!a) { | ||
| return b | ||
| } | ||
| const comp = compare(a.semver, b.semver, options) | ||
| return comp < 0 ? a | ||
| : comp > 0 ? b | ||
| : b.operator === '<' && a.operator === '<=' ? b | ||
| : a | ||
| } | ||
| module.exports = subset |
| 'use strict' | ||
| const Range = require('../classes/range') | ||
| // Mostly just for testing and legacy API reasons | ||
| const toComparators = (range, options) => | ||
| new Range(range, options).set | ||
| .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) | ||
| module.exports = toComparators |
| 'use strict' | ||
| const Range = require('../classes/range') | ||
| const validRange = (range, options) => { | ||
| try { | ||
| // Return '*' instead of '' so that truthiness works. | ||
| // This will throw if it's invalid anyway | ||
| return new Range(range, options).range || '*' | ||
| } catch (er) { | ||
| return null | ||
| } | ||
| } | ||
| module.exports = validRange |
| semver(1) -- The semantic versioner for npm | ||
| =========================================== | ||
| ## Install | ||
| ```bash | ||
| npm install semver | ||
| ```` | ||
| ## Usage | ||
| As a node module: | ||
| ```js | ||
| const semver = require('semver') | ||
| semver.valid('1.2.3') // '1.2.3' | ||
| semver.valid('a.b.c') // null | ||
| semver.clean(' =v1.2.3 ') // '1.2.3' | ||
| semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true | ||
| semver.gt('1.2.3', '9.8.7') // false | ||
| semver.lt('1.2.3', '9.8.7') // true | ||
| semver.minVersion('>=1.0.0') // '1.0.0' | ||
| semver.valid(semver.coerce('v2')) // '2.0.0' | ||
| semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' | ||
| ``` | ||
| You can also just load the module for the function that you care about if | ||
| you'd like to minimize your footprint. | ||
| ```js | ||
| // load the whole API at once in a single object | ||
| const semver = require('semver') | ||
| // or just load the bits you need | ||
| // all of them listed here, just pick and choose what you want | ||
| // classes | ||
| const SemVer = require('semver/classes/semver') | ||
| const Comparator = require('semver/classes/comparator') | ||
| const Range = require('semver/classes/range') | ||
| // functions for working with versions | ||
| const semverParse = require('semver/functions/parse') | ||
| const semverValid = require('semver/functions/valid') | ||
| const semverClean = require('semver/functions/clean') | ||
| const semverInc = require('semver/functions/inc') | ||
| const semverDiff = require('semver/functions/diff') | ||
| const semverMajor = require('semver/functions/major') | ||
| const semverMinor = require('semver/functions/minor') | ||
| const semverPatch = require('semver/functions/patch') | ||
| const semverPrerelease = require('semver/functions/prerelease') | ||
| const semverCompare = require('semver/functions/compare') | ||
| const semverRcompare = require('semver/functions/rcompare') | ||
| const semverCompareLoose = require('semver/functions/compare-loose') | ||
| const semverCompareBuild = require('semver/functions/compare-build') | ||
| const semverSort = require('semver/functions/sort') | ||
| const semverRsort = require('semver/functions/rsort') | ||
| const semverTruncate = require('semver/functions/truncate') | ||
| // low-level comparators between versions | ||
| const semverGt = require('semver/functions/gt') | ||
| const semverLt = require('semver/functions/lt') | ||
| const semverEq = require('semver/functions/eq') | ||
| const semverNeq = require('semver/functions/neq') | ||
| const semverGte = require('semver/functions/gte') | ||
| const semverLte = require('semver/functions/lte') | ||
| const semverCmp = require('semver/functions/cmp') | ||
| const semverCoerce = require('semver/functions/coerce') | ||
| // working with ranges | ||
| const semverSatisfies = require('semver/functions/satisfies') | ||
| const semverMaxSatisfying = require('semver/ranges/max-satisfying') | ||
| const semverMinSatisfying = require('semver/ranges/min-satisfying') | ||
| const semverToComparators = require('semver/ranges/to-comparators') | ||
| const semverMinVersion = require('semver/ranges/min-version') | ||
| const semverValidRange = require('semver/ranges/valid') | ||
| const semverOutside = require('semver/ranges/outside') | ||
| const semverGtr = require('semver/ranges/gtr') | ||
| const semverLtr = require('semver/ranges/ltr') | ||
| const semverIntersects = require('semver/ranges/intersects') | ||
| const semverSimplifyRange = require('semver/ranges/simplify') | ||
| const semverRangeSubset = require('semver/ranges/subset') | ||
| ``` | ||
| As a command-line utility: | ||
| ``` | ||
| $ semver -h | ||
| A JavaScript implementation of the https://semver.org/ specification | ||
| Copyright Isaac Z. Schlueter | ||
| Usage: semver [options] <version> [<version> [...]] | ||
| Prints valid versions sorted by SemVer precedence | ||
| Options: | ||
| -r --range <range> | ||
| Print versions that match the specified range. | ||
| -i --increment [<level>] | ||
| Increment a version by the specified level. Level can | ||
| be one of: major, minor, patch, premajor, preminor, | ||
| prepatch, prerelease, or release. Default level is 'patch'. | ||
| Only one version may be specified. | ||
| --preid <identifier> | ||
| Identifier to be used to prefix premajor, preminor, | ||
| prepatch or prerelease version increments. | ||
| -l --loose | ||
| Interpret versions and ranges loosely | ||
| -n <0|1|false> | ||
| Base number for prerelease identifier (default: 0). | ||
| Use false to omit the number altogether. | ||
| -p --include-prerelease | ||
| Always include prerelease versions in range matching | ||
| -c --coerce | ||
| Coerce a string into SemVer if possible | ||
| (does not imply --loose) | ||
| --rtl | ||
| Coerce version strings right to left | ||
| --ltr | ||
| Coerce version strings left to right (default) | ||
| Program exits successfully if any valid version satisfies | ||
| all supplied ranges, and prints all satisfying versions. | ||
| If no satisfying versions are found, then exits failure. | ||
| Versions are printed in ascending order, so supplying | ||
| multiple versions to the utility will just sort them. | ||
| ``` | ||
| ## Versions | ||
| A "version" is described by the `v2.0.0` specification found at | ||
| <https://semver.org/>. | ||
| A leading `"="` or `"v"` character is stripped off and ignored. | ||
| Support for stripping a leading "v" is kept for compatibility with `v1.0.0` of the SemVer | ||
| specification but should not be used anymore. | ||
| ## Ranges | ||
| A `version range` is a set of `comparators` that specify versions | ||
| that satisfy the range. | ||
| A `comparator` is composed of an `operator` and a `version`. The set | ||
| of primitive `operators` is: | ||
| * `<` Less than | ||
| * `<=` Less than or equal to | ||
| * `>` Greater than | ||
| * `>=` Greater than or equal to | ||
| * `=` Equal. If no operator is specified, then equality is assumed, | ||
| so this operator is optional but MAY be included. | ||
| For example, the comparator `>=1.2.7` would match the versions | ||
| `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` | ||
| or `1.1.0`. The comparator `>1` is equivalent to `>=2.0.0` and | ||
| would match the versions `2.0.0` and `3.1.0`, but not the versions | ||
| `1.0.1` or `1.1.0`. | ||
| Comparators can be joined by whitespace to form a `comparator set`, | ||
| which is satisfied by the **intersection** of all of the comparators | ||
| it includes. | ||
| A range is composed of one or more comparator sets, joined by `||`. A | ||
| version matches a range if and only if every comparator in at least | ||
| one of the `||`-separated comparator sets is satisfied by the version. | ||
| For example, the range `>=1.2.7 <1.3.0` would match the versions | ||
| `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, | ||
| or `1.1.0`. | ||
| The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, | ||
| `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. | ||
| ### Prerelease Tags | ||
| If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then | ||
| it will only be allowed to satisfy comparator sets if at least one | ||
| comparator with the same `[major, minor, patch]` tuple also has a | ||
| prerelease tag. | ||
| For example, the range `>1.2.3-alpha.3` would be allowed to match the | ||
| version `1.2.3-alpha.7`, but it would *not* be satisfied by | ||
| `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater | ||
| than" `1.2.3-alpha.3` according to the SemVer sort rules. The version | ||
| range only accepts prerelease tags on the `1.2.3` version. | ||
| Version `3.4.5` *would* satisfy the range because it does not have a | ||
| prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. | ||
| The purpose of this behavior is twofold. First, prerelease versions | ||
| frequently are updated very quickly, and contain many breaking changes | ||
| that are (by the author's design) not yet fit for public consumption. | ||
| Therefore, by default, they are excluded from range-matching | ||
| semantics. | ||
| Second, a user who has opted into using a prerelease version has | ||
| indicated the intent to use *that specific* set of | ||
| alpha/beta/rc versions. By including a prerelease tag in the range, | ||
| the user is indicating that they are aware of the risk. However, it | ||
| is still not appropriate to assume that they have opted into taking a | ||
| similar risk on the *next* set of prerelease versions. | ||
| Note that this behavior can be suppressed (treating all prerelease | ||
| versions as if they were normal versions, for range-matching) | ||
| by setting the `includePrerelease` flag on the options | ||
| object to any | ||
| [functions](https://github.com/npm/node-semver#functions) that do | ||
| range matching. | ||
| #### Prerelease Identifiers | ||
| The method `.inc` takes an additional `identifier` string argument that | ||
| will append the value of the string as a prerelease identifier: | ||
| ```javascript | ||
| semver.inc('1.2.3', 'prerelease', 'beta') | ||
| // '1.2.4-beta.0' | ||
| ``` | ||
| command-line example: | ||
| ```bash | ||
| $ semver 1.2.3 -i prerelease --preid beta | ||
| 1.2.4-beta.0 | ||
| ``` | ||
| Which then can be used to increment further: | ||
| ```bash | ||
| $ semver 1.2.4-beta.0 -i prerelease | ||
| 1.2.4-beta.1 | ||
| ``` | ||
| To get out of the prerelease phase, use the `release` option: | ||
| ```bash | ||
| $ semver 1.2.4-beta.1 -i release | ||
| 1.2.4 | ||
| ``` | ||
| #### Prerelease Identifier Base | ||
| The method `.inc` takes an optional parameter 'identifierBase' string | ||
| that will let you let your prerelease number as zero-based or one-based. | ||
| Set to `false` to omit the prerelease number altogether. | ||
| If you do not specify this parameter, it will default to zero-based. | ||
| ```javascript | ||
| semver.inc('1.2.3', 'prerelease', 'beta', '1') | ||
| // '1.2.4-beta.1' | ||
| ``` | ||
| ```javascript | ||
| semver.inc('1.2.3', 'prerelease', 'beta', false) | ||
| // '1.2.4-beta' | ||
| ``` | ||
| command-line example: | ||
| ```bash | ||
| $ semver 1.2.3 -i prerelease --preid beta -n 1 | ||
| 1.2.4-beta.1 | ||
| ``` | ||
| ```bash | ||
| $ semver 1.2.3 -i prerelease --preid beta -n false | ||
| 1.2.4-beta | ||
| ``` | ||
| ### Advanced Range Syntax | ||
| Advanced range syntax desugars to primitive comparators in | ||
| deterministic ways. | ||
| Advanced ranges may be combined in the same way as primitive | ||
| comparators using white space or `||`. | ||
| #### Hyphen Ranges `X.Y.Z - A.B.C` | ||
| Specifies an inclusive set. | ||
| * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` | ||
| If a partial version is provided as the first version in the inclusive | ||
| range, then the missing pieces are replaced with zeroes. | ||
| * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` | ||
| If a partial version is provided as the second version in the | ||
| inclusive range, then all versions that start with the supplied parts | ||
| of the tuple are accepted, but nothing that would be greater than the | ||
| provided tuple parts. | ||
| * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` | ||
| * `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` | ||
| #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` | ||
| Any of `X`, `x`, or `*` may be used to "stand in" for one of the | ||
| numeric values in the `[major, minor, patch]` tuple. | ||
| * `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless | ||
| `includePrerelease` is specified, in which case any version at all | ||
| satisfies) | ||
| * `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) | ||
| * `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) | ||
| A partial version range is treated as an X-Range, so the special | ||
| character is in fact optional. | ||
| * `""` (empty string) := `*` := `>=0.0.0` | ||
| * `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` | ||
| * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` | ||
| #### Tilde Ranges `~1.2.3` `~1.2` `~1` | ||
| Allows patch-level changes if a minor version is specified on the | ||
| comparator. Allows minor-level changes if not. | ||
| * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` | ||
| * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) | ||
| * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) | ||
| * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` | ||
| * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) | ||
| * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) | ||
| * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in | ||
| the `1.2.3` version will be allowed, if they are greater than or | ||
| equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but | ||
| `1.2.4-beta.2` would not, because it is a prerelease of a | ||
| different `[major, minor, patch]` tuple. | ||
| #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` | ||
| Allows changes that do not modify the left-most non-zero element in the | ||
| `[major, minor, patch]` tuple. In other words, this allows patch and | ||
| minor updates for versions `1.0.0` and above, patch updates for | ||
| versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. | ||
| Many authors treat a `0.x` version as if the `x` were the major | ||
| "breaking-change" indicator. | ||
| Caret ranges are ideal when an author may make breaking changes | ||
| between `0.2.4` and `0.3.0` releases, which is a common practice. | ||
| However, it presumes that there will *not* be breaking changes between | ||
| `0.2.4` and `0.2.5`. It allows for changes that are presumed to be | ||
| additive (but non-breaking), according to commonly observed practices. | ||
| * `^1.2.3` := `>=1.2.3 <2.0.0-0` | ||
| * `^0.2.3` := `>=0.2.3 <0.3.0-0` | ||
| * `^0.0.3` := `>=0.0.3 <0.0.4-0` | ||
| * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in | ||
| the `1.2.3` version will be allowed, if they are greater than or | ||
| equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but | ||
| `1.2.4-beta.2` would not, because it is a prerelease of a | ||
| different `[major, minor, patch]` tuple. | ||
| * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the | ||
| `0.0.3` version *only* will be allowed, if they are greater than or | ||
| equal to `beta`. So, `0.0.3-pr.2` would be allowed. | ||
| When parsing caret ranges, a missing `patch` value desugars to the | ||
| number `0`, but will allow flexibility within that value, even if the | ||
| major and minor versions are both `0`. | ||
| * `^1.2.x` := `>=1.2.0 <2.0.0-0` | ||
| * `^0.0.x` := `>=0.0.0 <0.1.0-0` | ||
| * `^0.0` := `>=0.0.0 <0.1.0-0` | ||
| A missing `minor` and `patch` values will desugar to zero, but also | ||
| allow flexibility within those values, even if the major version is | ||
| zero. | ||
| * `^1.x` := `>=1.0.0 <2.0.0-0` | ||
| * `^0.x` := `>=0.0.0 <1.0.0-0` | ||
| ### Range Grammar | ||
| Putting all this together, here is a Backus-Naur grammar for ranges, | ||
| for the benefit of parser authors: | ||
| ```bnf | ||
| range-set ::= range ( logical-or range ) * | ||
| logical-or ::= ( ' ' ) * '||' ( ' ' ) * | ||
| range ::= hyphen | simple ( ' ' simple ) * | '' | ||
| hyphen ::= partial ' - ' partial | ||
| simple ::= primitive | partial | tilde | caret | ||
| primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial | ||
| partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? | ||
| xr ::= 'x' | 'X' | '*' | nr | ||
| nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * | ||
| tilde ::= '~' partial | ||
| caret ::= '^' partial | ||
| qualifier ::= ( '-' pre )? ( '+' build )? | ||
| pre ::= prepart ( '.' prepart ) * | ||
| prepart ::= nr | alphanumid | ||
| build ::= buildid ( '.' buildid ) * | ||
| alphanumid ::= ( ['0'-'9'] ) * [-A-Za-z] [-0-9A-Za-z] * | ||
| buildid ::= [-0-9A-Za-z]+ | ||
| ``` | ||
| Note: Prerelease identifiers (`pre`) use `nr` for numeric parts, which | ||
| disallows leading zeros (e.g., `1.2.3-00` is invalid). Build metadata | ||
| identifiers (`build`) allow any alphanumeric string including leading | ||
| zeros (e.g., `1.2.3+00` is valid). This matches the | ||
| [SemVer 2.0.0 specification](https://semver.org/#spec-item-9). | ||
| ## Functions | ||
| All methods and classes take a final `options` object argument. All | ||
| options in this object are `false` by default. The options supported | ||
| are: | ||
| - `loose`: Be more forgiving about not-quite-valid semver strings. | ||
| (Any resulting output will always be 100% strict compliant, of | ||
| course.) For backwards compatibility reasons, if the `options` | ||
| argument is a boolean value instead of an object, it is interpreted | ||
| to be the `loose` param. | ||
| - `includePrerelease`: Set to suppress the [default | ||
| behavior](https://github.com/npm/node-semver#prerelease-tags) of | ||
| excluding prerelease tagged versions from ranges unless they are | ||
| explicitly opted into. | ||
| Strict-mode Comparators and Ranges will be strict about the SemVer | ||
| strings that they parse. | ||
| * `valid(v)`: Return the parsed version, or null if it's not valid. | ||
| * `inc(v, releaseType, options, identifier, identifierBase)`: | ||
| Return the version incremented by the release | ||
| type (`major`, `premajor`, `minor`, `preminor`, `patch`, | ||
| `prepatch`, `prerelease`, or `release`), or null if it's not valid | ||
| * `premajor` in one call will bump the version up to the next major | ||
| version and down to a prerelease of that major version. | ||
| `preminor`, and `prepatch` work the same way. | ||
| * If called from a non-prerelease version, `prerelease` will work the | ||
| same as `prepatch`. It increments the patch version and then makes a | ||
| prerelease. If the input version is already a prerelease it simply | ||
| increments it. | ||
| * `release` will remove any prerelease part of the version. | ||
| * `identifier` can be used to prefix `premajor`, `preminor`, | ||
| `prepatch`, or `prerelease` version increments. `identifierBase` | ||
| is the base to be used for the `prerelease` identifier. | ||
| * `prerelease(v)`: Returns an array of prerelease components, or null | ||
| if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` | ||
| * `major(v)`: Return the major version number. | ||
| * `minor(v)`: Return the minor version number. | ||
| * `patch(v)`: Return the patch version number. | ||
| * `intersects(r1, r2, loose)`: Return true if the two supplied ranges | ||
| or comparators intersect. | ||
| * `parse(v)`: Attempt to parse a string as a semantic version, returning either | ||
| a `SemVer` object or `null`. | ||
| * `truncate(v, releaseType)`: Return the version with components _lower_ | ||
| than `releaseType` dropped off, e.g.: | ||
| * `major` removes build & prerelease info and sets minor & patch to 0. | ||
| * `minor` removes build & prerelease info, and sets patch to 0 | ||
| * `patch` removes build & prerelease info | ||
| * All prerelease types remove build info only | ||
| ### Comparison | ||
| * `gt(v1, v2)`: `v1 > v2` | ||
| * `gte(v1, v2)`: `v1 >= v2` | ||
| * `lt(v1, v2)`: `v1 < v2` | ||
| * `lte(v1, v2)`: `v1 <= v2` | ||
| * `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, | ||
| even if they're not the same string. You already know how to | ||
| compare strings. | ||
| * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. | ||
| * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call | ||
| the corresponding function above. `"==="` and `"!=="` do simple | ||
| string comparison, but are included for completeness. Throws if an | ||
| invalid comparison string is provided. | ||
| * `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if | ||
| `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. | ||
| * `rcompare(v1, v2)`: The reverse of `compare`. Sorts an array of versions | ||
| in descending order when passed to `Array.sort()`. | ||
| * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions | ||
| are equal. Sorts in ascending order if passed to `Array.sort()`. | ||
| * `compareLoose(v1, v2)`: Short for `compare(v1, v2, { loose: true })`. | ||
| * `diff(v1, v2)`: Returns the difference between two versions by the release type | ||
| (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), | ||
| or null if the versions are the same. | ||
| ### Sorting | ||
| * `sort(versions)`: Returns a sorted array of versions based on the `compareBuild` | ||
| function. | ||
| * `rsort(versions)`: The reverse of `sort`. Returns an array of versions based on | ||
| the `compareBuild` function in descending order. | ||
| ### Comparators | ||
| * `intersects(comparator)`: Return true if the comparators intersect | ||
| ### Ranges | ||
| * `validRange(range)`: Return the valid range or null if it's not valid. | ||
| * `satisfies(version, range)`: Return true if the version satisfies the | ||
| range. | ||
| * `maxSatisfying(versions, range)`: Return the highest version in the list | ||
| that satisfies the range, or `null` if none of them do. | ||
| * `minSatisfying(versions, range)`: Return the lowest version in the list | ||
| that satisfies the range, or `null` if none of them do. | ||
| * `minVersion(range)`: Return the lowest version that can match | ||
| the given range. | ||
| * `gtr(version, range)`: Return `true` if the version is greater than all the | ||
| versions possible in the range. | ||
| * `ltr(version, range)`: Return `true` if the version is less than all the | ||
| versions possible in the range. | ||
| * `outside(version, range, hilo)`: Return true if the version is outside | ||
| the bounds of the range in either the high or low direction. The | ||
| `hilo` argument must be either the string `'>'` or `'<'`. (This is | ||
| the function called by `gtr` and `ltr`.) | ||
| * `intersects(range)`: Return true if any of the range comparators intersect. | ||
| * `simplifyRange(versions, range)`: Return a "simplified" range that | ||
| matches the same items in the `versions` list as the range specified. Note | ||
| that it does *not* guarantee that it would match the same versions in all | ||
| cases, only for the set of versions provided. This is useful when | ||
| generating ranges by joining together multiple versions with `||` | ||
| programmatically, to provide the user with something a bit more | ||
| ergonomic. If the provided range is shorter in string-length than the | ||
| generated range, then that is returned. | ||
| * `subset(subRange, superRange)`: Return `true` if the `subRange` range is | ||
| entirely contained by the `superRange` range. | ||
| Note that, since ranges may be non-contiguous, a version might not be | ||
| greater than a range, less than a range, *or* satisfy a range! For | ||
| example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` | ||
| until `2.0.0`, so version `1.2.10` would not be greater than the | ||
| range (because `2.0.1` satisfies, which is higher), nor less than the | ||
| range (since `1.2.8` satisfies, which is lower), and it also does not | ||
| satisfy the range. | ||
| If you want to know if a version satisfies or does not satisfy a | ||
| range, use the `satisfies(version, range)` function. | ||
| ### Coercion | ||
| * `coerce(version, options)`: Coerces a string to semver if possible | ||
| This aims to provide a very forgiving translation of a non-semver string to | ||
| semver. It looks for the first digit in a string and consumes all | ||
| remaining characters which satisfy at least a partial semver (e.g., `1`, | ||
| `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer | ||
| versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All | ||
| surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes | ||
| `3.4.0`). Only text which lacks digits will fail coercion (`version one` | ||
| is not valid). The maximum length for any semver component considered for | ||
| coercion is 16 characters; longer components will be ignored | ||
| (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any | ||
| semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value | ||
| components are invalid (`9999999999999999.4.7.4` is likely invalid). | ||
| If the `options.rtl` flag is set, then `coerce` will return the right-most | ||
| coercible tuple that does not share an ending index with a longer coercible | ||
| tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not | ||
| `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of | ||
| any other overlapping SemVer tuple. | ||
| If the `options.includePrerelease` flag is set, then the `coerce` result will contain | ||
| prerelease and build parts of a version. For example, `1.2.3.4-rc.1+rev.2` | ||
| will preserve prerelease `rc.1` and build `rev.2` in the result. | ||
| ### Clean | ||
| * `clean(version)`: Clean a string to be a valid semver if possible | ||
| This will return a cleaned and trimmed semver version. If the provided | ||
| version is not valid a null will be returned. This does not work for | ||
| ranges. | ||
| ex. | ||
| * `s.clean(' = v 2.1.5foo')`: `null` | ||
| * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` | ||
| * `s.clean(' = v 2.1.5-foo')`: `null` | ||
| * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` | ||
| * `s.clean('=v2.1.5')`: `'2.1.5'` | ||
| * `s.clean(' =v2.1.5')`: `'2.1.5'` | ||
| * `s.clean(' 2.1.5 ')`: `'2.1.5'` | ||
| * `s.clean('~1.0.0')`: `null` | ||
| ## Constants | ||
| As a convenience, helper constants are exported to provide information about what `node-semver` supports: | ||
| ### `RELEASE_TYPES` | ||
| - major | ||
| - premajor | ||
| - minor | ||
| - preminor | ||
| - patch | ||
| - prepatch | ||
| - prerelease | ||
| ``` | ||
| const semver = require('semver'); | ||
| if (semver.RELEASE_TYPES.includes(arbitraryUserInput)) { | ||
| console.log('This is a valid release type!'); | ||
| } else { | ||
| console.warn('This is NOT a valid release type!'); | ||
| } | ||
| ``` | ||
| ### `SEMVER_SPEC_VERSION` | ||
| 2.0.0 | ||
| ``` | ||
| const semver = require('semver'); | ||
| console.log('We are currently using the semver specification version:', semver.SEMVER_SPEC_VERSION); | ||
| ``` | ||
| ## Exported Modules | ||
| <!-- | ||
| TODO: Make sure that all of these items are documented (classes aren't, | ||
| eg), and then pull the module name into the documentation for that specific | ||
| thing. | ||
| --> | ||
| You may pull in just the part of this semver utility that you need if you | ||
| are sensitive to packing and tree-shaking concerns. The main | ||
| `require('semver')` export uses getter functions to lazily load the parts | ||
| of the API that are used. | ||
| The following modules are available: | ||
| * `require('semver')` | ||
| * `require('semver/classes')` | ||
| * `require('semver/classes/comparator')` | ||
| * `require('semver/classes/range')` | ||
| * `require('semver/classes/semver')` | ||
| * `require('semver/functions/clean')` | ||
| * `require('semver/functions/cmp')` | ||
| * `require('semver/functions/coerce')` | ||
| * `require('semver/functions/compare')` | ||
| * `require('semver/functions/compare-build')` | ||
| * `require('semver/functions/compare-loose')` | ||
| * `require('semver/functions/diff')` | ||
| * `require('semver/functions/eq')` | ||
| * `require('semver/functions/gt')` | ||
| * `require('semver/functions/gte')` | ||
| * `require('semver/functions/inc')` | ||
| * `require('semver/functions/lt')` | ||
| * `require('semver/functions/lte')` | ||
| * `require('semver/functions/major')` | ||
| * `require('semver/functions/minor')` | ||
| * `require('semver/functions/neq')` | ||
| * `require('semver/functions/parse')` | ||
| * `require('semver/functions/patch')` | ||
| * `require('semver/functions/prerelease')` | ||
| * `require('semver/functions/rcompare')` | ||
| * `require('semver/functions/rsort')` | ||
| * `require('semver/functions/satisfies')` | ||
| * `require('semver/functions/sort')` | ||
| * `require('semver/functions/truncate')` | ||
| * `require('semver/functions/valid')` | ||
| * `require('semver/ranges/gtr')` | ||
| * `require('semver/ranges/intersects')` | ||
| * `require('semver/ranges/ltr')` | ||
| * `require('semver/ranges/max-satisfying')` | ||
| * `require('semver/ranges/min-satisfying')` | ||
| * `require('semver/ranges/min-version')` | ||
| * `require('semver/ranges/outside')` | ||
| * `require('semver/ranges/simplify')` | ||
| * `require('semver/ranges/subset')` | ||
| * `require('semver/ranges/to-comparators')` | ||
| * `require('semver/ranges/valid')` | ||
| { | ||
| "name": "sharp", | ||
| "description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images", | ||
| "version": "0.34.5", | ||
| "author": "Lovell Fuller <npm@lovell.info>", | ||
| "homepage": "https://sharp.pixelplumbing.com", | ||
| "contributors": [ | ||
| "Pierre Inglebert <pierre.inglebert@gmail.com>", | ||
| "Jonathan Ong <jonathanrichardong@gmail.com>", | ||
| "Chanon Sajjamanochai <chanon.s@gmail.com>", | ||
| "Juliano Julio <julianojulio@gmail.com>", | ||
| "Daniel Gasienica <daniel@gasienica.ch>", | ||
| "Julian Walker <julian@fiftythree.com>", | ||
| "Amit Pitaru <pitaru.amit@gmail.com>", | ||
| "Brandon Aaron <hello.brandon@aaron.sh>", | ||
| "Andreas Lind <andreas@one.com>", | ||
| "Maurus Cuelenaere <mcuelenaere@gmail.com>", | ||
| "Linus Unnebäck <linus@folkdatorn.se>", | ||
| "Victor Mateevitsi <mvictoras@gmail.com>", | ||
| "Alaric Holloway <alaric.holloway@gmail.com>", | ||
| "Bernhard K. Weisshuhn <bkw@codingforce.com>", | ||
| "Chris Riley <criley@primedia.com>", | ||
| "David Carley <dacarley@gmail.com>", | ||
| "John Tobin <john@limelightmobileinc.com>", | ||
| "Kenton Gray <kentongray@gmail.com>", | ||
| "Felix Bünemann <Felix.Buenemann@gmail.com>", | ||
| "Samy Al Zahrani <samyalzahrany@gmail.com>", | ||
| "Chintan Thakkar <lemnisk8@gmail.com>", | ||
| "F. Orlando Galashan <frulo@gmx.de>", | ||
| "Kleis Auke Wolthuizen <info@kleisauke.nl>", | ||
| "Matt Hirsch <mhirsch@media.mit.edu>", | ||
| "Matthias Thoemmes <thoemmes@gmail.com>", | ||
| "Patrick Paskaris <patrick@paskaris.gr>", | ||
| "Jérémy Lal <kapouer@melix.org>", | ||
| "Rahul Nanwani <r.nanwani@gmail.com>", | ||
| "Alice Monday <alice0meta@gmail.com>", | ||
| "Kristo Jorgenson <kristo.jorgenson@gmail.com>", | ||
| "YvesBos <yves_bos@outlook.com>", | ||
| "Guy Maliar <guy@tailorbrands.com>", | ||
| "Nicolas Coden <nicolas@ncoden.fr>", | ||
| "Matt Parrish <matt.r.parrish@gmail.com>", | ||
| "Marcel Bretschneider <marcel.bretschneider@gmail.com>", | ||
| "Matthew McEachen <matthew+github@mceachen.org>", | ||
| "Jarda Kotěšovec <jarda.kotesovec@gmail.com>", | ||
| "Kenric D'Souza <kenric.dsouza@gmail.com>", | ||
| "Oleh Aleinyk <oleg.aleynik@gmail.com>", | ||
| "Marcel Bretschneider <marcel.bretschneider@gmail.com>", | ||
| "Andrea Bianco <andrea.bianco@unibas.ch>", | ||
| "Rik Heywood <rik@rik.org>", | ||
| "Thomas Parisot <hi@oncletom.io>", | ||
| "Nathan Graves <nathanrgraves+github@gmail.com>", | ||
| "Tom Lokhorst <tom@lokhorst.eu>", | ||
| "Espen Hovlandsdal <espen@hovlandsdal.com>", | ||
| "Sylvain Dumont <sylvain.dumont35@gmail.com>", | ||
| "Alun Davies <alun.owain.davies@googlemail.com>", | ||
| "Aidan Hoolachan <ajhoolachan21@gmail.com>", | ||
| "Axel Eirola <axel.eirola@iki.fi>", | ||
| "Freezy <freezy@xbmc.org>", | ||
| "Daiz <taneli.vatanen@gmail.com>", | ||
| "Julian Aubourg <j@ubourg.net>", | ||
| "Keith Belovay <keith@picthrive.com>", | ||
| "Michael B. Klein <mbklein@gmail.com>", | ||
| "Jordan Prudhomme <jordan@raboland.fr>", | ||
| "Ilya Ovdin <iovdin@gmail.com>", | ||
| "Andargor <andargor@yahoo.com>", | ||
| "Paul Neave <paul.neave@gmail.com>", | ||
| "Brendan Kennedy <brenwken@gmail.com>", | ||
| "Brychan Bennett-Odlum <git@brychan.io>", | ||
| "Edward Silverton <e.silverton@gmail.com>", | ||
| "Roman Malieiev <aromaleev@gmail.com>", | ||
| "Tomas Szabo <tomas.szabo@deftomat.com>", | ||
| "Robert O'Rourke <robert@o-rourke.org>", | ||
| "Guillermo Alfonso Varela Chouciño <guillevch@gmail.com>", | ||
| "Christian Flintrup <chr@gigahost.dk>", | ||
| "Manan Jadhav <manan@motionden.com>", | ||
| "Leon Radley <leon@radley.se>", | ||
| "alza54 <alza54@thiocod.in>", | ||
| "Jacob Smith <jacob@frende.me>", | ||
| "Michael Nutt <michael@nutt.im>", | ||
| "Brad Parham <baparham@gmail.com>", | ||
| "Taneli Vatanen <taneli.vatanen@gmail.com>", | ||
| "Joris Dugué <zaruike10@gmail.com>", | ||
| "Chris Banks <christopher.bradley.banks@gmail.com>", | ||
| "Ompal Singh <ompal.hitm09@gmail.com>", | ||
| "Brodan <christopher.hranj@gmail.com>", | ||
| "Ankur Parihar <ankur.github@gmail.com>", | ||
| "Brahim Ait elhaj <brahima@gmail.com>", | ||
| "Mart Jansink <m.jansink@gmail.com>", | ||
| "Lachlan Newman <lachnewman007@gmail.com>", | ||
| "Dennis Beatty <dennis@dcbeatty.com>", | ||
| "Ingvar Stepanyan <me@rreverser.com>", | ||
| "Don Denton <don@happycollision.com>" | ||
| ], | ||
| "scripts": { | ||
| "build": "node install/build.js", | ||
| "install": "node install/check.js || npm run build", | ||
| "clean": "rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*", | ||
| "test": "npm run lint && npm run test-unit", | ||
| "lint": "npm run lint-cpp && npm run lint-js && npm run lint-types", | ||
| "lint-cpp": "cpplint --quiet src/*.h src/*.cc", | ||
| "lint-js": "biome lint", | ||
| "lint-types": "tsd --files ./test/types/sharp.test-d.ts", | ||
| "test-leak": "./test/leak/leak.sh", | ||
| "test-unit": "node --experimental-test-coverage test/unit.mjs", | ||
| "package-from-local-build": "node npm/from-local-build.js", | ||
| "package-release-notes": "node npm/release-notes.js", | ||
| "docs-build": "node docs/build.mjs", | ||
| "docs-serve": "cd docs && npm start", | ||
| "docs-publish": "cd docs && npm run build && 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": { | ||
| "@img/colour": "^1.0.0", | ||
| "detect-libc": "^2.1.2", | ||
| "semver": "^7.7.3" | ||
| }, | ||
| "optionalDependencies": { | ||
| "@img/sharp-darwin-arm64": "0.34.5", | ||
| "@img/sharp-darwin-x64": "0.34.5", | ||
| "@img/sharp-libvips-darwin-arm64": "1.2.4", | ||
| "@img/sharp-libvips-darwin-x64": "1.2.4", | ||
| "@img/sharp-libvips-linux-arm": "1.2.4", | ||
| "@img/sharp-libvips-linux-arm64": "1.2.4", | ||
| "@img/sharp-libvips-linux-ppc64": "1.2.4", | ||
| "@img/sharp-libvips-linux-riscv64": "1.2.4", | ||
| "@img/sharp-libvips-linux-s390x": "1.2.4", | ||
| "@img/sharp-libvips-linux-x64": "1.2.4", | ||
| "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", | ||
| "@img/sharp-libvips-linuxmusl-x64": "1.2.4", | ||
| "@img/sharp-linux-arm": "0.34.5", | ||
| "@img/sharp-linux-arm64": "0.34.5", | ||
| "@img/sharp-linux-ppc64": "0.34.5", | ||
| "@img/sharp-linux-riscv64": "0.34.5", | ||
| "@img/sharp-linux-s390x": "0.34.5", | ||
| "@img/sharp-linux-x64": "0.34.5", | ||
| "@img/sharp-linuxmusl-arm64": "0.34.5", | ||
| "@img/sharp-linuxmusl-x64": "0.34.5", | ||
| "@img/sharp-wasm32": "0.34.5", | ||
| "@img/sharp-win32-arm64": "0.34.5", | ||
| "@img/sharp-win32-ia32": "0.34.5", | ||
| "@img/sharp-win32-x64": "0.34.5" | ||
| }, | ||
| "devDependencies": { | ||
| "@biomejs/biome": "^2.3.4", | ||
| "@cpplint/cli": "^0.1.0", | ||
| "@emnapi/runtime": "^1.7.0", | ||
| "@img/sharp-libvips-dev": "1.2.4", | ||
| "@img/sharp-libvips-dev-wasm32": "1.2.4", | ||
| "@img/sharp-libvips-win32-arm64": "1.2.4", | ||
| "@img/sharp-libvips-win32-ia32": "1.2.4", | ||
| "@img/sharp-libvips-win32-x64": "1.2.4", | ||
| "@types/node": "*", | ||
| "emnapi": "^1.7.0", | ||
| "exif-reader": "^2.0.2", | ||
| "extract-zip": "^2.0.1", | ||
| "icc": "^3.0.0", | ||
| "jsdoc-to-markdown": "^9.1.3", | ||
| "node-addon-api": "^8.5.0", | ||
| "node-gyp": "^11.5.0", | ||
| "tar-fs": "^3.1.1", | ||
| "tsd": "^0.33.0" | ||
| }, | ||
| "license": "Apache-2.0", | ||
| "engines": { | ||
| "node": "^18.17.0 || ^20.3.0 || >=21.0.0" | ||
| }, | ||
| "config": { | ||
| "libvips": ">=8.17.3" | ||
| }, | ||
| "funding": { | ||
| "url": "https://opencollective.com/libvips" | ||
| } | ||
| } |
| # sharp | ||
| <img src="https://sharp.pixelplumbing.com/sharp-logo.svg" width="160" height="160" alt="sharp logo" align="right"> | ||
| 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( | ||
| '<svg><rect x="0" y="0" width="200" height="200" rx="50" ry="50"/></svg>' | ||
| ); | ||
| 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. |
Sorry, the diff of this file is not supported yet
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| #include <algorithm> | ||
| #include <cstdlib> | ||
| #include <map> | ||
| #include <mutex> | ||
| #include <queue> | ||
| #include <string> | ||
| #include <tuple> | ||
| #include <utility> | ||
| #include <vector> | ||
| #include <napi.h> | ||
| #include <vips/vips8> | ||
| #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<Napi::String>(); | ||
| } | ||
| std::string AttrAsStr(Napi::Object obj, unsigned int const attr) { | ||
| return obj.Get(attr).As<Napi::String>(); | ||
| } | ||
| uint32_t AttrAsUint32(Napi::Object obj, std::string attr) { | ||
| return obj.Get(attr).As<Napi::Number>().Uint32Value(); | ||
| } | ||
| int32_t AttrAsInt32(Napi::Object obj, std::string attr) { | ||
| return obj.Get(attr).As<Napi::Number>().Int32Value(); | ||
| } | ||
| int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr) { | ||
| return obj.Get(attr).As<Napi::Number>().Int32Value(); | ||
| } | ||
| int64_t AttrAsInt64(Napi::Object obj, std::string attr) { | ||
| return obj.Get(attr).As<Napi::Number>().Int64Value(); | ||
| } | ||
| double AttrAsDouble(Napi::Object obj, std::string attr) { | ||
| return obj.Get(attr).As<Napi::Number>().DoubleValue(); | ||
| } | ||
| double AttrAsDouble(Napi::Object obj, unsigned int const attr) { | ||
| return obj.Get(attr).As<Napi::Number>().DoubleValue(); | ||
| } | ||
| bool AttrAsBool(Napi::Object obj, std::string attr) { | ||
| return obj.Get(attr).As<Napi::Boolean>().Value(); | ||
| } | ||
| std::vector<double> AttrAsVectorOfDouble(Napi::Object obj, std::string attr) { | ||
| Napi::Array napiArray = obj.Get(attr).As<Napi::Array>(); | ||
| std::vector<double> vectorOfDouble(napiArray.Length()); | ||
| for (unsigned int i = 0; i < napiArray.Length(); i++) { | ||
| vectorOfDouble[i] = AttrAsDouble(napiArray, i); | ||
| } | ||
| return vectorOfDouble; | ||
| } | ||
| std::vector<int32_t> AttrAsInt32Vector(Napi::Object obj, std::string attr) { | ||
| Napi::Array array = obj.Get(attr).As<Napi::Array>(); | ||
| std::vector<int32_t> 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<char> buffer = input.Get("buffer").As<Napi::Buffer<char>>(); | ||
| descriptor->bufferLength = buffer.Length(); | ||
| descriptor->buffer = buffer.Data(); | ||
| descriptor->isBuffer = true; | ||
| } | ||
| descriptor->failOn = AttrAsEnum<VipsFailOn>(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<VipsBandFormat>(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"); | ||
| descriptor->rawPageHeight = AttrAsUint32(input, "rawPageHeight"); | ||
| } | ||
| // Multi-page input (GIF, TIFF, PDF) | ||
| if (HasAttr(input, "pages")) { | ||
| descriptor->pages = AttrAsInt32(input, "pages"); | ||
| } | ||
| if (HasAttr(input, "page")) { | ||
| descriptor->page = AttrAsUint32(input, "page"); | ||
| } | ||
| // SVG | ||
| if (HasAttr(input, "svgStylesheet")) { | ||
| descriptor->svgStylesheet = AttrAsStr(input, "svgStylesheet"); | ||
| } | ||
| if (HasAttr(input, "svgHighBitdepth")) { | ||
| descriptor->svgHighBitdepth = AttrAsBool(input, "svgHighBitdepth"); | ||
| } | ||
| // Multi-level input (OpenSlide) | ||
| if (HasAttr(input, "openSlideLevel")) { | ||
| descriptor->openSlideLevel = AttrAsUint32(input, "openSlideLevel"); | ||
| } | ||
| // subIFD (OME-TIFF) | ||
| if (HasAttr(input, "subifd")) { | ||
| descriptor->tiffSubifd = AttrAsInt32(input, "tiffSubifd"); | ||
| } | ||
| // // PDF background color | ||
| if (HasAttr(input, "pdfBackground")) { | ||
| descriptor->pdfBackground = AttrAsVectorOfDouble(input, "pdfBackground"); | ||
| } | ||
| // Use JPEG 2000 oneshot mode? | ||
| if (HasAttr(input, "jp2Oneshot")) { | ||
| descriptor->jp2Oneshot = AttrAsBool(input, "jp2Oneshot"); | ||
| } | ||
| // Create new image | ||
| if (HasAttr(input, "createChannels")) { | ||
| descriptor->createChannels = AttrAsUint32(input, "createChannels"); | ||
| descriptor->createWidth = AttrAsUint32(input, "createWidth"); | ||
| descriptor->createHeight = AttrAsUint32(input, "createHeight"); | ||
| descriptor->createPageHeight = AttrAsUint32(input, "createPageHeight"); | ||
| 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<VipsAlign>(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<VipsTextWrap>(input, "textWrap", VIPS_TYPE_TEXT_WRAP); | ||
| } | ||
| } | ||
| // Join images together | ||
| if (HasAttr(input, "joinAnimated")) { | ||
| descriptor->joinAnimated = AttrAsBool(input, "joinAnimated"); | ||
| } | ||
| if (HasAttr(input, "joinAcross")) { | ||
| descriptor->joinAcross = AttrAsUint32(input, "joinAcross"); | ||
| } | ||
| if (HasAttr(input, "joinShim")) { | ||
| descriptor->joinShim = AttrAsUint32(input, "joinShim"); | ||
| } | ||
| if (HasAttr(input, "joinBackground")) { | ||
| descriptor->joinBackground = AttrAsVectorOfDouble(input, "joinBackground"); | ||
| } | ||
| if (HasAttr(input, "joinHalign")) { | ||
| descriptor->joinHalign = AttrAsEnum<VipsAlign>(input, "joinHalign", VIPS_TYPE_ALIGN); | ||
| } | ||
| if (HasAttr(input, "joinValign")) { | ||
| descriptor->joinValign = AttrAsEnum<VipsAlign>(input, "joinValign", VIPS_TYPE_ALIGN); | ||
| } | ||
| // Limit input images to a given number of pixels, where pixels = width * height | ||
| descriptor->limitInputPixels = static_cast<uint64_t>(AttrAsInt64(input, "limitInputPixels")); | ||
| if (HasAttr(input, "access")) { | ||
| descriptor->access = AttrAsBool(input, "sequentialRead") ? VIPS_ACCESS_SEQUENTIAL : VIPS_ACCESS_RANDOM; | ||
| } | ||
| // Remove safety features and allow unlimited input | ||
| descriptor->unlimited = AttrAsBool(input, "unlimited"); | ||
| // Use the EXIF orientation to auto orient the image | ||
| descriptor->autoOrient = AttrAsBool(input, "autoOrient"); | ||
| return descriptor; | ||
| } | ||
| // How many tasks are in the queue? | ||
| std::atomic<int> counterQueue{0}; | ||
| // How many tasks are being processed? | ||
| std::atomic<int> 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::RAD: id = "rad"; break; | ||
| case ImageType::DCRAW: id = "dcraw"; 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<std::string, ImageType> 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 }, | ||
| { "VipsForeignLoadRadFile", ImageType::RAD }, | ||
| { "VipsForeignLoadRadBuffer", ImageType::RAD }, | ||
| { "VipsForeignLoadDcRawFile", ImageType::DCRAW }, | ||
| { "VipsForeignLoadDcRawBuffer", ImageType::DCRAW }, | ||
| { "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::TIFF || | ||
| imageType == ImageType::HEIF; | ||
| } | ||
| /* | ||
| Format-specific options builder | ||
| */ | ||
| vips::VOption* GetOptionsForImageType(ImageType imageType, InputDescriptor *descriptor) { | ||
| vips::VOption *option = VImage::option() | ||
| ->set("access", descriptor->access) | ||
| ->set("fail_on", descriptor->failOn); | ||
| if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) { | ||
| option->set("unlimited", true); | ||
| } | ||
| if (ImageTypeSupportsPage(imageType)) { | ||
| option->set("n", descriptor->pages); | ||
| option->set("page", descriptor->page); | ||
| } | ||
| switch (imageType) { | ||
| case ImageType::SVG: | ||
| option->set("dpi", descriptor->density) | ||
| ->set("stylesheet", descriptor->svgStylesheet.data()) | ||
| ->set("high_bitdepth", descriptor->svgHighBitdepth); | ||
| break; | ||
| case ImageType::TIFF: | ||
| option->set("subifd", descriptor->tiffSubifd); | ||
| break; | ||
| case ImageType::PDF: | ||
| option->set("dpi", descriptor->density) | ||
| ->set("background", descriptor->pdfBackground); | ||
| break; | ||
| case ImageType::OPENSLIDE: | ||
| option->set("level", descriptor->openSlideLevel); | ||
| break; | ||
| case ImageType::JP2: | ||
| option->set("oneshot", descriptor->jp2Oneshot); | ||
| break; | ||
| case ImageType::MAGICK: | ||
| option->set("density", std::to_string(descriptor->density).data()); | ||
| break; | ||
| default: | ||
| break; | ||
| } | ||
| return option; | ||
| } | ||
| /* | ||
| Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data) | ||
| */ | ||
| std::tuple<VImage, ImageType> 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->rawPageHeight > 0) { | ||
| image.set(VIPS_META_PAGE_HEIGHT, descriptor->rawPageHeight); | ||
| image.set(VIPS_META_N_PAGES, static_cast<int>(descriptor->rawHeight / descriptor->rawPageHeight)); | ||
| } | ||
| 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 = GetOptionsForImageType(imageType, descriptor); | ||
| 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<VImage> 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<double> 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); | ||
| } | ||
| if (descriptor->createPageHeight > 0) { | ||
| image.set(VIPS_META_PAGE_HEIGHT, descriptor->createPageHeight); | ||
| image.set(VIPS_META_N_PAGES, static_cast<int>(descriptor->createHeight / descriptor->createPageHeight)); | ||
| } | ||
| 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<char*>(descriptor->textFont.data())); | ||
| } | ||
| if (descriptor->textFontfile.length() > 0) { | ||
| textOptions->set("fontfile", const_cast<char*>(descriptor->textFontfile.data())); | ||
| } | ||
| image = VImage::text(const_cast<char *>(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("<svg") != std::string::npos) { | ||
| throw vips::VError("Input file is missing, did you mean " | ||
| "sharp(Buffer.from('" + descriptor->file.substr(0, 8) + "...')?"); | ||
| } | ||
| throw vips::VError("Input file is missing: " + descriptor->file); | ||
| } | ||
| if (imageType != ImageType::UNKNOWN) { | ||
| try { | ||
| vips::VOption *option = GetOptionsForImageType(imageType, descriptor); | ||
| 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<uint64_t>(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<char*, size_t> GetProfile(VImage image) { | ||
| std::pair<char*, size_t> icc(nullptr, 0); | ||
| if (HasProfile(image)) { | ||
| size_t length; | ||
| const void *data = image.get_blob(VIPS_META_ICC_NAME, &length); | ||
| icc.first = static_cast<char*>(g_malloc(length)); | ||
| icc.second = length; | ||
| memcpy(icc.first, data, length); | ||
| } | ||
| return icc; | ||
| } | ||
| /* | ||
| Set embedded profile. | ||
| */ | ||
| VImage SetProfile(VImage image, std::pair<char*, size_t> icc) { | ||
| if (icc.first != nullptr) { | ||
| image = image.copy(); | ||
| image.set(VIPS_META_ICC_NAME, reinterpret_cast<VipsCallbackFn>(vips_area_free_cb), icc.first, icc.second); | ||
| } | ||
| return image; | ||
| } | ||
| static void* RemoveExifCallback(VipsImage *image, char const *field, GValue *value, void *data) { | ||
| std::vector<std::string> *fieldNames = static_cast<std::vector<std::string> *>(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<std::string> fieldNames; | ||
| vips_image_map(image.get_image(), static_cast<VipsImageMapFn>(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<int> delay, int loop) { | ||
| bool hasDelay = !delay.empty(); | ||
| 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) { | ||
| if (delay.size() == 1) { | ||
| // We have just one delay, repeat that value for all frames. | ||
| delay.insert(delay.end(), nPages - 1, delay[0]); | ||
| } | ||
| copy.set("delay", delay); | ||
| } | ||
| if (nPages == 1 && !hasDelay && loop == -1) { | ||
| loop = 1; | ||
| } | ||
| 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<int>(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<void(void*, char*)> FreeCallback = [](void*, char* data) { | ||
| g_free(data); | ||
| }; | ||
| /* | ||
| Temporary buffer of warnings | ||
| */ | ||
| std::queue<std::string> 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<std::mutex> lock(vipsWarningsMutex); | ||
| vipsWarnings.emplace(message); | ||
| } | ||
| /* | ||
| Pop the oldest warning message from the queue | ||
| */ | ||
| std::string VipsWarningPop() { | ||
| std::string warning; | ||
| std::lock_guard<std::mutex> 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<int, int> 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<int, int> 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<int, int> 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; | ||
| } | ||
| /* | ||
| Convert RGBA value to another colourspace | ||
| */ | ||
| std::vector<double> GetRgbaAsColourspace(std::vector<double> const rgba, | ||
| VipsInterpretation const interpretation, bool premultiply) { | ||
| int const bands = static_cast<int>(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<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> 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<double> 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(s) to alphaColour colour | ||
| if (colour[3] < 255.0 || image.has_alpha()) { | ||
| int extraBands = image.bands() > 4 ? image.bands() - 3 : 1; | ||
| alphaColour.insert(alphaColour.end(), extraBands, 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 && !image.has_alpha()) { | ||
| image = image.bandjoin_const({ 255 * multiplier }); | ||
| } | ||
| return std::make_tuple(image, alphaColour); | ||
| } | ||
| /* | ||
| Removes alpha channels, if any. | ||
| */ | ||
| VImage RemoveAlpha(VImage image) { | ||
| while (image.bands() > 1 && image.has_alpha()) { | ||
| 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 (!image.has_alpha()) { | ||
| image = image.bandjoin_const({ value * vips_interpretation_max_alpha(image.interpretation()) }); | ||
| } | ||
| return image; | ||
| } | ||
| std::pair<double, double> 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<double>(width) / targetWidth; | ||
| vshrink = static_cast<double>(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<double>(width) / targetWidth; | ||
| if (canvas != Canvas::IGNORE_ASPECT) { | ||
| // Auto height | ||
| vshrink = hshrink; | ||
| } | ||
| } else if (targetHeight > 0) { | ||
| // Fixed height | ||
| vshrink = static_cast<double>(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<double>(width)); | ||
| vshrink = std::min(vshrink, static_cast<double>(height)); | ||
| return std::make_pair(hshrink, vshrink); | ||
| } | ||
| /* | ||
| Ensure decoding remains sequential. | ||
| */ | ||
| VImage StaySequential(VImage image, bool condition) { | ||
| if (vips_image_is_sequential(image.get_image()) && condition) { | ||
| image = image.copy_memory().copy(); | ||
| image.remove(VIPS_META_SEQUENTIAL); | ||
| } | ||
| return image; | ||
| } | ||
| } // namespace sharp |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| #ifndef SRC_COMMON_H_ | ||
| #define SRC_COMMON_H_ | ||
| #include <atomic> | ||
| #include <string> | ||
| #include <tuple> | ||
| #include <utility> | ||
| #include <vector> | ||
| #include <napi.h> | ||
| #include <vips/vips8> | ||
| // Verify platform and compiler compatibility | ||
| #if (VIPS_MAJOR_VERSION < 8) || \ | ||
| (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 17) || \ | ||
| (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 17 && VIPS_MICRO_VERSION < 3) | ||
| #error "libvips version 8.17.3+ is required - please see https://sharp.pixelplumbing.com/install" | ||
| #endif | ||
| #if defined(__has_include) | ||
| #if !__has_include(<filesystem>) | ||
| #error "C++17 compiler required - please see https://sharp.pixelplumbing.com/install" | ||
| #endif | ||
| #endif | ||
| using vips::VImage; | ||
| namespace sharp { | ||
| struct InputDescriptor { | ||
| std::string name; | ||
| std::string file; | ||
| bool autoOrient; | ||
| 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 rawPageHeight; | ||
| int pages; | ||
| int page; | ||
| int createChannels; | ||
| int createWidth; | ||
| int createHeight; | ||
| int createPageHeight; | ||
| std::vector<double> 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; | ||
| bool joinAnimated; | ||
| int joinAcross; | ||
| int joinShim; | ||
| std::vector<double> joinBackground; | ||
| VipsAlign joinHalign; | ||
| VipsAlign joinValign; | ||
| std::string svgStylesheet; | ||
| bool svgHighBitdepth; | ||
| int tiffSubifd; | ||
| int openSlideLevel; | ||
| std::vector<double> pdfBackground; | ||
| bool jp2Oneshot; | ||
| InputDescriptor(): | ||
| autoOrient(false), | ||
| buffer(nullptr), | ||
| failOn(VIPS_FAIL_ON_WARNING), | ||
| limitInputPixels(0x3FFF * 0x3FFF), | ||
| unlimited(false), | ||
| access(VIPS_ACCESS_SEQUENTIAL), | ||
| bufferLength(0), | ||
| isBuffer(false), | ||
| density(72.0), | ||
| ignoreIcc(false), | ||
| rawDepth(VIPS_FORMAT_UCHAR), | ||
| rawChannels(0), | ||
| rawWidth(0), | ||
| rawHeight(0), | ||
| rawPremultiplied(false), | ||
| rawPageHeight(0), | ||
| pages(1), | ||
| page(0), | ||
| createChannels(0), | ||
| createWidth(0), | ||
| createHeight(0), | ||
| createPageHeight(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), | ||
| joinAnimated(false), | ||
| joinAcross(1), | ||
| joinShim(0), | ||
| joinBackground{ 0.0, 0.0, 0.0, 255.0 }, | ||
| joinHalign(VIPS_ALIGN_LOW), | ||
| joinValign(VIPS_ALIGN_LOW), | ||
| svgHighBitdepth(false), | ||
| tiffSubifd(-1), | ||
| openSlideLevel(0), | ||
| pdfBackground{ 255.0, 255.0, 255.0, 255.0 }, | ||
| jp2Oneshot(false) {} | ||
| }; | ||
| // 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<double> AttrAsVectorOfDouble(Napi::Object obj, std::string attr); | ||
| std::vector<int32_t> AttrAsInt32Vector(Napi::Object obj, std::string attr); | ||
| template <class T> T AttrAsEnum(Napi::Object obj, std::string attr, GType type) { | ||
| return static_cast<T>( | ||
| 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, | ||
| RAD, | ||
| DCRAW, | ||
| VIPS, | ||
| RAW, | ||
| UNKNOWN, | ||
| MISSING | ||
| }; | ||
| enum class Canvas { | ||
| CROP, | ||
| EMBED, | ||
| MAX, | ||
| MIN, | ||
| IGNORE_ASPECT | ||
| }; | ||
| // How many tasks are in the queue? | ||
| extern std::atomic<int> counterQueue; | ||
| // How many tasks are being processed? | ||
| extern std::atomic<int> 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); | ||
| /* | ||
| Format-specific options builder | ||
| */ | ||
| vips::VOption* GetOptionsForImageType(ImageType imageType, InputDescriptor *descriptor); | ||
| /* | ||
| Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data) | ||
| */ | ||
| std::tuple<VImage, ImageType> OpenInput(InputDescriptor *descriptor); | ||
| /* | ||
| Does this image have an embedded profile? | ||
| */ | ||
| bool HasProfile(VImage image); | ||
| /* | ||
| Get copy of embedded profile. | ||
| */ | ||
| std::pair<char*, size_t> GetProfile(VImage image); | ||
| /* | ||
| Set embedded profile. | ||
| */ | ||
| VImage SetProfile(VImage image, std::pair<char*, size_t> icc); | ||
| /* | ||
| 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<int> 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<void(void*, char*)> 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<int, int> 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<int, int> 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<int, int> 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); | ||
| /* | ||
| Convert RGBA value to another colourspace | ||
| */ | ||
| std::vector<double> GetRgbaAsColourspace(std::vector<double> const rgba, | ||
| VipsInterpretation const interpretation, bool premultiply); | ||
| /* | ||
| Apply the alpha channel to a given colour | ||
| */ | ||
| std::tuple<VImage, std::vector<double>> ApplyAlpha(VImage image, std::vector<double> colour, bool premultiply); | ||
| /* | ||
| Removes alpha channels, 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<double, double> ResolveShrink(int width, int height, int targetWidth, int targetHeight, | ||
| Canvas canvas, bool withoutEnlargement, bool withoutReduction); | ||
| /* | ||
| Ensure decoding remains sequential. | ||
| */ | ||
| VImage StaySequential(VImage image, bool condition = true); | ||
| } // namespace sharp | ||
| #endif // SRC_COMMON_H_ |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| #include <cmath> | ||
| #include <numeric> | ||
| #include <string> | ||
| #include <utility> | ||
| #include <vector> | ||
| #include <napi.h> | ||
| #include <vips/vips8> | ||
| #include "./common.h" | ||
| #include "./metadata.h" | ||
| static void* readPNGComment(VipsImage *image, const char *field, GValue *value, void *p); | ||
| 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(VIPS_META_PALETTE) == G_TYPE_INT) { | ||
| baton->isPalette = image.get_int(VIPS_META_PALETTE); | ||
| } | ||
| if (image.get_typeof(VIPS_META_BITS_PER_SAMPLE) == G_TYPE_INT) { | ||
| baton->bitsPerSample = image.get_int(VIPS_META_BITS_PER_SAMPLE); | ||
| } | ||
| 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<int, int>(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 = image.has_alpha(); | ||
| 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<char*>(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<char*>(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<char *>(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<char *>(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<char *>(g_malloc(tifftagPhotoshopLength)); | ||
| memcpy(baton->tifftagPhotoshop, tifftagPhotoshop, tifftagPhotoshopLength); | ||
| baton->tifftagPhotoshopLength = tifftagPhotoshopLength; | ||
| } | ||
| // PNG comments | ||
| vips_image_map(image.get_image(), readPNGComment, &baton->comments); | ||
| } | ||
| // 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); | ||
| info.Set("isPalette", baton->isPalette); | ||
| if (baton->bitsPerSample > 0) { | ||
| info.Set("bitsPerSample", baton->bitsPerSample); | ||
| if (baton->isPalette) { | ||
| // Deprecated, remove with libvips 8.17.0 | ||
| info.Set("paletteBitDepth", baton->bitsPerSample); | ||
| } | ||
| } | ||
| 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<size_t>(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<size_t>(baton->levels.size())); | ||
| for (const auto& [width, height] : baton->levels) { | ||
| Napi::Object level = Napi::Object::New(env); | ||
| level.Set("width", width); | ||
| level.Set("height", height); | ||
| levels.Set(i++, level); | ||
| } | ||
| info.Set("levels", levels); | ||
| } | ||
| if (baton->subifds > 0) { | ||
| info.Set("subifds", baton->subifds); | ||
| } | ||
| if (!baton->background.empty()) { | ||
| Napi::Object background = Napi::Object::New(env); | ||
| if (baton->background.size() == 3) { | ||
| background.Set("r", baton->background[0]); | ||
| background.Set("g", baton->background[1]); | ||
| background.Set("b", baton->background[2]); | ||
| } else { | ||
| background.Set("gray", round(baton->background[0] * 100 / 255)); | ||
| } | ||
| info.Set("background", background); | ||
| } | ||
| info.Set("hasProfile", baton->hasProfile); | ||
| info.Set("hasAlpha", baton->hasAlpha); | ||
| if (baton->orientation > 0) { | ||
| info.Set("orientation", baton->orientation); | ||
| } | ||
| Napi::Object autoOrient = Napi::Object::New(env); | ||
| info.Set("autoOrient", autoOrient); | ||
| if (baton->orientation >= 5) { | ||
| autoOrient.Set("width", baton->height); | ||
| autoOrient.Set("height", baton->width); | ||
| } else { | ||
| autoOrient.Set("width", baton->width); | ||
| autoOrient.Set("height", baton->height); | ||
| } | ||
| if (baton->exifLength > 0) { | ||
| info.Set("exif", Napi::Buffer<char>::NewOrCopy(env, baton->exif, baton->exifLength, sharp::FreeCallback)); | ||
| } | ||
| if (baton->iccLength > 0) { | ||
| info.Set("icc", Napi::Buffer<char>::NewOrCopy(env, baton->icc, baton->iccLength, sharp::FreeCallback)); | ||
| } | ||
| if (baton->iptcLength > 0) { | ||
| info.Set("iptc", Napi::Buffer<char>::NewOrCopy(env, baton->iptc, baton->iptcLength, sharp::FreeCallback)); | ||
| } | ||
| if (baton->xmpLength > 0) { | ||
| if (g_utf8_validate(static_cast<char const *>(baton->xmp), baton->xmpLength, nullptr)) { | ||
| info.Set("xmpAsString", | ||
| Napi::String::New(env, static_cast<char const *>(baton->xmp), baton->xmpLength)); | ||
| } | ||
| info.Set("xmp", Napi::Buffer<char>::NewOrCopy(env, baton->xmp, baton->xmpLength, sharp::FreeCallback)); | ||
| } | ||
| if (baton->tifftagPhotoshopLength > 0) { | ||
| info.Set("tifftagPhotoshop", | ||
| Napi::Buffer<char>::NewOrCopy(env, baton->tifftagPhotoshop, | ||
| baton->tifftagPhotoshopLength, sharp::FreeCallback)); | ||
| } | ||
| if (baton->comments.size() > 0) { | ||
| int i = 0; | ||
| Napi::Array comments = Napi::Array::New(env, baton->comments.size()); | ||
| for (const auto& [keyword, text] : baton->comments) { | ||
| Napi::Object comment = Napi::Object::New(env); | ||
| comment.Set("keyword", keyword); | ||
| comment.Set("text", text); | ||
| comments.Set(i++, comment); | ||
| } | ||
| info.Set("comments", comments); | ||
| } | ||
| 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<Napi::Object>(); | ||
| // Input | ||
| baton->input = sharp::CreateInputDescriptor(options.Get("input").As<Napi::Object>()); | ||
| // Function to notify of libvips warnings | ||
| Napi::Function debuglog = options.Get("debuglog").As<Napi::Function>(); | ||
| // Join queue for worker thread | ||
| Napi::Function callback = info[size_t(1)].As<Napi::Function>(); | ||
| MetadataWorker *worker = new MetadataWorker(callback, baton, debuglog); | ||
| worker->Receiver().Set("options", options); | ||
| worker->Queue(); | ||
| // Increment queued task counter | ||
| sharp::counterQueue++; | ||
| return info.Env().Undefined(); | ||
| } | ||
| const char *PNG_COMMENT_START = "png-comment-"; | ||
| const int PNG_COMMENT_START_LEN = strlen(PNG_COMMENT_START); | ||
| static void* readPNGComment(VipsImage *image, const char *field, GValue *value, void *p) { | ||
| MetadataComments *comments = static_cast<MetadataComments *>(p); | ||
| if (vips_isprefix(PNG_COMMENT_START, field)) { | ||
| const char *keyword = strchr(field + PNG_COMMENT_START_LEN, '-'); | ||
| const char *str; | ||
| if (keyword != NULL && !vips_image_get_string(image, field, &str)) { | ||
| keyword++; // Skip the hyphen | ||
| comments->push_back(std::make_pair(keyword, str)); | ||
| } | ||
| } | ||
| return NULL; | ||
| } |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| #ifndef SRC_METADATA_H_ | ||
| #define SRC_METADATA_H_ | ||
| #include <string> | ||
| #include <vector> | ||
| #include <napi.h> | ||
| #include "./common.h" | ||
| typedef std::vector<std::pair<std::string, std::string>> MetadataComments; | ||
| 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; | ||
| bool isPalette; | ||
| int bitsPerSample; | ||
| int pages; | ||
| int pageHeight; | ||
| int loop; | ||
| std::vector<int> delay; | ||
| int pagePrimary; | ||
| std::string compression; | ||
| std::string resolutionUnit; | ||
| std::string formatMagick; | ||
| std::vector<std::pair<int, int>> levels; | ||
| int subifds; | ||
| std::vector<double> 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; | ||
| MetadataComments comments; | ||
| std::string err; | ||
| MetadataBaton(): | ||
| input(nullptr), | ||
| width(0), | ||
| height(0), | ||
| channels(0), | ||
| density(0), | ||
| isProgressive(false), | ||
| isPalette(false), | ||
| bitsPerSample(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_ |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| #include <algorithm> | ||
| #include <functional> | ||
| #include <memory> | ||
| #include <tuple> | ||
| #include <vector> | ||
| #include <vips/vips8> | ||
| #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<double> const tint) { | ||
| std::vector<double> 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 (image.has_alpha()) { | ||
| 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 (image.has_alpha()) { | ||
| // 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 (image.has_alpha()) { | ||
| // 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<double> flattenBackground) { | ||
| double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0; | ||
| std::vector<double> 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 (image.has_alpha() && !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, VipsPrecision precision, double const minAmpl) { | ||
| 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).gaussblur(sigma, VImage::option() | ||
| ->set("precision", precision) | ||
| ->set("min_ampl", minAmpl)); | ||
| } | ||
| } | ||
| /* | ||
| * Convolution with a kernel. | ||
| */ | ||
| VImage Convolve(VImage image, int const width, int const height, | ||
| double const scale, double const offset, | ||
| std::vector<double> const &kernel_v | ||
| ) { | ||
| VImage kernel = VImage::new_from_memory( | ||
| static_cast<void*>(const_cast<double*>(kernel_v.data())), | ||
| 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::vector<double> const& matrix) { | ||
| double* m = const_cast<double*>(matrix.data()); | ||
| image = image.colourspace(VIPS_INTERPRETATION_sRGB); | ||
| if (matrix.size() == 9) { | ||
| return image | ||
| .recomb(image.bands() == 3 | ||
| ? VImage::new_matrix(3, 3, m, 9) | ||
| : 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)); | ||
| } else { | ||
| return image.recomb(VImage::new_matrix(4, 4, m, 16)); | ||
| } | ||
| } | ||
| VImage Modulate(VImage image, double const brightness, double const saturation, | ||
| int const hue, double const lightness) { | ||
| VipsInterpretation colourspaceBeforeModulate = image.interpretation(); | ||
| if (image.has_alpha()) { | ||
| // 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<double>(hue) } | ||
| ) | ||
| .colourspace(colourspaceBeforeModulate) | ||
| .bandjoin(alpha); | ||
| } else { | ||
| return image | ||
| .colourspace(VIPS_INTERPRETATION_LCH) | ||
| .linear( | ||
| { brightness, saturation, 1 }, | ||
| { lightness, 0.0, static_cast<double>(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<double> 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<double> backgroundAlpha({ background.back() }); | ||
| if (image.has_alpha()) { | ||
| 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 (image.has_alpha()) { | ||
| // 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<double> const a, std::vector<double> const b) { | ||
| size_t const bands = static_cast<size_t>(image.bands()); | ||
| if (a.size() > bands) { | ||
| throw VError("Band expansion using linear is unsupported"); | ||
| } | ||
| bool const uchar = !Is16Bit(image.interpretation()); | ||
| if (image.has_alpha() && 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 (image.has_alpha()) { | ||
| 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<VImage> pages; | ||
| pages.reserve(nPages); | ||
| // Split the image into cropped frames | ||
| image = StaySequential(image); | ||
| 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<double> 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<VImage> 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<VImage> 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; | ||
| } | ||
| } | ||
| /* | ||
| * Dilate an image | ||
| */ | ||
| VImage Dilate(VImage image, int const width) { | ||
| int const maskWidth = 2 * width + 1; | ||
| VImage mask = VImage::new_matrix(maskWidth, maskWidth); | ||
| return image.morph( | ||
| mask, | ||
| VIPS_OPERATION_MORPHOLOGY_DILATE).invert(); | ||
| } | ||
| /* | ||
| * Erode an image | ||
| */ | ||
| VImage Erode(VImage image, int const width) { | ||
| int const maskWidth = 2 * width + 1; | ||
| VImage mask = VImage::new_matrix(maskWidth, maskWidth); | ||
| return image.morph( | ||
| mask, | ||
| VIPS_OPERATION_MORPHOLOGY_ERODE).invert(); | ||
| } | ||
| } // namespace sharp |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| #ifndef SRC_OPERATIONS_H_ | ||
| #define SRC_OPERATIONS_H_ | ||
| #include <algorithm> | ||
| #include <functional> | ||
| #include <memory> | ||
| #include <tuple> | ||
| #include <vector> | ||
| #include <vips/vips8> | ||
| using vips::VImage; | ||
| namespace sharp { | ||
| /* | ||
| * Tint an image using the provided RGB. | ||
| */ | ||
| VImage Tint(VImage image, std::vector<double> 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<double> 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, VipsPrecision precision, double const minAmpl); | ||
| /* | ||
| * Convolution with a kernel. | ||
| */ | ||
| VImage Convolve(VImage image, int const width, int const height, | ||
| double const scale, double const offset, std::vector<double> 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<double> background, double threshold, bool const lineArt); | ||
| /* | ||
| * Linear adjustment (a * in + b) | ||
| */ | ||
| VImage Linear(VImage image, std::vector<double> const a, std::vector<double> 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::vector<double> 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<double> background, int nPages, int *pageHeight); | ||
| /* | ||
| * Dilate an image | ||
| */ | ||
| VImage Dilate(VImage image, int const maskWidth); | ||
| /* | ||
| * Erode an image | ||
| */ | ||
| VImage Erode(VImage image, int const maskWidth); | ||
| } // namespace sharp | ||
| #endif // SRC_OPERATIONS_H_ |
Sorry, the diff of this file is too big to display
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| #ifndef SRC_PIPELINE_H_ | ||
| #define SRC_PIPELINE_H_ | ||
| #include <memory> | ||
| #include <string> | ||
| #include <unordered_map> | ||
| #include <vector> | ||
| #include <napi.h> | ||
| #include <vips/vips8> | ||
| #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::vector<sharp::InputDescriptor *> join; | ||
| std::string formatOut; | ||
| std::string fileOut; | ||
| void *bufferOut; | ||
| size_t bufferOutLength; | ||
| int pageHeightOut; | ||
| int pagesOut; | ||
| std::vector<Composite *> composite; | ||
| std::vector<sharp::InputDescriptor *> 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<double> resizeBackground; | ||
| bool hasCropOffset; | ||
| int cropOffsetLeft; | ||
| int cropOffsetTop; | ||
| bool hasAttentionCenter; | ||
| int attentionX; | ||
| int attentionY; | ||
| bool premultiplied; | ||
| bool tileCentre; | ||
| bool fastShrinkOnLoad; | ||
| std::vector<double> tint; | ||
| bool flatten; | ||
| std::vector<double> flattenBackground; | ||
| bool unflatten; | ||
| bool negate; | ||
| bool negateAlpha; | ||
| double blurSigma; | ||
| VipsPrecision precision; | ||
| double minAmpl; | ||
| 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<double> trimBackground; | ||
| double trimThreshold; | ||
| bool trimLineArt; | ||
| int trimOffsetLeft; | ||
| int trimOffsetTop; | ||
| std::vector<double> linearA; | ||
| std::vector<double> linearB; | ||
| int dilateWidth; | ||
| int erodeWidth; | ||
| double gamma; | ||
| double gammaOut; | ||
| bool greyscale; | ||
| bool normalise; | ||
| int normaliseLower; | ||
| int normaliseUpper; | ||
| int claheWidth; | ||
| int claheHeight; | ||
| int claheMaxSlope; | ||
| int angle; | ||
| double rotationAngle; | ||
| std::vector<double> rotationBackground; | ||
| bool rotateBefore; | ||
| bool orientBefore; | ||
| bool flip; | ||
| bool flop; | ||
| int extendTop; | ||
| int extendBottom; | ||
| int extendLeft; | ||
| int extendRight; | ||
| std::vector<double> extendBackground; | ||
| VipsExtend extendWith; | ||
| bool withoutEnlargement; | ||
| bool withoutReduction; | ||
| std::vector<double> affineMatrix; | ||
| std::vector<double> 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; | ||
| bool webpSmartDeblock; | ||
| VipsForeignWebpPreset webpPreset; | ||
| int webpEffort; | ||
| bool webpMinSize; | ||
| bool webpMixed; | ||
| int gifBitdepth; | ||
| int gifEffort; | ||
| double gifDither; | ||
| double gifInterFrameMaxError; | ||
| double gifInterPaletteMaxError; | ||
| bool gifKeepDuplicateFrames; | ||
| bool gifReuse; | ||
| bool gifProgressive; | ||
| int tiffQuality; | ||
| VipsForeignTiffCompression tiffCompression; | ||
| bool tiffBigtiff; | ||
| 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; | ||
| bool errUseWarning; | ||
| int keepMetadata; | ||
| int withMetadataOrientation; | ||
| double withMetadataDensity; | ||
| std::string withIccProfile; | ||
| std::unordered_map<std::string, std::string> withExif; | ||
| bool withExifMerge; | ||
| std::string withXmp; | ||
| int timeoutSeconds; | ||
| std::vector<double> 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<int> delay; | ||
| int loop; | ||
| int tileSize; | ||
| int tileOverlap; | ||
| VipsForeignDzContainer tileContainer; | ||
| VipsForeignDzLayout tileLayout; | ||
| std::string tileFormat; | ||
| int tileAngle; | ||
| std::vector<double> tileBackground; | ||
| int tileSkipBlanks; | ||
| VipsForeignDzDepth tileDepth; | ||
| std::string tileId; | ||
| std::string tileBasename; | ||
| std::vector<double> recombMatrix; | ||
| PipelineBaton(): | ||
| input(nullptr), | ||
| bufferOutLength(0), | ||
| pageHeightOut(0), | ||
| pagesOut(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{}, | ||
| dilateWidth(0), | ||
| erodeWidth(0), | ||
| gamma(0.0), | ||
| greyscale(false), | ||
| normalise(false), | ||
| normaliseLower(1), | ||
| normaliseUpper(99), | ||
| claheWidth(0), | ||
| claheHeight(0), | ||
| claheMaxSlope(3), | ||
| 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), | ||
| webpSmartDeblock(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), | ||
| gifKeepDuplicateFrames(false), | ||
| gifReuse(true), | ||
| gifProgressive(false), | ||
| tiffQuality(80), | ||
| tiffCompression(VIPS_FOREIGN_TIFF_COMPRESSION_JPEG), | ||
| tiffBigtiff(false), | ||
| 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), | ||
| errUseWarning(false), | ||
| 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_ |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| #include <mutex> | ||
| #include <napi.h> | ||
| #include <vips/vips8> | ||
| #include "./common.h" | ||
| #include "./metadata.h" | ||
| #include "./pipeline.h" | ||
| #include "./stats.h" | ||
| #include "./utilities.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<GLogLevelFlags>(G_LOG_LEVEL_WARNING), | ||
| static_cast<GLogFunc>(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("_isUsingX64V2", Napi::Function::New(env, _isUsingX64V2)); | ||
| exports.Set("stats", Napi::Function::New(env, stats)); | ||
| return exports; | ||
| } | ||
| NODE_API_MODULE(sharp, init) |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| #include <iostream> | ||
| #include <numeric> | ||
| #include <string> | ||
| #include <vector> | ||
| #include <napi.h> | ||
| #include <vips/vips8> | ||
| #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<int>(stats.getpoint(STAT_MIN_INDEX, b).front()), | ||
| static_cast<int>(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<int>(stats.getpoint(STAT_MINX_INDEX, b).front()), | ||
| static_cast<int>(stats.getpoint(STAT_MINY_INDEX, b).front()), | ||
| static_cast<int>(stats.getpoint(STAT_MAXX_INDEX, b).front()), | ||
| static_cast<int>(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 (image.has_alpha()) { | ||
| double const minAlpha = static_cast<double>(stats.getpoint(STAT_MIN_INDEX, bands).front()); | ||
| if (minAlpha != vips_interpretation_max_alpha(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<double> maxpos = hist.maxpos(); | ||
| int const dx = static_cast<int>(std::real(maxpos)); | ||
| int const dy = static_cast<int>(std::imag(maxpos)); | ||
| std::vector<double> 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<ChannelStats>::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<Napi::Object>(); | ||
| // Input | ||
| baton->input = sharp::CreateInputDescriptor(options.Get("input").As<Napi::Object>()); | ||
| baton->input->access = VIPS_ACCESS_RANDOM; | ||
| // Function to notify of libvips warnings | ||
| Napi::Function debuglog = options.Get("debuglog").As<Napi::Function>(); | ||
| // Join queue for worker thread | ||
| Napi::Function callback = info[size_t(1)].As<Napi::Function>(); | ||
| StatsWorker *worker = new StatsWorker(callback, baton, debuglog); | ||
| worker->Receiver().Set("options", options); | ||
| worker->Queue(); | ||
| // Increment queued task counter | ||
| sharp::counterQueue++; | ||
| return info.Env().Undefined(); | ||
| } |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| #ifndef SRC_STATS_H_ | ||
| #define SRC_STATS_H_ | ||
| #include <string> | ||
| #include <vector> | ||
| #include <napi.h> | ||
| #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), // NOLINT(build/include_what_you_use) | ||
| mean(meanVal), stdev(stdevVal), minX(minXVal), minY(minYVal), maxX(maxXVal), maxY(maxYVal) {} | ||
| }; | ||
| struct StatsBaton { | ||
| // Input | ||
| sharp::InputDescriptor *input; | ||
| // Output | ||
| std::vector<ChannelStats> 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_ |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| #include <cmath> | ||
| #include <cstdio> | ||
| #include <string> | ||
| #include <napi.h> | ||
| #include <vips/vips8> | ||
| #include <vips/vector.h> | ||
| #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<Napi::Number>().Int32Value() * 1048576); | ||
| } | ||
| // Set file limit | ||
| if (info[size_t(1)].IsNumber()) { | ||
| vips_cache_set_max_files(info[size_t(1)].As<Napi::Number>().Int32Value()); | ||
| } | ||
| // Set items limit | ||
| if (info[size_t(2)].IsNumber()) { | ||
| vips_cache_set_max(info[size_t(2)].As<Napi::Number>().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<Napi::Number>().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<int>(sharp::counterQueue)); | ||
| counters.Set("process", static_cast<int>(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<Napi::Boolean>().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", "rad", "dcraw" | ||
| }) { | ||
| // 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<Napi::Array>(); | ||
| bool const state = info[size_t(1)].As<Napi::Boolean>().Value(); | ||
| for (unsigned int i = 0; i < ops.Length(); i++) { | ||
| vips_operation_block_set(ops.Get(i).As<Napi::String>().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<Napi::String>().Utf8Value().data()); | ||
| if (imageType1 != sharp::ImageType::UNKNOWN) { | ||
| try { | ||
| image1 = VImage::new_from_file(info[size_t(0)].As<Napi::String>().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<Napi::String>().Utf8Value().data()); | ||
| if (imageType2 != sharp::ImageType::UNKNOWN) { | ||
| try { | ||
| image2 = VImage::new_from_file(info[size_t(1)].As<Napi::String>().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 (image1.has_alpha()) { | ||
| image1 = image1.premultiply().extract_band(1, VImage::option()->set("n", image1.bands() - 1)); | ||
| } | ||
| if (image2.has_alpha()) { | ||
| 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 | ||
| #if defined(__GNUC__) && defined(__x86_64__) | ||
| // Are SSE 4.2 intrinsics available at runtime? | ||
| Napi::Value _isUsingX64V2(const Napi::CallbackInfo& info) { | ||
| Napi::Env env = info.Env(); | ||
| unsigned int eax, ebx, ecx, edx; | ||
| __asm__ __volatile__("cpuid" | ||
| : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) | ||
| : "a"(1)); | ||
| return Napi::Boolean::New(env, (ecx & 1U << 20) != 0); | ||
| } | ||
| #else | ||
| Napi::Value _isUsingX64V2(const Napi::CallbackInfo& info) { | ||
| Napi::Env env = info.Env(); | ||
| return Napi::Boolean::New(env, false); | ||
| } | ||
| #endif |
| /*! | ||
| Copyright 2013 Lovell Fuller and others. | ||
| SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
| #ifndef SRC_UTILITIES_H_ | ||
| #define SRC_UTILITIES_H_ | ||
| #include <napi.h> | ||
| 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); | ||
| Napi::Value _isUsingX64V2(const Napi::CallbackInfo& info); | ||
| #endif // SRC_UTILITIES_H_ |
| { | ||
| "name": "@archships/dim-image-codec-runtime", | ||
| "private": true, | ||
| "version": "1.0.0" | ||
| } |
| { | ||
| "version": 1, | ||
| "runtimeId": "image-codec", | ||
| "platform": "win32", | ||
| "arch": "x64", | ||
| "sharpVersion": "0.34.5", | ||
| "libvipsVersion": null, | ||
| "facade": "facade/package.json", | ||
| "components": { | ||
| "sharp": "0.34.5", | ||
| "detect-libc": "2.1.2", | ||
| "semver": "7.8.5", | ||
| "@img/colour": "1.1.0", | ||
| "@img/sharp-win32-x64": "0.34.5" | ||
| }, | ||
| "inventory": [ | ||
| { | ||
| "path": "facade/node_modules/sharp/install/build.js", | ||
| "size": 882, | ||
| "sha256": "37f7c9591d75dbc5fe734c5a196a46c355b3d7de5134260ba011efed8433a718" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/install/check.js", | ||
| "size": 383, | ||
| "sha256": "31fd360ede9ff3e80d643faff6c4570d0b2b5c621dc421b6c4086dfe86ce981f" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/channel.js", | ||
| "size": 5379, | ||
| "sha256": "4a699621c111427f9f6b3b767764a292f6a358616de2866e0078475830420f42" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/colour.js", | ||
| "size": 5336, | ||
| "sha256": "e29352a6bf26a45f4c360ad5d2ddbb2fb2ec65521f980ebcf875f48366ea89f8" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/composite.js", | ||
| "size": 8960, | ||
| "sha256": "73f04ab765a11bfc72771dbd0a6324e8e34ea354d16108cc1277bba4e80dd523" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/constructor.js", | ||
| "size": 19959, | ||
| "sha256": "b38f3e7ceecc305a8f81f278bf9219cba966993b8c2d7cebafdb8e8d5005760c" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/index.d.ts", | ||
| "size": 91039, | ||
| "sha256": "1d879125d1ec570bf04bc1f362fdbe0cb538315c7ac4bcfcdf0c1e9670846aa6" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/index.js", | ||
| "size": 385, | ||
| "sha256": "5e30578a16290fa0855c32fe3d544ce4f26c147de6bad69cffaf7bc416a2919a" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/input.js", | ||
| "size": 32973, | ||
| "sha256": "d88bdf5d807ef57ce8aa5d9be29bc7b9199974eac385bf559f19d5fc06bd632a" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/is.js", | ||
| "size": 2930, | ||
| "sha256": "7ecb71679b5b58e7ddf7e14fa697ff6a31bbe9ef107745170095031519e93463" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/libvips.js", | ||
| "size": 6128, | ||
| "sha256": "8bcb0344788d815016bf2f7ca2abec67a00c399d7e815b21631b93793b04657d" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/operation.js", | ||
| "size": 33282, | ||
| "sha256": "01019d62cfb83c5f6192a65a4a97635214e5dc61da07c51be59b8216ba907a7a" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/output.js", | ||
| "size": 61198, | ||
| "sha256": "71cec9ac95f3db764ee4d2e26eec1deb16da63c47fdd352f6a41af4dbb0f1831" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/resize.js", | ||
| "size": 21080, | ||
| "sha256": "d85081a35bb1195ff6f057d2db4343adfe3241abccc7e277d13673a116fea1ad" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/sharp.js", | ||
| "size": 4164, | ||
| "sha256": "e591c7b5ebd307906bb05cf530fe4287b5a93d91cef4a1bf4f3debad55bc24d7" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/lib/utility.js", | ||
| "size": 9535, | ||
| "sha256": "4d3b668e872214489dfcdfb0d400af72bdbd3dd3e4e7118ea906cd69bd22d251" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/LICENSE", | ||
| "size": 10273, | ||
| "sha256": "73ba74dfaa520b49a401b5d21459a8523a146f3b7518a833eea5efa85130bf68" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/.bin/semver", | ||
| "size": 1842, | ||
| "sha256": "b35180e0d9290fc2b3a8a50abf59bf7e19086b5a5df6dc1473ed9c0598520ba4" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/@img/colour/color.cjs", | ||
| "size": 45136, | ||
| "sha256": "f7c3efcf482624007f2019fffee3e1dec56b8cb893faa9a420b2832805888dce" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/@img/colour/index.cjs", | ||
| "size": 49, | ||
| "sha256": "e6e93e7fb209420a20fdf2ec676e9c67413be8d5ace99eec64f9468480f0368d" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/@img/colour/index.d.ts", | ||
| "size": 21569, | ||
| "sha256": "2467b00d963828f540f4acd7910f4c04cfe4b489550e6bb682212f65583bca5b" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/@img/colour/LICENSE.md", | ||
| "size": 4433, | ||
| "sha256": "e2eaa4603c14cb26f301e88648c12a853fa3f0f5da6d4b0972958c666e7f2ab8" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/@img/colour/package.json", | ||
| "size": 1515, | ||
| "sha256": "bc38c5097693ed53b91c32f35fb0a52569736c7854ba2eb6d080f3252071f75c" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/@img/colour/README.md", | ||
| "size": 562, | ||
| "sha256": "be7edf3bc6467f761168cef3bb2b9b3def2532c98a86249848376ea00338ad1d" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/@img/sharp-win32-x64/lib/libvips-42.dll", | ||
| "size": 19112960, | ||
| "sha256": "f8d356def73941668252347b825055310e99023ff77c7d3036e592d0771e1529" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/@img/sharp-win32-x64/lib/libvips-cpp-8.17.3.dll", | ||
| "size": 327168, | ||
| "sha256": "f1b3c3eeea1b6a8292a69d78dd2cd1debacb9951cabdd9217a57e34137570cd1" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/@img/sharp-win32-x64/lib/sharp-win32-x64.node", | ||
| "size": 433152, | ||
| "sha256": "afc813593f255968ddae8f1d66557e0f96484bb374606e4eb2267a7dbc7cb25a" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/@img/sharp-win32-x64/LICENSE", | ||
| "size": 10464, | ||
| "sha256": "dc1f5d2d43c5531dfe0acaf4e950ea5dbe3e61e1850cf0e983bda7efc10d6693" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/@img/sharp-win32-x64/package.json", | ||
| "size": 908, | ||
| "sha256": "3421485756b0a25573ee62e147a62908608e3014a2bfed64381473a22e9351d2" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/@img/sharp-win32-x64/README.md", | ||
| "size": 4899, | ||
| "sha256": "c416cd0af88256407c36a0613f189ac4257221c7206d0324f7ef5563c66f1125" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/@img/sharp-win32-x64/versions.json", | ||
| "size": 594, | ||
| "sha256": "e823074bfa33ed7b1861b797dd3c60d7ef8c34cd2faa9a7d22ec32dd6d6ad8ad" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/detect-libc/index.d.ts", | ||
| "size": 436, | ||
| "sha256": "9500090533aafe039c41d8d368a44959f04482bb75636d96bc843c06f3d6a348" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/detect-libc/lib/detect-libc.js", | ||
| "size": 7503, | ||
| "sha256": "5de6a1c1abec8bba5ea1261cf819d83a73c92ebe72b879ae48c59ca12320a462" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/detect-libc/lib/elf.js", | ||
| "size": 982, | ||
| "sha256": "0e8820f00ee11d179d94894d4f97a6e87c34ab59e5dd4d3a571dfabcecf043af" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/detect-libc/lib/filesystem.js", | ||
| "size": 1097, | ||
| "sha256": "5c98fb66b559d0b4fa82c7a3e39d9ab6840f022c4c73e6b1a73ac6d16ec13fd7" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/detect-libc/lib/process.js", | ||
| "size": 569, | ||
| "sha256": "f37dd0ead9f70b50c6f5529c600e1cdf076e3c3bc8e6b4a0a9820a8d65244628" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/detect-libc/LICENSE", | ||
| "size": 11357, | ||
| "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/detect-libc/package.json", | ||
| "size": 1278, | ||
| "sha256": "ee88e5b954fdf3a8480b1d01ef767d68d8ca2c6da269f58c5cf1c5550e9aa2a7" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/detect-libc/README.md", | ||
| "size": 3215, | ||
| "sha256": "51a97449c443889155bc872522e6de5a91a5fa73edeffa03d749e186bf0eebca" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/bin/semver.js", | ||
| "size": 4957, | ||
| "sha256": "bd6c871026985937dc945011fc54b74b47f5998154216d7b8d40d5ed782e4402" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/classes/comparator.js", | ||
| "size": 3631, | ||
| "sha256": "054202956430d63d5ff4599fae09760ce465b489e4f0b5ef5ce7cc7ac21157ac" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/classes/index.js", | ||
| "size": 143, | ||
| "sha256": "3bb69280c2a788d0eb16f915bb9df4dbe812075182024c753dca2283bcea1b17" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/classes/range.js", | ||
| "size": 15647, | ||
| "sha256": "a6544485aa8575aa9854c67e2caa67726815de18a482d0ceb8a1003244de3bc1" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/classes/semver.js", | ||
| "size": 9891, | ||
| "sha256": "813b2c185512d30c9b931c2fed8140889d9d7490ceeeedc370da30337dc8ca57" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/clean.js", | ||
| "size": 205, | ||
| "sha256": "4eadb0892844cf3ae295121a86163a66c73f89acd1b7f0b114ec115b4539512f" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/cmp.js", | ||
| "size": 961, | ||
| "sha256": "a63d74e87b73788e78e9ce0a4892b5333d6b809c0de88b31e4ed76cbf17f94b3" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/coerce.js", | ||
| "size": 2004, | ||
| "sha256": "28a251c5ab210ddf9e97551b9f37a53329fcce91f0c3943dcbc02de1a1de915a" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/compare-build.js", | ||
| "size": 281, | ||
| "sha256": "5ab651d5b40af289bd85c645a92b6d8cfe1a986dc413c797cfcc8d623d7c844c" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/compare-loose.js", | ||
| "size": 132, | ||
| "sha256": "07b6a3a1db0a5210ceb784c1708bd4679f3a94fc73a9c9eb349349e7070a6f78" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/compare.js", | ||
| "size": 170, | ||
| "sha256": "d404b5aa48aaddc8a654c5da8fb7d4443404b7948589b21ac4b045d1cee4e34c" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/diff.js", | ||
| "size": 1423, | ||
| "sha256": "7a11fd39b987cdf06c65e928cb1aca49bec583feb86fb5c8fe47a6fd61d7de31" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/eq.js", | ||
| "size": 126, | ||
| "sha256": "b6e30a7168e52723216fc163d300e2bbabf92ec0251f9ac5438bb6ccf57c8936" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/gt.js", | ||
| "size": 124, | ||
| "sha256": "135523704aa48cd98834dd170ee9f74f0e68043b379f32d021db11e6304c5c93" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/gte.js", | ||
| "size": 127, | ||
| "sha256": "991c5bbe48ecb210a562646872f05862ad9fc0d42186d85aa60bdc6fa323eb9d" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/inc.js", | ||
| "size": 478, | ||
| "sha256": "952069fc8690b7d3af0fe9d55f7c54fe2ac067b48c5e74f6a54f9ce19a334493" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/lt.js", | ||
| "size": 124, | ||
| "sha256": "1c897a9bc849320e2e9dc0f6c09555c01ee3ddf30734515d717b88ad7740ea25" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/lte.js", | ||
| "size": 127, | ||
| "sha256": "3a8d0b1d00423f60cc7cb810b36ab77b61330831ad237dbe73eb5cecfa412800" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/major.js", | ||
| "size": 136, | ||
| "sha256": "5c678480d882f511200fed2c16ec3847dfedb08a1d70328dc2f031d35d825276" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/minor.js", | ||
| "size": 136, | ||
| "sha256": "1b051794f1713adec2a236517196691687c35f82e0b596ff3316a78b3cc10ae6" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/neq.js", | ||
| "size": 128, | ||
| "sha256": "a662883751918822c162183b46b9e20d09489132f82686c92ab78bee67f3a127" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/parse.js", | ||
| "size": 331, | ||
| "sha256": "29a69e15b6d02fe381d573f861881a89590e9d0f0f0ca740c5f85eaf0234c4ad" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/patch.js", | ||
| "size": 136, | ||
| "sha256": "f02d3c1b059fe3d96ce124886f7eef321d381a95638fd3c4a8d5ccd8e76ffadd" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/prerelease.js", | ||
| "size": 234, | ||
| "sha256": "baedbf503d5610ad041bfb56071efa48feb331ca278295c399537d35d3ffb593" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/rcompare.js", | ||
| "size": 132, | ||
| "sha256": "84fa5e88adf08d15c993cac8cdec6d1a65045b7e95a9c55184230a7f807f4dc0" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/rsort.js", | ||
| "size": 163, | ||
| "sha256": "6ec659ce3b6c2b173c719286caab04409adba046c0917874ec3b5e36ddfbc7e3" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/satisfies.js", | ||
| "size": 247, | ||
| "sha256": "8cf5e122b757251671ed6c9d9680904b71cd375845853f05312e608cf2cc2946" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/sort.js", | ||
| "size": 161, | ||
| "sha256": "c2fe2d3ed0be8a4e9de8f02abdfd5d9c0d3bcc510d88e87af84185592882c4b8" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/truncate.js", | ||
| "size": 1021, | ||
| "sha256": "e145833a250311927c92f424f56498c52f1b7bb1271ce6afbf006db87773ff43" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/functions/valid.js", | ||
| "size": 176, | ||
| "sha256": "0de7ea736cb7807179d46dfac09c830a9338e02b6a07db12d7040cde2def6025" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/index.js", | ||
| "size": 2691, | ||
| "sha256": "4b3e57d3d40e29e0706002eba113d09f35aea593578376bbeec83b777b9912ab" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/internal/constants.js", | ||
| "size": 873, | ||
| "sha256": "38a112baf27ceca0260082ff26ac2fd7a9861cab1af12dd65e720277f68e6ce9" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/internal/debug.js", | ||
| "size": 240, | ||
| "sha256": "8a9f420572260f3cf944463b5090d62a60f0730589dc23a7ec4ca25e2ee41bb3" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/internal/identifiers.js", | ||
| "size": 525, | ||
| "sha256": "b4916b09dc7869ae0eb05e71c855c942a3a7365f7e6e89185d59a9e45a2451d7" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/internal/lrucache.js", | ||
| "size": 802, | ||
| "sha256": "14d087c87da87b6f5c36fc4cdd7d2d14077874b14a68e20fce5b6138fa2ca34f" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/internal/parse-options.js", | ||
| "size": 338, | ||
| "sha256": "fdf51d0de8d5442c35a997ef58cd530d239ce206f961d14c5121354451b01d01" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/internal/re.js", | ||
| "size": 8139, | ||
| "sha256": "5833262888e2b5d843a69193f83c05e374818dbe55379b497819b5bf58e48cd8" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/LICENSE", | ||
| "size": 765, | ||
| "sha256": "4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/package.json", | ||
| "size": 1661, | ||
| "sha256": "7c94cb7f2a53c27b20d76386ec144c062894dbcc909cfabd0f728c37874b1776" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/preload.js", | ||
| "size": 83, | ||
| "sha256": "edb6808911bebcb324b2df57e5c9935149e56984ff083b74c6cfe215f5b710ba" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/range.bnf", | ||
| "size": 702, | ||
| "sha256": "15d0baf9b7b98e6d862c0cb9e822d2533d2bc23e136bb75314d802ca1fcb0392" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/ranges/gtr.js", | ||
| "size": 231, | ||
| "sha256": "8fadad28e36d28e93d498ac7ac20badba2a407312845eabc18e82e90a0732b19" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/ranges/intersects.js", | ||
| "size": 224, | ||
| "sha256": "fe87ac5d3020010ad3ec00636dadbf0c669ff07d0f57e0a8165a8264f79a676f" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/ranges/ltr.js", | ||
| "size": 227, | ||
| "sha256": "e5186fcc03018acf9be6d968755d4c49727aeb0d981d179eb568ae5fbe983038" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/ranges/max-satisfying.js", | ||
| "size": 593, | ||
| "sha256": "e1a2c0d6144cc772cd20bbc8ecb9e8a3a4074e9172a3d8e794838b591cdeb416" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/ranges/min-satisfying.js", | ||
| "size": 591, | ||
| "sha256": "2681abf54098aa670f12826b76a6ec77a2441186ae4243afde3be8ae4908f7ca" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/ranges/min-version.js", | ||
| "size": 1514, | ||
| "sha256": "fefba0a88c2bf74d5cede504b5ae50a8dc3edfd69cf0174a491e2cf3e442614b" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/ranges/outside.js", | ||
| "size": 2204, | ||
| "sha256": "3a2b0b23593d2f49419c06af2af75450cab103b0c25d665d48fe5bca495a21ca" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/ranges/simplify.js", | ||
| "size": 1355, | ||
| "sha256": "7b78581c13322bc68ece2088685386b2a9b51c15b94d0a2063bdf2546bd41934" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/ranges/subset.js", | ||
| "size": 7478, | ||
| "sha256": "ceb9eb6ed5bfc6c7ac7af7f47e5c3535444a4e66a0e2b58cdad4bd02a35d454d" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/ranges/to-comparators.js", | ||
| "size": 282, | ||
| "sha256": "6c5e966210cff270fa2850668aaf8460fac7759f8d99f282521ef7a78f4564e9" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/ranges/valid.js", | ||
| "size": 326, | ||
| "sha256": "5ef6f995af801868925940cf8df5735d565ebabb090b068695cae65218bcd3ac" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/node_modules/semver/README.md", | ||
| "size": 25669, | ||
| "sha256": "f1a789dcec285150be24db2ea04dd3175031554fa9834ec92fab83fb5e025a57" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/package.json", | ||
| "size": 7478, | ||
| "sha256": "e6be69319929151be3aa240bf1485f25a3477cb6d2286f92510b9fceb3cbef26" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/README.md", | ||
| "size": 3160, | ||
| "sha256": "f8e331e11a401b062776d10f4e0c0f78447edc0490b4c0f548cb210b839e5b1d" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/binding.gyp", | ||
| "size": 10597, | ||
| "sha256": "dc753e7ef9a8b393e14ed6a6fa17baae89e6edb4f39740b1cc1e9d06cbd20478" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/common.cc", | ||
| "size": 39181, | ||
| "sha256": "9102e55ed0c5d3027fad3df16e751b5424265d32201568395958862ab3a3f6e1" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/common.h", | ||
| "size": 10639, | ||
| "sha256": "44940aefc7ec601e316dad5c3882041c56d6070f84cc2b2871f6236b75df5cb4" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/metadata.cc", | ||
| "size": 13221, | ||
| "sha256": "04366c98d90cf3415a50cb5f47a07c3a7f25ace2a67d603e72035807f99af33f" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/metadata.h", | ||
| "size": 1768, | ||
| "sha256": "bd50ae9c3e55d9ed5f8b3c4e09d9a79f496ef665b6c993ff1b2c7edecc32d03a" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/operations.cc", | ||
| "size": 16584, | ||
| "sha256": "db97d0ca7ec042279cf5b4331fdc19466c20318ca4bc52fda4e3fdc13781a8c2" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/operations.h", | ||
| "size": 3607, | ||
| "sha256": "80a4f350793f657c10769e2b4e82d3b103f5d4984dc27d10e592e14b8cc1b34b" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/pipeline.cc", | ||
| "size": 84430, | ||
| "sha256": "8fa9d1f70f46ea0f27f30203dfa1ebe8df8a5679b9d93a8f8dadf72dd1fa6e59" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/pipeline.h", | ||
| "size": 9828, | ||
| "sha256": "89f81e2d0308ed696a0f39099d42b7867b8ffb5fcd4969c7dbfb3e6778c0de23" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/sharp.cc", | ||
| "size": 1529, | ||
| "sha256": "9f407b50bb2d02e5eb711b769f05d3e6659028430e055c4271e5ab1593f5a257" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/stats.cc", | ||
| "size": 6683, | ||
| "sha256": "084df95f2cc863e522c35e5da31976e1dc4d370d40ab6d2a0b398763208af4ea" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/stats.h", | ||
| "size": 1267, | ||
| "sha256": "db854f0c3c4a0db1751021ed676413c6d5ca00becc08bdc13258b29047450b8c" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/utilities.cc", | ||
| "size": 9454, | ||
| "sha256": "7141d5bb1e7b1bca0fdd7d14c30b27b2a4b3f177441b04106e460e013cd061ed" | ||
| }, | ||
| { | ||
| "path": "facade/node_modules/sharp/src/utilities.h", | ||
| "size": 741, | ||
| "sha256": "0b126ab63cf1aedf8e71e6cb8179899d3ef02c46419100e847b2ca4284b8901b" | ||
| }, | ||
| { | ||
| "path": "facade/package.json", | ||
| "size": 92, | ||
| "sha256": "00842a690f23aa16d0cea634c3c1af8e12899926bf8fc2e0919f55eaad4c8c92" | ||
| } | ||
| ] | ||
| } |
| 'use strict'; | ||
| const fs = require('node:fs'); | ||
| const path = require('node:path'); | ||
| const { loadNative } = require('./load-native.cjs'); | ||
| const DEFAULT_MODEL = 'ppocrv6-small'; | ||
| const MODEL_PACKAGE = '@arcships/light-ocr-model-ppocrv6-small'; | ||
| const EXPECTED_BUNDLE_ID = 'ppocrv6-small-onnx-20260714.1'; | ||
| class OcrError extends Error { | ||
| constructor(code, message, detail) { | ||
| super(message); | ||
| this.name = 'OcrError'; | ||
| this.code = code; | ||
| if (detail !== undefined && detail !== '') this.detail = detail; | ||
| } | ||
| } | ||
| function normalizeNativeError(error) { | ||
| if (error && error.name === 'OcrError') { | ||
| Object.setPrototypeOf(error, OcrError.prototype); | ||
| } | ||
| return error; | ||
| } | ||
| function deepFreeze(value) { | ||
| if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value; | ||
| for (const child of Object.values(value)) deepFreeze(child); | ||
| return Object.freeze(value); | ||
| } | ||
| function validateSignal(signal) { | ||
| if ( | ||
| signal === null || | ||
| typeof signal !== 'object' || | ||
| typeof signal.aborted !== 'boolean' || | ||
| typeof signal.addEventListener !== 'function' || | ||
| typeof signal.removeEventListener !== 'function' | ||
| ) { | ||
| throw new OcrError('invalid_argument', 'signal must be an AbortSignal'); | ||
| } | ||
| } | ||
| function abortReason(signal) { | ||
| return signal.reason === undefined | ||
| ? new DOMException('The operation was aborted', 'AbortError') | ||
| : signal.reason; | ||
| } | ||
| function resolveBuiltInBundle(model) { | ||
| if (model !== DEFAULT_MODEL) { | ||
| throw new OcrError( | ||
| 'invalid_argument', | ||
| `model must be ${JSON.stringify(DEFAULT_MODEL)}`, | ||
| ); | ||
| } | ||
| let manifestPath; | ||
| try { | ||
| manifestPath = require.resolve(`${MODEL_PACKAGE}/bundle/manifest.json`); | ||
| } catch (cause) { | ||
| throw new OcrError( | ||
| 'package_load_failed', | ||
| `Unable to locate the built-in ${DEFAULT_MODEL} model`, | ||
| `Reinstall ${MODEL_PACKAGE}; ${cause instanceof Error ? cause.message : String(cause)}`, | ||
| ); | ||
| } | ||
| let manifest; | ||
| try { | ||
| manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); | ||
| } catch (cause) { | ||
| throw new OcrError( | ||
| 'package_load_failed', | ||
| 'Unable to read the built-in model manifest', | ||
| cause instanceof Error ? cause.message : String(cause), | ||
| ); | ||
| } | ||
| if (manifest.bundleId !== EXPECTED_BUNDLE_ID) { | ||
| throw new OcrError( | ||
| 'package_load_failed', | ||
| 'The installed model package is incompatible with this light-ocr release', | ||
| `expected ${EXPECTED_BUNDLE_ID}, received ${String(manifest.bundleId)}`, | ||
| ); | ||
| } | ||
| return path.dirname(manifestPath); | ||
| } | ||
| function resolveCreateOptions(options) { | ||
| if (options === undefined) options = {}; | ||
| if (options === null || typeof options !== 'object' || Array.isArray(options)) { | ||
| throw new OcrError('invalid_argument', 'createEngine options must be an object'); | ||
| } | ||
| const hasModel = Object.prototype.hasOwnProperty.call(options, 'model'); | ||
| const hasBundlePath = Object.prototype.hasOwnProperty.call(options, 'bundlePath'); | ||
| if (hasModel && hasBundlePath) { | ||
| throw new OcrError( | ||
| 'invalid_argument', | ||
| 'model and bundlePath cannot be used together', | ||
| ); | ||
| } | ||
| if (hasBundlePath) return options; | ||
| const model = hasModel ? options.model : DEFAULT_MODEL; | ||
| const resolved = { ...options, bundlePath: resolveBuiltInBundle(model) }; | ||
| delete resolved.model; | ||
| return resolved; | ||
| } | ||
| class OcrEngineImpl { | ||
| #native; | ||
| #closePromise; | ||
| constructor(nativeEngine) { | ||
| this.#native = nativeEngine; | ||
| this.info = deepFreeze(nativeEngine.info); | ||
| Object.defineProperty(this, 'info', { writable: false, configurable: false }); | ||
| } | ||
| recognize(image, options = {}) { | ||
| let signal; | ||
| let nativeOptions; | ||
| try { | ||
| if (options === null || typeof options !== 'object' || Array.isArray(options)) { | ||
| throw new OcrError('invalid_argument', 'recognize options must be an object'); | ||
| } | ||
| signal = options.signal; | ||
| if (signal !== undefined) { | ||
| validateSignal(signal); | ||
| if (signal.aborted) return Promise.reject(abortReason(signal)); | ||
| } | ||
| nativeOptions = { ...options }; | ||
| delete nativeOptions.signal; | ||
| } catch (error) { | ||
| return Promise.reject(normalizeNativeError(error)); | ||
| } | ||
| let operation; | ||
| try { | ||
| operation = this.#native.recognize(image, nativeOptions); | ||
| } catch (error) { | ||
| return Promise.reject(normalizeNativeError(error)); | ||
| } | ||
| return new Promise((resolve, reject) => { | ||
| let settled = false; | ||
| const cleanup = () => { | ||
| if (signal !== undefined) signal.removeEventListener('abort', onAbort); | ||
| }; | ||
| const settle = (callback, value) => { | ||
| if (settled) return; | ||
| settled = true; | ||
| cleanup(); | ||
| callback(value); | ||
| }; | ||
| const onAbort = () => { | ||
| if (settled) return; | ||
| try { | ||
| this.#native.cancel(operation.requestId); | ||
| } catch { | ||
| // Public cancellation still wins. Native teardown owns any remaining work. | ||
| } | ||
| settle(reject, abortReason(signal)); | ||
| }; | ||
| operation.promise.then( | ||
| (value) => settle(resolve, value), | ||
| (error) => settle(reject, normalizeNativeError(error)), | ||
| ); | ||
| if (signal !== undefined) { | ||
| signal.addEventListener('abort', onAbort, { once: true }); | ||
| if (signal.aborted) onAbort(); | ||
| } | ||
| }); | ||
| } | ||
| close() { | ||
| if (this.#closePromise === undefined) { | ||
| try { | ||
| this.#closePromise = Promise.resolve(this.#native.close()).catch((error) => { | ||
| throw normalizeNativeError(error); | ||
| }); | ||
| } catch (error) { | ||
| this.#closePromise = Promise.reject(normalizeNativeError(error)); | ||
| } | ||
| } | ||
| return this.#closePromise; | ||
| } | ||
| } | ||
| let binding; | ||
| async function createEngine(options) { | ||
| try { | ||
| const resolvedOptions = resolveCreateOptions(options); | ||
| if (!binding) binding = loadNative(); | ||
| const nativeEngine = await binding.createEngine(resolvedOptions); | ||
| return new OcrEngineImpl(nativeEngine); | ||
| } catch (error) { | ||
| throw normalizeNativeError(error); | ||
| } | ||
| } | ||
| module.exports = { createEngine, OcrError }; |
| /// <reference types="node" /> | ||
| export type PixelFormat = 'gray8' | 'rgb8' | 'bgr8' | 'rgba8'; | ||
| export type DetectionStrategy = 'bounded' | 'upstreamExact'; | ||
| export type BuiltInModel = 'ppocrv6-small'; | ||
| export interface DetectionOptions { | ||
| readonly strategy?: DetectionStrategy; | ||
| readonly maxSide?: number; | ||
| } | ||
| export interface RawImage { | ||
| readonly data: Uint8Array; | ||
| readonly width: number; | ||
| readonly height: number; | ||
| readonly stride: number; | ||
| readonly pixelFormat: PixelFormat; | ||
| } | ||
| export interface ResourceLimits { | ||
| readonly maxWidth: number; | ||
| readonly maxHeight: number; | ||
| readonly maxPixels: number; | ||
| readonly maxDetectionSide: number; | ||
| readonly maxDetectionCandidates: number; | ||
| readonly maxRecognitionBatchSize: number; | ||
| readonly maxRecognitionWidth: number; | ||
| readonly maxTemporaryBytes: number; | ||
| } | ||
| export interface CreateEngineOptions { | ||
| readonly model?: BuiltInModel; | ||
| readonly bundlePath?: string; | ||
| readonly intraOpThreads?: number; | ||
| readonly interOpThreads?: number; | ||
| readonly recognitionScoreThreshold?: number; | ||
| readonly recognitionBatchSize?: number; | ||
| readonly reducedLimits?: ResourceLimits; | ||
| readonly queueCapacity?: number; | ||
| readonly maxPendingInputBytes?: number; | ||
| readonly detection?: DetectionOptions; | ||
| } | ||
| export interface RecognizeOptions { | ||
| readonly recognitionScoreThreshold?: number; | ||
| readonly recognitionBatchSize?: number; | ||
| readonly includeDiagnostics?: boolean; | ||
| readonly signal?: AbortSignal; | ||
| readonly useTextlineOrientation?: boolean; | ||
| readonly detectionMaxSide?: number; | ||
| } | ||
| export interface Point { readonly x: number; readonly y: number } | ||
| export interface OcrLine { | ||
| readonly text: string; | ||
| readonly confidence: number; | ||
| readonly box: readonly [Point, Point, Point, Point]; | ||
| } | ||
| export type RejectionReason = 'below_score_threshold' | 'empty_decode'; | ||
| export interface RejectedLine { readonly line: OcrLine; readonly reason: RejectionReason } | ||
| export interface DiagnosticWarning { readonly code: string; readonly message: string } | ||
| export interface RecognitionBatchShape { | ||
| readonly batchSize: number; | ||
| readonly height: number; | ||
| readonly width: number; | ||
| } | ||
| export interface Diagnostics { | ||
| readonly rejectedLines: readonly RejectedLine[]; | ||
| readonly warnings: readonly DiagnosticWarning[]; | ||
| readonly detectedCandidates: number; | ||
| readonly acceptedBoxes: number; | ||
| readonly detectionInputWidth: number; | ||
| readonly detectionInputHeight: number; | ||
| readonly recognitionBatchShapes: readonly RecognitionBatchShape[]; | ||
| } | ||
| export interface TimingUs { | ||
| readonly total: number; | ||
| readonly inputValidation: number; | ||
| readonly detectionPreprocess: number; | ||
| readonly detectionInference: number; | ||
| readonly detectionPostprocess: number; | ||
| readonly cropAndSort: number; | ||
| readonly recognitionPreprocess: number; | ||
| readonly recognitionInference: number; | ||
| readonly recognitionPostprocess: number; | ||
| } | ||
| export interface OcrResult { | ||
| readonly lines: readonly OcrLine[]; | ||
| readonly imageWidth: number; | ||
| readonly imageHeight: number; | ||
| readonly modelBundleId: string; | ||
| readonly timingUs: TimingUs; | ||
| readonly diagnostics?: Diagnostics; | ||
| } | ||
| export interface EngineInfo { | ||
| readonly coreVersion: string; | ||
| readonly modelBundleId: string; | ||
| readonly modelBundleSchemaVersion: string; | ||
| readonly backend: string; | ||
| readonly executionProvider: string; | ||
| readonly capabilities: { | ||
| readonly detection: boolean; | ||
| readonly recognition: boolean; | ||
| readonly textlineOrientation: boolean; | ||
| }; | ||
| readonly concurrencyMode: 'serialized_reject_when_busy'; | ||
| readonly limits: ResourceLimits & { readonly maxConcurrentCalls: 1 }; | ||
| readonly intraOpThreads: number; | ||
| readonly interOpThreads: number; | ||
| readonly detectionStrategy: DetectionStrategy; | ||
| readonly detectionMaxSide: number; | ||
| readonly defaultRecognitionScoreThreshold: number; | ||
| readonly defaultRecognitionBatchSize: number; | ||
| readonly adapter: { | ||
| readonly scheduler: 'dedicated_fifo'; | ||
| readonly queueCapacity: number; | ||
| readonly maxPendingInputBytes: number; | ||
| }; | ||
| } | ||
| export type CoreErrorCode = | ||
| | 'invalid_argument' | 'invalid_image' | 'unsupported_pixel_format' | ||
| | 'unsupported_capability' | 'invalid_model_bundle' | 'unsupported_model' | ||
| | 'model_integrity_failed' | 'runtime_initialization_failed' | 'inference_failed' | ||
| | 'postprocess_failed' | 'resource_limit_exceeded' | 'invalid_engine' | ||
| | 'internal_error'; | ||
| export type AdapterErrorCode = | ||
| | 'bundle_io_failed' | 'queue_full' | 'environment_closing' | ||
| | 'unsupported_platform' | 'package_load_failed'; | ||
| export type OcrErrorCode = CoreErrorCode | AdapterErrorCode; | ||
| export class OcrError extends Error { | ||
| constructor(code: OcrErrorCode, message: string, detail?: string); | ||
| readonly name: 'OcrError'; | ||
| readonly code: OcrErrorCode; | ||
| readonly detail?: string; | ||
| } | ||
| export interface OcrEngine { | ||
| readonly info: EngineInfo; | ||
| recognize(image: RawImage, options?: RecognizeOptions): Promise<OcrResult>; | ||
| close(): Promise<void>; | ||
| } | ||
| export function createEngine(options?: CreateEngineOptions): Promise<OcrEngine>; |
| import cjs from './index.cjs'; | ||
| export const createEngine = cjs.createEngine; | ||
| export const OcrError = cjs.OcrError; |
| 'use strict'; | ||
| const fs = require('node:fs'); | ||
| const path = require('node:path'); | ||
| function candidatePaths() { | ||
| const candidates = []; | ||
| if (process.env.LIGHT_OCR_NODE_BINARY) { | ||
| candidates.push(path.resolve(process.env.LIGHT_OCR_NODE_BINARY)); | ||
| } | ||
| candidates.push(path.join(__dirname, 'native', 'light_ocr_node.node')); | ||
| candidates.push( | ||
| path.join( | ||
| __dirname, | ||
| '..', | ||
| 'prebuilds', | ||
| `${process.platform}-${process.arch}`, | ||
| 'light_ocr_node.node', | ||
| ), | ||
| ); | ||
| return candidates; | ||
| } | ||
| function adapterError(code, message, detail, cause) { | ||
| const error = new Error(message, cause === undefined ? undefined : { cause }); | ||
| error.name = 'OcrError'; | ||
| error.code = code; | ||
| if (detail) error.detail = detail; | ||
| return error; | ||
| } | ||
| function platformPackage() { | ||
| const key = `${process.platform}-${process.arch}`; | ||
| const packages = { | ||
| 'darwin-arm64': '@arcships/light-ocr-darwin-arm64', | ||
| 'darwin-x64': '@arcships/light-ocr-darwin-x64', | ||
| 'win32-x64': '@arcships/light-ocr-win32-x64', | ||
| }; | ||
| if (key === 'linux-x64') { | ||
| const report = process.report?.getReport?.(); | ||
| if (report?.header?.glibcVersionRuntime) { | ||
| return '@arcships/light-ocr-linux-x64-gnu'; | ||
| } | ||
| throw adapterError( | ||
| 'unsupported_platform', | ||
| 'light-ocr currently supports Linux x64 with glibc only', | ||
| `${process.platform}-${process.arch}`, | ||
| ); | ||
| } | ||
| const packageName = packages[key]; | ||
| if (!packageName) { | ||
| throw adapterError( | ||
| 'unsupported_platform', | ||
| `light-ocr does not support ${key}`, | ||
| key, | ||
| ); | ||
| } | ||
| return packageName; | ||
| } | ||
| function loadNative() { | ||
| const candidates = candidatePaths(); | ||
| const binary = candidates.find((candidate) => fs.existsSync(candidate)); | ||
| if (binary) return require(binary); | ||
| const packageName = platformPackage(); | ||
| try { | ||
| return require(packageName); | ||
| } catch (cause) { | ||
| throw adapterError( | ||
| 'package_load_failed', | ||
| `Unable to load ${packageName}`, | ||
| 'Reinstall @arcships/light-ocr without --omit=optional and verify that the ' + | ||
| 'current platform is supported.', | ||
| cause, | ||
| ); | ||
| } | ||
| } | ||
| module.exports = { loadNative }; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
| 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: | ||
| (a) You must give any other recipients of the Work or | ||
| Derivative Works a copy of this License; and | ||
| (b) You must cause any modified files to carry prominent notices | ||
| stating that You changed the files; and | ||
| (c) 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 | ||
| (d) 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. |
| light-ocr | ||
| Copyright 2026 light-ocr contributors | ||
| This product includes software developed by the light-ocr contributors. | ||
| Third-party licenses and notices for packaged dependencies and model | ||
| artifacts are distributed with their respective release artifacts. |
| { | ||
| "bugs": { | ||
| "url": "https://github.com/arcships/light-ocr/issues" | ||
| }, | ||
| "dependencies": { | ||
| "@arcships/light-ocr-model-ppocrv6-small": "0.1.0" | ||
| }, | ||
| "description": "Offline PP-OCRv6 OCR for Node.js, powered by an embeddable C++ core", | ||
| "engines": { | ||
| "node": "^22.0.0 || ^24.0.0" | ||
| }, | ||
| "exports": { | ||
| ".": { | ||
| "import": "./js/index.mjs", | ||
| "require": "./js/index.cjs", | ||
| "types": "./js/index.d.ts" | ||
| } | ||
| }, | ||
| "files": [ | ||
| "js/", | ||
| "README.md", | ||
| "LICENSE", | ||
| "NOTICE" | ||
| ], | ||
| "homepage": "https://github.com/arcships/light-ocr#readme", | ||
| "keywords": [ | ||
| "ocr", | ||
| "offline-ocr", | ||
| "pp-ocrv6", | ||
| "paddleocr", | ||
| "node-api", | ||
| "napi" | ||
| ], | ||
| "license": "Apache-2.0", | ||
| "main": "./js/index.cjs", | ||
| "module": "./js/index.mjs", | ||
| "name": "@arcships/light-ocr", | ||
| "optionalDependencies": { | ||
| "@arcships/light-ocr-darwin-arm64": "0.1.0", | ||
| "@arcships/light-ocr-darwin-x64": "0.1.0", | ||
| "@arcships/light-ocr-linux-x64-gnu": "0.1.0", | ||
| "@arcships/light-ocr-win32-x64": "0.1.0" | ||
| }, | ||
| "publishConfig": { | ||
| "access": "public", | ||
| "provenance": true | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/arcships/light-ocr.git" | ||
| }, | ||
| "type": "commonjs", | ||
| "types": "./js/index.d.ts", | ||
| "version": "0.1.0" | ||
| } |
| # @arcships/light-ocr | ||
| Offline OCR for Node.js applications, powered by PP-OCRv6 Small. | ||
| ```bash | ||
| npm install @arcships/light-ocr | ||
| ``` | ||
| The default PP-OCRv6 Small model is included as a required dependency; no | ||
| runtime model download or postinstall compilation is used. | ||
| Documentation: https://github.com/arcships/light-ocr | ||
| License: Apache-2.0 |
| { | ||
| "version": 1, | ||
| "runtimeId": "light-ocr", | ||
| "providerId": "light-ocr-local", | ||
| "modelId": "ppocrv6-small", | ||
| "platform": "win32", | ||
| "arch": "x64", | ||
| "lightOcrVersion": "0.1.0", | ||
| "bundleId": "ppocrv6-small-onnx-20260714.1", | ||
| "facade": "facade/js/index.cjs", | ||
| "modelBundle": "model/bundle", | ||
| "nativeAddon": "facade/js/native/light_ocr_node.node", | ||
| "inventory": [ | ||
| { | ||
| "path": "facade/js/index.cjs", | ||
| "size": 6027, | ||
| "sha256": "da6ea0ffea5c5a00ad5f2c80ebe068d5ee99fb85073ab414cca712fae8786f25" | ||
| }, | ||
| { | ||
| "path": "facade/js/index.d.ts", | ||
| "size": 4966, | ||
| "sha256": "fa0cd5f7ea7208a041a8ba198980972cb8770d4e4e2e1574a05e14239f3a83e4" | ||
| }, | ||
| { | ||
| "path": "facade/js/index.mjs", | ||
| "size": 116, | ||
| "sha256": "43f119a9043dddd3a32f1d1de3dbb85eba39a78b05903c5838067ff0cbb6f62a" | ||
| }, | ||
| { | ||
| "path": "facade/js/load-native.cjs", | ||
| "size": 2140, | ||
| "sha256": "12bb6568d8ecbd7cf57519ff1c36f460085c249d9626df0f2283588f23abb146" | ||
| }, | ||
| { | ||
| "path": "facade/js/native/light_ocr_node.node", | ||
| "size": 3588608, | ||
| "sha256": "9d8928440ce20085220afc98c6d6f5f389b3b98d43cb2db3d53b9bb0e83badcc" | ||
| }, | ||
| { | ||
| "path": "facade/js/native/onnxruntime.dll", | ||
| "size": 12418080, | ||
| "sha256": "579b636403983254346a5c1d80bd28f1519cd1e284cd204f8d4ff41f8d711559" | ||
| }, | ||
| { | ||
| "path": "facade/LICENSE", | ||
| "size": 11358, | ||
| "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" | ||
| }, | ||
| { | ||
| "path": "facade/NOTICE", | ||
| "size": 258, | ||
| "sha256": "24cb7b29285527efc05b8b85c3086fa589e06078dc3ad0075fb51546aa85f547" | ||
| }, | ||
| { | ||
| "path": "facade/package.json", | ||
| "size": 1275, | ||
| "sha256": "4369a8a49a3f26645c91fef9c1ec27592021bb4d341c4e5f636b60b8a9d58b8d" | ||
| }, | ||
| { | ||
| "path": "facade/README.md", | ||
| "size": 342, | ||
| "sha256": "66be005f72634728895b63c9f0405728946416a5ed90b85f93ad5dc50b0141cd" | ||
| }, | ||
| { | ||
| "path": "model/bundle/det/inference.onnx", | ||
| "size": 9880512, | ||
| "sha256": "d73e0058b7a8086bbd57f3d10b8bcd4ff95363f67e06e2762b5e814fe9c9410e" | ||
| }, | ||
| { | ||
| "path": "model/bundle/det/inference.yml", | ||
| "size": 885, | ||
| "sha256": "193f435274bf9f0b5f71a929bbfbcf148282df7e633b34e7c373e8f44741b516" | ||
| }, | ||
| { | ||
| "path": "model/bundle/LICENSES/MODEL-NOTICE.md", | ||
| "size": 312, | ||
| "sha256": "381c555aebec730789e4f7a60583024ba7d7c026a5a223ac938c91767e4e91ff" | ||
| }, | ||
| { | ||
| "path": "model/bundle/LICENSES/PaddleOCR-Apache-2.0.txt", | ||
| "size": 11376, | ||
| "sha256": "3840c5c0c61c294264d2dd77b8777be6ddd90121ef4e0e64abcd22edea581d6e" | ||
| }, | ||
| { | ||
| "path": "model/bundle/manifest.json", | ||
| "size": 1839, | ||
| "sha256": "8c956568b504e4cf93971999c1e7eff298683d95ddeed1bb8674bfe112ddbb9a" | ||
| }, | ||
| { | ||
| "path": "model/bundle/normalized-config.json", | ||
| "size": 1953, | ||
| "sha256": "9d90b41c8ce3f278cdd82c06556458df42c53e76decc4ed0cdf681db4ca3b11d" | ||
| }, | ||
| { | ||
| "path": "model/bundle/rec/dictionary.json", | ||
| "size": 112408, | ||
| "sha256": "6e93cc028ff774c8bef0801ad08391f8284f7ef897013a9aeb9cbd515db3276d" | ||
| }, | ||
| { | ||
| "path": "model/bundle/rec/inference.onnx", | ||
| "size": 21159378, | ||
| "sha256": "5435fd747c9e0efe15a96d0b378d5bd157e9492ed8fd80edf08f30d02fa24634" | ||
| }, | ||
| { | ||
| "path": "model/bundle/rec/inference.yml", | ||
| "size": 150579, | ||
| "sha256": "ab078671bb49f06228eadccd34f1bb501e157f7a047095ffb943ba81512c77d1" | ||
| }, | ||
| { | ||
| "path": "model/bundle/SHA256SUMS", | ||
| "size": 784, | ||
| "sha256": "ecde157656c32a4a5577a4e81f118c231c044fb4adb2ff5c6aebe67e11727b25" | ||
| }, | ||
| { | ||
| "path": "model/LICENSE", | ||
| "size": 11358, | ||
| "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" | ||
| }, | ||
| { | ||
| "path": "model/NOTICE", | ||
| "size": 258, | ||
| "sha256": "24cb7b29285527efc05b8b85c3086fa589e06078dc3ad0075fb51546aa85f547" | ||
| }, | ||
| { | ||
| "path": "model/package.json", | ||
| "size": 820, | ||
| "sha256": "3ab816bc63e590ff28dcc45c289cc96533f5c95aa74b6fe0412eda2306d4f936" | ||
| }, | ||
| { | ||
| "path": "model/README.md", | ||
| "size": 327, | ||
| "sha256": "ce14eb199e2b1810f6de792da87f13d4808136c9d72740f1c6e7dd6a56614ca2" | ||
| }, | ||
| { | ||
| "path": "native-metadata/artifact-hashes.json", | ||
| "size": 2986, | ||
| "sha256": "71b48216cb4baca68207e841978cc13cc2804947a9b513a3321205afb4fd394d" | ||
| }, | ||
| { | ||
| "path": "native-metadata/LICENSE", | ||
| "size": 11358, | ||
| "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" | ||
| }, | ||
| { | ||
| "path": "native-metadata/license-inventory.json", | ||
| "size": 1478, | ||
| "sha256": "55cf246c96f5d289bef038ef750cdb9bf7cedf303d4a3da6c3481f1a776f67cb" | ||
| }, | ||
| { | ||
| "path": "native-metadata/licenses/clipper-BSL-1.0.txt", | ||
| "size": 1110, | ||
| "sha256": "32ee7398e3123736fd14e9f08287edc2d97ace102ab54d8dc4edc8d31c651fa8" | ||
| }, | ||
| { | ||
| "path": "native-metadata/licenses/nlohmann-json-MIT.txt", | ||
| "size": 1076, | ||
| "sha256": "86b998c792894ccb911a1cb7994f7a9652894e7a094c0b5e45be2f553f45cf14" | ||
| }, | ||
| { | ||
| "path": "native-metadata/licenses/onnxruntime-MIT.txt", | ||
| "size": 1094, | ||
| "sha256": "c250d6278f0b47a6439fb7592b08b58a55eb9f535aa49a1db63211c3f982b674" | ||
| }, | ||
| { | ||
| "path": "native-metadata/licenses/onnxruntime-ThirdPartyNotices.txt", | ||
| "size": 333022, | ||
| "sha256": "e00f828e0a33de591a355ae6606d2625f5758da7d2c844db7821c9dd3e3647b6" | ||
| }, | ||
| { | ||
| "path": "native-metadata/licenses/opencv-Apache-2.0.txt", | ||
| "size": 11358, | ||
| "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" | ||
| }, | ||
| { | ||
| "path": "native-metadata/licenses/opencv-carotene-BSD-3-Clause.txt", | ||
| "size": 2048, | ||
| "sha256": "0bccc9a19466df14bd38c8722cc1a692327f5db8f7a0f75f4162620e0e3be59a" | ||
| }, | ||
| { | ||
| "path": "native-metadata/licenses/opencv-COPYRIGHT.txt", | ||
| "size": 733, | ||
| "sha256": "bba849c98da85a2b27b86113284a90812c959b1c1fc4ed67de9355475d1e6831" | ||
| }, | ||
| { | ||
| "path": "native-metadata/licenses/opencv-zlib.txt", | ||
| "size": 1002, | ||
| "sha256": "845efc77857d485d91fb3e0b884aaa929368c717ae8186b66fe1ed2495753243" | ||
| }, | ||
| { | ||
| "path": "native-metadata/licenses/PP-OCRv6-Apache-2.0.txt", | ||
| "size": 11376, | ||
| "sha256": "3840c5c0c61c294264d2dd77b8777be6ddd90121ef4e0e64abcd22edea581d6e" | ||
| }, | ||
| { | ||
| "path": "native-metadata/licenses/PP-OCRv6-MODEL-NOTICE.md", | ||
| "size": 312, | ||
| "sha256": "381c555aebec730789e4f7a60583024ba7d7c026a5a223ac938c91767e4e91ff" | ||
| }, | ||
| { | ||
| "path": "native-metadata/NOTICE", | ||
| "size": 258, | ||
| "sha256": "24cb7b29285527efc05b8b85c3086fa589e06078dc3ad0075fb51546aa85f547" | ||
| }, | ||
| { | ||
| "path": "native-metadata/package.json", | ||
| "size": 860, | ||
| "sha256": "a353cb5e45aed9a349dedce661e6c94e6effd14297f65980f4d61d0f4b3b68a5" | ||
| }, | ||
| { | ||
| "path": "native-metadata/README.md", | ||
| "size": 318, | ||
| "sha256": "1a77350f674a9a4c9c5f2f934230f0c64364eeae2e6539338c935d509c981c0e" | ||
| }, | ||
| { | ||
| "path": "native-metadata/sbom.spdx.json", | ||
| "size": 4345, | ||
| "sha256": "ba9b352bce512ef2951104437402dfab4d637378d6f61b0b20e44c184a8228aa" | ||
| } | ||
| ] | ||
| } |
Sorry, the diff of this file is not supported yet
| Global: | ||
| model_name: PP-OCRv6_small_det | ||
| Hpi: | ||
| backend_configs: | ||
| paddle_infer: | ||
| trt_dynamic_shapes: &id001 | ||
| x: | ||
| - - 1 | ||
| - 3 | ||
| - 32 | ||
| - 32 | ||
| - - 1 | ||
| - 3 | ||
| - 736 | ||
| - 736 | ||
| - - 1 | ||
| - 3 | ||
| - 4000 | ||
| - 4000 | ||
| tensorrt: | ||
| dynamic_shapes: *id001 | ||
| PostProcess: | ||
| box_thresh: 0.45 | ||
| max_candidates: 3000 | ||
| name: DBPostProcess | ||
| thresh: 0.2 | ||
| unclip_ratio: 1.4 | ||
| PreProcess: | ||
| transform_ops: | ||
| - DecodeImage: | ||
| channel_first: false | ||
| img_mode: BGR | ||
| - DetLabelEncode: null | ||
| - DetResizeForTest: null | ||
| - NormalizeImage: | ||
| mean: | ||
| - 0.485 | ||
| - 0.456 | ||
| - 0.406 | ||
| order: hwc | ||
| scale: 1./255. | ||
| std: | ||
| - 0.229 | ||
| - 0.224 | ||
| - 0.225 | ||
| - ToCHWImage: null | ||
| - KeepKeys: | ||
| keep_keys: | ||
| - image | ||
| - shape | ||
| - polys | ||
| - ignore_tags |
| PP-OCRv6 small ONNX model bundle | ||
| PaddleOCR revision: b03f46425e8ff4442b268ce449e3eef758146cd4 | ||
| Detection model revision: 28fe5895c24fd108c19eb3e8479f4ab385fbfc62 | ||
| Recognition model revision: b8f84f0b80c529de40b4fbb3544b84fa7233a513 | ||
| Sources: official PaddlePaddle model ecology archives listed in bundles.lock.json |
| 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: | ||
| (a) You must give any other recipients of the Work or | ||
| Derivative Works a copy of this License; and | ||
| (b) You must cause any modified files to carry prominent notices | ||
| stating that You changed the files; and | ||
| (c) 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 | ||
| (d) 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 (c) 2016 PaddlePaddle Authors. All Rights Reserved. | ||
| 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. |
| {"bundleId":"ppocrv6-small-onnx-20260714.1","capabilities":{"detection":true,"recognition":true,"textlineOrientation":false},"coreCompatibility":{"maximumMajor":0,"minimum":"0.1.0"},"family":"PP-OCRv6","files":{"LICENSES/MODEL-NOTICE.md":{"bytes":312,"sha256":"381c555aebec730789e4f7a60583024ba7d7c026a5a223ac938c91767e4e91ff"},"LICENSES/PaddleOCR-Apache-2.0.txt":{"bytes":11376,"sha256":"3840c5c0c61c294264d2dd77b8777be6ddd90121ef4e0e64abcd22edea581d6e"},"det/inference.onnx":{"bytes":9880512,"sha256":"d73e0058b7a8086bbd57f3d10b8bcd4ff95363f67e06e2762b5e814fe9c9410e"},"det/inference.yml":{"bytes":885,"sha256":"193f435274bf9f0b5f71a929bbfbcf148282df7e633b34e7c373e8f44741b516"},"normalized-config.json":{"bytes":1953,"sha256":"9d90b41c8ce3f278cdd82c06556458df42c53e76decc4ed0cdf681db4ca3b11d"},"rec/dictionary.json":{"bytes":112408,"sha256":"6e93cc028ff774c8bef0801ad08391f8284f7ef897013a9aeb9cbd515db3276d"},"rec/inference.onnx":{"bytes":21159378,"sha256":"5435fd747c9e0efe15a96d0b378d5bd157e9492ed8fd80edf08f30d02fa24634"},"rec/inference.yml":{"bytes":150579,"sha256":"ab078671bb49f06228eadccd34f1bb501e157f7a047095ffb943ba81512c77d1"}},"licenses":["Apache-2.0"],"models":{"detection":{"configPath":"det/inference.yml","id":"PP-OCRv6_small_det_onnx","inputRank":4,"modelPath":"det/inference.onnx","outputRanks":[3,4],"sourceRevision":"28fe5895c24fd108c19eb3e8479f4ab385fbfc62"},"recognition":{"configPath":"rec/inference.yml","dictionaryPath":"rec/dictionary.json","id":"PP-OCRv6_small_rec_onnx","inputRank":4,"modelPath":"rec/inference.onnx","outputRank":3,"sourceRevision":"b8f84f0b80c529de40b4fbb3544b84fa7233a513"}},"normalizedConfigPath":"normalized-config.json","schemaVersion":"1.0","upstream":{"release":"v3.7.0","repository":"https://github.com/PaddlePaddle/PaddleOCR","revision":"b03f46425e8ff4442b268ce449e3eef758146cd4"}} |
| {"bundleId":"ppocrv6-small-onnx-20260714.1","detection":{"input":{"colorOrder":"BGR","tensorLayout":"NCHW","tensorType":"float32"},"normalize":{"mean":[0.485,0.456,0.406],"scale":0.00392156862745098,"std":[0.229,0.224,0.225]},"postprocess":{"algorithm":"DB","boxThreshold":0.6,"boxType":"quad","maxCandidates":3000,"minimumBoxSide":3,"scoreMode":"fast","threshold":0.3,"unclipRatio":1.5,"useDilation":false}},"geometry":{"borderMode":"replicate","perspectiveInterpolation":"cubic","rowBandPixels":10,"tallLineRatio":1.5,"tallLineRotation":"counterclockwise90"},"recognition":{"batch":{"maximumSize":8,"sortByWidth":true},"decode":{"algorithm":"CTC","appendSpaceCharacter":true,"blankIndex":0,"collapseRepeats":true,"confidence":"mean_selected_argmax_probability","dictionaryEntries":18709,"dictionaryPath":"rec/dictionary.json"},"defaultScoreThreshold":0.0,"input":{"batchTensorWidth":"maximum_sample_tensor_width","colorOrder":"BGR","interpolation":"linear","maximumTensorWidth":3200,"minimumTensorWidth":320,"resizedContentWidthRounding":"ceil","shape":[3,48,320],"tensorLayout":"NCHW","tensorType":"float32","tensorWidthRounding":"truncate_toward_zero"},"normalize":{"mean":[0.5,0.5,0.5],"paddingValue":0.0,"scale":0.00392156862745098,"std":[0.5,0.5,0.5]}},"resourceLimits":{"maxConcurrentCalls":1,"maxDetectionCandidates":3000,"maxDetectionSide":4000,"maxHeight":10000,"maxPixels":40000000,"maxRecognitionBatchSize":8,"maxRecognitionWidth":3200,"maxTemporaryBytes":536870912,"maxWidth":10000},"runtimeDefaults":{"detection":{"dimensionMultipleRounding":"ceil","maxSide":960,"minimumShortSide":64,"strategy":"bounded"},"recognitionBatchSize":1},"schemaVersion":"1.1","sourceDetectionResize":{"dimensionMultiple":32,"interpolation":"linear","limitSideLen":64,"limitType":"min","maxSideLimit":4000,"maxSideLimitOrder":"before_multiple_rounding","minimumDimension":32,"multipleRounding":"half_to_even","scaledDimensionRounding":"truncate_toward_zero"}} |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
| 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: | ||
| (a) You must give any other recipients of the Work or | ||
| Derivative Works a copy of this License; and | ||
| (b) You must cause any modified files to carry prominent notices | ||
| stating that You changed the files; and | ||
| (c) 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 | ||
| (d) 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. |
| light-ocr | ||
| Copyright 2026 light-ocr contributors | ||
| This product includes software developed by the light-ocr contributors. | ||
| Third-party licenses and notices for packaged dependencies and model | ||
| artifacts are distributed with their respective release artifacts. |
| { | ||
| "bugs": { | ||
| "url": "https://github.com/arcships/light-ocr/issues" | ||
| }, | ||
| "description": "Pinned PP-OCRv6 Small model bundle for @arcships/light-ocr", | ||
| "exports": { | ||
| "./bundle/manifest.json": "./bundle/manifest.json" | ||
| }, | ||
| "files": [ | ||
| "bundle/", | ||
| "README.md", | ||
| "LICENSE", | ||
| "NOTICE" | ||
| ], | ||
| "homepage": "https://github.com/arcships/light-ocr#readme", | ||
| "license": "Apache-2.0", | ||
| "lightOcr": { | ||
| "bundleId": "ppocrv6-small-onnx-20260714.1", | ||
| "bundleSchemaVersion": "1.1", | ||
| "paddleOcrRevision": "b03f46425e8ff4442b268ce449e3eef758146cd4" | ||
| }, | ||
| "name": "@arcships/light-ocr-model-ppocrv6-small", | ||
| "publishConfig": { | ||
| "access": "public", | ||
| "provenance": true | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/arcships/light-ocr.git" | ||
| }, | ||
| "version": "0.1.0" | ||
| } |
| # @arcships/light-ocr-model-ppocrv6-small | ||
| The pinned PP-OCRv6 Small model bundle for `@arcships/light-ocr`. | ||
| This is an internal distribution package for `@arcships/light-ocr`. Install | ||
| the facade package instead of depending on this package directly. | ||
| Documentation: https://github.com/arcships/light-ocr | ||
| License: Apache-2.0 |
| { | ||
| "files": [ | ||
| { | ||
| "bytes": 11358, | ||
| "path": "LICENSE", | ||
| "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" | ||
| }, | ||
| { | ||
| "bytes": 258, | ||
| "path": "NOTICE", | ||
| "sha256": "24cb7b29285527efc05b8b85c3086fa589e06078dc3ad0075fb51546aa85f547" | ||
| }, | ||
| { | ||
| "bytes": 318, | ||
| "path": "README.md", | ||
| "sha256": "1a77350f674a9a4c9c5f2f934230f0c64364eeae2e6539338c935d509c981c0e" | ||
| }, | ||
| { | ||
| "bytes": 1478, | ||
| "path": "license-inventory.json", | ||
| "sha256": "55cf246c96f5d289bef038ef750cdb9bf7cedf303d4a3da6c3481f1a776f67cb" | ||
| }, | ||
| { | ||
| "bytes": 11376, | ||
| "path": "licenses/PP-OCRv6-Apache-2.0.txt", | ||
| "sha256": "3840c5c0c61c294264d2dd77b8777be6ddd90121ef4e0e64abcd22edea581d6e" | ||
| }, | ||
| { | ||
| "bytes": 312, | ||
| "path": "licenses/PP-OCRv6-MODEL-NOTICE.md", | ||
| "sha256": "381c555aebec730789e4f7a60583024ba7d7c026a5a223ac938c91767e4e91ff" | ||
| }, | ||
| { | ||
| "bytes": 1110, | ||
| "path": "licenses/clipper-BSL-1.0.txt", | ||
| "sha256": "32ee7398e3123736fd14e9f08287edc2d97ace102ab54d8dc4edc8d31c651fa8" | ||
| }, | ||
| { | ||
| "bytes": 1076, | ||
| "path": "licenses/nlohmann-json-MIT.txt", | ||
| "sha256": "86b998c792894ccb911a1cb7994f7a9652894e7a094c0b5e45be2f553f45cf14" | ||
| }, | ||
| { | ||
| "bytes": 1094, | ||
| "path": "licenses/onnxruntime-MIT.txt", | ||
| "sha256": "c250d6278f0b47a6439fb7592b08b58a55eb9f535aa49a1db63211c3f982b674" | ||
| }, | ||
| { | ||
| "bytes": 333022, | ||
| "path": "licenses/onnxruntime-ThirdPartyNotices.txt", | ||
| "sha256": "e00f828e0a33de591a355ae6606d2625f5758da7d2c844db7821c9dd3e3647b6" | ||
| }, | ||
| { | ||
| "bytes": 11358, | ||
| "path": "licenses/opencv-Apache-2.0.txt", | ||
| "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" | ||
| }, | ||
| { | ||
| "bytes": 733, | ||
| "path": "licenses/opencv-COPYRIGHT.txt", | ||
| "sha256": "bba849c98da85a2b27b86113284a90812c959b1c1fc4ed67de9355475d1e6831" | ||
| }, | ||
| { | ||
| "bytes": 2048, | ||
| "path": "licenses/opencv-carotene-BSD-3-Clause.txt", | ||
| "sha256": "0bccc9a19466df14bd38c8722cc1a692327f5db8f7a0f75f4162620e0e3be59a" | ||
| }, | ||
| { | ||
| "bytes": 1002, | ||
| "path": "licenses/opencv-zlib.txt", | ||
| "sha256": "845efc77857d485d91fb3e0b884aaa929368c717ae8186b66fe1ed2495753243" | ||
| }, | ||
| { | ||
| "bytes": 3588608, | ||
| "path": "native/light_ocr_node.node", | ||
| "sha256": "9d8928440ce20085220afc98c6d6f5f389b3b98d43cb2db3d53b9bb0e83badcc" | ||
| }, | ||
| { | ||
| "bytes": 12418080, | ||
| "path": "native/onnxruntime.dll", | ||
| "sha256": "579b636403983254346a5c1d80bd28f1519cd1e284cd204f8d4ff41f8d711559" | ||
| }, | ||
| { | ||
| "bytes": 860, | ||
| "path": "package.json", | ||
| "sha256": "a353cb5e45aed9a349dedce661e6c94e6effd14297f65980f4d61d0f4b3b68a5" | ||
| }, | ||
| { | ||
| "bytes": 4345, | ||
| "path": "sbom.spdx.json", | ||
| "sha256": "ba9b352bce512ef2951104437402dfab4d637378d6f61b0b20e44c184a8228aa" | ||
| } | ||
| ], | ||
| "package": "@arcships/light-ocr-win32-x64", | ||
| "schemaVersion": "1.0", | ||
| "version": "0.1.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: | ||
| (a) You must give any other recipients of the Work or | ||
| Derivative Works a copy of this License; and | ||
| (b) You must cause any modified files to carry prominent notices | ||
| stating that You changed the files; and | ||
| (c) 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 | ||
| (d) 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. |
| {"files":[{"component":"onnxruntime","file":"licenses/onnxruntime-MIT.txt","sha256":"c250d6278f0b47a6439fb7592b08b58a55eb9f535aa49a1db63211c3f982b674"},{"component":"onnxruntime","file":"licenses/onnxruntime-ThirdPartyNotices.txt","sha256":"e00f828e0a33de591a355ae6606d2625f5758da7d2c844db7821c9dd3e3647b6"},{"component":"opencv","file":"licenses/opencv-Apache-2.0.txt","sha256":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"},{"component":"opencv","file":"licenses/opencv-COPYRIGHT.txt","sha256":"bba849c98da85a2b27b86113284a90812c959b1c1fc4ed67de9355475d1e6831"},{"component":"zlib","file":"licenses/opencv-zlib.txt","sha256":"845efc77857d485d91fb3e0b884aaa929368c717ae8186b66fe1ed2495753243"},{"component":"clipper","file":"licenses/clipper-BSL-1.0.txt","sha256":"32ee7398e3123736fd14e9f08287edc2d97ace102ab54d8dc4edc8d31c651fa8"},{"component":"nlohmann-json","file":"licenses/nlohmann-json-MIT.txt","sha256":"86b998c792894ccb911a1cb7994f7a9652894e7a094c0b5e45be2f553f45cf14"},{"component":"PP-OCRv6-models","file":"licenses/PP-OCRv6-Apache-2.0.txt","sha256":"3840c5c0c61c294264d2dd77b8777be6ddd90121ef4e0e64abcd22edea581d6e"},{"component":"PP-OCRv6-models","file":"licenses/PP-OCRv6-MODEL-NOTICE.md","sha256":"381c555aebec730789e4f7a60583024ba7d7c026a5a223ac938c91767e4e91ff"},{"component":"carotene","file":"licenses/opencv-carotene-BSD-3-Clause.txt","sha256":"0bccc9a19466df14bd38c8722cc1a692327f5db8f7a0f75f4162620e0e3be59a"}],"schemaVersion":"1.0"} |
| The MIT License (MIT) | ||
| Copyright (c) 2015 Gregor Ratajc, Lukas Treyer, Maxime Chalton | ||
| 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. |
| MIT License | ||
| Copyright (c) 2013-2022 Niels Lohmann | ||
| 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. |
| MIT License | ||
| Copyright (c) Microsoft Corporation | ||
| 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. |
Sorry, the diff of this file is too big to display
| 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: | ||
| (a) You must give any other recipients of the Work or | ||
| Derivative Works a copy of this License; and | ||
| (b) You must cause any modified files to carry prominent notices | ||
| stating that You changed the files; and | ||
| (c) 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 | ||
| (d) 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. |
| /* | ||
| * By downloading, copying, installing or using the software you agree to this license. | ||
| * If you do not agree to this license, do not download, install, | ||
| * copy or use the software. | ||
| * | ||
| * | ||
| * License Agreement | ||
| * For Open Source Computer Vision Library | ||
| * (3-clause BSD License) | ||
| * | ||
| * Copyright (C) 2014-2015, NVIDIA Corporation, all rights reserved. | ||
| * Third party copyrights are property of their respective owners. | ||
| * | ||
| * Redistribution and use in source and binary forms, with or without modification, | ||
| * are permitted provided that the following conditions are met: | ||
| * | ||
| * * Redistributions of source code must retain the above copyright notice, | ||
| * this list of conditions and the following disclaimer. | ||
| * | ||
| * * Redistributions in binary form must reproduce the above copyright notice, | ||
| * this list of conditions and the following disclaimer in the documentation | ||
| * and/or other materials provided with the distribution. | ||
| * | ||
| * * Neither the names of the copyright holders nor the names of the contributors | ||
| * may be used to endorse or promote products derived from this software | ||
| * without specific prior written permission. | ||
| * | ||
| * This software is provided by the copyright holders and contributors "as is" and | ||
| * any express or implied warranties, including, but not limited to, the implied | ||
| * warranties of merchantability and fitness for a particular purpose are disclaimed. | ||
| * In no event shall copyright holders or contributors be liable for any direct, | ||
| * indirect, incidental, special, exemplary, or consequential damages | ||
| * (including, but not limited to, procurement of substitute goods or services; | ||
| * loss of use, data, or profits; or business interruption) however caused | ||
| * and on any theory of liability, whether in contract, strict liability, | ||
| * or tort (including negligence or otherwise) arising in any way out of | ||
| * the use of this software, even if advised of the possibility of such damage. | ||
| */ |
| Copyright (C) 2000-2022, Intel Corporation, all rights reserved. | ||
| Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. | ||
| Copyright (C) 2009-2016, NVIDIA Corporation, all rights reserved. | ||
| Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. | ||
| Copyright (C) 2015-2023, OpenCV Foundation, all rights reserved. | ||
| Copyright (C) 2008-2016, Itseez Inc., all rights reserved. | ||
| Copyright (C) 2019-2023, Xperience AI, all rights reserved. | ||
| Copyright (C) 2019-2022, Shenzhen Institute of Artificial Intelligence and Robotics for Society, all rights reserved. | ||
| Copyright (C) 2022-2023, Southern University of Science And Technology, all rights reserved. | ||
| Third party copyrights are property of their respective owners. |
| Copyright notice: | ||
| (C) 1995-2022 Jean-loup Gailly and Mark Adler | ||
| This software is provided 'as-is', without any express or implied | ||
| warranty. In no event will the authors be held liable for any damages | ||
| arising from the use of this software. | ||
| Permission is granted to anyone to use this software for any purpose, | ||
| including commercial applications, and to alter it and redistribute it | ||
| freely, subject to the following restrictions: | ||
| 1. The origin of this software must not be misrepresented; you must not | ||
| claim that you wrote the original software. If you use this software | ||
| in a product, an acknowledgment in the product documentation would be | ||
| appreciated but is not required. | ||
| 2. Altered source versions must be plainly marked as such, and must not be | ||
| misrepresented as being the original software. | ||
| 3. This notice may not be removed or altered from any source distribution. | ||
| Jean-loup Gailly Mark Adler | ||
| jloup@gzip.org madler@alumni.caltech.edu |
| 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: | ||
| (a) You must give any other recipients of the Work or | ||
| Derivative Works a copy of this License; and | ||
| (b) You must cause any modified files to carry prominent notices | ||
| stating that You changed the files; and | ||
| (c) 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 | ||
| (d) 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 (c) 2016 PaddlePaddle Authors. All Rights Reserved. | ||
| 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. |
| PP-OCRv6 small ONNX model bundle | ||
| PaddleOCR revision: b03f46425e8ff4442b268ce449e3eef758146cd4 | ||
| Detection model revision: 28fe5895c24fd108c19eb3e8479f4ab385fbfc62 | ||
| Recognition model revision: b8f84f0b80c529de40b4fbb3544b84fa7233a513 | ||
| Sources: official PaddlePaddle model ecology archives listed in bundles.lock.json |
| light-ocr | ||
| Copyright 2026 light-ocr contributors | ||
| This product includes software developed by the light-ocr contributors. | ||
| Third-party licenses and notices for packaged dependencies and model | ||
| artifacts are distributed with their respective release artifacts. |
| { | ||
| "bugs": { | ||
| "url": "https://github.com/arcships/light-ocr/issues" | ||
| }, | ||
| "cpu": [ | ||
| "x64" | ||
| ], | ||
| "description": "Native windows-x64 runtime for @arcships/light-ocr", | ||
| "engines": { | ||
| "node": "^22.0.0 || ^24.0.0" | ||
| }, | ||
| "exports": { | ||
| ".": "./native/light_ocr_node.node" | ||
| }, | ||
| "files": [ | ||
| "native/", | ||
| "licenses/", | ||
| "license-inventory.json", | ||
| "sbom.spdx.json", | ||
| "artifact-hashes.json", | ||
| "README.md", | ||
| "LICENSE", | ||
| "NOTICE" | ||
| ], | ||
| "homepage": "https://github.com/arcships/light-ocr#readme", | ||
| "license": "Apache-2.0", | ||
| "main": "./native/light_ocr_node.node", | ||
| "name": "@arcships/light-ocr-win32-x64", | ||
| "os": [ | ||
| "win32" | ||
| ], | ||
| "publishConfig": { | ||
| "access": "public", | ||
| "provenance": true | ||
| }, | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/arcships/light-ocr.git" | ||
| }, | ||
| "version": "0.1.0" | ||
| } |
| # @arcships/light-ocr-win32-x64 | ||
| The prebuilt windows-x64 native runtime for `@arcships/light-ocr`. | ||
| This is an internal distribution package for `@arcships/light-ocr`. Install | ||
| the facade package instead of depending on this package directly. | ||
| Documentation: https://github.com/arcships/light-ocr | ||
| License: Apache-2.0 |
| {"SPDXID":"SPDXRef-DOCUMENT","creationInfo":{"created":"2026-07-14T06:48:25Z","creators":["Tool: light-ocr-generate-release-metadata/1.0"]},"dataLicense":"CC0-1.0","documentDescribes":["SPDXRef-Package-light-ocr-core"],"documentNamespace":"https://light-ocr.invalid/spdx/8e5ffa2d5bb2eca5dae4ae58ca95db9a5615aaa4c09d0babd4dfb2abcae2b60b","name":"light-ocr-core-windows-x64","packages":[{"SPDXID":"SPDXRef-Package-light-ocr-core","copyrightText":"Copyright 2026 light-ocr contributors","downloadLocation":"NOASSERTION","filesAnalyzed":false,"licenseConcluded":"Apache-2.0","licenseDeclared":"Apache-2.0","name":"light-ocr-core","versionInfo":"0.1.0"},{"SPDXID":"SPDXRef-Package-onnxruntime","checksums":[{"algorithm":"SHA256","checksumValue":"d571e63a2329baacb713f441e65ad75284de354db6e1ac435fe4bebbb417986a"}],"copyrightText":"NOASSERTION","downloadLocation":"https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime/1.22.0/microsoft.ml.onnxruntime.1.22.0.nupkg","filesAnalyzed":false,"licenseConcluded":"MIT","licenseDeclared":"MIT","name":"onnxruntime","versionInfo":"1.22.0"},{"SPDXID":"SPDXRef-Package-opencv","checksums":[{"algorithm":"SHA256","checksumValue":"b2171af5be6b26f7a06b1229948bbb2bdaa74fcf5cd097e0af6378fce50a6eb9"}],"copyrightText":"NOASSERTION","downloadLocation":"https://codeload.github.com/opencv/opencv/tar.gz/refs/tags/4.10.0","filesAnalyzed":false,"licenseConcluded":"Apache-2.0","licenseDeclared":"Apache-2.0","name":"opencv","versionInfo":"4.10.0"},{"SPDXID":"SPDXRef-Package-opencv-zlib","copyrightText":"NOASSERTION","downloadLocation":"https://codeload.github.com/opencv/opencv/tar.gz/refs/tags/4.10.0","filesAnalyzed":false,"licenseConcluded":"Zlib","licenseDeclared":"Zlib","name":"zlib","versionInfo":"1.3.1"},{"SPDXID":"SPDXRef-Package-opencv-carotene","copyrightText":"NOASSERTION","downloadLocation":"https://codeload.github.com/opencv/opencv/tar.gz/refs/tags/4.10.0","filesAnalyzed":false,"licenseConcluded":"BSD-3-Clause","licenseDeclared":"BSD-3-Clause","name":"carotene","versionInfo":"0.0.1"},{"SPDXID":"SPDXRef-Package-clipper","checksums":[{"algorithm":"SHA256","checksumValue":"2be14496a1609fa8602d9d3672c83ee95d5ef44a08b765a60e65b93a68882ff6"}],"copyrightText":"NOASSERTION","downloadLocation":"https://codeload.github.com/fonttools/pyclipper/tar.gz/refs/tags/1.3.0.post6","filesAnalyzed":false,"licenseConcluded":"BSL-1.0","licenseDeclared":"BSL-1.0","name":"clipper","versionInfo":"6.4.2-pyclipper-1.3.0.post6"},{"SPDXID":"SPDXRef-Package-nlohmann-json","checksums":[{"algorithm":"SHA256","checksumValue":"0d8ef5af7f9794e3263480193c491549b2ba6cc74bb018906202ada498a79406"}],"copyrightText":"NOASSERTION","downloadLocation":"https://codeload.github.com/nlohmann/json/tar.gz/refs/tags/v3.11.3","filesAnalyzed":false,"licenseConcluded":"MIT","licenseDeclared":"MIT","name":"nlohmann-json","versionInfo":"3.11.3"},{"SPDXID":"SPDXRef-Package-PP-OCRv6-small-models","checksums":[{"algorithm":"SHA256","checksumValue":"74e246bf075c141da51e58515c731298fdabee9fd5bd8feb7cf6c7f4f352de17"}],"copyrightText":"NOASSERTION","downloadLocation":"https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-OCRv6_small_det_onnx_infer.tar","filesAnalyzed":false,"licenseConcluded":"Apache-2.0","licenseDeclared":"Apache-2.0","name":"PP-OCRv6-small-ONNX-models","versionInfo":"ppocrv6-small-onnx-20260714.1"}],"relationships":[{"relatedSpdxElement":"SPDXRef-Package-onnxruntime","relationshipType":"DEPENDS_ON","spdxElementId":"SPDXRef-Package-light-ocr-core"},{"relatedSpdxElement":"SPDXRef-Package-opencv","relationshipType":"DEPENDS_ON","spdxElementId":"SPDXRef-Package-light-ocr-core"},{"relatedSpdxElement":"SPDXRef-Package-opencv-zlib","relationshipType":"CONTAINS","spdxElementId":"SPDXRef-Package-opencv"},{"relatedSpdxElement":"SPDXRef-Package-opencv-carotene","relationshipType":"CONTAINS","spdxElementId":"SPDXRef-Package-opencv"},{"relatedSpdxElement":"SPDXRef-Package-clipper","relationshipType":"DEPENDS_ON","spdxElementId":"SPDXRef-Package-light-ocr-core"},{"relatedSpdxElement":"SPDXRef-Package-nlohmann-json","relationshipType":"DEPENDS_ON","spdxElementId":"SPDXRef-Package-light-ocr-core"},{"relatedSpdxElement":"SPDXRef-Package-PP-OCRv6-small-models","relationshipType":"DEPENDS_ON","spdxElementId":"SPDXRef-Package-light-ocr-core"}],"spdxVersion":"SPDX-2.3"} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
| MIT License | ||
| Copyright (c) 2024 CloudPDF, Ji Chang | ||
| 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. |
| Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Noto Sans'. | ||
| Copyright 2014-2021 Google Inc (http://www.google.com/), with Reserved Font Name 'Noto Sans'. | ||
| This Font Software is licensed under the SIL Open Font License, Version 1.1. | ||
| This license is copied below, and is also available with a FAQ at: | ||
| http://scripts.sil.org/OFL | ||
| ----------------------------------------------------------- | ||
| SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 | ||
| ----------------------------------------------------------- | ||
| PREAMBLE | ||
| The goals of the Open Font License (OFL) are to stimulate worldwide | ||
| development of collaborative font projects, to support the font creation | ||
| efforts of academic and linguistic communities, and to provide a free and | ||
| open framework in which fonts may be shared and improved in partnership | ||
| with others. | ||
| The OFL allows the licensed fonts to be used, studied, modified and | ||
| redistributed freely as long as they are not sold by themselves. The | ||
| fonts, including any derivative works, can be bundled, embedded, | ||
| redistributed and/or sold with any software provided that any reserved | ||
| names are not used by derivative works. The fonts and derivatives, | ||
| however, cannot be released under any other type of license. The | ||
| requirement for fonts to remain under this license does not apply | ||
| to any document created using the fonts or their derivatives. | ||
| DEFINITIONS | ||
| "Font Software" refers to the set of files released by the Copyright | ||
| Holder(s) under this license and clearly marked as such. This may | ||
| include source files, build scripts and documentation. | ||
| "Reserved Font Name" refers to any names specified as such after the | ||
| copyright statement(s). | ||
| "Original Version" refers to the collection of Font Software components as | ||
| distributed by the Copyright Holder(s). | ||
| "Modified Version" refers to any derivative made by adding to, deleting, | ||
| or substituting -- in part or in whole -- any of the components of the | ||
| Original Version, by changing formats or by porting the Font Software to a | ||
| new environment. | ||
| "Author" refers to any designer, engineer, programmer, technical | ||
| writer or other person who contributed to the Font Software. | ||
| PERMISSION & CONDITIONS | ||
| Permission is hereby granted, free of charge, to any person obtaining | ||
| a copy of the Font Software, to use, study, copy, merge, embed, modify, | ||
| redistribute, and sell modified and unmodified copies of the Font | ||
| Software, subject to the following conditions: | ||
| 1) Neither the Font Software nor any of its individual components, | ||
| in Original or Modified Versions, may be sold by itself. | ||
| 2) Original or Modified Versions of the Font Software may be bundled, | ||
| redistributed and/or sold with any software, provided that each copy | ||
| contains the above copyright notice and this license. These can be | ||
| included either as stand-alone text files, human-readable headers or | ||
| in the appropriate machine-readable metadata fields within text or | ||
| binary files as long as those fields can be easily viewed by the user. | ||
| 3) No Modified Version of the Font Software may use the Reserved Font | ||
| Name(s) unless explicit written permission is granted by the corresponding | ||
| Copyright Holder. This restriction only applies to the primary font name as | ||
| presented to the users. | ||
| 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font | ||
| Software shall not be used to promote, endorse or advertise any | ||
| Modified Version, except to acknowledge the contribution(s) of the | ||
| Copyright Holder(s) and the Author(s) or with their explicit written | ||
| permission. | ||
| 5) The Font Software, modified or unmodified, in part or in whole, | ||
| must be distributed entirely under this license, and must not be | ||
| distributed under any other license. The requirement for fonts to | ||
| remain under this license does not apply to any document created | ||
| using the Font Software. | ||
| TERMINATION | ||
| This license becomes null and void if any of the above conditions are | ||
| not met. | ||
| DISCLAIMER | ||
| THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
| EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF | ||
| MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT | ||
| OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE | ||
| COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | ||
| INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL | ||
| DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | ||
| FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM | ||
| OTHER DEALINGS IN THE FONT SOFTWARE. |
| // Copyright 2014 PDFium Authors. All rights reserved. | ||
| // | ||
| // Redistribution and use in source and binary forms, with or without | ||
| // modification, are permitted provided that the following conditions are | ||
| // met: | ||
| // | ||
| // * Redistributions of source code must retain the above copyright | ||
| // notice, this list of conditions and the following disclaimer. | ||
| // * Redistributions in binary form must reproduce the above | ||
| // copyright notice, this list of conditions and the following disclaimer | ||
| // in the documentation and/or other materials provided with the | ||
| // distribution. | ||
| // * Neither the name of Google Inc. nor the names of its | ||
| // contributors may be used to endorse or promote products derived from | ||
| // this software without specific prior written permission. | ||
| // | ||
| // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | ||
| // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | ||
| // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | ||
| // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | ||
| // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ||
| // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | ||
| // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | ||
| // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | ||
| // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | ||
| // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
| // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
| Apache License | ||
| Version 2.0, January 2004 | ||
| https://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: | ||
| (a) You must give any other recipients of the Work or | ||
| Derivative Works a copy of this License; and | ||
| (b) You must cause any modified files to carry prominent notices | ||
| stating that You changed the files; and | ||
| (c) 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 | ||
| (d) 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 | ||
| 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. |
| { | ||
| "version": 1, | ||
| "runtimeId": "pdfium", | ||
| "pdfiumVersion": "2.14.4", | ||
| "enginesVersion": "2.14.4", | ||
| "wasm": { | ||
| "path": "pdfium.wasm", | ||
| "size": 4633788, | ||
| "sha256": "c0af5a6aca30d7e54a149c3a68e317116ca906d6edc28fd3318b12c7d9478ac8" | ||
| }, | ||
| "fonts": [ | ||
| { | ||
| "package": "@embedpdf/fonts-latin", | ||
| "version": "1.0.0", | ||
| "path": "fonts/NotoSans-Regular.ttf", | ||
| "charsets": [ | ||
| "DEFAULT", | ||
| "ANSI", | ||
| "GREEK", | ||
| "VIETNAMESE", | ||
| "CYRILLIC", | ||
| "EASTERNEUROPEAN" | ||
| ], | ||
| "size": 629024, | ||
| "sha256": "fe8c022f48d8dd29f17b744d16f9346f4357e16f7d4f7be58b000ae7c291b614" | ||
| }, | ||
| { | ||
| "package": "@embedpdf/fonts-sc", | ||
| "version": "1.0.0", | ||
| "path": "fonts/NotoSansHans-Regular.otf", | ||
| "charsets": [ | ||
| "GB2312" | ||
| ], | ||
| "size": 8364644, | ||
| "sha256": "7db3c634bbd0301b3082a80ffcac2f422e8ef9ce0730f8b279c3e8f756598f68" | ||
| }, | ||
| { | ||
| "package": "@embedpdf/fonts-tc", | ||
| "version": "1.0.0", | ||
| "path": "fonts/NotoSansHant-Regular.otf", | ||
| "charsets": [ | ||
| "CHINESEBIG5" | ||
| ], | ||
| "size": 5663120, | ||
| "sha256": "81f39cffba8b45367a21249720782603b852bee71aad710f8f66fec3d3776af3" | ||
| }, | ||
| { | ||
| "package": "@embedpdf/fonts-jp", | ||
| "version": "1.0.0", | ||
| "path": "fonts/NotoSansJP-Regular.otf", | ||
| "charsets": [ | ||
| "SHIFTJIS" | ||
| ], | ||
| "size": 4538888, | ||
| "sha256": "dcc75e20d91d09c793fa5a97c9c7678e8b580d0fc255314cbc45c08b075f46f1" | ||
| }, | ||
| { | ||
| "package": "@embedpdf/fonts-kr", | ||
| "version": "1.0.0", | ||
| "path": "fonts/NotoSansKR-Regular.otf", | ||
| "charsets": [ | ||
| "HANGEUL" | ||
| ], | ||
| "size": 4579008, | ||
| "sha256": "ff59f91fe8d6e6246f548bb67bf371810af3d5cc53b65e8680461fabd043b506" | ||
| }, | ||
| { | ||
| "package": "@embedpdf/fonts-arabic", | ||
| "version": "1.0.0", | ||
| "path": "fonts/NotoNaskhArabic-Regular.ttf", | ||
| "charsets": [ | ||
| "ARABIC" | ||
| ], | ||
| "size": 134028, | ||
| "sha256": "45664d3913368eb216be981969ed383e31143cef790ae803afd4f69b87d7923b" | ||
| }, | ||
| { | ||
| "package": "@embedpdf/fonts-hebrew", | ||
| "version": "1.0.0", | ||
| "path": "fonts/NotoSansHebrew-Regular.ttf", | ||
| "charsets": [ | ||
| "HEBREW" | ||
| ], | ||
| "size": 25744, | ||
| "sha256": "898ed1f83dcebdd4d9abcfc9aa4582fb36f2eeb704a3dcbb588ce01132a40f13" | ||
| } | ||
| ], | ||
| "inventory": [ | ||
| { | ||
| "path": "fonts/NotoNaskhArabic-Regular.ttf", | ||
| "size": 134028, | ||
| "sha256": "45664d3913368eb216be981969ed383e31143cef790ae803afd4f69b87d7923b" | ||
| }, | ||
| { | ||
| "path": "fonts/NotoSans-Regular.ttf", | ||
| "size": 629024, | ||
| "sha256": "fe8c022f48d8dd29f17b744d16f9346f4357e16f7d4f7be58b000ae7c291b614" | ||
| }, | ||
| { | ||
| "path": "fonts/NotoSansHans-Regular.otf", | ||
| "size": 8364644, | ||
| "sha256": "7db3c634bbd0301b3082a80ffcac2f422e8ef9ce0730f8b279c3e8f756598f68" | ||
| }, | ||
| { | ||
| "path": "fonts/NotoSansHant-Regular.otf", | ||
| "size": 5663120, | ||
| "sha256": "81f39cffba8b45367a21249720782603b852bee71aad710f8f66fec3d3776af3" | ||
| }, | ||
| { | ||
| "path": "fonts/NotoSansHebrew-Regular.ttf", | ||
| "size": 25744, | ||
| "sha256": "898ed1f83dcebdd4d9abcfc9aa4582fb36f2eeb704a3dcbb588ce01132a40f13" | ||
| }, | ||
| { | ||
| "path": "fonts/NotoSansJP-Regular.otf", | ||
| "size": 4538888, | ||
| "sha256": "dcc75e20d91d09c793fa5a97c9c7678e8b580d0fc255314cbc45c08b075f46f1" | ||
| }, | ||
| { | ||
| "path": "fonts/NotoSansKR-Regular.otf", | ||
| "size": 4579008, | ||
| "sha256": "ff59f91fe8d6e6246f548bb67bf371810af3d5cc53b65e8680461fabd043b506" | ||
| }, | ||
| { | ||
| "path": "licenses/EmbedPDF-MIT.txt", | ||
| "size": 1075, | ||
| "sha256": "f5031b66adba8ef5ef57666deff980a7f2ccff5c8a8c22a8117e854d2b8dfcd3" | ||
| }, | ||
| { | ||
| "path": "licenses/Noto-OFL-1.1.txt", | ||
| "size": 4484, | ||
| "sha256": "cea028c0b5185b804ae79f1eab96ca5ee469d61d44925972a2379430890bbec1" | ||
| }, | ||
| { | ||
| "path": "licenses/PDFium-Apache-2.0.txt", | ||
| "size": 12880, | ||
| "sha256": "b033ffb8fc19c23ca81f7e98019ab658cc6f4cf14587c7c6a2a67fb0f6ac0f5a" | ||
| }, | ||
| { | ||
| "path": "pdfium.wasm", | ||
| "size": 4633788, | ||
| "sha256": "c0af5a6aca30d7e54a149c3a68e317116ca906d6edc28fd3318b12c7d9478ac8" | ||
| }, | ||
| { | ||
| "path": "sbom/components.json", | ||
| "size": 742, | ||
| "sha256": "2a839a5926684910919733c05222ac7f922ab9251df1027017998c89068258d6" | ||
| } | ||
| ] | ||
| } |
Sorry, the diff of this file is not supported yet
| { | ||
| "format": "dim-runtime-components-v1", | ||
| "components": [ | ||
| { | ||
| "name": "@embedpdf/pdfium", | ||
| "version": "2.14.4" | ||
| }, | ||
| { | ||
| "name": "@embedpdf/engines", | ||
| "version": "2.14.4" | ||
| }, | ||
| { | ||
| "name": "@embedpdf/fonts-latin", | ||
| "version": "1.0.0" | ||
| }, | ||
| { | ||
| "name": "@embedpdf/fonts-sc", | ||
| "version": "1.0.0" | ||
| }, | ||
| { | ||
| "name": "@embedpdf/fonts-tc", | ||
| "version": "1.0.0" | ||
| }, | ||
| { | ||
| "name": "@embedpdf/fonts-jp", | ||
| "version": "1.0.0" | ||
| }, | ||
| { | ||
| "name": "@embedpdf/fonts-kr", | ||
| "version": "1.0.0" | ||
| }, | ||
| { | ||
| "name": "@embedpdf/fonts-arabic", | ||
| "version": "1.0.0" | ||
| }, | ||
| { | ||
| "name": "@embedpdf/fonts-hebrew", | ||
| "version": "1.0.0" | ||
| } | ||
| ] | ||
| } |
+1
-1
| { | ||
| "name": "dimcode-windows-x64", | ||
| "version": "0.2.31", | ||
| "version": "0.2.33-beta.0", | ||
| "description": "dimcode binary for Windows x64", | ||
@@ -5,0 +5,0 @@ "os": [ |
Sorry, the diff of this file is not supported yet
Install scripts
Supply chain riskInstall scripts are run when the package is installed or built. Malicious packages often use scripts that run automatically to execute payloads or fetch additional code.
Native code
Supply chain riskContains native code (e.g., compiled binaries or shared libraries). Including native code can obscure malicious behavior.
Shell access
Supply chain riskThis module accesses the system shell. Accessing the system shell increases the risk of executing arbitrary code.
Found 2 instances
Copyleft License
LicenseCopyleft license information was found.
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 7 instances
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 2 instances
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Mixed license
LicensePackage contains multiple licenses.
Non-permissive License
LicenseA license not known to be considered permissive was found.
Unidentified License
LicenseSomething that seems like a license was found, but its contents could not be matched with a known license.
Found 4 instances
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Mixed license
LicensePackage contains multiple licenses.
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
248137625
65.01%472
53.75%49651
42.24%7
600%70
-30%1
Infinity%86
30.3%29
38.1%