text: "use strict";
  
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  
  exports.__esModule = true;
  exports.getImageMetadata = getImageMetadata;
  exports.generateImageData = generateImageData;
  
  var _utils = require("./utils");
  
  var _ = require(".");
  
  var _safeSharp = _interopRequireDefault(require("./safe-sharp"));
  
  var _pluginOptions = require("./plugin-options");
  
  /* eslint-disable no-unused-expressions */
  const DEFAULT_BLURRED_IMAGE_WIDTH = 20;
  const metadataCache = new Map();
  
  async function getImageMetadata(file, getDominantColor) {
    if (!getDominantColor) {
      // If we don't need the dominant color we can use the cheaper size function
      const {
        width,
        height,
        type
      } = await (0, _.getImageSizeAsync)(file);
      return {
        width,
        height,
        format: type
      };
    }
  
    let metadata = metadataCache.get(file.internal.contentDigest);
  
    if (metadata && process.env.NODE_ENV !== `test`) {
      return metadata;
    }
  
    const pipeline = (0, _safeSharp.default)(file.absolutePath);
    const {
      width,
      height,
      density,
      format
    } = await pipeline.metadata();
    const {
      dominant
    } = await pipeline.stats(); // Fallback in case sharp doesn't support dominant
  
    const dominantColor = dominant ? (0, _utils.rgbToHex)(dominant.r, dominant.g, dominant.b) : `#000000`;
    metadata = {
      width,
      height,
      density,
      format,
      dominantColor
    };
    metadataCache.set(file.internal.contentDigest, metadata);
    return metadata;
  }
  
  function normalizeFormat(format) {
    if (format === `jpeg`) {
      return `jpg`;
    }
  
    return format;
  }
  
  async function generateImageData({
    file,
    args,
    pathPrefix,
    reporter,
    cache
  }) {
    const {
      layout = `constrained`,
      placeholder = `blurred`,
      tracedSVGOptions = {},
      transformOptions = {},
      quality
    } = args;
    args.formats = args.formats || [`auto`, `webp`];
    const {
      fit = `cover`,
      cropFocus = _safeSharp.default.strategy.attention
    } = transformOptions;
    const metadata = await getImageMetadata(file, placeholder === `dominantColor`);
  
    if (layout === `fixed` && !args.width && !args.height) {
      args.width = metadata.width;
    }
  
    if (layout !== `fixed` && !args.maxWidth && !args.maxHeight && metadata.width) {
      if (layout === `constrained`) {
        args.maxWidth = metadata.width;
      } else if (layout === `fluid`) {
        args.maxWidth = Math.round(metadata.width / 2);
      }
    }
  
    const formats = new Set(args.formats);
    let useAuto = formats.has(``) || formats.has(`auto`) || formats.size === 0;
  
    if (formats.has(`jpg`) && formats.has(`png`)) {
      reporter.warn(`Specifying both "jpg" and "png" formats is not supported and will be ignored. Please use "auto" instead.`);
      useAuto = true;
    }
  
    let primaryFormat;
  
    if (useAuto) {
      primaryFormat = normalizeFormat(metadata.format || file.extension);
    } else if (formats.has(`png`)) {
      primaryFormat = `png`;
    } else if (formats.has(`jpg`)) {
      primaryFormat = `jpg`;
    } else if (formats.has(`webp`)) {
      primaryFormat = `webp`;
    } else if (formats.has(`avif`)) {
      reporter.warn(`Image ${file.relativePath} specified only AVIF format, with no fallback format. This will mean your site cannot be viewed in all browsers.`);
      primaryFormat = `avif`;
    }
  
    const optionsMap = {
      jpg: args.jpgOptions,
      png: args.pngOptions,
      webp: args.webpOptions,
      avif: args.avifOptions
    };
    const options = primaryFormat ? optionsMap[primaryFormat] : undefined;
    const imageSizes = (0, _utils.calculateImageSizes)({
      file,
      layout,
      ...args,
      imgDimensions: metadata,
      reporter
    });
    const transforms = imageSizes.sizes.map(outputWidth => {
      const width = Math.round(outputWidth);
      const transform = (0, _pluginOptions.createTransformObject)({
        quality,
        ...transformOptions,
        fit,
        cropFocus,
        ...options,
        tracedSVGOptions,
        width,
        height: Math.round(width / imageSizes.aspectRatio),
        toFormat: primaryFormat
      });
  
      if (pathPrefix) {
        transform.pathPrefix = pathPrefix;
      }
  
      return transform;
    });
    const images = (0, _.batchQueueImageResizing)({
      file,
      transforms,
      reporter
    });
    const srcSet = (0, _utils.getSrcSet)(images);
    const sizes = args.sizes || (0, _utils.getSizes)(imageSizes.unscaledWidth, layout);
    const primaryIndex = imageSizes.sizes.findIndex(size => size === imageSizes.unscaledWidth);
  
    if (primaryIndex === -1) {
      reporter.error(`No image of the specified size found. Images may not have been processed correctly.`);
      return undefined;
    }
  
    const primaryImage = images[primaryIndex];
  
    if (!(images === null || images === void 0 ? void 0 : images.length)) {
      return undefined;
    }
  
    const imageProps = {
      layout,
      placeholder: undefined,
      images: {
        fallback: {
          src: primaryImage.src,
          srcSet,
          sizes
        },
        sources: []
      }
    };
  
    if (primaryFormat !== `avif` && formats.has(`avif`)) {
      var _imageProps$images$so;
  
      const transforms = imageSizes.sizes.map(outputWidth => {
        const width = Math.round(outputWidth);
        const transform = (0, _pluginOptions.createTransformObject)({
          quality,
          ...transformOptions,
          fit,
          cropFocus,
          ...args.avifOptions,
          width,
          height: Math.round(width / imageSizes.aspectRatio),
          toFormat: `avif`
        });
  
        if (pathPrefix) {
          transform.pathPrefix = pathPrefix;
        }
  
        return transform;
      });
      const avifImages = (0, _.batchQueueImageResizing)({
        file,
        transforms,
        reporter
      });
      (_imageProps$images$so = imageProps.images.sources) === null || _imageProps$images$so === void 0 ? void 0 : _imageProps$images$so.push({
        srcSet: (0, _utils.getSrcSet)(avifImages),
        type: `image/avif`,
        sizes
      });
    }
  
    if (primaryFormat !== `webp` && formats.has(`webp`)) {
      var _imageProps$images$so2;
  
      const transforms = imageSizes.sizes.map(outputWidth => {
        const width = Math.round(outputWidth);
        const transform = (0, _pluginOptions.createTransformObject)({
          quality,
          ...transformOptions,
          fit,
          cropFocus,
          ...args.webpOptions,
          width,
          height: Math.round(width / imageSizes.aspectRatio),
          toFormat: `webp`
        });
  
        if (pathPrefix) {
          transform.pathPrefix = pathPrefix;
        }
  
        return transform;
      });
      const webpImages = (0, _.batchQueueImageResizing)({
        file,
        transforms,
        reporter
      });
      (_imageProps$images$so2 = imageProps.images.sources) === null || _imageProps$images$so2 === void 0 ? void 0 : _imageProps$images$so2.push({
        srcSet: (0, _utils.getSrcSet)(webpImages),
        type: `image/webp`,
        sizes
      });
    }
  
    if (placeholder === `blurred`) {
      var _args$blurredOptions, _args$blurredOptions2;
  
      const placeholderWidth = ((_args$blurredOptions = args.blurredOptions) === null || _args$blurredOptions === void 0 ? void 0 : _args$blurredOptions.width) || DEFAULT_BLURRED_IMAGE_WIDTH;
      const {
        src: fallback
      } = await (0, _.base64)({
        file,
        args: { ...options,
          ...transformOptions,
          fit,
          cropFocus,
          toFormatBase64: (_args$blurredOptions2 = args.blurredOptions) === null || _args$blurredOptions2 === void 0 ? void 0 : _args$blurredOptions2.toFormat,
          width: placeholderWidth,
          height: Math.round(placeholderWidth / imageSizes.aspectRatio)
        },
        reporter
      });
      imageProps.placeholder = {
        fallback
      };
    } else if (placeholder === `tracedSVG`) {
      const fallback = await (0, _.traceSVG)({
        file,
        args: tracedSVGOptions,
        fileArgs: args,
        cache,
        reporter
      });
      imageProps.placeholder = {
        fallback
      };
    } else if (metadata.dominantColor) {
      imageProps.backgroundColor = metadata.dominantColor;
    }
  
    primaryImage.aspectRatio = primaryImage.aspectRatio || 1;
  
    switch (layout) {
      case `fixed`:
        imageProps.width = imageSizes.presentationWidth;
        imageProps.height = imageSizes.presentationHeight;
        break;
  
      case `fluid`:
        imageProps.width = 1;
        imageProps.height = 1 / primaryImage.aspectRatio;
        break;
  
      case `constrained`:
        imageProps.width = args.maxWidth || primaryImage.width || 1;
        imageProps.height = (imageProps.width || 1) / primaryImage.aspectRatio;
    }
  
    return imageProps;
  }