{"version":3,"file":"lens.umd.cjs","sources":["../src/color-interpolator/AverageInterpolator.ts","../src/color-interpolator/BackgroundInterpolator.ts","../src/color-interpolator/IntegerInterpolator.ts","../src/color-interpolator/InterpolationMethod.ts","../src/color-interpolator/BaseColorInterpolatorFactory.ts","../src/color-resampler/BaseColorResamplerResolver.ts","../src/color-resampler/ColorResampler.ts","../src/pixel-accessor/virtual-pixel-decorator/AbstractVirtualPixelDecorator.ts","../src/pixel-accessor/virtual-pixel-decorator/BackgroundVirtualPixel.ts","../src/pixel-accessor/virtual-pixel-decorator/ConstantVirtualPixel.ts","../src/pixel-accessor/virtual-pixel-decorator/EdgeVirtualPixel.ts","../src/pixel-accessor/virtual-pixel-decorator/HorizontalTileEdgeVirtualPixel.ts","../src/pixel-accessor/virtual-pixel-decorator/HorizontalTileVirtualPixel.ts","../src/pixel-accessor/virtual-pixel-decorator/MirrorVirtualPixel.ts","../src/pixel-accessor/virtual-pixel-decorator/RandomVirtualPixel.ts","../src/pixel-accessor/virtual-pixel-decorator/TileVirtualPixel.ts","../src/pixel-accessor/virtual-pixel-decorator/VerticalTileEdgeVirtualPixel.ts","../src/pixel-accessor/virtual-pixel-decorator/VerticalTileVirtualPixel.ts","../src/pixel-accessor/VirtualPixelMethod.ts","../src/pixel-accessor/BaseVirtualPixelDecoratorApplicator.ts","../src/pixel-accessor/HasAverageColor.ts","../src/pixel-accessor/HasBackgroundColor.ts","../src/pixel-accessor/PixelAccessor.ts","../src/pixel-accessor/PixelAccessorWithDimensions.ts","../src/pixel-accessor/Viewport.ts","../src/pixel-accessor/VirtualViewportPixelAccessor.ts","../src/color-resampler/EwaColorResampler.ts","../src/constants.ts","../src/utils/blendColors.ts","../src/utils/createDeferred.ts","../src/utils/degreesToRadians.ts","../src/utils/perceptibleReciprocal.ts","../src/utils/gaussJordanElimination.ts","../src/utils/LeastSquares.ts","../src/utils/makeCanvas.ts","../src/utils/preloadHtmlImage.ts","../src/exception/LensException.ts","../src/exception/AbortException.ts","../src/exception/InvalidArgument.ts","../src/exception/InvalidArgumentsLength.ts","../src/pixel-mapper/distortions/affine/Affine.ts","../src/pixel-mapper/distortions/affine/AffineFactory.ts","../src/pixel-mapper/distortions/affine/AffineProjectionFactory.ts","../src/pixel-mapper/distortions/arc/Arc.ts","../src/pixel-mapper/distortions/arc/ArcFactory.ts","../src/pixel-mapper/distortions/perspective/Perspective.ts","../src/pixel-mapper/distortions/perspective/PerspectiveFactory.ts","../src/pixel-mapper/distortions/perspective/PerspectiveProjectionFactory.ts","../src/pixel-mapper/distortions/polynomial/Polynomial.ts","../src/pixel-mapper/BaseReversePixelMapperResolver.ts","../src/pixel-mapper/ReversePixelMapper.ts","../src/pixel-mapper/BestFitReversePixelMapper.ts","../src/pixel-mapper/Distortion.ts","../src/pixel-mapper/EwaReversePixelMapper.ts","../src/color-resampler/EwaResampler.ts","../src/color-resampler/EwaResamplerFactory.ts","../src/color-resampler/PointResampler.ts","../src/color-resampler/PointResamplerFactory.ts","../src/color-string-parser/CompositeColorStringParser.ts","../src/color-string-parser/HexColorStringParser.ts","../src/types/Color.ts","../src/types/Point.ts","../src/color-string-parser/RgbaColorStringParser.ts","../src/color-string-parser/TransparentStringParser.ts","../src/distortion-processing/ReversePixelMappingProcessor.ts","../src/distortion-processing/SuperSamplingProxy.ts","../src/image-adapter/AbstractImageAdapter.ts","../src/image-adapter/BaseImageAdapterResolver.ts","../src/image-adapter/Canvas.ts","../src/image-adapter/CanvasFactory.ts","../src/image-adapter/ImageAdapter.ts","../src/image-adapter/VirtualViewportProxy.ts","../src/distortion-processing/RepageProxy.ts","../src/distortion-processing/BaseDistortionProcessorFactory.ts","../src/distortion-processing/DistortionController.ts","../src/distortion-processing/DistortionService.ts","../src/output-viewport-strategy/BaseOutputViewportResolver.ts","../src/output-viewport-strategy/BestFitViewport.ts","../src/output-viewport-strategy/SourceImageViewport.ts","../src/output-viewport-strategy/UserProvidedViewport.ts","../src/pool/BasePool.ts","../src/resample-filter/BaseResampleFilter.ts","../src/resample-filter/BaseResampleFilterFactory.ts","../src/resample-filter/ResampleFilter.ts","../src/resample-filter/ResampleFilterPreset.ts","../src/resample-filter/BaseResampleFilterResolver.ts","../src/resample-filter/FilterName.ts","../src/service-container/BaseServiceContainer.ts","../src/weighting-function/BoxFactory.ts","../src/weighting-function/CubicBCFactory.ts","../src/weighting-function/WeightingFunctionName.ts","../src/color-resampler/colorResamplerProvider.ts","../src/serviceContainer.ts","../src/service-container/createServiceContainer.ts","../src/color-string-parser/colorStringParserProvider.ts","../src/distortion-processing/distortionProcessingProvider.ts","../src/image-adapter/imageAdapterProvider.ts","../src/output-viewport-strategy/outputViewportStrategyProvider.ts","../src/pixel-mapper/pixelMappingProvider.ts","../src/resample-filter/resampleFilterProvider.ts","../src/weighting-function/weightingFunctionProvider.ts","../src/color-interpolator/colorInterpolationProvider.ts","../src/pixel-accessor/pixelAccessorProvider.ts","../src/exception/InvalidMethodCall.ts","../src/version.ts","../src/distort.ts","../src/distortUnwrap.ts","../src/utils/toHTMLCanvasElement.ts"],"sourcesContent":["import type { PixelAccessor } from \"../pixel-accessor\";\nimport type { Color } from \"../types\";\nimport type { ColorInterpolator } from \"./ColorInterpolator\";\n\n/**\n * Average color interpolation by 4, 9 or 16 nearest neighbors.\n */\nexport class AverageInterpolator implements ColorInterpolator {\n  /**\n   * AverageInterpolator constructor.\n   *\n   * @param neighborsCount Neighbors count per each dimension\n   */\n  constructor(private neighborsCount: 2 | 3 | 4) {\n    if (![2, 3, 4].includes(this.neighborsCount)) {\n      throw new RangeError(\n        `Neighbors count must be 2, 3 or 4. ${this.neighborsCount} given`\n      );\n    }\n  }\n\n  /**\n   * @inheritDoc\n   */\n  interpolate(image: PixelAccessor, x: number, y: number): Color {\n    let startX, startY;\n    const count = this.neighborsCount;\n\n    switch (count) {\n      case 2:\n        startX = Math.floor(x);\n        startY = Math.floor(y);\n        break;\n\n      case 3:\n        startX = Math.floor(x + 0.5) - 1;\n        startY = Math.floor(y + 0.5) - 1;\n        break;\n      case 4:\n        startX = Math.floor(x) - 1;\n        startY = Math.floor(y) - 1;\n        break;\n    }\n\n    const endX = startX + count;\n    const endY = startY + count;\n    const color = [0, 0, 0, 0];\n\n    for (let v = startY; v < endY; v++) {\n      for (let u = startX; u < endX; u++) {\n        const pixelColor = image.getPixelColor(u, v);\n        color[0] += pixelColor[0];\n        color[1] += pixelColor[1];\n        color[2] += pixelColor[2];\n        color[3] += pixelColor[3];\n      }\n    }\n\n    const gamma = 1 / (count * count);\n\n    return [\n      Math.round(color[0] * gamma),\n      Math.round(color[1] * gamma),\n      Math.round(color[2] * gamma),\n      Math.round(color[3] * gamma),\n    ];\n  }\n}\n","import type { HasBackgroundColor } from \"../pixel-accessor\";\nimport type { Color } from \"../types\";\nimport type { ColorInterpolator } from \"./ColorInterpolator\";\n\n/**\n * Background Color interpolator. Used for debugging EWA failures.\n */\nexport class BackgroundInterpolator implements ColorInterpolator {\n  /**\n   * Returns image background color.\n   *\n   * @param image\n   */\n  interpolate(image: HasBackgroundColor): Color {\n    return image.getBackgroundColor();\n  }\n}\n","import type { PixelAccessor } from \"../pixel-accessor\";\nimport type { Color } from \"../types\";\nimport type { ColorInterpolator } from \"./ColorInterpolator\";\n\n/**\n * No interpolation -- just returns single pixel color.\n */\nexport class IntegerInterpolator implements ColorInterpolator {\n  /**\n   * @inheritDoc\n   */\n  interpolate(image: PixelAccessor, x: number, y: number): Color {\n    return image.getPixelColor(Math.floor(x), Math.floor(y));\n  }\n}\n","/**\n * Color interpolation methods.\n */\nexport enum InterpolationMethod {\n  /**\n   * Average 4 nearest neighbours.\n   */\n  AVERAGE = 1,\n\n  /**\n   * Average 9 nearest neighbours.\n   */\n  AVERAGE_9 = 2,\n\n  /**\n   * Average 16 nearest neighbours.\n   */\n  AVERAGE_16 = 3,\n\n  /**\n   * Just return background color.\n   */\n  BACKGROUND = 4,\n\n  // /**\n  //  * Triangular filter interpolation. (Not implemented, will throw NotImplemented exception)\n  //  */\n  // BILINEAR = 5, // TODO: implement\n  //\n  // /**\n  //  * Blend of nearest 1, 2 or 4 pixels. (Not implemented, will throw NotImplemented exception)\n  //  */\n  // BLEND = 6, // TODO: implement\n  //\n  // /**\n  //  * Catmull-Rom interpolation. (Not implemented, will throw NotImplemented exception)\n  //  */\n  // CATROM = 7, // TODO: implement\n\n  /**\n   * Integer (floor) interpolation.\n   */\n  INTEGER = 8,\n\n  // /**\n  //  * Triangular Mesh interpolation. (Not implemented, will throw NotImplemented exception)\n  //  */\n  // MESH = 9, // TODO: implement\n  //\n  // /**\n  //  * Nearest Neighbour Only. (Not implemented, will throw NotImplemented exception)\n  //  */\n  // NEAREST = 10, // TODO: implement\n  //\n  // /**\n  //  * Cubic Spline (blurred) interpolation. (Not implemented, will throw NotImplemented exception)\n  //  */\n  // SPLINE = 11, // TODO: implement\n}\n","import { AverageInterpolator } from \"./AverageInterpolator\";\nimport { BackgroundInterpolator } from \"./BackgroundInterpolator\";\nimport type { ColorInterpolator } from \"./ColorInterpolator\";\nimport type { ColorInterpolatorFactory } from \"./ColorInterpolatorFactory\";\nimport { IntegerInterpolator } from \"./IntegerInterpolator\";\nimport { InterpolationMethod } from \"./InterpolationMethod\";\n\n/**\n * Base implementation of ColorInterpolatorFactory interface.\n */\nexport class BaseColorInterpolatorFactory implements ColorInterpolatorFactory {\n  /**\n   * @inheritDoc\n   */\n  create(method: InterpolationMethod): ColorInterpolator {\n    switch (method) {\n      case InterpolationMethod.AVERAGE:\n        return new AverageInterpolator(2);\n      case InterpolationMethod.AVERAGE_9:\n        return new AverageInterpolator(3);\n      case InterpolationMethod.AVERAGE_16:\n        return new AverageInterpolator(4);\n      case InterpolationMethod.BACKGROUND:\n        return new BackgroundInterpolator();\n      case InterpolationMethod.INTEGER:\n        return new IntegerInterpolator();\n    }\n\n    // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n    // @ts-ignore\n    throw new TypeError(`Unknown interpolation method: ${method}`);\n  }\n}\n","import type {\n  HasAverageColor,\n  HasBackgroundColor,\n  VirtualViewportPixelAccessor,\n} from \"../pixel-accessor\";\nimport type { ReversePixelMapper } from \"../pixel-mapper\";\nimport type {\n  ResampleFilterResolver,\n  ResampleFilter,\n  ResampleFilterPresetsPoolKeyMap,\n  ResampleFilterPreset,\n} from \"../resample-filter\";\nimport type { ColorResampler } from \"./ColorResampler\";\nimport type {\n  ColorResamplerFactoriesPool,\n  ColorResamplerFactoriesPoolKeyMap,\n} from \"./ColorResamplerFactoriesPool\";\nimport type { ColorResamplerFactory } from \"./ColorResamplerFactory\";\nimport type {\n  ColorResamplerResolver,\n  ColorResamplerResolverOptions,\n} from \"./ColorResamplerResolver\";\n\n/**\n * Base implementation of ColorResamplerResolver interface.\n */\nexport class BaseColorResamplerResolver implements ColorResamplerResolver {\n  /**\n   * BaseColorResamplerResolver constructor.\n   *\n   * @param colorResamplerFactoriesPool\n   * @param resampleFilterResolver\n   */\n  constructor(\n    private readonly colorResamplerFactoriesPool: ColorResamplerFactoriesPool,\n    private readonly resampleFilterResolver: ResampleFilterResolver\n  ) {}\n\n  /**\n   * @inheritDoc\n   */\n  resolve(\n    image: VirtualViewportPixelAccessor & HasAverageColor & HasBackgroundColor,\n    reversePixelMapper: ReversePixelMapper,\n    options: ColorResamplerResolverOptions = {}\n  ): ColorResampler {\n    const {\n      preferredResampler,\n      filter,\n      matteColor,\n      interpolationMethod,\n      virtualPixelMethod,\n    } = options;\n    const factory = this.getColorResamplerFactory(preferredResampler, filter);\n    let resampleFilter: ResampleFilter | undefined;\n    if (filter && factory.supportsEwa) {\n      resampleFilter = this.resampleFilterResolver.resolve(filter, options);\n    }\n    return factory.create(image, reversePixelMapper, {\n      resampleFilter,\n      matteColor,\n      interpolationMethod,\n      virtualPixelMethod,\n    });\n  }\n\n  /**\n   * Returns matching color resampler factory.\n   *\n   * @param preferredResampler\n   * @param filter\n   * @private\n   */\n  private getColorResamplerFactory(\n    preferredResampler?: keyof ColorResamplerFactoriesPoolKeyMap | string,\n    filter?:\n      | keyof ResampleFilterPresetsPoolKeyMap\n      | ResampleFilterPreset\n      | ResampleFilter\n  ): ColorResamplerFactory {\n    let factory: ColorResamplerFactory | undefined;\n    if (preferredResampler !== undefined) {\n      const factory = this.colorResamplerFactoriesPool.get(preferredResampler);\n      if (factory.requiresResampleFilter && !filter) {\n        throw new TypeError(\n          `Preferred color resampler \"${preferredResampler}\" requires ResampleFilter`\n        );\n      }\n      return factory;\n    } else if (filter !== undefined) {\n      factory = this.colorResamplerFactoriesPool\n        .items()\n        .find((f) => f.supportsEwa);\n      if (factory) {\n        return factory;\n      }\n    }\n    const factories = this.colorResamplerFactoriesPool\n      .items()\n      .filter((f) => !f.requiresResampleFilter);\n    if (!factories.length) {\n      throw new Error(\"No color resampler factories in pool.\");\n    }\n    return factories[0];\n  }\n}\n","import type { Color } from \"../types\";\n\n/**\n * Color resampler interface.\n */\nexport interface ColorResampler {\n  /**\n   * Returns resampled color for given destination image coordinates.\n   *\n   * @param x Destination image X pixel coordinate.\n   * @param y Destination image Y pixel coordinate.\n   * @returns Resampled pixel color.\n   */\n  getResampledColor(x: number, y: number): Color;\n\n  /**\n   * Sets scaling factor for super-sampling.\n   *\n   * @param scaling Scaling factor.\n   */\n  setScaling(scaling: number): void;\n\n  /**\n   * Returns scaling factor for super-sampling.\n   */\n  getScaling(): number;\n}\n\n/**\n * Checks if given argument implements ColorResampler interface.\n *\n * @param candidate\n */\nexport function isColorResampler(\n  candidate: unknown\n): candidate is ColorResampler {\n  type C = Partial<ColorResampler>;\n  return (\n    typeof candidate === \"object\" &&\n    candidate !== null &&\n    typeof (candidate as C).getResampledColor === \"function\" &&\n    typeof (candidate as C).setScaling === \"function\" &&\n    typeof (candidate as C).getScaling === \"function\"\n  );\n}\n","import type { Color } from \"../../types\";\nimport type { HasAverageColor } from \"../HasAverageColor\";\nimport type { HasBackgroundColor } from \"../HasBackgroundColor\";\nimport type { Viewport } from \"../Viewport\";\nimport type { VirtualViewportPixelAccessor } from \"../VirtualViewportPixelAccessor\";\nimport type { VirtualPixelDecorator } from \"./VirtualPixelDecorator\";\n\n/**\n * Abstract virtual pixel decorator.\n */\nexport abstract class AbstractVirtualPixelDecorator<\n  DecoratedType extends VirtualViewportPixelAccessor &\n    HasAverageColor &\n    HasBackgroundColor\n> implements VirtualPixelDecorator<DecoratedType>\n{\n  /**\n   * @inheritDoc\n   */\n  readonly width: number;\n\n  /**\n   * @inheritDoc\n   */\n  readonly height: number;\n\n  /**\n   * Origin X offset in virtual viewport.\n   * @protected\n   */\n  protected offsetX: number;\n\n  /**\n   * Origin Y offset in virtual viewport.\n   * @protected\n   */\n  protected offsetY: number;\n\n  /**\n   * BaseVirtualPixelDecorator constructor.\n   *\n   * @param decorated\n   */\n  constructor(protected readonly decorated: DecoratedType) {\n    this.width = this.decorated.width;\n    this.height = this.decorated.height;\n    ({ x1: this.offsetX, y1: this.offsetY } = this.decorated.getViewport());\n  }\n\n  /**\n   * @inheritDoc\n   */\n  abstract getVirtualPixelColor(x: number, y: number): Color;\n\n  /**\n   * @inheritDoc\n   */\n  getPixelColor(x: number, y: number): Color {\n    x = Math.floor(x - this.offsetX);\n    y = Math.floor(y - this.offsetY);\n\n    if (x >= 0 && x < this.width && y >= 0 && y < this.height) {\n      return this.decorated.getPixelColor(x, y);\n    }\n\n    return this.getVirtualPixelColor(x, y);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  setPixelColor(x: number, y: number, color: Color): void {\n    x = Math.floor(x - this.offsetX);\n    y = Math.floor(y - this.offsetY);\n\n    if (x >= 0 && x < this.width && y >= 0 && y < this.height) {\n      this.decorated.setPixelColor(x, y, color);\n    }\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getQuantumRange(): number {\n    return this.decorated.getQuantumRange();\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getViewport(): Viewport {\n    return this.decorated.getViewport();\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getAverageColor(): Color {\n    return this.decorated.getAverageColor();\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getBackgroundColor(): Color {\n    return this.decorated.getBackgroundColor();\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getDecorated(): DecoratedType {\n    return this.decorated;\n  }\n}\n","import type { Color } from \"../../types\";\nimport type { HasAverageColor } from \"../HasAverageColor\";\nimport type { HasBackgroundColor } from \"../HasBackgroundColor\";\nimport type { VirtualViewportPixelAccessor } from \"../VirtualViewportPixelAccessor\";\nimport { AbstractVirtualPixelDecorator } from \"./AbstractVirtualPixelDecorator\";\n\n/**\n * Background virtual tile decorator.\n */\nexport class BackgroundVirtualPixel<\n  DecoratedType extends VirtualViewportPixelAccessor &\n    HasAverageColor &\n    HasBackgroundColor\n> extends AbstractVirtualPixelDecorator<DecoratedType> {\n  /**\n   * @inheritDoc\n   */\n  getVirtualPixelColor(): Color {\n    return this.decorated.getBackgroundColor();\n  }\n}\n","import type { Color } from \"../../types\";\nimport type { HasAverageColor } from \"../HasAverageColor\";\nimport type { HasBackgroundColor } from \"../HasBackgroundColor\";\nimport type { VirtualViewportPixelAccessor } from \"../VirtualViewportPixelAccessor\";\nimport { AbstractVirtualPixelDecorator } from \"./AbstractVirtualPixelDecorator\";\n\n/**\n * Constant color virtual pixel decorator.\n */\nexport class ConstantVirtualPixel<\n  DecoratedType extends VirtualViewportPixelAccessor &\n    HasAverageColor &\n    HasBackgroundColor\n> extends AbstractVirtualPixelDecorator<DecoratedType> {\n  constructor(decorated: DecoratedType, protected color: Color) {\n    super(decorated);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getVirtualPixelColor(): Color {\n    return this.color;\n  }\n}\n","import type { Color } from \"../../types\";\nimport type { HasAverageColor } from \"../HasAverageColor\";\nimport type { HasBackgroundColor } from \"../HasBackgroundColor\";\nimport type { VirtualViewportPixelAccessor } from \"../VirtualViewportPixelAccessor\";\nimport { AbstractVirtualPixelDecorator } from \"./AbstractVirtualPixelDecorator\";\n\n/**\n * Edge virtual pixel decorator.\n */\nexport class EdgeVirtualPixel<\n  DecoratedType extends VirtualViewportPixelAccessor &\n    HasAverageColor &\n    HasBackgroundColor\n> extends AbstractVirtualPixelDecorator<DecoratedType> {\n  getVirtualPixelColor(x: number, y: number): Color {\n    return this.decorated.getPixelColor(\n      Math.max(0, Math.min(this.width - 1, x)),\n      Math.max(0, Math.min(this.height - 1, y))\n    );\n  }\n}\n","import type { Color } from \"../../types\";\nimport type { HasAverageColor } from \"../HasAverageColor\";\nimport type { HasBackgroundColor } from \"../HasBackgroundColor\";\nimport type { VirtualViewportPixelAccessor } from \"../VirtualViewportPixelAccessor\";\nimport { AbstractVirtualPixelDecorator } from \"./AbstractVirtualPixelDecorator\";\n\n/**\n * HorizontalTileEdge virtual pixel decorator.\n */\nexport class HorizontalTileEdgeVirtualPixel<\n  DecoratedType extends VirtualViewportPixelAccessor &\n    HasAverageColor &\n    HasBackgroundColor\n> extends AbstractVirtualPixelDecorator<DecoratedType> {\n  /**\n   * @inheritDoc\n   */\n  getVirtualPixelColor(x: number, y: number): Color {\n    if (y < 0 || y >= this.height) {\n      return this.decorated.getPixelColor(\n        Math.max(0, Math.min(this.width - 1, x)),\n        Math.max(0, Math.min(this.height - 1, y))\n      );\n    }\n    const rx = x % this.width;\n    const ry = y % this.height;\n\n    return this.decorated.getPixelColor(\n      rx < 0 ? this.width + rx : rx,\n      ry < 0 ? this.height + ry : ry\n    );\n  }\n}\n","import type { Color } from \"../../types\";\nimport type { HasAverageColor } from \"../HasAverageColor\";\nimport type { HasBackgroundColor } from \"../HasBackgroundColor\";\nimport type { VirtualViewportPixelAccessor } from \"../VirtualViewportPixelAccessor\";\nimport { AbstractVirtualPixelDecorator } from \"./AbstractVirtualPixelDecorator\";\n\n/**\n * HorizontalTile virtual pixel decorator.\n */\nexport class HorizontalTileVirtualPixel<\n  DecoratedType extends VirtualViewportPixelAccessor &\n    HasAverageColor &\n    HasBackgroundColor\n> extends AbstractVirtualPixelDecorator<DecoratedType> {\n  /**\n   * @inheritDoc\n   */\n  getVirtualPixelColor(x: number, y: number): Color {\n    if (y < 0 || y >= this.height) {\n      return this.decorated.getBackgroundColor();\n    }\n    const rx = x % this.width;\n    const ry = y % this.height;\n\n    return this.decorated.getPixelColor(\n      rx < 0 ? this.width + rx : rx,\n      ry < 0 ? this.height + ry : ry\n    );\n  }\n}\n","import type { Color } from \"../../types\";\nimport type { HasAverageColor } from \"../HasAverageColor\";\nimport type { HasBackgroundColor } from \"../HasBackgroundColor\";\nimport type { VirtualViewportPixelAccessor } from \"../VirtualViewportPixelAccessor\";\nimport { AbstractVirtualPixelDecorator } from \"./AbstractVirtualPixelDecorator\";\n\n/**\n * Mirror virtual pixel decorator.\n */\nexport class MirrorVirtualPixel<\n  DecoratedType extends VirtualViewportPixelAccessor &\n    HasAverageColor &\n    HasBackgroundColor\n> extends AbstractVirtualPixelDecorator<DecoratedType> {\n  /**\n   * @inheritDoc\n   */\n  getVirtualPixelColor(x: number, y: number): Color {\n    const doubleWidth = this.width * 2;\n    const doubleHeight = this.height * 2;\n    const rx = x % doubleWidth;\n    const ry = y % doubleHeight;\n    let tx = rx < 0 ? doubleWidth + rx : rx;\n    let ty = ry < 0 ? doubleHeight + ry : ry;\n    if (tx > this.width - 1) {\n      tx = this.width - (tx - this.width) - 1;\n    }\n    if (ty > this.height - 1) {\n      ty = this.height - (ty - this.height) - 1;\n    }\n    return this.decorated.getPixelColor(tx, ty);\n  }\n}\n","import type { Color } from \"../../types\";\nimport type { HasAverageColor } from \"../HasAverageColor\";\nimport type { HasBackgroundColor } from \"../HasBackgroundColor\";\nimport type { VirtualViewportPixelAccessor } from \"../VirtualViewportPixelAccessor\";\nimport { AbstractVirtualPixelDecorator } from \"./AbstractVirtualPixelDecorator\";\n\n/**\n * Random virtual pixel decorator.\n */\nexport class RandomVirtualPixel<\n  DecoratedType extends VirtualViewportPixelAccessor &\n    HasAverageColor &\n    HasBackgroundColor\n> extends AbstractVirtualPixelDecorator<DecoratedType> {\n  /**\n   * @inheritDoc\n   */\n  getVirtualPixelColor(): Color {\n    return this.decorated.getPixelColor(\n      Math.floor(Math.random() * this.width),\n      Math.floor(Math.random() * this.height)\n    );\n  }\n}\n","import type { Color } from \"../../types\";\nimport type { HasAverageColor } from \"../HasAverageColor\";\nimport type { HasBackgroundColor } from \"../HasBackgroundColor\";\nimport type { VirtualViewportPixelAccessor } from \"../VirtualViewportPixelAccessor\";\nimport { AbstractVirtualPixelDecorator } from \"./AbstractVirtualPixelDecorator\";\n\n/**\n * Tile virtual pixel decorator.\n */\nexport class TileVirtualPixel<\n  DecoratedType extends VirtualViewportPixelAccessor &\n    HasAverageColor &\n    HasBackgroundColor\n> extends AbstractVirtualPixelDecorator<DecoratedType> {\n  /**\n   * @inheritDoc\n   */\n  getVirtualPixelColor(x: number, y: number): Color {\n    const rx = x % this.width;\n    const ry = y % this.height;\n\n    return this.decorated.getPixelColor(\n      rx < 0 ? this.width + rx : rx,\n      ry < 0 ? this.height + ry : ry\n    );\n  }\n}\n","import type { Color } from \"../../types\";\nimport type { HasAverageColor } from \"../HasAverageColor\";\nimport type { HasBackgroundColor } from \"../HasBackgroundColor\";\nimport type { VirtualViewportPixelAccessor } from \"../VirtualViewportPixelAccessor\";\nimport { AbstractVirtualPixelDecorator } from \"./AbstractVirtualPixelDecorator\";\n\n/**\n * VerticalTileEdge virtual pixel decorator.\n */\nexport class VerticalTileEdgeVirtualPixel<\n  DecoratedType extends VirtualViewportPixelAccessor &\n    HasAverageColor &\n    HasBackgroundColor\n> extends AbstractVirtualPixelDecorator<DecoratedType> {\n  /**\n   * @inheritDoc\n   */\n  getVirtualPixelColor(x: number, y: number): Color {\n    if (x < 0 || x >= this.width) {\n      return this.decorated.getPixelColor(\n        Math.max(0, Math.min(this.width - 1, x)),\n        Math.max(0, Math.min(this.height - 1, y))\n      );\n    }\n    const rx = x % this.width;\n    const ry = y % this.height;\n\n    return this.decorated.getPixelColor(\n      rx < 0 ? this.width + rx : rx,\n      ry < 0 ? this.height + ry : ry\n    );\n  }\n}\n","import type { Color } from \"../../types\";\nimport type { HasAverageColor } from \"../HasAverageColor\";\nimport type { HasBackgroundColor } from \"../HasBackgroundColor\";\nimport type { VirtualViewportPixelAccessor } from \"../VirtualViewportPixelAccessor\";\nimport { AbstractVirtualPixelDecorator } from \"./AbstractVirtualPixelDecorator\";\n\n/**\n * VerticalTile virtual pixel decorator.\n */\nexport class VerticalTileVirtualPixel<\n  DecoratedType extends VirtualViewportPixelAccessor &\n    HasAverageColor &\n    HasBackgroundColor\n> extends AbstractVirtualPixelDecorator<DecoratedType> {\n  /**\n   * @inheritDoc\n   */\n  getVirtualPixelColor(x: number, y: number): Color {\n    if (x < 0 || x >= this.width) {\n      return this.decorated.getBackgroundColor();\n    }\n    const rx = x % this.width;\n    const ry = y % this.height;\n\n    return this.decorated.getPixelColor(\n      rx < 0 ? this.width + rx : rx,\n      ry < 0 ? this.height + ry : ry\n    );\n  }\n}\n","/**\n * Virtual pixel methods.\n *\n * @see https://www.imagemagick.org/Usage/misc/#virtual-pixel Virtual pixel details at ImageMagick docs.\n */\nexport enum VirtualPixelMethod {\n  /**\n   * Use image background color.\n   */\n  BACKGROUND = 1,\n\n  // /**\n  //  * Dither virtual pixel method. (Not implemented, will throw NotImplemented exception)\n  //  */\n  // DITHER = 2, // TODO: implement\n\n  /**\n   * Closest edge color.\n   */\n  EDGE = 3,\n\n  /**\n   * Mirror effect.\n   */\n  MIRROR = 4,\n\n  /**\n   * Random color from image.\n   */\n  RANDOM = 5,\n\n  /**\n   * Tile effect.\n   */\n  TILE = 6,\n\n  /**\n   * Transparent color.\n   */\n  TRANSPARENT = 7,\n\n  /**\n   * Black color.\n   */\n  BLACK = 9,\n\n  /**\n   * Gray color.\n   */\n  GRAY = 10,\n\n  /**\n   * White color.\n   */\n  WHITE = 11,\n\n  /**\n   * Tile effect horizontally, background color vertically.\n   */\n  HORIZONTAL_TILE = 12,\n\n  /**\n   * Tile effect vertically, background color horizontally.\n   */\n  VERTICAL_TILE = 13,\n\n  /**\n   * Tile effect horizontally, closest edge color vertically.\n   */\n  HORIZONTAL_TILE_EDGE = 14,\n\n  /**\n   * Tile effect vertically, closest edge color horizontally.\n   */\n  VERTICAL_TILE_EDGE = 15,\n\n  // /**\n  //  * Checker tile.  (Not implemented, will throw NotImplemented exception)\n  //  */\n  // CHECKER_TILE = 16, // TODO: implement\n}\n","import type { HasAverageColor } from \"./HasAverageColor\";\nimport type { HasBackgroundColor } from \"./HasBackgroundColor\";\nimport {\n  BackgroundVirtualPixel,\n  ConstantVirtualPixel,\n  EdgeVirtualPixel,\n  HorizontalTileEdgeVirtualPixel,\n  HorizontalTileVirtualPixel,\n  MirrorVirtualPixel,\n  RandomVirtualPixel,\n  TileVirtualPixel,\n  VerticalTileEdgeVirtualPixel,\n  VerticalTileVirtualPixel,\n  type VirtualPixelDecorator,\n} from \"./virtual-pixel-decorator\";\nimport type { VirtualPixelDecoratorApplicator } from \"./VirtualPixelDecoratorApplicator\";\nimport { VirtualPixelMethod } from \"./VirtualPixelMethod\";\nimport type { VirtualViewportPixelAccessor } from \"./VirtualViewportPixelAccessor\";\n\n/**\n * Base implementation of VirtualPixelDecoratorApplicator\n */\nexport class BaseVirtualPixelDecoratorApplicator\n  implements VirtualPixelDecoratorApplicator\n{\n  /**\n   * @inheritDoc\n   */\n  decorate<\n    DecoratedType extends VirtualViewportPixelAccessor &\n      HasAverageColor &\n      HasBackgroundColor\n  >(\n    decorated: DecoratedType,\n    method: VirtualPixelMethod\n  ): VirtualPixelDecorator<DecoratedType> {\n    switch (method) {\n      case VirtualPixelMethod.BACKGROUND:\n        return new BackgroundVirtualPixel(decorated);\n      case VirtualPixelMethod.EDGE:\n        return new EdgeVirtualPixel(decorated);\n      case VirtualPixelMethod.MIRROR:\n        return new MirrorVirtualPixel(decorated);\n      case VirtualPixelMethod.RANDOM:\n        return new RandomVirtualPixel(decorated);\n      case VirtualPixelMethod.TILE:\n        return new TileVirtualPixel(decorated);\n      case VirtualPixelMethod.TRANSPARENT:\n        return new ConstantVirtualPixel(decorated, [0, 0, 0, 0]);\n      case VirtualPixelMethod.BLACK:\n        return new ConstantVirtualPixel(decorated, [\n          0,\n          0,\n          0,\n          decorated.getQuantumRange(),\n        ]);\n      case VirtualPixelMethod.GRAY:\n        return new ConstantVirtualPixel(decorated, [\n          Math.floor(decorated.getQuantumRange() / 2),\n          Math.floor(decorated.getQuantumRange() / 2),\n          Math.floor(decorated.getQuantumRange() / 2),\n          decorated.getQuantumRange(),\n        ]);\n      case VirtualPixelMethod.WHITE:\n        return new ConstantVirtualPixel(decorated, [\n          decorated.getQuantumRange(),\n          decorated.getQuantumRange(),\n          decorated.getQuantumRange(),\n          decorated.getQuantumRange(),\n        ]);\n      case VirtualPixelMethod.HORIZONTAL_TILE:\n        return new HorizontalTileVirtualPixel(decorated);\n      case VirtualPixelMethod.VERTICAL_TILE:\n        return new VerticalTileVirtualPixel(decorated);\n      case VirtualPixelMethod.HORIZONTAL_TILE_EDGE:\n        return new HorizontalTileEdgeVirtualPixel(decorated);\n      case VirtualPixelMethod.VERTICAL_TILE_EDGE:\n        return new VerticalTileEdgeVirtualPixel(decorated);\n      default:\n        throw new TypeError(`Unknown Virtual Pixel Method \"${method}\" given.`);\n    }\n  }\n}\n","import type { Color } from \"../types\";\n\n/**\n * Interface of entity which has average color.\n */\nexport interface HasAverageColor {\n  /**\n   * Returns average color.\n   */\n  getAverageColor(): Color;\n}\n\n/**\n * Checks if given argument is HasAverageColor.\n *\n * @param obj\n */\nexport function isHasAverageColor(obj: unknown): obj is HasAverageColor {\n  return (\n    typeof obj === \"object\" &&\n    obj !== null &&\n    typeof (obj as Partial<HasAverageColor>).getAverageColor === \"function\"\n  );\n}\n","import type { Color } from \"../types\";\n\n/**\n * Interface of entity with background color.\n */\nexport interface HasBackgroundColor {\n  getBackgroundColor(): Color;\n}\n\n/**\n * Checks if given argument is HasBackgroundColor.\n *\n * @param obj\n */\nexport function isHasBackgroundColor(obj: unknown): obj is HasBackgroundColor {\n  return (\n    typeof obj === \"object\" &&\n    obj !== null &&\n    typeof (obj as Partial<HasBackgroundColor>).getBackgroundColor ===\n      \"function\"\n  );\n}\n","import type { Color } from \"../types\";\n\nexport interface PixelAccessor {\n  /**\n   * Returns pixel color at given coordinates.\n   *\n   * @param x\n   * @param y\n   */\n  getPixelColor(x: number, y: number): Color;\n\n  /**\n   * Sets pixel color at given image coordinates.\n   *\n   * @param x\n   * @param y\n   * @param color\n   */\n  setPixelColor(x: number, y: number, color: Color): void;\n\n  /**\n   * Returns quantum range (max color channel value).\n   */\n  getQuantumRange(): number;\n}\n\n/**\n * Checks if given argument is PixelAccessor.\n *\n * @param obj\n */\nexport function isPixelAccessor(obj: unknown): obj is PixelAccessor {\n  return (\n    typeof obj === \"object\" &&\n    obj !== null &&\n    typeof (obj as Partial<PixelAccessor>).getPixelColor === \"function\" &&\n    typeof (obj as Partial<PixelAccessor>).setPixelColor === \"function\" &&\n    typeof (obj as Partial<PixelAccessor>).getQuantumRange === \"function\"\n  );\n}\n","import { isPixelAccessor, type PixelAccessor } from \"./PixelAccessor\";\n\n/**\n * Image pixel accessor interface.\n */\nexport interface PixelAccessorWithDimensions extends PixelAccessor {\n  /**\n   * Width\n   */\n  readonly width: number;\n\n  /**\n   * Height\n   */\n  readonly height: number;\n}\n\n/**\n * Checks if given argument is PixelAccessorWithDimensions.\n *\n * @param obj\n */\nexport function isPixelAccessorWithDimensions(\n  obj: unknown\n): obj is PixelAccessorWithDimensions {\n  return (\n    typeof isPixelAccessor(obj) &&\n    typeof (obj as Partial<PixelAccessorWithDimensions>).width === \"number\" &&\n    typeof (obj as Partial<PixelAccessorWithDimensions>).height === \"number\"\n  );\n}\n","/**\n * Virtual viewport class.\n * Represents image's virtual position at its coordinate space.\n *\n * @see https://www.imagemagick.org/Usage/basics/#page Virtual canvas offset at ImageMagick docs.\n */\nexport class Viewport {\n  /**\n   * Left edge coordinate of viewport.\n   */\n  x1: number;\n\n  /**\n   * Top edge coordinate of viewport.\n   */\n  y1: number;\n\n  /**\n   * Right edge coordinate of viewport.\n   */\n  x2: number;\n\n  /**\n   * Bottom edge coordinate of viewport.\n   */\n  y2: number;\n\n  /**\n   * Viewport constructor.\n   *\n   * @param x1 Left edge coordinate of viewport.\n   * @param y1 Top edge coordinate  of viewport.\n   * @param x2 Right edge coordinate of viewport.\n   * @param y2 Bottom edge coordinate of viewport.\n   */\n  constructor(x1: number, y1: number, x2: number, y2: number) {\n    this.x1 = x1;\n    this.y1 = y1;\n    this.x2 = x2;\n    this.y2 = y2;\n  }\n\n  /**\n   * Creates Viewport instance from viewport literal.\n   *\n   * @param obj\n   */\n  static fromLiteral(obj: ViewportLiteral): Viewport {\n    let x1, y1, x2, y2;\n\n    if (\"width\" in obj && \"height\" in obj) {\n      x1 = obj.x || 0;\n      y1 = obj.y || 0;\n      x2 = x1 + obj.width - 1;\n      y2 = y1 + obj.height - 1;\n    } else {\n      x1 = obj.x1;\n      y1 = obj.y1;\n      x2 = obj.x2;\n      y2 = obj.y2;\n    }\n\n    return new Viewport(x1, y1, x2, y2);\n  }\n\n  /**\n   * Returns virtual viewport width -- same as image actual width.\n   */\n  getWidth(): number {\n    return this.x2 - this.x1 + 1;\n  }\n\n  /**\n   * Returns virtual viewport height -- same as image actual height.\n   */\n  getHeight(): number {\n    return this.y2 - this.y1 + 1;\n  }\n\n  /**\n   * Returns viewport area.\n   */\n  getArea(): number {\n    return this.getWidth() * this.getHeight();\n  }\n\n  /**\n   * Expands viewport to contain given coords.\n   *\n   * @param x X-coordinate.\n   * @param y Y-coordinate.\n   */\n  expand(x: number, y: number): this {\n    this.x1 = Math.min(this.x1, x);\n    this.x2 = Math.max(this.x2, x);\n    this.y1 = Math.min(this.y1, y);\n    this.y2 = Math.max(this.y2, y);\n    return this;\n  }\n\n  /**\n   * Clones viewport into new instance.\n   *\n   * @returns New Viewport instance with same dimensions.\n   */\n  clone(): Viewport {\n    return new Viewport(this.x1, this.y1, this.x2, this.y2);\n  }\n\n  /**\n   * Fix bounds after best fit viewport calculation.\n   */\n  fixBounds(): this {\n    this.x1 = Math.floor(this.x1 - 0.5);\n    this.y1 = Math.floor(this.y1 - 0.5);\n    this.x2 = Math.ceil(this.x2 - 0.5);\n    this.y2 = Math.ceil(this.y2 - 0.5);\n    return this;\n  }\n\n  /**\n   * Scales viewport bounds.\n   *\n   * @param scale Scale value.\n   */\n  scale(scale: number): this {\n    const scaledWidth = this.getWidth() * scale;\n    const scaledHeight = this.getHeight() * scale;\n    this.x1 = this.x1 * scale;\n    this.y1 = this.y1 * scale;\n    this.x2 = this.x1 + scaledWidth - 1;\n    this.y2 = this.y1 + scaledHeight - 1;\n    return this;\n  }\n\n  /**\n   * Resets viewport offset.\n   */\n  reset(): this {\n    const width = this.getWidth(),\n      height = this.getHeight();\n    this.x1 = 0;\n    this.y1 = 0;\n    this.x2 = this.x1 + width - 1;\n    this.y2 = this.y1 + height - 1;\n    return this;\n  }\n\n  /**\n   * Sets viewport offset.\n   *\n   * @param x X-offset.\n   * @param y Y-offset.\n   */\n  offset(x: number, y: number): this {\n    this.x1 += x;\n    this.y1 += y;\n    this.x2 += x;\n    this.y2 += y;\n    return this;\n  }\n}\n\n/**\n * Plain object, describing image viewport.\n */\nexport type ViewportLiteral =\n  | {\n      x1: number;\n      y1: number;\n      x2: number;\n      y2: number;\n    }\n  | {\n      width: number;\n      height: number;\n      x?: number;\n      y?: number;\n    };\n\n/**\n * Checks if passed object implements ViewportLiteral interface.\n *\n * @param obj\n */\nexport function isViewportLiteral(obj: unknown): obj is ViewportLiteral {\n  if (typeof obj !== \"object\" || obj === null) {\n    return false;\n  }\n  const candidate = obj as Partial<ViewportLiteral>;\n  return (\n    (\"x1\" in candidate &&\n      typeof candidate.x1 === \"number\" &&\n      \"y1\" in candidate &&\n      typeof candidate.y1 === \"number\" &&\n      \"x2\" in candidate &&\n      typeof candidate.x2 === \"number\" &&\n      \"y2\" in candidate &&\n      typeof candidate.y2 === \"number\") ||\n    (\"width\" in candidate &&\n      typeof candidate.width === \"number\" &&\n      \"height\" in candidate &&\n      typeof candidate.height === \"number\" &&\n      (!(\"x\" in candidate) || typeof candidate.x === \"number\") &&\n      (!(\"y\" in candidate) || typeof candidate.y === \"number\"))\n  );\n}\n","import {\n  isPixelAccessorWithDimensions,\n  type PixelAccessorWithDimensions,\n} from \"./PixelAccessorWithDimensions\";\nimport type { Viewport } from \"./Viewport\";\n\n/**\n * ImagePixelAccessor, having virtual viewport.\n */\nexport interface VirtualViewportPixelAccessor\n  extends PixelAccessorWithDimensions {\n  /**\n   * Returns virtual viewport.\n   */\n  getViewport(): Viewport;\n}\n\n/**\n * Checks if given argument is VirtualViewportPixelAccessor.\n *\n * @param obj\n */\nexport function isVirtualViewportPixelAccessor(\n  obj: unknown\n): obj is VirtualViewportPixelAccessor {\n  return (\n    isPixelAccessorWithDimensions(obj) &&\n    typeof (obj as Partial<VirtualViewportPixelAccessor>).getViewport ===\n      \"function\"\n  );\n}\n","import type { ColorResampler } from \"./ColorResampler\";\nimport { isColorResampler } from \"./ColorResampler\";\n\n/**\n * Color resampler with support of Elliptical Weighted Average technique.\n */\nexport interface EwaColorResampler extends ColorResampler {\n  /**\n   * Returns weight lookup table used by resampler.\n   */\n  getWeightLookupTable(): number[];\n}\n\n/**\n * Checks if given argument implements EwaColorResampler interface.\n *\n * @param candidate\n */\nexport function isEwaColorResampler(\n  candidate: unknown\n): candidate is EwaColorResampler {\n  return (\n    isColorResampler(candidate) &&\n    typeof (candidate as Partial<EwaColorResampler>).getWeightLookupTable ===\n      \"function\"\n  );\n}\n","/**\n * Machine epsilon used in calculations.\n *\n * @see https://en.wikipedia.org/wiki/Machine_epsilon\n */\nexport const EPSILON =\n  Number.EPSILON === undefined ? Math.pow(2, -52) : Number.EPSILON;\n\n/**\n * The largest number that can be represented in JavaScript.\n */\nexport const MAXIMUM_VALUE = Number.MAX_VALUE;\n\n/**\n * Pi/2\n */\nexport const M_PI2 = Math.PI / 2;\n\n/**\n * Pi * 2\n */\nexport const M_2PI = Math.PI * 2;\n","import type { Color } from \"../types\";\n\n/**\n * Blends two colors by given balance. Balance should be number between 0 and 1.\n * Balance is weight of first color. Second color weight is (1 - balance).\n *\n * @param color1\n * @param color2\n * @param balance\n */\nexport function blendColors(\n  color1: Color,\n  color2: Color,\n  balance = 0.5\n): Color {\n  const weight2 = 1 - balance;\n  const result = [0, 0, 0, 0];\n\n  for (let i = 0; i < 4; i++) {\n    result[i] = Math.round(color1[i] * balance + color2[i] * weight2);\n  }\n\n  return result as unknown as Color;\n}\n","/**\n * Deferred object.\n */\nexport type Deferred<T> = {\n  /**\n   * Resolves deferred promise with given value.\n   * @param value\n   */\n  resolve(value: T): void;\n\n  /**\n   * Rejects deferred promise with given reason.\n   * @param reason\n   */\n  reject(reason?: Error | any): void; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n  /**\n   * Deferred promise.\n   */\n  promise: Promise<T>;\n};\n\n/**\n * Creates Deferred object.\n */\nexport function createDeferred<T>(): Deferred<T> {\n  const deferred = {} as Deferred<T>;\n  deferred.promise = new Promise<T>((resolve, reject) => {\n    deferred.resolve = resolve;\n    deferred.reject = reject;\n  });\n  return deferred;\n}\n","/**\n * Converts degrees to radians.\n *\n * @param degrees\n */\nexport function degreesToRadians(degrees: number): number {\n  return (Math.PI * degrees) / 180;\n}\n","import { EPSILON } from \"../constants\";\n\n/**\n * Return 1/x where x is perceptible (not unlimited or infinitesimal).\n *\n * @param x\n *\n * @see https://imagemagick.org/api/MagickCore/pixel-accessor_8h_source.html#l00234 PerceptibleReciprocal()\n * at ImageMagick source.\n */\nexport function perceptibleReciprocal(x: number): number {\n  const sign = x < 0 ? -1 : 1;\n\n  if (sign * x >= EPSILON) {\n    return 1 / x;\n  }\n\n  return sign / EPSILON;\n}\n","import { perceptibleReciprocal } from \"./perceptibleReciprocal\";\n\n/**\n * Array of numbers.\n */\nexport type Vector = number[];\n\n/**\n * Array of vectors.\n */\nexport type Matrix = Vector[];\n\n/**\n * Solves system of equations using Gauss-Jordan elimination.\n *\n * Brings the matrix to reduced row echelon form, while simultaneously reducing and thus solving the augmented results\n * matrix.\n *\n * See also http://en.wikipedia.org/wiki/Gauss-Jordan_elimination\n *\n *\n *  Note that the 'matrix' is given as a 'array of arrays' of rank size. That is values can be assigned\n *  as   matrix[row][column]   where 'row' is typically the equation, and 'column' is the term of the equation.\n *  That is the matrix is in the form of a 'row first array'.\n *\n *  However, 'vectors' is a 'array of arrays' which can have any number of columns, with each column array the same\n *  'rank' size as 'matrix'.\n *\n *  This allows for simpler handling of the results, especially is only one column 'vector' is all that is required\n *  to produce the desired solution.\n *\n *  For example, the 'vectors' can consist of simple array of numbers.  when only one set of simultaneous equations is\n *  to be solved from the given set of coefficient weighted terms.\n *\n *  However, by specifying more 'columns' (as an 'array of vector columns', you can use this function to solve a set of\n *  'separable' equations.\n *\n *  For example a distortion function where\n *  ```\n *  u = U(x,y)  v = V(x,y)\n *  ```\n *  And the functions U() and V() have separate coefficients, but are being generated from a common x,y->u,v  data set.\n *\n *  You can also use the 'vectors' to generate an inverse of the given 'matrix' though as a 'column first array' rather\n *  than a 'row first array'. For details see http://en.wikipedia.org/wiki/Gauss-Jordan_elimination\n *\n *\n * @see https://imagemagick.org/api/MagickCore/matrix_8c_source.html#l00480 GaussJordanElimination() at\n * ImageMagick source.\n *\n * @param coefficients Linear equations system coefficients.\n * @param results Augment results matrix.\n */\nexport function gaussJordanElimination(\n  coefficients: Matrix,\n  results: Matrix\n): Matrix {\n  validate(coefficients, results);\n  coefficients = cloneMatrix(coefficients);\n  results = cloneMatrix(results);\n  const rank = coefficients.length;\n  const numVectors = results.length;\n  const cols = new Array(rank).fill(0);\n  const rows = new Array(rank).fill(0);\n  const pivots = new Array(rank).fill(0);\n  let col = 0;\n  let row = 0;\n\n  for (let i = 0; i < rank; i++) {\n    let max = 0;\n\n    for (let j = 0; j < rank; j++) {\n      if (pivots[j] !== 1) {\n        for (let k = 0; k < rank; k++) {\n          if (pivots[k] !== 0) {\n            if (pivots[k] > 1) {\n              unsolvable();\n            }\n          } else if (Math.abs(coefficients[j][k]) >= max) {\n            max = Math.abs(coefficients[j][k]);\n            row = j;\n            col = k;\n          }\n        }\n      }\n    }\n\n    pivots[col]++;\n\n    if (row !== col) {\n      for (let k = 0; k < rank; k++) {\n        swap(coefficients, row, k, col, k);\n      }\n\n      for (let k = 0; k < numVectors; k++) {\n        swap(results, k, row, k, col);\n      }\n    }\n\n    rows[i] = row;\n    cols[i] = col;\n\n    if (coefficients[col][col] === 0) {\n      unsolvable();\n    }\n\n    const scale = perceptibleReciprocal(coefficients[col][col]);\n    coefficients[col][col] = 1;\n\n    for (let j = 0; j < rank; j++) {\n      coefficients[col][j] *= scale;\n    }\n\n    for (let j = 0; j < numVectors; j++) {\n      results[j][col] *= scale;\n    }\n\n    for (let j = 0; j < rank; j++) {\n      if (j !== col) {\n        const scale = coefficients[j][col];\n        coefficients[j][col] = 0;\n\n        for (let k = 0; k < rank; k++) {\n          coefficients[j][k] -= scale * coefficients[col][k];\n        }\n\n        for (let k = 0; k < numVectors; k++) {\n          results[k][j] -= scale * results[k][col];\n        }\n      }\n    }\n  }\n\n  for (let j = rank - 1; j >= 0; j--) {\n    if (cols[j] !== rows[j]) {\n      for (let i = 0; i < rank; i++) {\n        swap(coefficients, i, rows[j], i, cols[j]);\n      }\n    }\n  }\n\n  return results;\n}\n\n/**\n * Swaps matrix values by given row and col.\n *\n * @internal\n * @param array\n * @param row1\n * @param col1\n * @param row2\n * @param col2\n */\nfunction swap(\n  array: Matrix,\n  row1: number,\n  col1: number,\n  row2: number,\n  col2: number\n): void {\n  if (array[row1][col1] !== array[row2][col2]) {\n    array[row1][col1] += array[row2][col2];\n    array[row2][col2] = array[row1][col1] - array[row2][col2];\n    array[row1][col1] -= array[row2][col2];\n  }\n}\n\nfunction cloneMatrix(matrix: Matrix): Matrix {\n  return matrix.map((vector) => vector.slice());\n}\n\nfunction unsolvable() {\n  throw new TypeError(\"Can't solve given matrix using Gauss-Jordan method\");\n}\n\nfunction validate(matrix: Matrix, vectors: Matrix): void | never {\n  const rank = matrix.length;\n\n  matrix.forEach((vector) => {\n    if (vector.length !== rank) {\n      throw new TypeError(\"Matrix must be square\");\n    }\n  });\n\n  vectors.forEach((vector) => {\n    if (vector.length !== rank) {\n      throw new TypeError(\n        \"Augment matrix vector length must be same as matrix rank\"\n      );\n    }\n  });\n}\n","import {\n  gaussJordanElimination,\n  type Matrix,\n  type Vector,\n} from \"./gaussJordanElimination\";\n\n/**\n * Solves system of equations using Least Squares method.\n * @see https://imagemagick.org/api/MagickCore/matrix_8c_source.html#l00829 LeastSquaresAddTerms() at\n * ImageMagick source.\n */\nexport class LeastSquares {\n  /**\n   * Coefficients of equations to solve.\n   *\n   * @private\n   */\n  private readonly coefficients: Matrix;\n\n  /**\n   * Results of equations to solve.\n   *\n   * @private\n   */\n  private readonly results: Matrix;\n\n  /**\n   * LeastSquares constructor.\n   *\n   * @param rank The rank or size of the dimensions of the square matrix.\n   * Also, the length of vectors, and number of terms being added.\n   * @param numVectors Number of result vectors, and number of results being\n   * added.  Also represents the number of separable systems of equations\n   * that is being solved.\n   */\n  constructor(rank: number, numVectors = 1) {\n    this.coefficients = [];\n    this.results = [];\n\n    for (let i = 0; i < rank; i++) {\n      this.coefficients.push(new Array(rank).fill(0));\n    }\n\n    for (let i = 0; i < numVectors; i++) {\n      this.results.push(new Array(rank).fill(0));\n    }\n  }\n\n  /**\n   * Adds one set of terms and associate results to the given matrix and vectors for solving using least-squares\n   * function fitting.\n   *\n   * @param terms The pre-calculated terms (without any coefficient weights) that forms the equation being added.\n   * @param results The result(s) that should be generated from the given terms weighted by the yet-to-be-solved\n   * coefficients.\n   *\n   * @see https://imagemagick.org/api/MagickCore/matrix_8c_source.html#l00829 LeastSquaresAddTerms() at\n   * ImageMagick source.\n   */\n  addTerms(terms: Vector, results: Vector) {\n    const rank = this.coefficients.length;\n\n    for (let j = 0; j < rank; j++) {\n      for (let i = 0; i < rank; i++) {\n        this.coefficients[i][j] += terms[i] * terms[j];\n      }\n\n      for (let i = 0; i < this.results.length; i++) {\n        this.results[i][j] += results[i] * terms[j];\n      }\n    }\n\n    return this;\n  }\n\n  /**\n   * Returns equations solving results matrix\n   */\n  solve(): Matrix {\n    return gaussJordanElimination(this.coefficients, this.results);\n  }\n}\n","/**\n * Creates OffscreenCanvas of given size.\n *\n * @param width\n * @param height\n */\nexport function makeCanvas(width: number, height: number): OffscreenCanvas;\n\n/**\n * Creates OffscreenCanvas of given size.\n *\n * @param width\n * @param height\n * @param onscreen\n */\nexport function makeCanvas(\n  width: number,\n  height: number,\n  onscreen: false\n): OffscreenCanvas;\n\n/**\n * Creates HTMLCanvasElement of given size.\n *\n * @param width\n * @param height\n * @param onscreen\n */\nexport function makeCanvas(\n  width: number,\n  height: number,\n  onscreen: true\n): HTMLCanvasElement;\n\n/**\n * Creates OffscreenCanvas or HTMLCanvasElement.\n *\n * @param width\n * @param height\n * @param onscreen\n */\nexport function makeCanvas(\n  width: number,\n  height: number,\n  onscreen: boolean\n): OffscreenCanvas | HTMLCanvasElement;\n\n/**\n * makeCanvas implementation.\n *\n * @param width\n * @param height\n * @param forceOnscreen\n */\nexport function makeCanvas(\n  width: number,\n  height: number,\n  forceOnscreen = false\n): HTMLCanvasElement | OffscreenCanvas {\n  if (forceOnscreen) {\n    const canvas = document.createElement(\"canvas\");\n    canvas.width = width;\n    canvas.height = height;\n    return canvas;\n  }\n\n  return new OffscreenCanvas(width, height);\n}\n","/**\n * Returns promise of preloaded HTMLImageElement.\n *\n * @param src\n * @param image\n */\nexport function preloadHtmlImage(\n  src: string,\n  image = new Image()\n): Promise<HTMLImageElement> {\n  return new Promise((resolve, reject) => {\n    const cleanup = () => {\n      image.onload = null;\n      image.onerror = null;\n    };\n\n    image.onload = () => {\n      cleanup();\n      resolve(image);\n    };\n\n    image.onerror = () => {\n      cleanup();\n      reject(new Error(`Couldn't load image \"${src}\"`));\n    };\n    image.src = src;\n  });\n}\n","/**\n * Base Lens exception.\n */\nexport class LensException extends Error {\n  /**\n   * @param message Error message.\n   */\n  constructor(message: string) {\n    super(message);\n    this.name = \"LensException\";\n\n    if (\n      typeof (Error as unknown & { captureStackTrace?: unknown })\n        .captureStackTrace === \"function\"\n    ) {\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      (Error as any).captureStackTrace(this, this.constructor);\n    } else {\n      this.stack = new Error(message).stack;\n    }\n  }\n}\n","import { LensException } from \"./LensException\";\n\n/**\n * Operation abort exception.\n */\nexport class AbortException extends LensException {\n  /**\n   * @param message Error message.\n   */\n  constructor(message: string) {\n    super(message);\n    this.name = \"AbortException\";\n  }\n}\n","import { LensException } from \"./LensException\";\n\n/**\n * Invalid Argument Exception.\n */\nexport class InvalidArgument extends LensException {\n  /**\n   * @param message Error message.\n   */\n  constructor(message: string) {\n    super(message);\n    this.name = \"InvalidArgument\";\n  }\n}\n","import { LensException } from \"./LensException\";\n\n/**\n * Exception for cases when invalid number of arguments passed.\n */\nexport class InvalidArgumentsLength extends LensException {\n  /**\n   * @param message Error message.\n   */\n  constructor(message: string) {\n    super(message);\n    this.name = \"InvalidArgumentsLength\";\n  }\n}\n","import { Viewport } from \"../../../pixel-accessor\";\nimport type { Point } from \"../../../types\";\nimport type {\n  EwaReversePixelMapper,\n  PartialDerivatives,\n} from \"../../EwaReversePixelMapper\";\nimport type { BestFitReversePixelMapper } from \"../../BestFitReversePixelMapper\";\nimport type { ForwardPixelMapper } from \"../../ForwardPixelMapper\";\nimport { perceptibleReciprocal } from \"../../../utils\";\nimport { InvalidArgument } from \"../../../exception\";\n\n/**\n * Affine matrix represented by 1-dimension array: [sx, rx, tx, ry, sy, ty].\n */\nexport type AffineMatrix = [number, number, number, number, number, number];\n\n/**\n * Project coordinates using affine projection matrix.\n *\n * @param x\n * @param y\n * @param matrix\n */\nexport function applyAffineMatrix(\n  x: number,\n  y: number,\n  matrix: AffineMatrix\n): Point {\n  return [\n    matrix[0] * x + matrix[1] * y + matrix[2],\n    matrix[3] * x + matrix[4] * y + matrix[5],\n  ];\n}\n\n/**\n * Returns inverted affine matrix.\n *\n * @param matrix\n *\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l00095 Inverting affine matrix at ImageMagick source\n */\nexport function invertAffineMatrix(matrix: AffineMatrix): AffineMatrix {\n  /* From \"Digital Image Warping\" by George Wolberg, page 50 */\n\n  const determinant = perceptibleReciprocal(\n    matrix[0] * matrix[4] - matrix[1] * matrix[3]\n  );\n\n  if (!determinant) {\n    throw new InvalidArgument(\"Given matrix can't be inverted\");\n  }\n\n  return [\n    determinant * matrix[4],\n    determinant * -matrix[1],\n    determinant * (matrix[1] * matrix[5] - matrix[2] * matrix[4]),\n    determinant * -matrix[3],\n    determinant * matrix[0],\n    determinant * (matrix[2] * matrix[3] - matrix[0] * matrix[5]),\n  ];\n}\n\n/**\n * Affine distortion.\n *\n * @see https://www.imagemagick.org/Usage/distorts/#affine Affine distortion details at ImageMagick docs\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l02443 Affine distortion at ImageMagick source\n */\nexport class Affine\n  implements\n    EwaReversePixelMapper,\n    BestFitReversePixelMapper,\n    ForwardPixelMapper\n{\n  /**\n   * Forward matrix.\n   */\n  readonly forwardMatrix: AffineMatrix;\n\n  /**\n   * @inheritDoc\n   */\n  readonly isConstantPartialDerivatives = true;\n\n  /**\n   * Affine constructor.\n   *\n   * @param matrix Reverse Affine matrix.\n   */\n  constructor(readonly matrix: AffineMatrix) {\n    this.forwardMatrix = invertAffineMatrix(matrix);\n  }\n\n  /**\n   * Creates affine distortion using affine matrix.\n   *\n   * @param matrix Affine projection coefficients: [sx, rx, tx, ry, sy, ty].\n   * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l00609 Generating inverted affine distortion matrix from forward affine matrix at ImageMagick source\n   */\n  static fromForwardMatrix(matrix: AffineMatrix): Affine {\n    return new Affine(invertAffineMatrix(matrix));\n  }\n\n  /**\n   * @inheritDoc\n   */\n  reverseMap(x: number, y: number): Point {\n    return [\n      this.matrix[0] * x + this.matrix[1] * y + this.matrix[2],\n      this.matrix[3] * x + this.matrix[4] * y + this.matrix[5],\n    ];\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getValidity(): 1 {\n    return 1;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getPartialDerivatives(): PartialDerivatives {\n    return [this.matrix[0], this.matrix[1], this.matrix[3], this.matrix[4]];\n  }\n\n  /**\n   * @inheritDoc\n   */\n  forwardMap(u: number, v: number): Point {\n    return applyAffineMatrix(u, v, this.forwardMatrix);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getBestFitViewport(viewport: Viewport): Viewport {\n    const u1 = viewport.x1,\n      v1 = viewport.y1,\n      u2 = viewport.x2 + 1,\n      v2 = viewport.y2 + 1,\n      [x, y] = this.forwardMap(u1, v1),\n      bestFit = new Viewport(x, y, x, y);\n\n    (\n      [\n        [u2, v1],\n        [u2, v2],\n        [u1, v2],\n      ] as Point[]\n    ).forEach((apex) => bestFit.expand(...this.forwardMap(...apex)));\n\n    bestFit.fixBounds();\n\n    return bestFit;\n  }\n}\n","import { Affine, type AffineMatrix } from \"./Affine\";\nimport { InvalidArgumentsLength } from \"../../../exception\";\nimport { LeastSquares } from \"../../../utils\";\nimport type { ReversePixelMapperFactory } from \"../../ReversePixelMapperFactory\";\n\n/**\n * Creates affine distortion using control points array.\n *\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l00501 Generating affine distortion matrix from control points at ImageMagick source\n */\nexport class AffineFactory implements ReversePixelMapperFactory {\n  /**\n   * Returns Affine instance.\n   *\n   * @param controlPoints Mappings of control points [u0, v0, x0, y0, ... , un, vn, xn, yn] where\n   * (u*, v*) are source(x, y) point and (x*, y*) are destination (x, y) point.\n   */\n  create(controlPoints: number[]): Affine {\n    if (!controlPoints.length || controlPoints.length % 4 !== 0) {\n      throw new InvalidArgumentsLength(\n        `Number of arguments must be multiple of 4 and at least 4 arguments (1 control point) expected.` +\n          `${controlPoints.length} arguments given.`\n      );\n    }\n\n    /*\n     * handle special cases of not enough arguments\n     */\n    if (controlPoints.length === 4) {\n      // Only 1 CP Set Given\n      return new Affine([\n        1,\n        0,\n        controlPoints[0] - controlPoints[2],\n        0,\n        1,\n        controlPoints[1] - controlPoints[3],\n      ]);\n    } else {\n      // 2 or more points (usually 3) given.\n      // Solve a least squares simultaneous equation for coefficients.\n      const leastSquares = new LeastSquares(3, 2);\n\n      for (let i = 0; i < controlPoints.length; i += 4) {\n        const [u, v, x, y] = controlPoints.slice(i, i + 4);\n\n        leastSquares.addTerms([x, y, 1], [u, v]);\n      }\n\n      if (controlPoints.length === 8) {\n        /*\n         * Only two pairs were given, but we need 3 to solve the affine.\n         * Fake extra coordinates by rotating p1 around p0 by 90 degrees.\n         * x2 = x0 - (y1-y0)   y2 = y0 + (x1-x0)\n         */\n        leastSquares.addTerms(\n          [\n            controlPoints[2] - (controlPoints[7] - controlPoints[3]),\n            controlPoints[3] + (controlPoints[6] - controlPoints[2]),\n            1,\n          ],\n          [\n            controlPoints[0] - controlPoints[5] + controlPoints[1],\n            controlPoints[1] + controlPoints[4] - controlPoints[0],\n          ]\n        );\n      }\n\n      const vectors = leastSquares.solve();\n\n      return new Affine(vectors[0].concat(vectors[1]) as AffineMatrix);\n    }\n  }\n}\n","import { Affine, type AffineMatrix } from \"./Affine\";\nimport type { ReversePixelMapperFactory } from \"../../ReversePixelMapperFactory\";\n\n/**\n * Creates affine distortion using forward affine matrix.\n *\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l00609 Generating inverted affine distortion matrix from forward affine matrix at ImageMagick source\n */\nexport class AffineProjectionFactory\n  implements ReversePixelMapperFactory<AffineMatrix>\n{\n  /**\n   * Returns Affine instance.\n   *\n   * @param matrix Affine projection coefficients: [sx, ry, rx, sy, tx, ty].\n   */\n  create(matrix: AffineMatrix): Affine {\n    // arguments order is different from actual affine matrix for compatibility with ImageMagick\n    // AffineProjection distortion arguments order.\n    const [sx, ry, rx, sy, tx, ty] = matrix;\n    return Affine.fromForwardMatrix([sx, rx, tx, ry, sy, ty]);\n  }\n}\n","import { EPSILON, M_2PI, M_PI2 } from \"../../../constants\";\nimport { Viewport } from \"../../../pixel-accessor\";\nimport type { Point } from \"../../../types\";\nimport type {\n  EwaReversePixelMapper,\n  PartialDerivatives,\n} from \"../../EwaReversePixelMapper\";\nimport type { BestFitReversePixelMapper } from \"../../BestFitReversePixelMapper\";\n\n/**\n * Arc distortion.\n * _Note the coefficients use a center angle, so asymptotic join is\n * furthest from both sides of the source image. This also means that\n * for arc angles greater than 360 the sides of the image will be\n * trimmed equally._\n *\n * @see https://www.imagemagick.org/Usage/distorts/#arc Arc distortion details at ImageMagick docs.\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l02561 Arc distortion at ImageMagick\n * source.\n */\nexport class Arc implements EwaReversePixelMapper, BestFitReversePixelMapper {\n  /**\n   * @inheritDoc\n   */\n  readonly isConstantPartialDerivatives = false;\n\n  /**\n   * @inheritDoc\n   */\n  readonly forceBestFit = true;\n\n  /**\n   * Angle for center of source image.\n   */\n  readonly c0: number;\n\n  /**\n   * Angle scale for mapping to source image.\n   */\n  readonly c1: number;\n\n  /**\n   * Radius for top of source image.\n   */\n  readonly c2: number;\n\n  /**\n   * Radius scale for mapping source image.\n   */\n  readonly c3: number;\n\n  /**\n   * Center line of arc within source image.\n   */\n  readonly c4: number;\n\n  /**\n   * Angle to width ratio.\n   */\n  private readonly angleToWidth: number;\n\n  /**\n   * Radius to height ratio.\n   */\n  private readonly radiusToHeight: number;\n\n  /**\n   * Source image viewport.\n   */\n  private viewport: Viewport;\n\n  /**\n   * Cached double viewport width.\n   * @private\n   */\n  private viewportWidthX2: number;\n\n  /**\n   * Arc constructor.\n   *\n   * @param viewport Source image viewport.\n   * @param c0 Angle for center of source image.\n   * @param c1 Angle scale for mapping to source image.\n   * @param c2 Radius for top of source image.\n   * @param c3 Radius scale for mapping source image.\n   * @param c4 Center line of arc within source image.\n   */\n  constructor(\n    viewport: Viewport,\n    c0: number,\n    c1: number,\n    c2: number,\n    c3: number,\n    c4: number\n  ) {\n    this.viewport = viewport;\n    this.c0 = c0;\n    this.c1 = c1;\n    this.c2 = c2;\n    this.c3 = c3;\n    this.c4 = c4;\n\n    /*\n     * Convert the angle_to_width and radius_to_height\n     * to appropriate scaling factors, to allow faster processing\n     * in the mapping function.\n     */\n    this.angleToWidth = (M_2PI * this.viewport.getWidth()) / this.c1;\n    this.radiusToHeight = this.viewport.getHeight() / this.c3;\n    this.viewportWidthX2 = this.viewport.getWidth() * 2;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  reverseMap(x: number, y: number): Point {\n    let [u, v] = this.getUV(x, y);\n\n    // now scale the angle and radius for source image lookup point\n    u = u * this.angleToWidth + this.c4 + this.viewport.x1 + 0.5;\n    v = (this.c2 - v) * this.radiusToHeight + this.viewport.y1;\n\n    //console.log(u, v, x, y);\n\n    return [u, v];\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getValidity(): 1 {\n    return 1;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getPartialDerivatives(x: number, y: number): PartialDerivatives {\n    const [, v] = this.getUV(x, y);\n\n    /*\n     * Arc Distortion Partial Scaling Vectors\n     * Are derived by mapping the perpendicular unit vectors\n     * dR  and  dA*R*2PI  rather than trying to map dx and dy\n     * The results is a very simple orthogonal aligned ellipse.\n     */\n    if (v > EPSILON) {\n      return [this.angleToWidth / (M_2PI * v), 0, 0, this.radiusToHeight];\n    } else {\n      return [this.viewportWidthX2, 0, 0, this.radiusToHeight];\n    }\n  }\n\n  /**\n   * @inheritDoc\n   */\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  getBestFitViewport(viewport: Viewport): Viewport {\n    // Forward Map Corners\n    let a = this.c0 - this.c1 / 2,\n      ca = Math.cos(a),\n      sa = Math.sin(a),\n      x = this.c2 * ca,\n      y = this.c2 * sa;\n    const vp = new Viewport(x, y, x, y);\n\n    x = (this.c2 - this.c3) * ca;\n    y = (this.c2 - this.c3) * sa;\n    vp.expand(x, y);\n\n    a = this.c0 + this.c1 / 2;\n    ca = Math.cos(a);\n    sa = Math.sin(a);\n    x = this.c2 * ca;\n    y = this.c2 * sa;\n    vp.expand(x, y);\n\n    x = (this.c2 - this.c3) * ca;\n    y = (this.c2 - this.c3) * sa;\n    vp.expand(x, y);\n\n    // Orthogonal points along top of arc\n    for (\n      a = Math.ceil((this.c0 - this.c1 / 2) / M_PI2) * M_PI2;\n      a < this.c0 + this.c1 / 2;\n      a += M_PI2\n    ) {\n      ca = Math.cos(a);\n      sa = Math.sin(a);\n      x = this.c2 * ca;\n      y = this.c2 * sa;\n      vp.expand(x, y);\n    }\n\n    vp.fixBounds();\n\n    return vp;\n  }\n\n  /**\n   * @param x\n   * @param y\n   * @private\n   */\n  private getUV(x: number, y: number): Point {\n    // what is the angle and radius in the destination image\n    let u = (Math.atan2(y, x) - this.c0) / M_2PI;\n    u -= Math.round(u);\n    const v = Math.hypot(x, y);\n\n    return [u, v];\n  }\n}\n","import { Viewport } from \"../../../pixel-accessor\";\nimport { Arc } from \"./Arc\";\nimport { EPSILON, M_2PI, M_PI2 } from \"../../../constants\";\nimport { InvalidArgument } from \"../../../exception\";\nimport { degreesToRadians } from \"../../../utils\";\nimport type { ReversePixelMapperFactory } from \"../../ReversePixelMapperFactory\";\n\n/**\n * Arc distortion arguments.\n */\nexport type ArcDistortionArgs =\n  | [number, number, number, number]\n  | [number, number, number]\n  | [number, number]\n  | [number];\n\n/**\n * Creates arc distortion class from arguments.\n *\n * Arguments:  **[angle, rotation, outer_radius, inner_radius]**\n * All but first argument are optional.\n *\n * By default, if the radii arguments are nor provided the image radius\n * is calculated so the horizontal center-line is fits the given arc\n * without scaling.\n *\n * The output image size is ALWAYS adjusted to contain the whole image,\n * and an offset is given to position image relative to the 0,0 point of\n * the origin, allowing users to use relative positioning onto larger\n * background.\n *\n * The arguments are converted to distortion coefficients.\n *\n *\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l01095 Generating coefficients for arc\n * distortion at ImageMagick source.\n */\nexport class ArcFactory\n  implements ReversePixelMapperFactory<ArcDistortionArgs>\n{\n  /**\n   * Creates Arc instance.\n   *\n   * @param args Arguments:\n   * * 0: **angle** - The angle over which to arc the image side-to-side.\n   * * 1: **rotation** - Angle to rotate image from vertical center.\n   * * 2: **outer_radius** - Set top edge of source image at this radius.\n   * * 3: **inner_radius** - Set bottom edge to this radius (radial scaling).\n   * @param viewport Source image viewport.\n   */\n  create(args: ArcDistortionArgs, viewport: Viewport): Arc {\n    if (args.length >= 1 && args[0] < EPSILON) {\n      throw new InvalidArgument(\"Angle too small\");\n    }\n\n    if (args.length >= 3 && args[2] !== undefined && args[2] < EPSILON) {\n      throw new InvalidArgument(\"Outer radius too small\");\n    }\n\n    let c0, c1, c2, c3;\n\n    c0 = -M_PI2; // -90, place at top!\n\n    if (args.length >= 1) {\n      c1 = degreesToRadians(args[0]);\n    } else {\n      c1 = M_PI2; // zero arguments - center is at top\n    }\n\n    if (args.length >= 2 && args[1] !== undefined) {\n      c0 += degreesToRadians(args[1]);\n    }\n\n    c0 /= M_2PI; // normalize radians\n    c0 -= Math.round(c0);\n    c0 *= M_2PI; // de-normalize back to radians\n\n    c3 = viewport.getHeight() - 1;\n    c2 = viewport.getWidth() / c1 + c3 / 2;\n\n    if (args.length >= 3 && args[2] !== undefined && args[3] !== undefined) {\n      if (args.length >= 4) {\n        c3 = args[2] - args[3];\n      } else {\n        c3 *= args[2] / c2;\n      }\n\n      c2 = args[2];\n    }\n\n    const c4 = (viewport.getWidth() - 1) / 2;\n\n    return new Arc(viewport, c0, c1, c2, c3, c4);\n  }\n}\n","import { Viewport } from \"../../../pixel-accessor\";\nimport type { Point } from \"../../../types\";\nimport type {\n  EwaReversePixelMapper,\n  PartialDerivatives,\n} from \"../../EwaReversePixelMapper\";\nimport type { BestFitReversePixelMapper } from \"../../BestFitReversePixelMapper\";\nimport type { ForwardPixelMapper } from \"../../ForwardPixelMapper\";\nimport { perceptibleReciprocal } from \"../../../utils\";\nimport { InvalidArgument } from \"../../../exception\";\n\n// prettier-ignore\n/**\n * Perspective matrix:\n * [ sx, ry, tx,\n *   rx, sy, ty,\n *   px, py, 1 ].\n */\nexport type PerspectiveMatrix = [\n  number, number, number,\n  number, number, number,\n  number, number\n];\n\n/**\n * Returns inverted perspective matrix.\n *\n * @param matrix\n *\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l00109 Inverting perspective matrix at ImageMagick source\n */\nexport function invertPerspectiveMatrix(\n  matrix: PerspectiveMatrix\n): PerspectiveMatrix {\n  const determinant = perceptibleReciprocal(\n    matrix[0] * matrix[4] - matrix[3] * matrix[1]\n  );\n\n  if (!determinant) {\n    throw new InvalidArgument(\"Given matrix can't be inverted\");\n  }\n\n  return [\n    determinant * (matrix[4] - matrix[7] * matrix[5]),\n    determinant * (matrix[7] * matrix[2] - matrix[1]),\n    determinant * (matrix[1] * matrix[5] - matrix[4] * matrix[2]),\n    determinant * (matrix[6] * matrix[5] - matrix[3]),\n    determinant * (matrix[0] - matrix[6] * matrix[2]),\n    determinant * (matrix[3] * matrix[2] - matrix[0] * matrix[5]),\n    determinant * (matrix[3] * matrix[7] - matrix[6] * matrix[4]),\n    determinant * (matrix[6] * matrix[1] - matrix[0] * matrix[7]),\n  ];\n}\n\n/**\n * Project coordinates using perspective projection matrix.\n *\n * @param x\n * @param y\n * @param matrix\n */\nexport function applyPerspectiveMatrix(\n  x: number,\n  y: number,\n  matrix: PerspectiveMatrix\n): [number, number] {\n  const p = matrix[0] * x + matrix[1] * y + matrix[2],\n    q = matrix[3] * x + matrix[4] * y + matrix[5],\n    r = matrix[6] * x + matrix[7] * y + 1;\n\n  return [p / r, q / r];\n}\n\n/**\n * Perspective Distortion (a ratio of affine distortions).\n *\n * ```\n *     p(x,y)    c0*x + c1*y + c2\n * u = ------ = ------------------\n *     r(x,y)    c6*x + c7*y + 1\n *\n *     q(x,y)    c3*x + c4*y + c5\n * v = ------ = ------------------\n *      r(x,y)    c6*x + c7*y + 1\n * ```\n *\n * denominator = Sign of 'r', or the denominator affine, for the actual image.\n * This determines what part of the distorted image is 'ground' side of the horizon, the other part is 'sky' or invalid.\n * Valid values are  +1.0  or  -1.0  only.\n *\n *\n * @see https://www.imagemagick.org/Usage/distorts/#perspective Perspective distortion details at ImageMagick docs\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l02450 Perspective distortion at ImageMagick source\n */\nexport class Perspective\n  implements\n    EwaReversePixelMapper,\n    BestFitReversePixelMapper,\n    ForwardPixelMapper\n{\n  /**\n   * Reverse matrix.\n   */\n  readonly matrix: PerspectiveMatrix;\n\n  /**\n   * Denominator for mapping validity calculation.\n   */\n  readonly denominator: number;\n\n  /**\n   * Forward matrix.\n   */\n  readonly forwardMatrix: PerspectiveMatrix;\n\n  /**\n   * @inheritDoc\n   */\n  readonly isConstantPartialDerivatives = false;\n\n  /**\n   * Cached Math.abs(matrix[6])\n   * @private\n   */\n  private absC6: number;\n\n  /**\n   * Cached Math.abs(matrix[7])\n   * @private\n   */\n  private absC7: number;\n\n  /**\n   * Perspective constructor.\n   *\n   * @param reverseMatrix Perspective projection matrix for reverse pixel mapping.\n   * @param denominator Sign of 'r', or the denominator affine, for the actual image.\n   * This determines what part of the distorted image is 'ground' side of the horizon, the other part is 'sky' or invalid.\n   * Valid values are  +1.0  or  -1.0  only.\n   */\n  constructor(reverseMatrix: PerspectiveMatrix, denominator: number) {\n    this.matrix = reverseMatrix;\n    this.denominator = denominator;\n    this.forwardMatrix = invertPerspectiveMatrix(reverseMatrix);\n    this.absC6 = Math.abs(reverseMatrix[6]);\n    this.absC7 = Math.abs(reverseMatrix[7]);\n  }\n\n  /**\n   * Creates Perspective instance using perspective matrix.\n   *\n   * @param matrix Perspective matrix.\n   *\n   * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l00853 Generating inverted perspective\n   * distortion matrix from forward perspective matrix at ImageMagick docs\n   */\n  static fromForwardMatrix(matrix: PerspectiveMatrix): Perspective {\n    const inverse = invertPerspectiveMatrix(matrix);\n\n    /*\n     * Calculate denominator! The ground-sky determination.\n     * What is sign of the 'ground' in r() denominator affine function?\n     * Just use any valid image coordinate in destination for determination.\n     * For a forward mapped perspective the images 0,0 coord will map to\n     * c2,c5 in the distorted image, so set the sign of denominator of that.\n     */\n    const denominator =\n      inverse[6] * matrix[2] + inverse[7] * matrix[5] + 1 < 0 ? -1 : 1;\n    return new Perspective(inverse, denominator);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  reverseMap(x: number, y: number): Point {\n    const p = this.matrix[0] * x + this.matrix[1] * y + this.matrix[2],\n      q = this.matrix[3] * x + this.matrix[4] * y + this.matrix[5],\n      r = this.matrix[6] * x + this.matrix[7] * y + 1;\n\n    return [p / r, q / r];\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getValidity(x: number, y: number, scaling: number): number {\n    const r = this.matrix[6] * x + this.matrix[7] * y + 1;\n    let validity = r * this.denominator < 0 ? 0 : 1;\n    const absR = Math.abs(r) * 2;\n\n    if (this.absC6 > this.absC7) {\n      if (absR < this.absC6) {\n        validity = 0.5 - (this.denominator * r) / (this.matrix[6] * scaling);\n      }\n    } else if (absR < this.absC7) {\n      validity = 0.5 - (this.denominator * r) / (this.matrix[7] * scaling);\n    }\n\n    return validity;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getPartialDerivatives(x: number, y: number): PartialDerivatives {\n    const p = this.matrix[0] * x + this.matrix[1] * y + this.matrix[2],\n      q = this.matrix[3] * x + this.matrix[4] * y + this.matrix[5],\n      r = this.matrix[6] * x + this.matrix[7] * y + 1,\n      scale = Math.pow(1 / r, 2);\n\n    return [\n      (r * this.matrix[0] - p * this.matrix[6]) * scale, // dUx\n      (r * this.matrix[1] - p * this.matrix[7]) * scale, // dUy\n      (r * this.matrix[3] - q * this.matrix[6]) * scale, // dVx\n      (r * this.matrix[4] - q * this.matrix[7]) * scale, //dVy\n    ];\n  }\n\n  /**\n   * @inheritDoc\n   */\n  forwardMap(u: number, v: number): Point {\n    return applyPerspectiveMatrix(u, v, this.forwardMatrix);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getBestFitViewport(viewport: Viewport): Viewport {\n    const u1 = viewport.x1,\n      v1 = viewport.y1,\n      u2 = viewport.x2 + 1,\n      v2 = viewport.y2 + 1,\n      [x, y] = this.forwardMap(u1, v1),\n      bestFit = new Viewport(x, y, x, y);\n\n    (\n      [\n        [u2, v1],\n        [u2, v2],\n        [u1, v2],\n      ] as [number, number][]\n    ).forEach((apex: [number, number]) =>\n      bestFit.expand(...this.forwardMap(...apex))\n    );\n\n    bestFit.fixBounds();\n\n    return bestFit;\n  }\n}\n","import { Perspective } from \"./Perspective\";\nimport { InvalidArgumentsLength } from \"../../../exception\";\nimport { LeastSquares } from \"../../../utils\";\nimport type { PerspectiveMatrix } from \"./Perspective\";\nimport type { ReversePixelMapperFactory } from \"../../ReversePixelMapperFactory\";\n\n/**\n * Perspective distortion factory.\n *\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l00745 Generating perspective distortion matrix\n * from control points at ImageMagick source\n */\nexport class PerspectiveFactory implements ReversePixelMapperFactory {\n  /**\n   * Creates Perspective instance using control points array.\n   *\n   * @param controlPoints Mappings of control points [u0, v0, x0, y0, ... , un, vn, xn, yn] where\n   * (u*, v*) are source (x, y) point and (x*, y*) are destination (x, y) point.\n   */\n  create(controlPoints: number[]): Perspective {\n    if (controlPoints.length < 16 || controlPoints.length % 4 !== 0) {\n      throw new InvalidArgumentsLength(\n        `Number of arguments must be multiple of 4 and at least 16 arguments (4 control points) expected. ` +\n          `${controlPoints.length} arguments given.`\n      );\n    }\n\n    const leastSquares = new LeastSquares(8, 1);\n\n    for (let i = 0; i < controlPoints.length; i += 4) {\n      const [u, v, x, y] = controlPoints.slice(i, i + 4);\n\n      leastSquares\n        .addTerms([x, y, 1, 0, 0, 0, -x * u, -y * u], [u])\n        .addTerms([0, 0, 0, x, y, 1, -x * v, -y * v], [v]);\n    }\n\n    const matrix = leastSquares.solve()[0] as PerspectiveMatrix;\n\n    /*\n     * Calculate denominator! The ground-sky determination.\n     * What is sign of the 'ground' in r() denominator affine function?\n     * Just use any valid image coordinate (first control point) in\n     * destination for determination of what part of view is 'ground'.\n     */\n    const denominator =\n      matrix[6] * controlPoints[2] + matrix[7] * controlPoints[3] + 1 < 0\n        ? -1\n        : 1;\n\n    return new Perspective(matrix, denominator);\n  }\n}\n","import { Perspective, type PerspectiveMatrix } from \"./Perspective\";\nimport type { ReversePixelMapperFactory } from \"../../ReversePixelMapperFactory\";\n\n/**\n * Creates PerspectiveProjection distortion.\n *\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l00853 Generating inverted perspective distortion\n * matrix from forward perspective matrix at ImageMagick source.\n */\nexport class PerspectiveProjectionFactory\n  implements ReversePixelMapperFactory<PerspectiveMatrix>\n{\n  /**\n   * Creates perspective distortion using perspective matrix.\n   *\n   * @param args Perspective matrix.\n   */\n  create(args: PerspectiveMatrix): Perspective {\n    return Perspective.fromForwardMatrix(args);\n  }\n}\n","import { EPSILON } from \"../../../constants\";\nimport { InvalidArgument, InvalidArgumentsLength } from \"../../../exception\";\nimport type { Point } from \"../../../types\";\nimport { LeastSquares } from \"../../../utils\";\nimport type {\n  EwaReversePixelMapper,\n  PartialDerivatives,\n} from \"../../EwaReversePixelMapper\";\nimport type { ReversePixelMapper } from \"../../ReversePixelMapper\";\nimport type { ReversePixelMapperFactory } from \"../../ReversePixelMapperFactory\";\n\n/**\n * Polynomial Distortion\n *\n * First two coefficients are used to hole global polynomial information\n *  c0 = Order of the polynomial being created\n *  c1 = number_of_terms in one polynomial equation\n *\n * Rest of the coefficients map to the equations....\n *    v = c0 + c1*x + c2*y + c3*x*y + c4*x^2 + c5*y^2 + c6*x^3 + ...\n * for each control point.\n * As such total coefficients =  2 + number_terms * 2\n *\n * Polynomial Distortion Notes:\n * + Order 1.5 is fudged to map into a bilinear distortion.\n *   though it is not the same order as that distortion.\n *\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l02631\n */\nexport class Polynomial implements ReversePixelMapper, EwaReversePixelMapper {\n  /**\n   * @inheritDoc\n   */\n  isConstantPartialDerivatives = false;\n\n  /**\n   * Polynomial constructor.\n   *\n   * @param coeffs\n   */\n  constructor(readonly coeffs: number[]) {}\n\n  /**\n   * @inheritDoc\n   */\n  reverseMap(x: number, y: number): Point {\n    const n = this.coeffs[1];\n    let sx = 0,\n      sy = 0;\n\n    for (let k = 0; k < n; k++) {\n      const basis = polyBasisFn(k, x, y);\n      sx += basis * this.coeffs[2 + k];\n      sy += basis * this.coeffs[2 + k + n];\n    }\n\n    return [sx, sy];\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getValidity(): 1 {\n    return 1;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getPartialDerivatives(x: number, y: number): PartialDerivatives {\n    const n = this.coeffs[1];\n    let dux = 0,\n      duy = 0,\n      dvx = 0,\n      dvy = 0;\n\n    for (let k = 0; k < n; k++) {\n      const basisDx = polyBasisDx(k, x, y);\n      const basisDy = polyBasisDy(k, x, y);\n      const indexX = 2 + k;\n      const indexY = indexX + n;\n      dux = basisDx * this.coeffs[indexX];\n      duy = basisDy * this.coeffs[indexX];\n      dvx = basisDx * this.coeffs[indexY];\n      dvy = basisDy * this.coeffs[indexY];\n    }\n\n    return [dux, duy, dvx, dvy];\n  }\n}\n\n/**\n * Polynomial distortion factory.\n *\n * First input argument is polynomial order.\n * Rest input Arguments are sets of control points.\n * order [u,v, x,y] ...\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l01094\n */\nexport class PolynomialFactory implements ReversePixelMapperFactory {\n  create(args: number[]): Polynomial {\n    const termsCount = numTerms(args[0]);\n\n    if (args.length < 1 + termsCount * 4) {\n      throw new InvalidArgumentsLength(\n        `Polynomial distortion of order ${\n          args[0]\n        } requires at least ${termsCount} control point pairs (1 + ${\n          termsCount * 4\n        } arguments)`\n      );\n    }\n\n    const leastSquares = new LeastSquares(termsCount, 2);\n\n    for (let i = 1; i < args.length; i += 4) {\n      const terms: number[] = [];\n      for (let j = 0; j < termsCount; j++) {\n        terms[j] = polyBasisFn(j, args[i + 2], args[i + 3]);\n      }\n      leastSquares.addTerms(terms, args.slice(i, i + 2));\n    }\n\n    return new Polynomial(\n      [args[0], termsCount].concat(leastSquares.solve().flat())\n    );\n  }\n}\n\n/**\n * Returns number of terms for a 2d polynomial\n *\n * @param order\n * @internal\n */\nfunction numTerms(order: number): number {\n  if (\n    order < 1 ||\n    order > 5 ||\n    (order != Math.floor(order) && order - 1.5 > EPSILON)\n  ) {\n    /* invalid polynomial order */\n    throw new InvalidArgument(`Invalid polynomial order: ${order}`);\n  }\n  return Math.floor(((order + 1) * (order + 2)) / 2);\n}\n\n/**\n * Returns result for given polynomial term\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l00153\n *\n * @param n\n * @param x\n * @param y\n * @internal\n */\nfunction polyBasisFn(n: number, x: number, y: number): number {\n  switch (n) {\n    case 0:\n      return 1.0; /* constant */\n    case 1:\n      return x;\n    case 2:\n      return y; /* affine          order = 1   terms = 3 */\n    case 3:\n      return x * y; /* bilinear        order = 1.5 terms = 4 */\n    case 4:\n      return x * x;\n    case 5:\n      return y * y; /* quadratic       order = 2   terms = 6 */\n    case 6:\n      return x * x * x;\n    case 7:\n      return x * x * y;\n    case 8:\n      return x * y * y;\n    case 9:\n      return y * y * y; /* cubic         order = 3   terms = 10 */\n    case 10:\n      return x * x * x * x;\n    case 11:\n      return x * x * x * y;\n    case 12:\n      return x * x * y * y;\n    case 13:\n      return x * y * y * y;\n    case 14:\n      return y * y * y * y; /* quartic     order = 4   terms = 15 */\n    case 15:\n      return x * x * x * x * x;\n    case 16:\n      return x * x * x * x * y;\n    case 17:\n      return x * x * x * y * y;\n    case 18:\n      return x * x * y * y * y;\n    case 19:\n      return x * y * y * y * y;\n    case 20:\n      return y * y * y * y * y; /* quintic   order = 5   terms = 21 */\n  }\n  return 0; /* should never happen */\n}\n\n/**\n * Returns polynomial term for x derivative\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l00209\n *\n * @param n\n * @param x\n * @param y\n * @internal\n */\nfunction polyBasisDx(n: number, x: number, y: number): number {\n  switch (n) {\n    case 0:\n      return 0.0; /* constant */\n    case 1:\n      return 1.0;\n    case 2:\n      return 0.0; /* affine      order = 1   terms = 3 */\n    case 3:\n      return y; /* bilinear    order = 1.5 terms = 4 */\n    case 4:\n      return x;\n    case 5:\n      return 0.0; /* quadratic   order = 2   terms = 6 */\n    case 6:\n      return x * x;\n    case 7:\n      return x * y;\n    case 8:\n      return y * y;\n    case 9:\n      return 0.0; /* cubic       order = 3   terms = 10 */\n    case 10:\n      return x * x * x;\n    case 11:\n      return x * x * y;\n    case 12:\n      return x * y * y;\n    case 13:\n      return y * y * y;\n    case 14:\n      return 0.0; /* quartic     order = 4   terms = 15 */\n    case 15:\n      return x * x * x * x;\n    case 16:\n      return x * x * x * y;\n    case 17:\n      return x * x * y * y;\n    case 18:\n      return x * y * y * y;\n    case 19:\n      return y * y * y * y;\n    case 20:\n      return 0.0; /* quintic     order = 5   terms = 21 */\n  }\n  return 0.0; /* should never happen */\n}\n\n/**\n * Returns polynomial term for y derivative.\n * @see https://imagemagick.org/api/MagickCore/distort_8c_source.html#l00237\n *\n * @param n\n * @param x\n * @param y\n * @internal\n */\nfunction polyBasisDy(n: number, x: number, y: number): number {\n  switch (n) {\n    case 0:\n      return 0.0; /* constant */\n    case 1:\n      return 0.0;\n    case 2:\n      return 1.0; /* affine      order = 1   terms = 3 */\n    case 3:\n      return x; /* bilinear    order = 1.5 terms = 4 */\n    case 4:\n      return 0.0;\n    case 5:\n      return y; /* quadratic   order = 2   terms = 6 */\n    default:\n      return polyBasisDx(n - 1, x, y); /* weird but true */\n  }\n  /* NOTE: the only reason that last is not true for 'quadratic'\n     is due to the re-arrangement of terms to allow for 'bilinear'\n  */\n}\n","import { Viewport } from \"../pixel-accessor\";\nimport type { ReversePixelMapperResolver } from \"./ReversePixelMapperResolver\";\nimport type {\n  GetReversePixelMapperFactoryArgs,\n  ReversePixelMapperFactoriesPool,\n  ReversePixelMapperFactoriesPoolKeyMap,\n} from \"./ReversePixelMapperFactoriesPool\";\nimport type { ReversePixelMapper } from \"./ReversePixelMapper\";\n\n/**\n * Base implementation of ReversePixelMapperResolver interface.\n */\nexport class BaseReversePixelMapperResolver\n  implements ReversePixelMapperResolver\n{\n  /**\n   * BaseReversePixelMapperResolver constructor.\n   *\n   * @param reversePixelMapperFactoriesPool\n   */\n  constructor(\n    private readonly reversePixelMapperFactoriesPool: ReversePixelMapperFactoriesPool\n  ) {}\n\n  /**\n   * @inheritDoc\n   */\n  resolve<K extends keyof ReversePixelMapperFactoriesPoolKeyMap | string>(\n    name: K,\n    args: GetReversePixelMapperFactoryArgs<K>,\n    viewport: Viewport\n  ): K extends keyof ReversePixelMapperFactoriesPoolKeyMap\n    ? ReturnType<ReversePixelMapperFactoriesPoolKeyMap[K][\"create\"]>\n    : ReversePixelMapper {\n    const factory = this.reversePixelMapperFactoriesPool.get(name);\n    return factory.create(\n      args,\n      viewport\n    ) as K extends keyof ReversePixelMapperFactoriesPoolKeyMap\n      ? ReturnType<ReversePixelMapperFactoriesPoolKeyMap[K][\"create\"]>\n      : ReversePixelMapper;\n  }\n}\n","import type { Point } from \"../types\";\n\n/**\n * Reverse pixel mapper interface.\n */\nexport interface ReversePixelMapper {\n  /**\n   * Maps destination image coordinates into source image coordinates.\n   *\n   * @param x Result image X coordinate.\n   * @param y Result image Y coordinate.\n   */\n  reverseMap(x: number, y: number): Point;\n\n  /**\n   * Returns number that represents how mathematically valid is mapping. If validity is < 0 -- the mapping is invalid.\n   * When mapping is invalid, matte color will be used. When validity is between 0 and 1, blended color of matte color\n   * and resampled color will be used.\n   *\n   * @param x\n   * @param y\n   * @param scaling\n   */\n  getValidity(x: number, y: number, scaling: number): number;\n}\n\n/**\n * Checks if passed object implements ReversePixelMapper interface.\n *\n * @param obj\n */\nexport function isReversePixelMapper(obj: unknown): obj is ReversePixelMapper {\n  if (typeof obj !== \"object\" || obj === null) {\n    return false;\n  }\n  type C = Partial<ReversePixelMapper>;\n  return (\n    typeof (obj as C).reverseMap === \"function\" &&\n    typeof (obj as C).getValidity === \"function\"\n  );\n}\n","import { Viewport } from \"../pixel-accessor\";\nimport type { ReversePixelMapper } from \"./ReversePixelMapper\";\nimport { isReversePixelMapper } from \"./ReversePixelMapper\";\n\nexport interface BestFitReversePixelMapper extends ReversePixelMapper {\n  /**\n   * Flags that distortion forces best fit for its performing.\n   */\n  readonly forceBestFit?: boolean;\n\n  /**\n   * Returns calculated best-fit viewport for given source image viewport.\n   *\n   * @param viewport Source image viewport.\n   */\n  getBestFitViewport(viewport: Viewport): Viewport;\n}\n\n/**\n * Checks if passed object implements BestFitReversePixelMapper interface.\n *\n * @param obj\n */\nexport function isBestFitReversePixelMapper(\n  obj: unknown\n): obj is BestFitReversePixelMapper {\n  type C = Partial<BestFitReversePixelMapper>;\n  return (\n    isReversePixelMapper(obj) &&\n    typeof (obj as C).getBestFitViewport === \"function\"\n  );\n}\n","/**\n * Names of built-in distortions.\n */\nexport enum Distortion {\n  /**\n   * Affine distortion using control points. Arguments are sets of control points mappings:\n   * [u0, v0, x0, y0, ..., uN, vN, xN, yN], where u*, v* are source image coords, x*, y* are destination image coords.\n   */\n  AFFINE = \"Affine\",\n\n  /**\n   * Affine distortion using forward affine matrix. Arguments are affine matrix coefficients: [sx, ry, rx, sy, tx, ty].\n   * *IMPORTANT NOTE: Arguments order differs from Affine.fromForwardMatrix arguments order which is\n   * [sx, rx, tx, ry, sy, ty]*\n   */\n  AFFINE_PROJECTION = \"AffineProjection\",\n\n  /**\n   * Perspective distortion using control points. Arguments are sets of control points mappings:\n   * [u0, v0, x0, y0, ..., uN, vN, xN, yN], where u*, v* are source image coords, x*, y* are destination image coords.\n   */\n  PERSPECTIVE = \"Perspective\",\n\n  /**\n   * Perspective distortion using forward perspective matrix.\n   * Arguments are perspective matrix coefficients: [sx, ry, tx, rx, sy, ty, px, py].\n   */\n  PERSPECTIVE_PROJECTION = \"PerspectiveProjection\",\n\n  /**\n   * Arc distortion. Arguments are: [arcAngle, rotation, outerRadius, innerRadius].\n   * All arguments except arcAngle are optional.\n   */\n  ARC = \"Arc\",\n\n  /**\n   * Polynomial distortion. Arguments: [order, u0, v0, x0, y0, ..., uN, vN, xN, yN].\n   * First argument is polynomial order, rest arguments are control points.\n   */\n  POLYNOMIAL = \"Polynomial\",\n\n  // /**\n  //  * Not implemented.\n  //  */\n  // SCALE_ROTATE_TRANSLATE = \"ScaleRotateTranslate\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // BILINEAR_FORWARD = \"BilinearForward\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // BILINEAR_REVERSE = \"BilinearReverse\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // POLAR = \"Polar\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // DE_POLAR = \"DePolar\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // CYLINDER_TO_PLANE = \"Cylinder2Plane\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // PLANE_TO_CYLINDER = \"Plane2Cylinder\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // BARREL = \"Barrel\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // BARREL_INVERSE = \"BarrelInverse\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // SHEPARDS = \"Shepards\", // TODO: implement\n}\n","import type { ReversePixelMapper } from \"./ReversePixelMapper\";\nimport { isReversePixelMapper } from \"./ReversePixelMapper\";\n\n/**\n * Partial derivatives of reverse mapping function.\n */\nexport type PartialDerivatives = [number, number, number, number];\n\n/**\n * ReversePixelMapper with support of Elliptical Weighted Average color resapmling.\n */\nexport interface EwaReversePixelMapper extends ReversePixelMapper {\n  /**\n   * Flags that pixel mapper has constant partial derivatives, so there is\n   * no need to recalculate EWA ellipse for each point.\n   */\n  readonly isConstantPartialDerivatives: boolean;\n\n  /**\n   * Returns mapper partial derivatives for given point.\n   *\n   * @param x\n   * @param y\n   */\n  getPartialDerivatives(x: number, y: number): PartialDerivatives;\n}\n\n/**\n * Checks if passed object implements EwaReversePixelMapper interface.\n *\n * @param obj\n */\nexport function isEwaReversePixelMapper(\n  obj: unknown\n): obj is EwaReversePixelMapper {\n  type C = Partial<EwaReversePixelMapper>;\n  return (\n    isReversePixelMapper(obj) &&\n    typeof (obj as C).getPartialDerivatives === \"function\" &&\n    typeof (obj as C).isConstantPartialDerivatives === \"boolean\"\n  );\n}\n","import type { ColorInterpolator } from \"../color-interpolator\";\nimport { MAXIMUM_VALUE } from \"../constants\";\nimport {\n  type HasAverageColor,\n  type HasBackgroundColor,\n  Viewport,\n  VirtualPixelMethod,\n  type VirtualViewportPixelAccessor,\n} from \"../pixel-accessor\";\nimport { isEwaReversePixelMapper } from \"../pixel-mapper\";\nimport type { Color } from \"../types\";\nimport { InvalidArgument } from \"../exception\";\nimport type {\n  EwaReversePixelMapper,\n  ReversePixelMapper,\n} from \"../pixel-mapper\";\nimport { blendColors } from \"../utils\";\nimport type { EwaColorResampler } from \"./EwaColorResampler\";\n\n/**\n * Clamps color channel value to given quantum range.\n *\n * @internal\n * @param value Color channel value.\n * @param quantumRange Quantum range.\n * @returns Color channel value, clamped to given range.\n * @public\n */\nfunction clampToQuantum(value: number, quantumRange: number): number {\n  return Math.max(0, Math.min(quantumRange, value));\n}\n\n/**\n * ClampEllipseAxes() function converts the input vectors into a major and\n * minor axis unit vectors, and their magnitude.  This allows us to\n * ensure that the ellipse generated is never smaller than the unit\n * circle and thus never too small for use in EWA resampling.\n *\n * This purely mathematical 'magic' was provided by Professor Nicolas\n * Robidoux and his Masters student Chantal Racette.\n *\n * Reference: \"We Recommend Singular Value Decomposition\", David Austin\n *   @link http://www.ams.org/samplings/feature-column/fcarc-svd\n *\n * By generating major and minor axis vectors, we can actually use the\n * ellipse in its \"canonical form\", by remapping the dx,dy of the\n * sampled point into distances along the major and minor axis unit\n * vectors.\n *\n * Reference: @link http://en.wikipedia.org/wiki/Ellipse#Canonical_form\n *\n * @see https://imagemagick.org/api/MagickCore/resample_8c_source.html#l00709 ClampUpAxes() at ImageMagick source\n *\n * @param dux\n * @param duy\n * @param dvx\n * @param dvy\n *\n * @internal\n */\nfunction clampEllipseAxes(\n  dux: number,\n  duy: number,\n  dvx: number,\n  dvy: number\n): [number, number, number, number, number, number] {\n  /*\n   * ClampUpAxes takes an input 2x2 matrix\n   *\n   * [ a b ] = [ dux duy ]\n   * [ c d ] = [ dvx dvy ]\n   *\n   * and computes from it the major and minor axis vectors [major_x, major_y] and [minor_x,minor_y] of the smallest\n   * ellipse containing both the unit disk and the ellipse which is the image of the unit disk by the linear\n   * transformation\n   *\n   * [ dux duy ] [S] = [s]\n   * [ dvx dvy ] [T] = [t]\n   *\n   * (The vector [S,T] is the difference between a position in output space and [X,Y]; the vector [s,t] is the\n   * difference between a position in input space and [x,y].)\n   *\n   * Output:\n   *\n   * major_mag is the half-length of the major axis of the \"new\" ellipse.\n   *\n   * minor_mag is the half-length of the minor axis of the \"new\" ellipse.\n   *\n   * major_unit_x is the x-coordinate of the major axis direction vector of both the \"old\" and \"new\" ellipses.\n   *\n   * major_unit_y is the y-coordinate of the major axis direction vector.\n   *\n   * minor_unit_x is the x-coordinate of the minor axis direction vector.\n   *\n   * minor_unit_y is the y-coordinate of the minor axis direction vector.\n   *\n   * Unit vectors are useful for computing projections, in particular, to compute the distance between a point in\n   * output space and the center of a unit disk in output space, using the position of the corresponding point [s,t]\n   * in input space. Following the clamping, the square of this distance is\n   *\n   * ( ( s * major_unit_x + t * major_unit_y ) / major_mag )^2\n   * +\n   * ( ( s * minor_unit_x + t * minor_unit_y ) / minor_mag )^2\n   *\n   * If such distances will be computed for many [s,t]'s, it makes sense to actually compute the reciprocal\n   * of major_mag and minor_mag and multiply them by the above unit lengths.\n   *\n   * Now, if you want to modify the input pair of tangent vectors so that it defines the modified ellipse,\n   * all you have to do is set\n   *\n   * newdux = major_mag * major_unit_x\n   * newdvx = major_mag * major_unit_y\n   * newduy = minor_mag * minor_unit_x = minor_mag * -major_unit_y\n   * newdvy = minor_mag * minor_unit_y = minor_mag *  major_unit_x\n   *\n   * and use these tangent vectors as if they were the original ones.\n   * Usually, this is a drastic change in the tangent vectors even if the singular values are not clamped; for example,\n   * the minor axis vector always points in a direction which is 90 degrees counterclockwise from the direction of the\n   * major axis vector.\n   *\n   * Discussion:\n   *\n   * GOAL: Fix things so that the pullback, in input space, of a disk of radius r in output space is an ellipse which\n   * contains, at least, a disc of radius r. (Make this hold for any r>0.)\n   *\n   * ESSENCE OF THE METHOD: Compute the product of the first two factors of an SVD of the linear transformation\n   * defining the ellipse and make sure that both its columns have norm at least 1.\n   * Because rotations and reflexions map disks to themselves, it is not necessary to compute the third (rightmost)\n   * factor of the SVD.\n   *\n   * DETAILS: Find the singular values and (unit) left singular vectors of Jinv, clampling up the singular values to 1,\n   * and multiply the unit left singular vectors by the new singular values in order to get the minor and major ellipse\n   * axis vectors.\n   *\n   * Image resampling context:\n   *\n   * The Jacobian matrix of the transformation at the output point under consideration is defined as follows:\n   *\n   * Consider the transformation (x,y) -> (X,Y) from input locations to output locations.\n   * (Anthony Thyssen, elsewhere in resample.c, uses the notation (u,v) -> (x,y).)\n   *\n   * The Jacobian matrix of the transformation at (x,y) is equal to\n   *\n   *   J = [ A, B ] = [ dX/dx, dX/dy ]\n   *       [ C, D ]   [ dY/dx, dY/dy ]\n   *\n   * that is, the vector [A,C] is the tangent vector corresponding to input changes in the horizontal direction, and\n   * the vector [B,D] is the tangent vector corresponding to input changes in the vertical direction.\n   *\n   * In the context of resampling, it is natural to use the inverse Jacobian matrix Jinv because resampling is\n   * generally performed by pulling pixel locations in the output image back to locations in the input image.\n   * Jinv is\n   *\n   *   Jinv = [ a, b ] = [ dx/dX, dx/dY ]\n   *          [ c, d ]   [ dy/dX, dy/dY ]\n   *\n   * Note: Jinv can be computed from J with the following matrix formula:\n   *\n   *   Jinv = 1/(A*D-B*C) [  D, -B ]\n   *                      [ -C,  A ]\n   *\n   * What we do is modify Jinv so that it generates an ellipse which is as close as possible to the original but which\n   * contains the unit disk. This can be accomplished as follows:\n   *\n   * Let\n   *\n   *   Jinv = U Sigma V^T\n   *\n   * be an SVD decomposition of Jinv. (The SVD is not unique, but the final ellipse does not depend on the\n   * particular SVD.)\n   *\n   * We could clamp up the entries of the diagonal matrix Sigma so that they are at least 1, and then set\n   *\n   *   Jinv = U newSigma V^T.\n   *\n   * However, we do not need to compute V for the following reason: V^T is an orthogonal matrix (that is, it represents\n   * a combination of rotations and reflexions) so that it maps the unit circle to itself. For this reason, the exact\n   * value of V does not affect the final ellipse, and we can choose V to be the identity matrix. This gives\n   *\n   *   Jinv = U newSigma.\n   *\n   * In the end, we return the two diagonal entries of newSigma together with the two columns of U.\n   *\n   * ClampUpAxes was written by Nicolas Robidoux and Chantal Racette of Laurentian University with insightful\n   * suggestions from Anthony Thyssen and funding from the National Science and Engineering Research Council of Canada.\n   * It is distinguished from its predecessors by its efficient handling of degenerate cases.\n   *\n   * The idea of clamping up the EWA ellipse's major and minor axes so that the result contains the reconstruction\n   * kernel filter support is taken from Andreas Gustaffson's Masters thesis \"Interactive Image Warping\", Helsinki\n   * University of Technology, Faculty of Information Technology, 59 pages, 1993 (see Section 3.6).\n   *\n   * The use of the SVD to clamp up the singular values of the Jacobian matrix of the pullback transformation for\n   * EWA resampling is taken from the astrophysicist Craig DeForest.  It is implemented in his PDL::Transform code\n   * (PDL = Perl Data Language).\n   */\n\n  const a = dux;\n  const b = duy;\n  const c = dvx;\n  const d = dvy;\n\n  /*\n   * n is the matrix Jinv * transpose(Jinv). Eigenvalues of n are the squares of the singular values of Jinv.\n   */\n  const aa = a * a;\n  const bb = b * b;\n  const cc = c * c;\n  const dd = d * d;\n\n  /*\n   * Eigenvectors of n are left singular vectors of Jinv.\n   */\n  const n11 = aa + bb;\n  const n12 = a * c + b * d;\n  const n21 = n12;\n  const n22 = cc + dd;\n  const det = a * d - b * c;\n  const twice_det = det + det;\n  const frobenius_squared = n11 + n22;\n  const discriminant =\n    (frobenius_squared + twice_det) * (frobenius_squared - twice_det);\n\n  /*\n   * In exact arithmetic, discriminant can't be negative. In floating point, it can, because of the bad conditioning\n   * of SVD decompositions done through the associated normal matrix.\n   */\n  const sqrt_discriminant = Math.sqrt(discriminant > 0 ? discriminant : 0);\n\n  /*\n   * s1 is the largest singular value of the inverse Jacobian matrix. In other words, its reciprocal is the smallest\n   * singular value of the Jacobian matrix itself.\n   * If s1 = 0, both singular values are 0, and any orthogonal pair of left and right factors produces a singular\n   * decomposition of Jinv.\n   *\n   * Initially, we only compute the squares of the singular values.\n   */\n  const s1s1 = 0.5 * (frobenius_squared + sqrt_discriminant);\n\n  /*\n   * s2 the smallest singular value of the inverse Jacobian matrix. Its reciprocal is the largest singular value of the\n   * Jacobian matrix itself.\n   */\n  const s2s2 = 0.5 * (frobenius_squared - sqrt_discriminant);\n  const s1s1minusn11 = s1s1 - n11;\n  const s1s1minusn22 = s1s1 - n22;\n\n  /*\n   * u1, the first column of the U factor of a singular decomposition of Jinv, is a (non-normalized) left singular\n   * vector corresponding to s1. It has entries u11 and u21. We compute u1 from the fact that it is an eigenvector\n   * of n corresponding to the eigenvalue s1^2.\n   */\n  const s1s1minusn11_squared = s1s1minusn11 * s1s1minusn11;\n  const s1s1minusn22_squared = s1s1minusn22 * s1s1minusn22;\n\n  /*\n   * The following selects the largest row of n-s1^2 I as the one which is used to find the eigenvector.\n   * If both s1^2-n11 and s1^2-n22 are zero, n-s1^2 I is the zero matrix.  In that case, any vector is an eigenvector;\n   * in addition, norm below is equal to zero, and, in exact arithmetic, this is the only case in which norm = 0.\n   * So, setting u1 to the simple but arbitrary vector [1,0] if norm = 0 safely takes care of all cases.\n   */\n  const temp_u11 =\n    s1s1minusn11_squared >= s1s1minusn22_squared ? n12 : s1s1minusn22;\n  const temp_u21 =\n    s1s1minusn11_squared >= s1s1minusn22_squared ? s1s1minusn11 : n21;\n  const norm = Math.sqrt(temp_u11 * temp_u11 + temp_u21 * temp_u21);\n\n  /*\n   * Finalize the entries of first left singular vector (associated with the largest singular value).\n   */\n  const u11 = norm > 0 ? temp_u11 / norm : 1;\n  const u21 = norm > 0 ? temp_u21 / norm : 0;\n\n  /*\n   * Clamp the singular values up to 1.\n   */\n  const major_mag = s1s1 <= 1 ? 1 : Math.sqrt(s1s1);\n  const minor_mag = s2s2 <= 1 ? 1 : Math.sqrt(s2s2);\n\n  const major_x = u11 * major_mag;\n  const major_y = u21 * major_mag;\n  const minor_x = -u21 * minor_mag;\n  const minor_y = u11 * minor_mag;\n\n  return [major_x, major_y, minor_x, minor_y, major_mag, minor_mag];\n}\n\n/**\n * Elliptical Weighted Average color resampler.\n * Resamples pixel color using Elliptical Weighted Average technique.\n *\n * @see https://www.imagemagick.org/Usage/distorts/#distort_ewa EWA details at ImageMagick docs.\n * @see https://www2.eecs.berkeley.edu/Pubs/TechRpts/1989/CSD-89-516.pdf Fundamentals of Texture Mapping and Image Warping by Paul S. Heckbert\n * page 41, section 3.4, 3.5\n * @see https://imagemagick.org/api/MagickCore/resample_8c_source.html#l01038 ScaleResampleFilter() at\n * ImageMagick source.\n * @see https://imagemagick.org/api/MagickCore/resample_8c_source.html#l00315 ResamplePixelColor() at\n * ImageMagick source.\n */\nexport class EwaResampler implements EwaColorResampler {\n  /**\n   * Distortion mapper.\n   */\n  private pixelMapper: EwaReversePixelMapper;\n\n  /**\n   * Squared practical working support of the filter.\n   */\n  private readonly supportSq: number;\n\n  /**\n   * Matte color for invalid mappings.\n   */\n  private readonly matteColor: Color;\n\n  /**\n   * Lookup table of weights for filtered average in elliptical area.\n   */\n  private readonly weightLookupTable: number[];\n\n  /**\n   * Image being resampled.\n   */\n  private readonly image: VirtualViewportPixelAccessor &\n    HasBackgroundColor &\n    HasAverageColor;\n\n  /**\n   * Cached for direct access image virtual viewport.\n   */\n  private readonly imageViewport: Viewport;\n\n  /**\n   * Cached image area.\n   */\n  private readonly imageArea: number;\n\n  /**\n   * Cached for direct access image virtual pixel method.\n   */\n  private readonly imageVirtualPixelMethod: VirtualPixelMethod;\n\n  /**\n   * Cached image average color.\n   */\n  private imageAverageColor: Color | null;\n\n  /**\n   * Ellipse equation A.\n   */\n  private A: number;\n\n  /**\n   * Ellipse equation B.\n   */\n  private B: number;\n\n  /**\n   * Ellipse equation C.\n   */\n  private C: number;\n\n  /**\n   * Ellipse equation F.\n   */\n  private F: number;\n\n  /**\n   * Ellipse bounding parallelogram limit by u-axis.\n   */\n  private uLimit: number;\n\n  /**\n   * Ellipse bounding parallelogram limit by v-axis.\n   */\n  private vLimit: number;\n\n  /**\n   * Ellipse bounding parallelogram width by u-axis.\n   */\n  private uWidth: number;\n\n  /**\n   * Ellipse bounding parallelogram slope.\n   */\n  private slope: number;\n\n  /**\n   * Used for distortions with constant partial derivatives to flag that ellipse already has been set up.\n   */\n  private ellipseIsSetUp: boolean;\n\n  /**\n   * Flags that ellipse is too large, and it is impractical to resample color -- better use some of possible\n   * optimizations.\n   */\n  private limitReached: boolean;\n\n  /**\n   * Output image scaling factor.\n   */\n  private scaling: number;\n\n  /**\n   * Image quantum range.\n   */\n  private readonly quantumRange: number;\n\n  /**\n   * Cached weight lookup table length.\n   * @private\n   */\n  private readonly weightLookupTableSize: number;\n\n  /**\n   * Average color interpolator\n   * @private\n   */\n  private readonly averageInterpolator: ColorInterpolator;\n\n  /**\n   * Default color interpolator.\n   * @private\n   */\n  private readonly defaultInterpolator: ColorInterpolator;\n\n  /**\n   * EwaResampler constructor.\n   *\n   * @param image\n   * @param pixelMapper\n   * @param weightLookupTable\n   * @param workingSupport\n   * @param averageInterpolator\n   * @param defaultInterpolator\n   * @param matteColor\n   * @param imageVirtualPixelMethod\n   */\n  constructor(\n    image: VirtualViewportPixelAccessor & HasBackgroundColor & HasAverageColor,\n    pixelMapper: ReversePixelMapper,\n    weightLookupTable: number[],\n    workingSupport: number,\n    averageInterpolator: ColorInterpolator,\n    defaultInterpolator: ColorInterpolator,\n    matteColor: Color = [0, 0, 0, 0],\n    imageVirtualPixelMethod: VirtualPixelMethod\n  ) {\n    if (!isEwaReversePixelMapper(pixelMapper)) {\n      throw new InvalidArgument(\n        \"Pixel Mapper must implement ReversePixelMapperWithEwaSupport in \" +\n          \"order to use Elliptical Weighted Average re-sampling.\"\n      );\n    }\n    this.supportSq = workingSupport * workingSupport;\n    this.matteColor = matteColor;\n    this.weightLookupTable = weightLookupTable;\n    this.weightLookupTableSize = weightLookupTable.length;\n    this.image = image;\n    this.pixelMapper = pixelMapper;\n    this.imageViewport = this.image.getViewport();\n    this.imageArea = this.imageViewport.getArea();\n    this.imageVirtualPixelMethod = imageVirtualPixelMethod;\n    this.imageAverageColor = null;\n    this.A = 0;\n    this.B = 0;\n    this.C = 0;\n    this.F = 0;\n    this.uLimit = 0;\n    this.vLimit = 0;\n    this.uWidth = 0;\n    this.slope = 0;\n    this.ellipseIsSetUp = false;\n    this.limitReached = false;\n    this.scaling = 1;\n    this.quantumRange = image.getQuantumRange();\n    this.averageInterpolator = averageInterpolator;\n    this.defaultInterpolator = defaultInterpolator;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getWeightLookupTable(): number[] {\n    return this.weightLookupTable;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getScaling(): number {\n    return this.scaling;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  setScaling(scaling: number): this {\n    this.scaling = scaling;\n    return this;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getResampledColor(x: number, y: number): Color {\n    x = (x + 0.5) * this.scaling;\n    y = (y + 0.5) * this.scaling;\n\n    const validity = this.pixelMapper.getValidity(x, y, this.scaling);\n\n    if (validity > 0) {\n      const [u, v] = this.pixelMapper.reverseMap(x, y);\n\n      if (\n        !this.pixelMapper.isConstantPartialDerivatives ||\n        !this.ellipseIsSetUp\n      ) {\n        const derivatives = this.pixelMapper.getPartialDerivatives(x, y);\n        this.setupEllipse(\n          derivatives[0],\n          derivatives[1],\n          derivatives[2],\n          derivatives[3]\n        );\n        this.ellipseIsSetUp = true;\n      }\n\n      const color = this.getWeightedAverage(u - 0.5, v - 0.5);\n\n      if (validity < 1) {\n        return blendColors(color, this.matteColor, validity);\n      }\n\n      return color;\n    }\n\n    return this.matteColor;\n  }\n\n  /**\n   * Calculates ellipse for EWA resampling using partial derivatives.\n   *\n   * @param dux\n   * @param duy\n   * @param dvx\n   * @param dvy\n   */\n  private setupEllipse(\n    dux: number,\n    duy: number,\n    dvx: number,\n    dvy: number\n  ): this {\n    this.limitReached = false;\n    const s = this.scaling;\n    return this.initEllipse(dux * s, duy * s, dvx * s, dvy * s).scaleEllipse();\n  }\n\n  /**\n   * Calculates ellipse equation for given distortion partial derivatives.\n   *\n   * @param dux\n   * @param duy\n   * @param dvx\n   * @param dvy\n   */\n  private initEllipse(\n    dux: number,\n    duy: number,\n    dvx: number,\n    dvy: number\n  ): this {\n    const [major_x, major_y, minor_x, minor_y, major_mag, minor_mag] =\n      clampEllipseAxes(dux, duy, dvx, dvy);\n\n    this.A = major_y * major_y + minor_y * minor_y;\n    this.B = -2 * (major_x * major_y + minor_x * minor_y);\n    this.C = major_x * major_x + minor_x * minor_x;\n    this.F = major_mag * minor_mag;\n    this.F *= this.F;\n\n    /*\n     * If one or both of the scaling vectors is impossibly large (producing a very large raw F value), we may as well\n     * not bother doing any form of resampling since resampled area is very large.\n     * In this case some alternative means of pixel sampling, such as the average of the whole image is needed to get\n     * a reasonable result. Calculate only as needed.\n     */\n    this.limitReached = 4 * this.A * this.C - this.B * this.B > MAXIMUM_VALUE;\n\n    return this;\n  }\n\n  /**\n   * Scales ellipse to match filter support.\n   */\n  private scaleEllipse(): this {\n    if (!this.limitReached) {\n      this.F *= this.supportSq;\n      this.uLimit = Math.sqrt(\n        (this.C * this.F) / (this.A * this.C - 0.25 * this.B * this.B)\n      );\n      this.vLimit = Math.sqrt(\n        (this.A * this.F) / (this.A * this.C - 0.25 * this.B * this.B)\n      );\n      this.uWidth = Math.sqrt(this.F / this.A);\n      this.slope = -this.B / (2 * this.A);\n\n      /*\n       * Check the absolute area of the parallelogram involved.\n       * This limit needs more work, as it is too slow for larger images with tiled views of the horizon.\n       */\n      if (this.uWidth * this.vLimit > 4 * this.imageArea) {\n        this.limitReached = true;\n        return this;\n      }\n\n      /* Scale ellipse formula to directly index the Filter Lookup Table */\n      const scale = this.weightLookupTableSize / this.F;\n      this.A *= scale;\n      this.B *= scale;\n      this.C *= scale;\n    }\n\n    return this;\n  }\n\n  /**\n   * Returns weighted average color at given point using scaled EWA ellipse.\n   *\n   * @param u0 Source image x-coordinate.\n   * @param v0 Source image y-coordinate.\n   */\n  private getWeightedAverage(u0: number, v0: number): Color {\n    if (this.doesntNeedResampling(u0, v0)) {\n      /* The area being resampled is simply a solid color just return a single lookup color. */\n      return this.image.getPixelColor(u0, v0);\n    }\n\n    if (this.limitReached) {\n      // When Scaling limits reached, return an 'averaged' result.\n\n      switch (this.imageVirtualPixelMethod) {\n        case VirtualPixelMethod.EDGE:\n        case VirtualPixelMethod.HORIZONTAL_TILE_EDGE:\n        case VirtualPixelMethod.VERTICAL_TILE_EDGE:\n          /*\n           * We need an average edge pixel, from the correct edge!\n           * How should I calculate an average edge color?\n           * Just returning an averaged neighbourhood,\n           * works well in general, but falls down for TileEdge methods.\n           * This needs to be done properly!!!!!!\n           */\n          return this.averageInterpolator.interpolate(this.image, u0, v0);\n        case VirtualPixelMethod.HORIZONTAL_TILE:\n        case VirtualPixelMethod.VERTICAL_TILE:\n          /*\n           * just return the background pixel - Is there more direct way?\n           */\n          return this.image.getPixelColor(\n            this.imageViewport.x1 - 1,\n            this.imageViewport.y1 - 1\n          );\n        default:\n          return this.getImageAverageColor();\n      }\n    }\n\n    let divisorM = 0,\n      divisorC = 0,\n      red = 0,\n      green = 0,\n      blue = 0,\n      alpha = 0;\n\n    /*\n     * Determine the parallelogram bounding box fitted to the ellipse centered at u0,v0.\n     * This area is bounding by the lines...\n     */\n    const v1 = Math.ceil(v0 - this.vLimit);\n    const v2 = Math.floor(v0 + this.vLimit);\n\n    // scan line start and getWidth across the parallelogram\n    let u1 = u0 + (v1 - v0) * this.slope - this.uWidth;\n    const uw = 2 * this.uWidth + 1;\n\n    const A = this.A;\n    const B = this.B;\n    const image = this.image;\n    const weightLookupTable = this.weightLookupTable;\n\n    /*\n     * Do weighted resampling of all pixels,  within the scaled ellipse,\n     * bound by a Parallelogram fitted to the ellipse.\n     */\n\n    const DDQ = 2 * A;\n\n    for (let v = v1; v < v2; v++) {\n      const ustart = Math.ceil(u1); // first pixel in scanline\n      u1 += this.slope; // start of next scan line\n      const uend = ustart + uw;\n\n      // location of this first pixel, relative to u0,v0\n      const U = ustart - u0;\n      const V = v - v0;\n\n      // Q = ellipse quotent ( if Q<F then pixel is inside ellipse)\n      let Q = (A * U + B * V) * U + this.C * V * V;\n      let DQ = A * (2 * U + 1) + B * V;\n\n      // count up the weighted pixel colors\n      for (let u = ustart; u < uend; u++) {\n        // Note that the ellipse has been pre-scaled so F = this.weightLookupTableLength\n        if (Q < this.weightLookupTableSize) {\n          let weight = weightLookupTable[Math.floor(Q)];\n          const [r, g, b, a] = image.getPixelColor(u, v);\n          alpha += weight * a;\n          divisorM += weight;\n\n          weight *= a / this.quantumRange;\n\n          red += r * weight;\n          green += g * weight;\n          blue += b * weight;\n          divisorC += weight;\n        }\n\n        Q += DQ;\n        DQ += DDQ;\n      }\n    }\n\n    // Result sanity check -- this should NOT happen\n    if (!divisorC || !divisorM) {\n      /*\n       * not enough pixels, or bad weighting in resampling, resort to direct interpolation\n       */\n      return this.defaultInterpolator.interpolate(this.image, u0, v0);\n    }\n\n    return [\n      clampToQuantum(Math.round(red / divisorC), this.quantumRange),\n      clampToQuantum(Math.round(green / divisorC), this.quantumRange),\n      clampToQuantum(Math.round(blue / divisorC), this.quantumRange),\n      clampToQuantum(Math.round(alpha / divisorM), this.quantumRange),\n    ];\n  }\n\n  /**\n   * Checks if no resampling is needed (if single pixel color should be returned).\n   *\n   * @param u Source image x-coordinate.\n   * @param v Source image y-coordinate.\n   */\n  private doesntNeedResampling(u: number, v: number): boolean {\n    switch (this.imageVirtualPixelMethod) {\n      case VirtualPixelMethod.TRANSPARENT:\n      case VirtualPixelMethod.BACKGROUND:\n      case VirtualPixelMethod.BLACK:\n      case VirtualPixelMethod.WHITE:\n      case VirtualPixelMethod.GRAY:\n        return this.limitReached || this.outOfImageBounds(u, v);\n      case VirtualPixelMethod.EDGE:\n        return (\n          (u + this.uLimit < this.imageViewport.x1 &&\n            v + this.vLimit < this.imageViewport.y1) ||\n          (u + this.uLimit < this.imageViewport.x1 &&\n            v - this.vLimit > this.imageViewport.y2) ||\n          (u - this.uLimit > this.imageViewport.x2 &&\n            v + this.vLimit < this.imageViewport.y1) ||\n          (u - this.uLimit > this.imageViewport.x2 &&\n            v - this.vLimit > this.imageViewport.y2)\n        );\n      case VirtualPixelMethod.HORIZONTAL_TILE:\n        return (\n          v + this.vLimit < this.imageViewport.y1 ||\n          v - this.vLimit > this.imageViewport.y2\n        );\n      case VirtualPixelMethod.VERTICAL_TILE:\n        return (\n          u + this.uLimit < this.imageViewport.x1 ||\n          u - this.uLimit > this.imageViewport.x2\n        );\n      default:\n        return false;\n    }\n  }\n\n  /**\n   * Lazily returns cached image average color.\n   */\n  private getImageAverageColor(): Color {\n    if (this.imageAverageColor === null) {\n      this.imageAverageColor = this.image.getAverageColor();\n    }\n\n    return this.imageAverageColor;\n  }\n\n  /**\n   * Checks if ellipse is completely out of image bounds.\n   *\n   * @private\n   * @param u Source image x-coordinate.\n   * @param v Source image y-coordinate.\n   */\n  private outOfImageBounds(u: number, v: number): boolean {\n    return (\n      u + this.uLimit < this.imageViewport.x1 ||\n      u - this.uLimit > this.imageViewport.x2 ||\n      v + this.vLimit < this.imageViewport.y1 ||\n      v - this.vLimit > this.imageViewport.y2\n    );\n  }\n}\n","import {\n  type ColorInterpolatorFactory,\n  InterpolationMethod,\n} from \"../color-interpolator\";\nimport {\n  type HasAverageColor,\n  type HasBackgroundColor,\n  VirtualPixelMethod,\n  type VirtualViewportPixelAccessor,\n} from \"../pixel-accessor\";\nimport type { ReversePixelMapper } from \"../pixel-mapper\";\nimport type { ResampleFilter } from \"../resample-filter\";\nimport type {\n  ColorResamplerFactory,\n  ColorResamplerFactoryOptions,\n} from \"./ColorResamplerFactory\";\nimport { EwaResampler } from \"./EwaResampler\";\n\n/**\n * EwaResampler factory class.\n */\nexport class EwaResamplerFactory implements ColorResamplerFactory {\n  /**\n   * EwaResamplerFactory constructor.\n   *\n   * @param colorInterpolatorFactory\n   */\n  constructor(\n    private readonly colorInterpolatorFactory: ColorInterpolatorFactory\n  ) {}\n\n  /**\n   * @inheritDoc\n   */\n  readonly supportsEwa = true;\n\n  /**\n   * @inheritDoc\n   */\n  readonly requiresResampleFilter = true;\n\n  /**\n   * @inheritDoc\n   */\n  create(\n    image: VirtualViewportPixelAccessor & HasAverageColor & HasBackgroundColor,\n    reversePixelMapper: ReversePixelMapper,\n    options: ColorResamplerFactoryOptions = {}\n  ): EwaResampler {\n    const {\n      resampleFilter,\n      matteColor = [0, 0, 0, 0],\n      interpolationMethod = InterpolationMethod.AVERAGE,\n      virtualPixelMethod = VirtualPixelMethod.TRANSPARENT,\n    } = options;\n\n    if (!resampleFilter) {\n      throw new TypeError(\"EWA resampler requires ResampleFilter.\");\n    }\n\n    const weightLookupTable = buildWeightLookupTable(resampleFilter);\n    const workingSupport = resampleFilter.getWorkingSupport();\n\n    const averageInterpolator = this.colorInterpolatorFactory.create(\n      InterpolationMethod.AVERAGE\n    );\n    const defaultInterpolator =\n      interpolationMethod === InterpolationMethod.AVERAGE\n        ? averageInterpolator\n        : this.colorInterpolatorFactory.create(interpolationMethod);\n\n    return new EwaResampler(\n      image,\n      reversePixelMapper,\n      weightLookupTable,\n      workingSupport,\n      averageInterpolator,\n      defaultInterpolator,\n      matteColor,\n      virtualPixelMethod\n    );\n  }\n}\n\n/**\n * Weight lookup table array length.\n * @internal\n */\nconst WEIGHT_LOOKUP_TABLE_WIDTH = 1024;\n\n/**\n * Builds weight lookup table.\n *\n * @internal\n * @param filter Resample filter.\n */\nfunction buildWeightLookupTable(filter: ResampleFilter): number[] {\n  const table = [];\n  const support = filter.getWorkingSupport();\n\n  const rScale = support * Math.sqrt(1 / WEIGHT_LOOKUP_TABLE_WIDTH);\n\n  for (let Q = 0; Q < WEIGHT_LOOKUP_TABLE_WIDTH; Q++) {\n    table[Q] = filter.getWeight(Math.sqrt(Q) * rScale);\n  }\n\n  return table;\n}\n","import type { ColorInterpolator } from \"../color-interpolator\";\nimport type { HasBackgroundColor, PixelAccessor } from \"../pixel-accessor\";\nimport type { Color } from \"../types\";\nimport { blendColors } from \"../utils\";\nimport type { ColorResampler } from \"./ColorResampler\";\nimport type { ReversePixelMapper } from \"../pixel-mapper\";\n\n/**\n * Simple ColorResampler implementation without resampling, using interpolation only.\n * It uses pixel color interpolation and works much faster than EllipticalWeightedAverage but produces aliasing\n * effects.\n * It is good for quick creation of distortion previews and also used for ReversePixelMapper implementations\n * that doesn't have partial derivatives.\n * It works most quickly when ImageAdapter.interpolationMethod is set to InterpolationMethod.INTEGER.\n */\nexport class PointResampler implements ColorResampler {\n  /**\n   * Image being resampled.\n   */\n  private readonly image: PixelAccessor & HasBackgroundColor;\n\n  /**\n   * Distortion mapper.\n   */\n  private readonly pixelMapper: ReversePixelMapper;\n\n  /**\n   * Matte color for invalid mappings.\n   */\n  private readonly matteColor: Color;\n\n  /**\n   * Output image scaling factor.\n   */\n  private scaling: number;\n\n  /**\n   * Color interpolator.\n   * @private\n   */\n  private readonly interpolator: ColorInterpolator;\n\n  /**\n   * PointResampler constructor.\n   *\n   * @param image\n   * @param pixelMapper\n   * @param interpolator\n   * @param matteColor\n   */\n  constructor(\n    image: PixelAccessor & HasBackgroundColor,\n    pixelMapper: ReversePixelMapper,\n    interpolator: ColorInterpolator,\n    matteColor: Color = [0, 0, 0, 0]\n  ) {\n    this.image = image;\n    this.pixelMapper = pixelMapper;\n    this.interpolator = interpolator;\n    this.matteColor = matteColor;\n    this.scaling = 1;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getScaling(): number {\n    return this.scaling;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  setScaling(scaling: number): this {\n    this.scaling = scaling;\n    return this;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getResampledColor(x: number, y: number): Color {\n    x = (x + 0.5) * this.scaling;\n    y = (y + 0.5) * this.scaling;\n\n    const validity = this.pixelMapper.getValidity(x, y, this.scaling);\n\n    if (validity > 0) {\n      const [u, v] = this.pixelMapper.reverseMap(x, y);\n      const color = this.interpolator.interpolate(this.image, u - 0.5, v - 0.5);\n\n      if (validity < 1) {\n        return blendColors(color, this.matteColor, validity);\n      }\n\n      return color;\n    }\n\n    return this.matteColor;\n  }\n}\n","import {\n  type ColorInterpolatorFactory,\n  InterpolationMethod,\n} from \"../color-interpolator\";\nimport type { HasBackgroundColor, PixelAccessor } from \"../pixel-accessor\";\nimport type {\n  ColorResamplerFactory,\n  ColorResamplerFactoryOptions,\n} from \"./ColorResamplerFactory\";\nimport { PointResampler } from \"./PointResampler\";\nimport type { ReversePixelMapper } from \"../pixel-mapper\";\n\n/**\n * PointResampler factory class.\n */\nexport class PointResamplerFactory implements ColorResamplerFactory {\n  /**\n   * PointResamplerFactory constructor.\n   * @param colorInterpolatorFactory\n   */\n  constructor(\n    private readonly colorInterpolatorFactory: ColorInterpolatorFactory\n  ) {}\n\n  /**\n   * @inheritDoc\n   */\n  readonly supportsEwa = false;\n\n  /**\n   * @inheritDoc\n   */\n  readonly requiresResampleFilter = false;\n\n  /**\n   * @inheritDoc\n   */\n  create(\n    image: PixelAccessor & HasBackgroundColor,\n    reversePixelMapper: ReversePixelMapper,\n    options: ColorResamplerFactoryOptions = {}\n  ): PointResampler {\n    const {\n      matteColor = [0, 0, 0, 0],\n      interpolationMethod = InterpolationMethod.AVERAGE,\n    } = options;\n\n    return new PointResampler(\n      image,\n      reversePixelMapper,\n      this.colorInterpolatorFactory.create(interpolationMethod),\n      matteColor\n    );\n  }\n}\n","import type { Color } from \"../types\";\nimport type { ColorStringParser } from \"./ColorStringParser\";\nimport type { ColorStringParsersPool } from \"./ColorStringParsersPool\";\n\n/**\n * Composite color string parser. Trying to parse given color string using parsers from pool unless appropriate\n * parser is found.\n */\nexport class CompositeColorStringParser implements ColorStringParser {\n  /**\n   * CompositeColorStringParser constructor.\n   *\n   * @param parsersPool\n   */\n  constructor(private readonly parsersPool: ColorStringParsersPool) {}\n\n  /**\n   * @inheritDoc\n   */\n  parse(colorString: string, quantumRange = 255): Color | undefined {\n    for (const parser of this.parsersPool.items()) {\n      const color = parser.parse(colorString, quantumRange);\n      if (color) {\n        return color;\n      }\n    }\n  }\n}\n","import type { Color } from \"../types\";\nimport type { ColorStringParser } from \"./ColorStringParser\";\n\n/**\n * HEX color string parser. Parses color strings in hex format.\n * @example \"#f00\", \"#00BB99\", \"#ff00ff77\"\n */\nexport class HexColorStringParser implements ColorStringParser {\n  /**\n   * @inheritDoc\n   */\n  parse(colorString: string, quantumRange = 255): Color | undefined {\n    if (/^#[a-f\\d]{3}$/i.test(colorString)) {\n      colorString =\n        \"#\" +\n        colorString\n          .slice(1)\n          .split(\"\")\n          .map((char) => char.repeat(2))\n          .join(\"\");\n    }\n\n    const match = colorString.match(\n      /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})?$/i\n    );\n\n    if (!match) {\n      return;\n    }\n\n    return [\n      Math.round((parseInt(match[1], 16) / 255) * quantumRange),\n      Math.round((parseInt(match[2], 16) / 255) * quantumRange),\n      Math.round((parseInt(match[3], 16) / 255) * quantumRange),\n      match[4]\n        ? Math.round((parseInt(match[4], 16) / 255) * quantumRange)\n        : quantumRange,\n    ];\n  }\n}\n","/**\n * Color type.\n *\n * Array of 4 elements representing color channel values:\n * 0: red;\n * 1: green;\n * 2: blue;\n * 3: alpha.\n * Each channel value must be in range [0; _QuantumRange_].\n * Alpha channel must be 0 for completely transparent color and quantumRange (255 for 8 bit\n * per channel images) for 100% opaque color.\n */\nexport type Color = readonly [number, number, number, number];\n\n/**\n * Checks if given argument is assignable to color type.\n *\n * @param candidate\n */\nexport function isColor(candidate: unknown): candidate is Color {\n  if (!Array.isArray(candidate)) {\n    return false;\n  }\n  if (candidate.length !== 4) {\n    return false;\n  }\n  return candidate.every((channel) => typeof channel === \"number\");\n}\n","/**\n * Tuple of X and Y coordinates.\n */\nexport type Point = [number, number];\n\n/**\n * Checks if given argument is assignable to Point type.\n *\n * @param candidate\n */\nexport function isPoint(candidate: unknown): candidate is Point {\n  return (\n    Array.isArray(candidate) &&\n    candidate.length === 2 &&\n    typeof candidate[0] === \"number\" &&\n    typeof candidate[1] === \"number\"\n  );\n}\n","import { isColor } from \"../types\";\nimport type { Color } from \"../types\";\nimport type { ColorStringParser } from \"./ColorStringParser\";\n\n/**\n * RGBA color string parser. Parses color string in rgb(R, G, B) and rgba(R, G, B, A) formats.\n * @example \"rgb(100%, 50%, 25%)\", \"rgba(255, 127, 63, .5)\"\n */\nexport class RgbaColorStringParser implements ColorStringParser {\n  /**\n   * @inheritDoc\n   */\n  parse(colorString: string, quantumRange = 255): Color | undefined {\n    if (!/^\\s*rgba?/.test(colorString)) {\n      return;\n    }\n\n    const match = colorString\n      .replace(/\\s/g, \"\")\n      .match(/(\\d+(\\.\\d+)?%?)|(\\.\\d+%?)/g);\n\n    if (!match || match.length < 3) {\n      return;\n    }\n\n    if (match.length === 3) {\n      match.push(\"1\");\n    }\n\n    const color = match\n      .map((channel, index) => {\n        const num = parseFloat(channel);\n        if (index === 3) {\n          // alpha channel value should be between 0 and 1\n          return Math.round(num * quantumRange);\n        }\n        if (channel.indexOf(\"%\") !== -1) {\n          return Math.round((num / 100) * quantumRange);\n        }\n        return Math.round((num / 255) * quantumRange);\n      })\n      .filter((n) => !isNaN(n));\n\n    if (isColor(color)) {\n      return color;\n    }\n  }\n}\n","import type { Color } from \"../types\";\nimport type { ColorStringParser } from \"./ColorStringParser\";\n\n/**\n * Parses \"transparent\" color string.\n */\nexport class TransparentStringParser implements ColorStringParser {\n  /**\n   * @inheritDoc\n   */\n  parse(colorString: string): Color | undefined {\n    if (colorString !== \"transparent\") {\n      return;\n    }\n    return [0, 0, 0, 0];\n  }\n}\n","import type { ColorResampler } from \"../color-resampler\";\nimport { AbortException } from \"../exception\";\nimport type { ImageAdapter } from \"../image-adapter\";\nimport { createDeferred, type Deferred } from \"../utils\";\nimport type { DistortionProcessor } from \"./DistortionProcessor\";\n\n/**\n * Reverse pixel mapping process scope.\n * @internal\n */\nexport interface ProcessScope<ResourceType> {\n  /**\n   * Deferred object which will be resolved when all image pixels are processed.\n   */\n  deferred: Deferred<void>;\n\n  /**\n   * Target image.\n   */\n  image: ImageAdapter<ResourceType>;\n\n  /**\n   * Color resampler.\n   */\n  resampler: ColorResampler;\n\n  /**\n   * Current X position, remembered between partial image pixels loops.\n   */\n  currentX: number;\n\n  /**\n   * Current Y position, remembered between partial image pixels loops.\n   */\n  currentY: number;\n\n  /**\n   * Start X position, remembered between partial image pixels loops.\n   */\n  startX: number;\n\n  /**\n   * End X position, remembered between partial image pixels loops.\n   */\n  endX: number;\n\n  /**\n   * End Y position, remembered between partial image pixels loops.\n   */\n  endY: number;\n}\n\n/**\n * Reverse Pixel Mapping processor.\n */\nexport class ReversePixelMappingProcessor implements DistortionProcessor {\n  /**\n   * ReversePixelMappingProcessor constructor.\n   *\n   * @param asyncTimeout Timeout for delaying further pixel processing.\n   */\n  constructor(\n    private asyncTimeout: number,\n    private abortSignal?: AbortSignal\n  ) {}\n\n  /**\n   * Processes reverse pixel mapping.\n   *\n   * @param targetImage\n   * @param resampler\n   */\n  async process<ResourceType>(\n    targetImage: ImageAdapter<ResourceType>,\n    resampler: ColorResampler\n  ): Promise<ImageAdapter<ResourceType>> {\n    const scope = this.createProcessScope(targetImage, resampler);\n    this.doProcess(scope, this.asyncTimeout);\n    await scope.deferred.promise;\n    targetImage.commit();\n    return targetImage;\n  }\n\n  /**\n   * Creates scope for particular image processing.\n   *\n   * @param image\n   * @param resampler\n   * @private\n   */\n  private createProcessScope<ResourceType>(\n    image: ImageAdapter<ResourceType>,\n    resampler: ColorResampler\n  ): ProcessScope<ResourceType> {\n    const vp = image.getViewport();\n    const startX = Math.floor(vp.x1);\n    const endX = Math.floor(vp.x2);\n    const endY = Math.floor(vp.y2);\n    const currentX = startX;\n    const currentY = Math.floor(vp.y1);\n    return {\n      deferred: createDeferred(),\n      image,\n      resampler,\n      startX,\n      endX,\n      endY,\n      currentX,\n      currentY,\n    };\n  }\n\n  /**\n   * Processes copying of resampled colors of source image to target image.\n   *\n   * @param scope\n   * @param asyncTimeout\n   * @private\n   */\n  private doProcess<ResourceType>(\n    scope: ProcessScope<ResourceType>,\n    asyncTimeout: number\n  ): void {\n    if (this.abortSignal && this.abortSignal.aborted) {\n      scope.deferred.reject(\n        this.abortSignal.reason instanceof Error\n          ? this.abortSignal.reason\n          : new AbortException(String(this.abortSignal.reason))\n      );\n      return;\n    }\n    const startTime = Date.now();\n    const { image, resampler, startX, endX, endY } = scope;\n    let { currentX: x, currentY: y } = scope;\n\n    while (y <= endY) {\n      while (x <= endX) {\n        image.setPixelColor(x, y, resampler.getResampledColor(x, y));\n        x++;\n\n        if (Date.now() - startTime >= asyncTimeout) {\n          scope.currentX = x;\n          scope.currentY = y;\n          setTimeout(this.doProcess.bind(this, scope, asyncTimeout), 0);\n          return;\n        }\n      }\n      y++;\n      x = startX;\n    }\n\n    scope.deferred.resolve();\n  }\n}\n","import type { DistortionProcessor } from \"./DistortionProcessor\";\nimport type { ImageAdapter } from \"../image-adapter\";\nimport type { ColorResampler } from \"../color-resampler\";\n\n/**\n * Proxy for performing image colors super-sampling.\n */\nexport class SuperSamplingProxy implements DistortionProcessor {\n  /**\n   * SuperSamplingProxy constructor.\n   *\n   * @param processor\n   * @param superSamplingFactor\n   */\n  constructor(\n    private readonly processor: DistortionProcessor,\n    private readonly superSamplingFactor: number\n  ) {}\n\n  /**\n   * Sets resampler's scaling before distortion processing and scales processed image after distortion is processed.\n   *\n   * @param targetImage\n   * @param resampler\n   */\n  async process<ResourceType>(\n    targetImage: ImageAdapter<ResourceType>,\n    resampler: ColorResampler\n  ): Promise<ImageAdapter<ResourceType>> {\n    if (this.superSamplingFactor !== 1) {\n      resampler.setScaling(1 / this.superSamplingFactor);\n    }\n    const result = await this.processor.process(targetImage, resampler);\n    if (this.superSamplingFactor !== 1) {\n      return result.scale(1 / this.superSamplingFactor);\n    }\n    return result;\n  }\n}\n","import type { ImageAdapter } from \"./ImageAdapter\";\nimport { Viewport } from \"../pixel-accessor\";\nimport type { Color } from \"../types\";\n\n/**\n * Abstract image class for ImageAdapter implementation.\n */\nexport abstract class AbstractImageAdapter<ResourceType>\n  implements ImageAdapter<ResourceType>\n{\n  /**\n   * Image width.\n   */\n  readonly width: number;\n\n  /**\n   * Image height.\n   */\n  readonly height: number;\n\n  /**\n   * Image virtual viewport.\n   */\n  protected viewport: Viewport;\n\n  /**\n   * Image background color.\n   */\n  protected backgroundColor: Color;\n\n  /**\n   * Image quantum range (per channel).\n   */\n  protected quantumRange: number;\n\n  /**\n   * AbstractImageAdapter constructor.\n   *\n   * @param width Image width.\n   * @param height Image height.\n   */\n  protected constructor(width: number, height: number) {\n    this.width = width;\n    this.height = height;\n    this.viewport = new Viewport(0, 0, this.width - 1, this.height - 1);\n    this.backgroundColor = [0, 0, 0, 0];\n    this.quantumRange = 255;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  abstract getPixelColor(x: number, y: number): Color;\n\n  /**\n   * @inheritDoc\n   */\n  abstract setPixelColor(x: number, y: number, color: Color): void;\n\n  /**\n   * @inheritDoc\n   */\n  abstract getAverageColor(): Color;\n\n  /**\n   * Returns resized instance of self.\n   *\n   * @param width New width.\n   * @param height New height.\n   * @returns New resized instance.\n   */\n  protected abstract resize(\n    width: number,\n    height: number\n  ): ImageAdapter<ResourceType>;\n\n  /**\n   * @inheritDoc\n   */\n  abstract getResource(): ResourceType;\n\n  /**\n   * Prepares blank image for ImageAdapter.getBlank method.\n   *\n   * @param width Image width.\n   * @param height Image height.\n   */\n  protected abstract prepareBlank(\n    width: number,\n    height: number\n  ): ImageAdapter<ResourceType>;\n\n  /**\n   * @inheritDoc\n   */\n  abstract commit(): void;\n\n  /**\n   * @inheritDoc\n   */\n  getViewport(): Viewport {\n    return this.viewport;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  setViewport(viewport: Viewport): this {\n    this.viewport = viewport;\n    return this;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getBackgroundColor(): Color {\n    return this.backgroundColor;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  setBackgroundColor(color: Color): this {\n    this.backgroundColor = color;\n    return this;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getQuantumRange(): number {\n    return this.quantumRange;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getBlank(viewport: Viewport): ImageAdapter<ResourceType> {\n    const blank = this.prepareBlank(viewport.getWidth(), viewport.getHeight());\n    blank.setViewport(viewport);\n    return this.duplicateProps(blank);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  scale(scale: number): ImageAdapter<ResourceType> {\n    const viewport = this.viewport.clone();\n    viewport.scale(scale);\n\n    const resized = this.resize(viewport.getWidth(), viewport.getHeight());\n    resized.setViewport(viewport);\n    return this.duplicateProps(resized);\n  }\n\n  /**\n   * Used to copy some props in methods that returns new instance.\n   *\n   * @param instance Instance which props should be set.\n   */\n  protected duplicateProps(\n    instance: ImageAdapter<ResourceType>\n  ): ImageAdapter<ResourceType> {\n    instance.setBackgroundColor(this.backgroundColor);\n    return instance;\n  }\n}\n","import type { ImageAdapterResolver } from \"./ImageAdapterResolver\";\nimport type { ImageAdapter } from \"./ImageAdapter\";\nimport type { ImageAdapterFactoriesPool } from \"./ImageAdapterFactoriesPool\";\nimport type { ImageAdapterFactory } from \"./ImageAdapterFactory\";\n\n/**\n * Base implementation of ImageAdapterResolver interface.\n */\nexport class BaseImageAdapterResolver implements ImageAdapterResolver {\n  /**\n   * BaseImageAdapterResolver constructor.\n   *\n   * @param factoriesPool\n   */\n  constructor(private readonly factoriesPool: ImageAdapterFactoriesPool) {}\n\n  /**\n   * @inheritDoc\n   */\n  resolve<ResourceType>(resource: ResourceType): ImageAdapter<ResourceType> {\n    const factories = this.factoriesPool.items();\n    const factory = factories.find((f) => f.match(resource));\n    if (factory) {\n      return (factory as ImageAdapterFactory<ResourceType>).create(resource);\n    }\n    const resourceName = Object.prototype.toString.call(resource).slice(8, -1);\n    throw new TypeError(\n      `No matching image adapter factory for resource of type ${resourceName}`\n    );\n  }\n}\n","import { preloadHtmlImage, makeCanvas } from \"../utils\";\nimport { AbstractImageAdapter } from \"./AbstractImageAdapter\";\nimport type { ImageAdapter } from \"./ImageAdapter\";\nimport type { Color } from \"../types\";\n\n/**\n * Canvas element or offscreen canvas.\n */\nexport type BrowserCanvas = HTMLCanvasElement | OffscreenCanvas;\n\n/**\n * Browser canvas rendering context 2d.\n */\nexport type BrowserCanvasContext2d =\n  | CanvasRenderingContext2D\n  | OffscreenCanvasRenderingContext2D;\n\n/**\n * Returns canvas rendering context.\n *\n * @param canvas\n */\nfunction getCanvasContext(canvas: BrowserCanvas): BrowserCanvasContext2d {\n  const context = canvas.getContext(\"2d\", { willReadFrequently: true });\n  if (!context) {\n    throw new Error(\"Couldn't get canvas context\");\n  }\n  return context as BrowserCanvasContext2d;\n}\n\n/**\n * ImageAdapter implementation for distortion using HTML5 Canvas objects.\n */\nexport class Canvas\n  extends AbstractImageAdapter<BrowserCanvas>\n  implements ImageAdapter<BrowserCanvas>\n{\n  /**\n   * Browser canvas (HTMLCanvasElement or OffscreenCanvas) with image resource.\n   */\n  protected canvas: BrowserCanvas;\n\n  /**\n   * ImageData object to work with.\n   */\n  protected imageData: ImageData;\n\n  /**\n   * ImageData.data array stored for faster access.\n   */\n  protected data: Uint8ClampedArray;\n\n  /**\n   * Canvas constructor.\n   *\n   * @param canvas HTML5 Canvas or offscreen canvas with image data.\n   */\n  constructor(canvas: BrowserCanvas) {\n    super(canvas.width, canvas.height);\n    this.canvas = canvas;\n    this.imageData = getCanvasContext(canvas).getImageData(\n      0,\n      0,\n      canvas.width,\n      canvas.height\n    );\n    this.data = this.imageData.data;\n  }\n\n  /**\n   * Creates new instance using CanvasImageSource.\n   *\n   * @param image\n   */\n  static createFromImage(\n    image: CanvasImageSource & { width: number; height: number }\n  ): Canvas {\n    const canvas = makeCanvas(image.width, image.height);\n    getCanvasContext(canvas).drawImage(image, 0, 0);\n    return new Canvas(canvas);\n  }\n\n  /**\n   * Asynchronously creates Canvas instance from image url.\n   *\n   * @param url\n   */\n  static async createFromUrl(url: string): Promise<Canvas> {\n    const image = await preloadHtmlImage(url);\n    return this.createFromImage(image);\n  }\n\n  /**\n   * Asynchronously creates Canvas instance from Blob or File.\n   *\n   * @param blob\n   */\n  static async createFromBlob(blob: Blob): Promise<Canvas> {\n    const bitmap = await createImageBitmap(blob);\n    return this.createFromImage(bitmap);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getPixelColor(x: number, y: number): Color {\n    const offset = (y * this.width + x) * 4;\n    return [\n      this.data[offset],\n      this.data[offset + 1],\n      this.data[offset + 2],\n      this.data[offset + 3],\n    ];\n  }\n\n  /**\n   * @inheritDoc\n   */\n  setPixelColor(x: number, y: number, color: Color): void {\n    const offset = (y * this.width + x) * 4;\n    this.data[offset] = color[0];\n    this.data[offset + 1] = color[1];\n    this.data[offset + 2] = color[2];\n    this.data[offset + 3] = color[3];\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getAverageColor(): Color {\n    const canvas = makeCanvas(1, 1);\n    const context = getCanvasContext(canvas);\n    context.drawImage(this.canvas, 0, 0, this.width, this.height, 0, 0, 1, 1);\n    return Array.prototype.slice.call(\n      context.getImageData(0, 0, 1, 1).data\n    ) as unknown as Color;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  protected resize(width: number, height: number): Canvas {\n    const dst = makeCanvas(width, height, !this.isOffscreen());\n    getCanvasContext(dst).drawImage(\n      this.canvas,\n      0,\n      0,\n      this.width,\n      this.height,\n      0,\n      0,\n      width,\n      height\n    );\n    return new Canvas(dst);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getResource(): BrowserCanvas {\n    return this.canvas;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  protected prepareBlank(width: number, height: number): Canvas {\n    return new Canvas(makeCanvas(width, height, !this.isOffscreen()));\n  }\n\n  /**\n   * @inheritDoc\n   */\n  commit(): void {\n    getCanvasContext(this.canvas).putImageData(this.imageData, 0, 0);\n  }\n\n  /**\n   * Returns true if underlying canvas resource is OffscreenCanvas\n   */\n  isOffscreen(): boolean {\n    return (\n      typeof OffscreenCanvas !== undefined &&\n      this.canvas instanceof OffscreenCanvas\n    );\n  }\n}\n","import type { ImageAdapterFactory } from \"./ImageAdapterFactory\";\nimport { type BrowserCanvas, Canvas } from \"./Canvas\";\nimport type { ImageAdapter } from \"./ImageAdapter\";\n\n/**\n * Canvas image adapter factory.\n */\nexport class CanvasFactory implements ImageAdapterFactory<BrowserCanvas> {\n  /**\n   * @inheritDoc\n   */\n  match(resource: unknown): boolean {\n    return (\n      (typeof HTMLCanvasElement !== \"undefined\" &&\n        resource instanceof HTMLCanvasElement) ||\n      (typeof OffscreenCanvas !== \"undefined\" &&\n        resource instanceof OffscreenCanvas)\n    );\n  }\n\n  /**\n   * @inheritDoc\n   */\n  create(resource: BrowserCanvas): ImageAdapter<BrowserCanvas> {\n    return new Canvas(resource);\n  }\n}\n","import {\n  type VirtualViewportPixelAccessor,\n  type Viewport,\n  type HasBackgroundColor,\n  type HasAverageColor,\n  isVirtualViewportPixelAccessor,\n  isHasAverageColor,\n  isHasBackgroundColor,\n} from \"../pixel-accessor\";\nimport type { Color } from \"../types\";\n\n/**\n * Image adapter interface.\n */\nexport interface ImageAdapter<ResourceType>\n  extends VirtualViewportPixelAccessor,\n    HasBackgroundColor,\n    HasAverageColor {\n  /**\n   * Sets image virtual viewport.\n   *\n   * @param viewport\n   */\n  setViewport(viewport: Viewport): void;\n\n  /**\n   * Sets image background color.\n   *\n   * @param color\n   */\n  setBackgroundColor(color: Color): void;\n\n  /**\n   * Returns new blank image with given virtual viewport.\n   *\n   * @param viewport\n   */\n  getBlank(viewport: Viewport): ImageAdapter<ResourceType>;\n\n  /**\n   * Scales image and its virtual viewport.\n   *\n   * @param scale\n   */\n  scale(scale: number): ImageAdapter<ResourceType>;\n\n  /**\n   * Returns underlying image resource.\n   */\n  getResource(): ResourceType;\n\n  /**\n   * Method called after distortion process to synchronize distorted image data with underlying image resource if needed.\n   */\n  commit(): void;\n}\n\n/**\n * Checks if passed object implements ImageAdapter interface.\n *\n * @param obj\n */\nexport function isImageAdapter(obj: unknown): obj is ImageAdapter<unknown> {\n  type C = Partial<ImageAdapter<unknown>>;\n  return (\n    isVirtualViewportPixelAccessor(obj) &&\n    isHasAverageColor(obj) &&\n    isHasBackgroundColor(obj) &&\n    typeof (obj as C).setViewport === \"function\" &&\n    typeof (obj as C).setBackgroundColor === \"function\" &&\n    typeof (obj as C).getBlank === \"function\" &&\n    typeof (obj as C).scale === \"function\" &&\n    typeof (obj as C).getResource === \"function\" &&\n    typeof (obj as C).commit === \"function\"\n  );\n}\n","import { Viewport } from \"../pixel-accessor\";\nimport type { Color } from \"../types\";\nimport type { ImageAdapter } from \"./ImageAdapter\";\n\n/**\n * Adds virtual viewport offset support to ImageAdapter.\n */\nexport class VirtualViewportProxy<ResourceType>\n  implements ImageAdapter<ResourceType>\n{\n  /**\n   * @inheritDoc\n   */\n  readonly width: number;\n\n  /**\n   * @inheritDoc\n   */\n  readonly height: number;\n\n  /**\n   * Virtual viewport X offset.\n   * @private\n   */\n  private offsetX: number;\n\n  /**\n   * Virtual viewport Y offset.\n   * @private\n   */\n  private offsetY: number;\n\n  /**\n   * VirtualViewportProxy constructor.\n   *\n   * @param adapter\n   */\n  constructor(private readonly adapter: ImageAdapter<ResourceType>) {\n    ({ x1: this.offsetX, y1: this.offsetY } = adapter.getViewport());\n    ({ width: this.width, height: this.height } = adapter);\n  }\n\n  /**\n   * Returns wrapped ImageAdapter.\n   */\n  getAdapter(): ImageAdapter<ResourceType> {\n    return this.adapter;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getPixelColor(x: number, y: number): Color {\n    return this.adapter.getPixelColor(\n      Math.floor(x - this.offsetX),\n      Math.floor(y - this.offsetY)\n    );\n  }\n\n  /**\n   * @inheritDoc\n   */\n  setPixelColor(x: number, y: number, color: Color): void {\n    this.adapter.setPixelColor(\n      Math.floor(x - this.offsetX),\n      Math.floor(y - this.offsetY),\n      color\n    );\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getViewport(): Viewport {\n    return this.adapter.getViewport();\n  }\n\n  /**\n   * @inheritDoc\n   */\n  setViewport(viewport: Viewport): void {\n    this.adapter.setViewport(viewport);\n    ({ x1: this.offsetX, y1: this.offsetY } = viewport);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getBackgroundColor(): Color {\n    return this.adapter.getBackgroundColor();\n  }\n\n  /**\n   * @inheritDoc\n   */\n  setBackgroundColor(color: Color): void {\n    this.adapter.setBackgroundColor(color);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getAverageColor(): Color {\n    return this.adapter.getAverageColor();\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getQuantumRange(): number {\n    return this.adapter.getQuantumRange();\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getBlank(viewport: Viewport): ImageAdapter<ResourceType> {\n    const blank = this.adapter.getBlank(viewport);\n    return new VirtualViewportProxy(blank);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  scale(scale: number): ImageAdapter<ResourceType> {\n    const scaled = this.adapter.scale(scale);\n    return new VirtualViewportProxy(scaled);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getResource(): ResourceType {\n    return this.adapter.getResource();\n  }\n\n  /**\n   * @inheritDoc\n   */\n  commit(): void {\n    return this.adapter.commit();\n  }\n}\n","import {\n  isViewportLiteral,\n  Viewport,\n  type ViewportLiteral,\n} from \"../pixel-accessor\";\nimport { isPoint } from \"../types\";\nimport type { DistortionProcessor } from \"./DistortionProcessor\";\nimport { type ImageAdapter } from \"../image-adapter\";\nimport type { ColorResampler } from \"../color-resampler\";\nimport type { Point } from \"../types\";\n\n/**\n * Proxy for performing image virtual viewport re-paging after distortion process.\n */\nexport class RepageProxy implements DistortionProcessor {\n  /**\n   * RepageProxy constructor.\n   *\n   * @param processor\n   * @param repage\n   */\n  constructor(\n    private readonly processor: DistortionProcessor,\n    private readonly repage?: Point | ViewportLiteral\n  ) {}\n\n  /**\n   * Applies provided offset to image virtual viewport or resets image viewport offset to (0, 0) if no offset was provided.\n   *\n   * @param targetImage\n   * @param resampler\n   */\n  async process<ResourceType>(\n    targetImage: ImageAdapter<ResourceType>,\n    resampler: ColorResampler\n  ): Promise<ImageAdapter<ResourceType>> {\n    const result = await this.processor.process(targetImage, resampler);\n    result.getViewport().reset();\n    if (isPoint(this.repage)) {\n      result.getViewport().offset(...this.repage);\n    } else if (isViewportLiteral(this.repage)) {\n      result.setViewport(Viewport.fromLiteral(this.repage));\n    }\n    return result;\n  }\n}\n","import { isViewportLiteral } from \"../pixel-accessor\";\nimport { isPoint } from \"../types\";\nimport type {\n  DistortionProcessorFactory,\n  DistortionProcessorFactoryOptions,\n} from \"./DistortionProcessorFactory\";\nimport type { DistortionProcessor } from \"./DistortionProcessor\";\nimport { ReversePixelMappingProcessor } from \"./ReversePixelMappingProcessor\";\nimport { SuperSamplingProxy } from \"./SuperSamplingProxy\";\nimport { RepageProxy } from \"./RepageProxy\";\n\n/**\n * Base implementation of DistortionProcessor factory.\n */\nexport class BaseDistortionProcessorFactory\n  implements DistortionProcessorFactory\n{\n  /**\n   * @inheritDoc\n   */\n  create(options: DistortionProcessorFactoryOptions = {}): DistortionProcessor {\n    const {\n      asyncTimeout = 50,\n      outputScaling = 1,\n      repage = false,\n      abortSignal,\n    } = options;\n    let processor: DistortionProcessor = new ReversePixelMappingProcessor(\n      asyncTimeout,\n      abortSignal\n    );\n    if (outputScaling !== 1) {\n      processor = new SuperSamplingProxy(processor, outputScaling);\n    }\n    if (repage) {\n      processor = new RepageProxy(\n        processor,\n        isPoint(repage) || isViewportLiteral(repage) ? repage : undefined\n      );\n    }\n    return processor;\n  }\n}\n","import { type ImageAdapter, VirtualViewportProxy } from \"../image-adapter\";\nimport type { OutputViewportResolver } from \"../output-viewport-strategy\";\nimport type { ViewportLiteral } from \"../pixel-accessor\";\nimport type { ReversePixelMapper } from \"../pixel-mapper\";\nimport type { ColorResampler } from \"../color-resampler\";\nimport type {\n  DistortionProcessorFactory,\n  DistortionProcessorFactoryOptions,\n} from \"./DistortionProcessorFactory\";\n\n/**\n * DistortionController options.\n */\nexport interface DistortionControllerOptions\n  extends DistortionProcessorFactoryOptions {\n  /**\n   * Destination image viewport option.\n   * * When set to ViewportLiteral (or Viewport, which also implements ViewportLiteral) object, output image will\n   *  have such viewport.\n   * * When set to 'bestFit' string or boolean true, best-fit viewport will be used if possible.\n   * * When set to false or omitted, source image viewport will be used.\n   */\n  viewport?: \"bestFit\" | boolean | ViewportLiteral;\n}\n\n/**\n * Distortion process controller.\n */\nexport class DistortionController {\n  /**\n   * DistortionController constructor.\n   *\n   * @param outputViewportResolver\n   * @param distortionProcessorFactory\n   */\n  constructor(\n    private outputViewportResolver: OutputViewportResolver,\n    private distortionProcessorFactory: DistortionProcessorFactory\n  ) {}\n\n  /**\n   * Performs distortion of given image and returns distorted image.\n   *\n   * @param image\n   * @param reversePixelMapper\n   * @param resampler\n   * @param options\n   */\n  async distort<ResourceType>(\n    image: ImageAdapter<ResourceType>,\n    reversePixelMapper: ReversePixelMapper,\n    resampler: ColorResampler,\n    options: DistortionControllerOptions = {}\n  ): Promise<ImageAdapter<ResourceType>> {\n    const {\n      viewport = false,\n      outputScaling = 1,\n      repage,\n      asyncTimeout = 50,\n      abortSignal,\n    } = options;\n\n    const targetImage = this.createTargetImage(\n      image,\n      reversePixelMapper,\n      viewport,\n      outputScaling\n    );\n\n    // Wrap target image adapter into virtual viewport proxy to support virtual viewport offset.\n    const virtualViewportProxy = new VirtualViewportProxy(targetImage);\n\n    const distortionProcessor = this.distortionProcessorFactory.create({\n      outputScaling,\n      repage,\n      asyncTimeout,\n      abortSignal,\n    });\n\n    const result = await distortionProcessor.process(\n      virtualViewportProxy,\n      resampler\n    );\n\n    if (result instanceof VirtualViewportProxy) {\n      return result.getAdapter();\n    }\n\n    return result;\n  }\n\n  /**\n   * Creates blank target image which will be filled by pixel colors in distortion processor.\n   *\n   * @param image\n   * @param reversePixelMapper\n   * @param viewport\n   * @param outputScaling\n   * @private\n   */\n  private createTargetImage<ResourceType>(\n    image: ImageAdapter<ResourceType>,\n    reversePixelMapper: ReversePixelMapper,\n    viewport: \"bestFit\" | boolean | ViewportLiteral,\n    outputScaling: number\n  ): ImageAdapter<ResourceType> {\n    const outputViewport = this.outputViewportResolver.resolve(\n      image,\n      reversePixelMapper,\n      viewport\n    );\n    if (outputScaling !== 1) {\n      outputViewport.scale(outputScaling);\n    }\n    return image.getBlank(outputViewport);\n  }\n}\n","import { InterpolationMethod } from \"../color-interpolator\";\nimport { isEwaColorResampler } from \"../color-resampler\";\nimport type { ColorStringParser } from \"../color-string-parser\";\nimport { isImageAdapter } from \"../image-adapter\";\nimport {\n  type VirtualPixelDecoratorApplicator,\n  VirtualPixelMethod,\n} from \"../pixel-accessor\";\nimport { isReversePixelMapper } from \"../pixel-mapper\";\nimport { isColor } from \"../types\";\nimport type {\n  DistortionController,\n  DistortionControllerOptions,\n} from \"./DistortionController\";\nimport type {\n  ReversePixelMapperResolver,\n  GetReversePixelMapperFactoryArgs,\n  ReversePixelMapperFactoriesPoolKeyMap,\n  ReversePixelMapper,\n} from \"../pixel-mapper\";\nimport type { ImageAdapter, ImageAdapterResolver } from \"../image-adapter\";\nimport type {\n  ColorResamplerResolver,\n  ColorResamplerResolverOptions,\n  ColorResampler,\n} from \"../color-resampler\";\nimport type { Color, Point } from \"../types\";\n\n/**\n * Distortion service options.\n */\nexport type DistortionServiceOptions = DistortionControllerOptions &\n  Omit<ColorResamplerResolverOptions, \"matteColor\"> & {\n    /**\n     * Matte color. Used for invalid pixel mappings, for which no real color can be calculated from source image.\n     * @default [0, 0, 0, 0]\n     */\n    matteColor?: Color | string;\n\n    /**\n     * Image background color. May be used as virtual pixel color or interpolation color.\n     *\n     * @default [0, 0, 0, 0] (transparent).\n     */\n    imageBackgroundColor?: Color | string;\n\n    /**\n     * Source image viewport offset. May impact on pixel mapping calculation.\n     */\n    imageViewportOffset?: Point;\n  };\n\n/**\n * Distortion result interface.\n */\nexport interface DistortionResult<ResourceType> {\n  /**\n   * Distorted image.\n   */\n  image: ImageAdapter<ResourceType>;\n\n  /**\n   * Reverse pixel mapper instance, used for distortion.\n   */\n  distortion: ReversePixelMapper;\n\n  /**\n   * Distortion process start timestamp.\n   */\n  startTimestamp: number;\n\n  /**\n   * Distortion process end timestamp.\n   */\n  endTimestamp: number;\n\n  /**\n   * Distortion process duration (ms)\n   */\n  duration: number;\n\n  /**\n   * Color weight lookup table used in EWA resampler.\n   */\n  weightLookupTable?: number[];\n}\n\n/**\n * Distortion service class.\n */\nexport class DistortionService {\n  /**\n   * DistortionService constructor.\n   *\n   * @param reversePixelMapperResolver\n   * @param colorResamplerResolver\n   * @param distortionController\n   * @param imageAdapterResolver\n   * @param colorStringParser\n   * @param virtualPixelDecoratorApplicator\n   */\n  constructor(\n    private readonly reversePixelMapperResolver: ReversePixelMapperResolver,\n    private readonly colorResamplerResolver: ColorResamplerResolver,\n    private readonly distortionController: DistortionController,\n    private readonly imageAdapterResolver: ImageAdapterResolver,\n    private readonly colorStringParser: ColorStringParser,\n    private readonly virtualPixelDecoratorApplicator: VirtualPixelDecoratorApplicator\n  ) {}\n\n  /**\n   * Distorts image using distortion name and distortion arguments.\n   *\n   * @param image\n   * @param distortion\n   * @param args\n   * @param options\n   */\n  distort<ResourceType, K extends keyof ReversePixelMapperFactoriesPoolKeyMap>(\n    image: ResourceType | ImageAdapter<ResourceType>,\n    distortion: K,\n    args: GetReversePixelMapperFactoryArgs<K>,\n    options?: DistortionServiceOptions\n  ): Promise<DistortionResult<ResourceType>>;\n\n  /**\n   * Distorts image using provided ReversePixelMapper.\n   *\n   * @param image\n   * @param reversePixelMapper\n   * @param options\n   */\n  distort<ResourceType>(\n    image: ResourceType | ImageAdapter<ResourceType>,\n    reversePixelMapper: ReversePixelMapper,\n    options?: DistortionServiceOptions\n  ): Promise<DistortionResult<ResourceType>>;\n\n  /**\n   * Distorts image.\n   *\n   * @param image\n   * @param distortionOrMapper\n   * @param argsOrOptions\n   * @param mayBeOptions\n   */\n  distort<ResourceType>(\n    image: ResourceType | ImageAdapter<ResourceType>,\n    distortionOrMapper:\n      | keyof ReversePixelMapperFactoriesPoolKeyMap\n      | string\n      | ReversePixelMapper,\n    argsOrOptions: number[] | DistortionServiceOptions | undefined,\n    mayBeOptions?: DistortionServiceOptions\n  ): Promise<DistortionResult<ResourceType>>;\n\n  /**\n   * distort method implementation.\n   *\n   * @param image\n   * @param distortionOrMapper\n   * @param argsOrOptions\n   * @param mayBeOptions\n   */\n  async distort<ResourceType>(\n    image: ResourceType | ImageAdapter<ResourceType>,\n    distortionOrMapper:\n      | keyof ReversePixelMapperFactoriesPoolKeyMap\n      | string\n      | ReversePixelMapper,\n    argsOrOptions: number[] | DistortionServiceOptions | undefined,\n    mayBeOptions?: DistortionServiceOptions\n  ): Promise<DistortionResult<ResourceType>> {\n    const [imageAdapter, reversePixelMapper, options] = this.clarifyArguments(\n      image,\n      distortionOrMapper,\n      argsOrOptions,\n      mayBeOptions\n    );\n\n    this.setImageAdapterOptions(imageAdapter, options);\n\n    const colorResampler = this.getColorResampler(\n      imageAdapter,\n      reversePixelMapper,\n      options\n    );\n\n    const startTimestamp = Date.now();\n    const distortedImage = await this.distortionController.distort(\n      imageAdapter,\n      reversePixelMapper,\n      colorResampler,\n      options\n    );\n    const endTimestamp = Date.now();\n\n    const weightLookupTable = isEwaColorResampler(colorResampler)\n      ? colorResampler.getWeightLookupTable()\n      : undefined;\n\n    return {\n      image: distortedImage,\n      distortion: reversePixelMapper,\n      startTimestamp,\n      endTimestamp,\n      duration: endTimestamp - startTimestamp,\n      weightLookupTable,\n    };\n  }\n\n  /**\n   * Resolves source image adapter for distortion.\n   *\n   * @param image\n   * @private\n   */\n  private resolveImageAdapter<ResourceType>(\n    image: ResourceType | ImageAdapter<ResourceType>\n  ): ImageAdapter<ResourceType> {\n    if (isImageAdapter(image)) {\n      return image;\n    }\n    return this.imageAdapterResolver.resolve(image);\n  }\n\n  /**\n   * Clarifies ambiguous arguments.\n   *\n   * @param image\n   * @param distortionOrMapper\n   * @param argsOrOptions\n   * @param mayBeOptions\n   * @private\n   */\n  private clarifyArguments<ResourceType>(\n    image: ResourceType | ImageAdapter<ResourceType>,\n    distortionOrMapper:\n      | keyof ReversePixelMapperFactoriesPoolKeyMap\n      | string\n      | ReversePixelMapper,\n    argsOrOptions: number[] | DistortionServiceOptions | undefined,\n    mayBeOptions?: DistortionServiceOptions\n  ): [\n    ImageAdapter<ResourceType>,\n    ReversePixelMapper,\n    DistortionServiceOptions\n  ] {\n    const imageAdapter = this.resolveImageAdapter(image);\n\n    let reversePixelMapper: ReversePixelMapper;\n    let options: DistortionServiceOptions | undefined;\n\n    if (isReversePixelMapper(distortionOrMapper)) {\n      if (Array.isArray(argsOrOptions)) {\n        throw new TypeError(\n          \"Argument 3 should be options object or undefined when passing ReversePixelMapper as second argument\"\n        );\n      }\n      reversePixelMapper = distortionOrMapper;\n      options = argsOrOptions;\n    } else {\n      if (!Array.isArray(argsOrOptions)) {\n        throw new TypeError(\"Missing distortion arguments\");\n      }\n      reversePixelMapper = this.reversePixelMapperResolver.resolve(\n        distortionOrMapper,\n        argsOrOptions,\n        imageAdapter.getViewport()\n      );\n      options = mayBeOptions;\n    }\n\n    return [imageAdapter, reversePixelMapper, options || {}];\n  }\n\n  /**\n   * Returns color resampler for image distortion.\n   *\n   * @param image\n   * @param reversePixelMapper\n   * @param options\n   * @private\n   */\n  private getColorResampler<T>(\n    image: ImageAdapter<T>,\n    reversePixelMapper: ReversePixelMapper,\n    options: DistortionServiceOptions\n  ): ColorResampler {\n    const {\n      matteColor,\n      filter = \"RobidouxSharp\",\n      preferredResampler,\n      virtualPixelMethod = VirtualPixelMethod.TRANSPARENT,\n      interpolationMethod = InterpolationMethod.AVERAGE,\n    } = options;\n\n    const realMatteColor = this.resolveColor(\n      matteColor,\n      image.getQuantumRange()\n    );\n\n    // Apply virtual pixel decorator\n    const virtualPixelDecoratedImage =\n      this.virtualPixelDecoratorApplicator.decorate(image, virtualPixelMethod);\n\n    return this.colorResamplerResolver.resolve(\n      virtualPixelDecoratedImage,\n      reversePixelMapper,\n      {\n        preferredResampler,\n        matteColor: realMatteColor,\n        filter,\n        interpolationMethod,\n        virtualPixelMethod,\n      }\n    );\n  }\n\n  /**\n   * Sets image adapter options from provided distortion options.\n   *\n   * @param image\n   * @param options\n   * @private\n   */\n  private setImageAdapterOptions<T>(\n    image: ImageAdapter<T>,\n    options: DistortionServiceOptions\n  ): void {\n    const { imageBackgroundColor, imageViewportOffset } = options;\n\n    image.setBackgroundColor(\n      this.resolveColor(imageBackgroundColor, image.getQuantumRange())\n    );\n    if (imageViewportOffset) {\n      image.getViewport().offset(...imageViewportOffset);\n    }\n  }\n\n  /**\n   * Resolves color from color options.\n   *\n   * @param color\n   * @param quantumRange\n   * @param defaultValue\n   * @private\n   */\n  private resolveColor(\n    color: Color | string | undefined,\n    quantumRange: number,\n    defaultValue: Color = [0, 0, 0, 0]\n  ): Color {\n    if (color === undefined) {\n      return defaultValue;\n    }\n    if (isColor(color)) {\n      return color;\n    }\n    const parsedColor = this.colorStringParser.parse(color, quantumRange);\n    if (!parsedColor) {\n      return defaultValue;\n    }\n    return parsedColor;\n  }\n}\n","import { Viewport, type ViewportLiteral } from \"../pixel-accessor\";\nimport type { OutputViewportResolver } from \"./OutputViewportResolver\";\nimport type { ImageAdapter } from \"../image-adapter\";\nimport type { ReversePixelMapper } from \"../pixel-mapper\";\nimport type { OutputViewportStrategiesPool } from \"./OutputViewportStrategiesPool\";\n\n/**\n * Base implementation of OutputViewportResolver interface.\n */\nexport class BaseOutputViewportResolver implements OutputViewportResolver {\n  /**\n   * BaseOutputViewportResolver constructor.\n   *\n   * @param outputViewportStrategiesPool\n   */\n  constructor(\n    private readonly outputViewportStrategiesPool: OutputViewportStrategiesPool\n  ) {}\n\n  /**\n   * @inheritDoc\n   */\n  resolve(\n    image: ImageAdapter<unknown>,\n    reversePixelMapper: ReversePixelMapper,\n    viewport: \"bestFit\" | boolean | ViewportLiteral\n  ): Viewport {\n    const strategies = this.outputViewportStrategiesPool.items();\n    strategies.sort((a, b) => a.priority - b.priority);\n    const strategy = strategies.find((s) =>\n      s.match(reversePixelMapper, viewport)\n    );\n    if (!strategy) {\n      throw new Error(\n        \"Couldn't find matching output viewport resolution strategy\"\n      );\n    }\n    return strategy.getOutputViewport(image, reversePixelMapper, viewport);\n  }\n}\n","import { Viewport, type ViewportLiteral } from \"../pixel-accessor\";\nimport { isBestFitReversePixelMapper } from \"../pixel-mapper\";\nimport type { OutputViewportStrategy } from \"./OutputViewportStrategy\";\nimport type { ImageAdapter } from \"../image-adapter\";\nimport type { ReversePixelMapper } from \"../pixel-mapper\";\n\n/**\n * Best fit viewport resolution strategy.\n * Matches if reverse pixel mapper supports best-fit viewport calculation and when 'viewport' option is set to\n * \"bestFit\" or true, or if pixel mapper forces best-fit viewport.\n */\nexport class BestFitViewport implements OutputViewportStrategy {\n  /**\n   * @inheritDoc\n   */\n  readonly priority = 2;\n\n  /**\n   * @inheritDoc\n   */\n  match(\n    reversePixelMapper: ReversePixelMapper,\n    viewport: \"bestFit\" | boolean | ViewportLiteral\n  ): boolean {\n    return (\n      isBestFitReversePixelMapper(reversePixelMapper) &&\n      (reversePixelMapper.forceBestFit ||\n        viewport === \"bestFit\" ||\n        viewport === true)\n    );\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getOutputViewport(\n    image: ImageAdapter<unknown>,\n    reversePixelMapper: ReversePixelMapper\n  ): Viewport {\n    if (isBestFitReversePixelMapper(reversePixelMapper)) {\n      return reversePixelMapper.getBestFitViewport(image.getViewport());\n    }\n    throw new TypeError(\n      \"Given ReversePixelMapper don't support best-fit output viewport\"\n    );\n  }\n}\n","import { Viewport } from \"../pixel-accessor\";\nimport type { OutputViewportStrategy } from \"./OutputViewportStrategy\";\nimport type { ImageAdapter } from \"../image-adapter\";\n\n/**\n * Uses clone of source image viewport as output image viewport.\n * Matches always.\n */\nexport class SourceImageViewport implements OutputViewportStrategy {\n  /**\n   * @inheritDoc\n   */\n  readonly priority = 3;\n\n  /**\n   * @inheritDoc\n   */\n  getOutputViewport(image: ImageAdapter<unknown>): Viewport {\n    return image.getViewport().clone();\n  }\n\n  /**\n   * @inheritDoc\n   */\n  match(): true {\n    return true;\n  }\n}\n","import {\n  isViewportLiteral,\n  Viewport,\n  type ViewportLiteral,\n} from \"../pixel-accessor\";\nimport type { OutputViewportStrategy } from \"./OutputViewportStrategy\";\nimport type { ReversePixelMapper } from \"../pixel-mapper\";\nimport type { ImageAdapter } from \"../image-adapter\";\n\n/**\n * Uses user-provided viewport as output image viewport.\n * Have highest priority.\n * Matches if user provided output viewport via option.\n */\nexport class UserProvidedViewport implements OutputViewportStrategy {\n  /**\n   * @inheritDoc\n   */\n  readonly priority = 1;\n\n  /**\n   * @inheritDoc\n   */\n  match(\n    reversePixelMapper: ReversePixelMapper,\n    viewport: \"bestFit\" | boolean | ViewportLiteral\n  ): boolean {\n    return isViewportLiteral(viewport);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getOutputViewport(\n    image: ImageAdapter<unknown>,\n    reversePixelMapper: ReversePixelMapper,\n    viewport: \"bestFit\" | boolean | ViewportLiteral\n  ): Viewport {\n    if (isViewportLiteral(viewport)) {\n      return Viewport.fromLiteral(viewport);\n    }\n    throw new TypeError(\"'viewport argument should be ViewportLiteral\");\n  }\n}\n","import type { Pool, PoolKeyMap } from \"./Pool\";\n\n/**\n * Base Pool interface implementation.\n */\nexport class BasePool<T = unknown, M extends PoolKeyMap<T> = PoolKeyMap<T>>\n  implements Pool<T, M>\n{\n  /**\n   * Pool items storage.\n   * @private\n   */\n  private readonly storage: Map<keyof M | string, T>;\n\n  /**\n   * BasePool constructor.\n   */\n  constructor() {\n    this.storage = new Map();\n  }\n\n  /**\n   * @inheritDoc\n   */\n  has(key: keyof M | string): boolean {\n    return this.storage.has(key);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  get<K extends keyof M | string>(key: K): K extends keyof M ? M[K] : T {\n    const item = this.storage.get(key);\n    if (item === undefined) {\n      throw new RangeError(\n        `Item with key \"${key as string}\" was not found in pool.`\n      );\n    }\n    return item as K extends keyof M ? M[K] : T;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  add<K extends keyof M | string>(\n    key: K,\n    item: K extends keyof M ? M[K] : T,\n    replace = false\n  ): void {\n    if (this.storage.has(key) && !replace) {\n      throw new TypeError(\n        `Item with key \"${key as string}\" already exists in pool`\n      );\n    }\n    this.storage.set(key, item);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  remove(key: keyof M | string): void {\n    this.storage.delete(key);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  keys(): (keyof M | string)[] {\n    return Array.from(this.storage.keys());\n  }\n\n  /**\n   * @inheritDoc\n   */\n  items(): T[] {\n    return Array.from(this.storage.values());\n  }\n}\n","import { EPSILON } from \"../constants\";\nimport type { ResampleFilter } from \"./ResampleFilter\";\nimport type { WeightingFunction } from \"../weighting-function\";\n\n/**\n * Base ResampleFilter interface implementation.\n *\n * @see https://www.imagemagick.org/Usage/filter/#filter Resampling Filters at ImageMagick docs\n * @see https://www2.eecs.berkeley.edu/Pubs/TechRpts/1989/CSD-89-516.pdf Fundamentals of Texture Mapping and\n * Image Warping by Paul S. Heckbert, page 41, section 3.4, 3.5\n * @see https://imagemagick.org/api/MagickCore/resize_8c_source.html#l00757 AquireResizeFilter at ImageMagick source\n */\nexport class BaseResampleFilter implements ResampleFilter {\n  /**\n   * Window support, usually equal to support (expert only).\n   */\n  private readonly windowSupport: number;\n\n  /**\n   * BaseResampleFilter constructor.\n   *\n   * @param filterFunction Filtering function.\n   * @param windowingFunction Windowing function.\n   * @param support Filter region of support - the filter support limit.\n   * @param scale Dimension scaling to fit window support (usually 1.0).\n   * @param [blur=1] X-scale (blur-sharpen).\n   * @param [windowSupport=null] Window support, usually equal to support (expert only).\n   */\n  constructor(\n    private readonly filterFunction: WeightingFunction,\n    private readonly windowingFunction: WeightingFunction,\n    private readonly support: number,\n    private readonly scale: number,\n    private readonly blur = 1,\n    windowSupport?: number\n  ) {\n    this.windowSupport =\n      windowSupport !== undefined ? windowSupport : this.support;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getWorkingSupport(): number {\n    return this.support * this.blur;\n  }\n\n  /**\n   * @inheritDoc\n   */\n  getWeight(x: number): number {\n    const xBlur = x / this.blur;\n    const scale = xBlur < EPSILON ? 1 : this.window(this.scale * xBlur);\n    return scale * this.filter(xBlur);\n  }\n\n  /**\n   * @param x\n   */\n  private filter(x: number): number {\n    return this.filterFunction(x, this.support, this.windowSupport);\n  }\n\n  /**\n   *\n   * @param x\n   */\n  private window(x: number): number {\n    return this.windowingFunction(x, this.support, this.windowSupport);\n  }\n}\n","import type {\n  GetWeightingFunctionFactoryArgs,\n  WeightingFunctionFactoriesPool,\n  WeightingFunctionFactoriesPoolKeyMap,\n} from \"../weighting-function\";\nimport { BaseResampleFilter } from \"./BaseResampleFilter\";\nimport type { ResampleFilterFactory } from \"./ResampleFilterFactory\";\n\n/**\n * BaseResampleFilter factory class.\n */\nexport class BaseResampleFilterFactory implements ResampleFilterFactory {\n  /**\n   * BaseResampleFilterFactory constructor.\n   *\n   * @param weightingFunctionFactoriesPool\n   */\n  constructor(\n    private readonly weightingFunctionFactoriesPool: WeightingFunctionFactoriesPool\n  ) {}\n\n  /**\n   * @inheritDoc\n   */\n  create<\n    F extends keyof WeightingFunctionFactoriesPoolKeyMap | string,\n    W extends keyof WeightingFunctionFactoriesPoolKeyMap | string\n  >(\n    filterFunctionName: F,\n    filterFunctionFactoryArgs: GetWeightingFunctionFactoryArgs<F>,\n    windowFunctionFactoryName: W,\n    windowFunctionFactoryArgs: GetWeightingFunctionFactoryArgs<W>,\n    support: number,\n    scale: number,\n    blur = 1,\n    windowSupport?: number\n  ): BaseResampleFilter {\n    const filterFunctionFactory =\n      this.weightingFunctionFactoriesPool.get(filterFunctionName);\n    const filterFunction = filterFunctionFactory.create(\n      ...filterFunctionFactoryArgs\n    );\n    const windowFunctionFactory = this.weightingFunctionFactoriesPool.get(\n      windowFunctionFactoryName\n    );\n    const windowFunction = windowFunctionFactory.create(\n      ...windowFunctionFactoryArgs\n    );\n    return new BaseResampleFilter(\n      filterFunction,\n      windowFunction,\n      support,\n      scale,\n      blur,\n      windowSupport\n    );\n  }\n}\n","/**\n * Resample filter interface.\n *\n * @see https://www.imagemagick.org/Usage/filter/#filter Resampling Filters at ImageMagick docs\n */\nexport interface ResampleFilter {\n  /**\n   * Returns filter practical working support.\n   */\n  getWorkingSupport(): number;\n\n  /**\n   * Returns color weight at given distance from EWA ellipse center.\n   *\n   * @param x\n   */\n  getWeight(x: number): number;\n}\n\n/**\n * Checks if passed object implements ResampleFilter interface.\n *\n * @param candidate\n */\nexport function isResampleFilter(\n  candidate: unknown\n): candidate is ResampleFilter {\n  type C = Partial<ResampleFilter>;\n  return (\n    typeof candidate === \"object\" &&\n    candidate !== null &&\n    typeof (candidate as C).getWorkingSupport === \"function\" &&\n    typeof (candidate as C).getWeight === \"function\"\n  );\n}\n","import type { WeightingFunctionFactoriesPoolKeyMap } from \"../weighting-function\";\n\n/**\n * ResampleFilter preset interface.\n */\nexport interface ResampleFilterPreset {\n  /**\n   * Filter function factory name (in WeightingFunctionFactoriesPool).\n   */\n  filterFunctionFactory: keyof WeightingFunctionFactoriesPoolKeyMap | string;\n\n  /**\n   * Filter function factory arguments.\n   */\n  filterFunctionFactoryArgs: number[];\n\n  /**\n   * Window function factory name (in WeightingFunctionFactoriesPool).\n   */\n  windowFunctionFactory: keyof WeightingFunctionFactoriesPoolKeyMap | string;\n\n  /**\n   * Window function factory arguments.\n   */\n  windowFunctionFactoryArgs: number[];\n\n  /**\n   * Filter support.\n   */\n  support: number;\n\n  /**\n   * Filter scale.\n   */\n  scale: number;\n\n  /**\n   * Filter blur.\n   */\n  blur?: number;\n\n  /**\n   * Filter window support.\n   */\n  windowSupport?: number;\n}\n\n/**\n * Checks if passed object implements ResampleFilterPreset interface.\n *\n * @param candidate\n */\nexport function isResampleFilterPreset(\n  candidate: unknown\n): candidate is ResampleFilterPreset {\n  type C = Partial<ResampleFilterPreset>;\n  return (\n    typeof candidate === \"object\" &&\n    candidate !== null &&\n    typeof (candidate as C).filterFunctionFactory === \"string\" &&\n    Array.isArray((candidate as C).filterFunctionFactoryArgs) &&\n    typeof (candidate as C).windowFunctionFactory === \"string\" &&\n    Array.isArray((candidate as C).windowFunctionFactoryArgs) &&\n    typeof (candidate as C).support === \"number\" &&\n    typeof (candidate as C).scale === \"number\"\n  );\n}\n","import { isResampleFilter } from \"./ResampleFilter\";\nimport { isResampleFilterPreset } from \"./ResampleFilterPreset\";\nimport type {\n  ResampleFilterResolver,\n  ResampleFilterResolverOptions,\n} from \"./ResampleFilterResolver\";\nimport type {\n  ResampleFilterPresetsPool,\n  ResampleFilterPresetsPoolKeyMap,\n} from \"./ResampleFilterPresetsPool\";\nimport type { ResampleFilterPreset } from \"./ResampleFilterPreset\";\nimport type { ResampleFilter } from \"./ResampleFilter\";\nimport type { ResampleFilterFactory } from \"./ResampleFilterFactory\";\n\n/**\n * Base implementation of ResampleFilterResolver interface.\n */\nexport class BaseResampleFilterResolver implements ResampleFilterResolver {\n  /**\n   * BaseResampleFilterResolver constructor.\n   *\n   * @param filterPresetsPool\n   * @param filterFactory\n   */\n  constructor(\n    private readonly filterPresetsPool: ResampleFilterPresetsPool,\n    private readonly filterFactory: ResampleFilterFactory\n  ) {}\n\n  /**\n   * @inheritDoc\n   */\n  resolve(\n    filter:\n      | keyof ResampleFilterPresetsPoolKeyMap\n      | ResampleFilterPreset\n      | ResampleFilter,\n    options: ResampleFilterResolverOptions = {}\n  ): ResampleFilter {\n    if (isResampleFilter(filter)) {\n      return filter;\n    }\n    let preset: ResampleFilterPreset;\n    if (isResampleFilterPreset(filter)) {\n      preset = filter;\n    } else {\n      preset = this.filterPresetsPool.get(filter);\n    }\n    const { blur = 1, windowSupport } = preset;\n    const { filterBlur = blur, filterWindowSupport = windowSupport } = options;\n    return this.filterFactory.create(\n      preset.filterFunctionFactory,\n      preset.filterFunctionFactoryArgs,\n      preset.windowFunctionFactory,\n      preset.windowFunctionFactoryArgs,\n      preset.support,\n      preset.scale,\n      filterBlur,\n      filterWindowSupport\n    );\n  }\n}\n","/**\n * Built-in resample filter presets names.\n */\nexport enum FilterName {\n  /**\n   * * Filter function: Cubic BC; B = 0.37821575509399867, C = 0.31089212245300067.\n   * * Window function: Box.\n   * * Support: 2.\n   * * Scale: 1.1685777620836932.\n   * * Blur: 1.\n   */\n  ROBIDOUX = \"Robidoux\",\n\n  /**\n   * * Filter function: Cubic BC; B = 0.2620145123990142, C = 0.3689927438004929.\n   * * Window function: Box.\n   * * Support: 2.\n   * * Scale: 1.105822933719019.\n   * * Blur: 1.\n   */\n  ROBIDOUX_SHARP = \"RobidouxSharp\",\n\n  /**\n   * * Filter function: Box.\n   * * Window function: Box.\n   * * Support: 0.5.\n   * * Scale: 0.5.\n   * * Blur: 1\n   */\n  BOX = \"Box\",\n\n  // /**\n  //  * Not implemented.\n  //  */\n  // TRIANGLE = \"Triangle\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // HERMITE = \"Hermite\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // HANN = \"Hann\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // HAMMING = \"Hamming\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // BLACKMAN = \"Blackman\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // GAUSSIAN = \"Gaussian\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // QUADRATIC = \"Quadratic\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // CUBIC = \"Cubic\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // CATROM = \"Catrom\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // MITCHELL = \"Mitchell\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // JINC = \"Jinc\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // SINC = \"Sinc\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // SINC_FAST = \"SincFast\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // KAISER = \"Kaiser\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // WELCH = \"Welch\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // PARZEN = \"Parzen\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // BOHMAN = \"Bohman\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // BARTLETT = \"Bartlett\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // LAGRANGE = \"Lagrange\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // LANCZOS = \"Lanczos\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // LANCZOS_SHARP = \"LanczosSharp\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // LANCZOS_2 = \"Lanczos2\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // LANCZOS_2_SHARP = \"Lanczos2Sharp\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // COSINE = \"Cosine\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // SPLINE = \"Spline\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // LANCZOS_RADIUS = \"LanczosRadius\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // CUBIC_SPLINE = \"CubicSpline\", // TODO: implement\n}\n","import type { ServiceContainer } from \"./ServiceContainer\";\nimport type { TypesMap } from \"./TypesMap\";\n\n/**\n * Base ServiceContainer interface implementation.\n */\nexport class BaseServiceContainer<M extends TypesMap = TypesMap>\n  implements ServiceContainer<M>\n{\n  /**\n   * Parent container.\n   *\n   * @protected\n   */\n  protected parent: BaseServiceContainer<M> | null = null;\n\n  /**\n   * Services storage.\n   *\n   * @protected\n   */\n  protected services: Map<keyof M, unknown>;\n\n  /**\n   * Backups storage.\n   *\n   * @private\n   */\n  private backups: Map<keyof M, unknown>[];\n\n  /**\n   * BaseServiceContainer constructor.\n   */\n  constructor() {\n    this.services = new Map();\n    this.backups = [];\n  }\n\n  /**\n   * @inheritDoc\n   */\n  register<K extends keyof M>(\n    key: K,\n    service: M[K] | ((locator: ServiceContainer<M>) => M[K])\n  ) {\n    this.services.set(key, service);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  unregister<K extends keyof M>(key: K) {\n    this.services.delete(key);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  resolve<K extends keyof M>(key: K): M[K] {\n    const service = this.services.get(key);\n    if (service === undefined) {\n      if (this.parent) {\n        return this.parent.resolve(key);\n      }\n      throw new RangeError(\n        `Service \"${key as string}\" was not found in container.`\n      );\n    }\n    if (typeof service === \"function\") {\n      return service(this);\n    }\n    return service as M[K];\n  }\n\n  /**\n   * @inheritDoc\n   */\n  backup() {\n    const backup = new Map(this.services);\n    this.backups.push(backup);\n  }\n\n  /**\n   * @inheritDoc\n   */\n  restore() {\n    const backup = this.backups.pop();\n    if (backup) {\n      this.services.clear();\n      this.services = backup;\n    }\n  }\n\n  /**\n   * @inheritDoc\n   */\n  createChild(): BaseServiceContainer<M> {\n    const child = new BaseServiceContainer<M>();\n    child.parent = this;\n    return child;\n  }\n}\n","import type { WeightingFunction } from \"./WeightingFunction\";\nimport type { WeightingFunctionFactory } from \"./WeightingFunctionFactory\";\n\n/**\n * Makes box filter function.\n * A Box filter is an equal weighting function (all weights equal).\n * DO NOT LIMIT results by support or resize point sampling will work as it requests points beyond its normal 0.0\n * support size.\n *\n * @see https://imagemagick.org/api/MagickCore/resize_8c_source.html#l00181 Box filter function at ImageMagick source\n */\nexport class BoxFactory implements WeightingFunctionFactory {\n  /**\n   * Creates box() weighting function.\n   */\n  create(): WeightingFunction {\n    return function box(): 1 {\n      return 1;\n    };\n  }\n}\n","import type { WeightingFunction } from \"./WeightingFunction\";\nimport type { WeightingFunctionFactory } from \"./WeightingFunctionFactory\";\n\n/**\n * CubicBC weighting function factory.\n *\n * Cubic Filters using B,C determined values:\n * ```\n *     Mitchell-Netravali  B = 1/3 C = 1/3  \"Balanced\" cubic spline filter\n *     Catmull-Rom         B = 0   C = 1/2  Interpolatory and exact on linears\n *     Spline              B = 1   C = 0    B-Spline Gaussian approximation\n *     Hermite             B = 0   C = 0    B-Spline interpolator\n * ```\n *\n * See paper by Mitchell and Netravali, Reconstruction Filters in Computer Graphics Computer Graphics,\n * Volume 22, Number 4, August 1988\n * @link http://www.cs.utexas.edu/users/fussell/courses/cs384g/lectures/mitchell/Mitchell.pdf.\n *\n * Coefficents are determined from B,C values:\n * ```\n *    P0 = (  6 - 2*B       )/6 = coeff[0]\n *    P1 =         0\n *    P2 = (-18 +12*B + 6*C )/6 = coeff[1]\n *    P3 = ( 12 - 9*B - 6*C )/6 = coeff[2]\n *    Q0 = (      8*B +24*C )/6 = coeff[3]\n *    Q1 = (    -12*B -48*C )/6 = coeff[4]\n *    Q2 = (      6*B +30*C )/6 = coeff[5]\n *    Q3 = (    - 1*B - 6*C )/6 = coeff[6]\n * ```\n * which are used to define the filter:\n * ```\n *    P0 + P1*x + P2*x^2 + P3*x^3      0 <= x < 1\n *    Q0 + Q1*x + Q2*x^2 + Q3*x^3      1 <= x < 2\n * ```\n * which ensures function is continuous in value and derivative (slope).\n *\n * @see https://imagemagick.org/api/MagickCore/resize_8c_source.html#l00207 CubicBC filter function at ImageMagick source\n */\nexport class CubicBCFactory\n  implements WeightingFunctionFactory<[number, number]>\n{\n  /**\n   * Creates cubicBC() function.\n   *\n   * @param b B value.\n   * @param c C value.\n   */\n  create(b: number, c: number): WeightingFunction {\n    const p0 = (6 - 2 * b) / 6;\n    // const p1 = 0;\n    const p2 = (-18 + 12 * b + 6 * c) / 6;\n    const p3 = (12 - 9 * b - 6 * c) / 6;\n    const q0 = (8 * b + 24 * c) / 6;\n    const q1 = (-12 * b - 48 * c) / 6;\n    const q2 = (6 * b + 30 * c) / 6;\n    const q3 = (-1 * b - 6 * c) / 6;\n\n    return function cubicBC(x?: number): number {\n      if (typeof x === \"number\") {\n        if (x < 1) {\n          return p0 + x * (x * (p2 + x * p3));\n        } else if (x < 2) {\n          return q0 + x * (q1 + x * (q2 + x * q3));\n        }\n      }\n      return 0;\n    };\n  }\n}\n","/**\n * Built-in weighting function names.\n */\nexport enum WeightingFunctionName {\n  /**\n   * A Box filter is an equal weighting function (all weights equal).\n   * DO NOT LIMIT results by support or resize point sampling will work\n   * as it requests points beyond its normal 0.0 support size.\n   */\n  BOX = \"Box\",\n\n  /**\n   * Cubic Filters using B,C determined values:\n   * ```\n   *     Mitchell-Netravali  B = 1/3 C = 1/3  \"Balanced\" cubic spline filter\n   *     Catmull-Rom         B = 0   C = 1/2  Interpolatory and exact on linears\n   *     Spline              B = 1   C = 0    B-Spline Gaussian approximation\n   *     Hermite             B = 0   C = 0    B-Spline interpolator\n   * ```\n   *\n   * See paper by Mitchell and Netravali, Reconstruction Filters in Computer Graphics Computer Graphics,\n   * Volume 22, Number 4, August 1988\n   * @link https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf\n   *\n   * Coefficents are determined from B,C values:\n   * ```\n   *    P0 = (  6 - 2*B       )/6 = coeff[0]\n   *    P1 =         0\n   *    P2 = (-18 +12*B + 6*C )/6 = coeff[1]\n   *    P3 = ( 12 - 9*B - 6*C )/6 = coeff[2]\n   *    Q0 = (      8*B +24*C )/6 = coeff[3]\n   *    Q1 = (    -12*B -48*C )/6 = coeff[4]\n   *    Q2 = (      6*B +30*C )/6 = coeff[5]\n   *    Q3 = (    - 1*B - 6*C )/6 = coeff[6]\n   * ```\n   * which are used to define the filter:\n   * ```\n   *    P0 + P1*x + P2*x^2 + P3*x^3      0 <= x < 1\n   *    Q0 + Q1*x + Q2*x^2 + Q3*x^3      1 <= x < 2\n   * ```\n   * which ensures function is continuous in value and derivative (slope).\n   */\n  CUBIC_BC = \"CubicBC\",\n\n  // /**\n  //  * Not implemented.\n  //  */\n  // TRIANGLE = \"Triangle\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // HANN = \"Hann\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // HAMMING = \"Hamming\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // BLACKMAN = \"Blackman\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // GAUSSIAN = \"Gaussian\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // QUADRATIC = \"Quadratic\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // JINC = \"Jinc\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // SINC = \"Sinc\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // SINC_FAST = \"SincFast\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // KAISER = \"Kaiser\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // WELCH = \"Welch\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // BOHMAN = \"Bohman\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // LAGRANGE = \"Lagrange\", // TODO: implement\n  //\n  // /**\n  //  * Not implemented.\n  //  */\n  // COSINE = \"Cosine\", // TODO: implement\n}\n","import type { ServiceProvider, ServiceContainer } from \"../service-container\";\nimport type { ColorResamplerFactoriesPool } from \"./ColorResamplerFactoriesPool\";\nimport { BasePool } from \"../pool\";\nimport { EwaResamplerFactory } from \"./EwaResamplerFactory\";\nimport { PointResamplerFactory } from \"./PointResamplerFactory\";\nimport { BaseColorResamplerResolver } from \"./BaseColorResamplerResolver\";\n\n/**\n * Color Resampling service provider.\n * @internal\n */\nexport const colorResamplerProvider: ServiceProvider = {\n  /**\n   * Registers entities, related to color resampling in service container.\n   *\n   * @param container\n   */\n  register(container: ServiceContainer) {\n    // register pool items once. TODO: improve ServiceContainer for better handling such cases\n    let colorResamplerFactoriesPoolRegistered = false;\n\n    // Register default color resampler resolver in service container.\n    container.register(\"ColorResamplerResolver\", (c) => {\n      if (!colorResamplerFactoriesPoolRegistered) {\n        const colorInterpolatorFactory = c.resolve(\"ColorInterpolatorFactory\");\n        // Add built-in color resampler factories to the pool and register pool in service container.\n        const pool: ColorResamplerFactoriesPool = new BasePool();\n        pool.add(\"ewa\", new EwaResamplerFactory(colorInterpolatorFactory));\n        pool.add(\"point\", new PointResamplerFactory(colorInterpolatorFactory));\n        c.register(\"ColorResamplerFactoriesPool\", pool);\n        colorResamplerFactoriesPoolRegistered = true;\n      }\n\n      return new BaseColorResamplerResolver(\n        c.resolve(\"ColorResamplerFactoriesPool\"),\n        c.resolve(\"ResampleFilterResolver\")\n      );\n    });\n  },\n};\n","import { colorInterpolationProvider } from \"./color-interpolator/colorInterpolationProvider\";\nimport { colorStringParserProvider } from \"./color-string-parser/colorStringParserProvider\";\nimport { pixelAccessorProvider } from \"./pixel-accessor/pixelAccessorProvider\";\nimport { createServiceContainer } from \"./service-container/createServiceContainer\";\nimport { colorResamplerProvider } from \"./color-resampler/colorResamplerProvider\";\nimport { distortionProcessingProvider } from \"./distortion-processing/distortionProcessingProvider\";\nimport { imageAdapterProvider } from \"./image-adapter/imageAdapterProvider\";\nimport { outputViewportStrategyProvider } from \"./output-viewport-strategy/outputViewportStrategyProvider\";\nimport { pixelMappingProvider } from \"./pixel-mapper/pixelMappingProvider\";\nimport { resampleFilterProvider } from \"./resample-filter/resampleFilterProvider\";\nimport { weightingFunctionProvider } from \"./weighting-function/weightingFunctionProvider\";\n\nexport const serviceContainer = createServiceContainer([\n  colorResamplerProvider,\n  colorStringParserProvider,\n  distortionProcessingProvider,\n  imageAdapterProvider,\n  outputViewportStrategyProvider,\n  pixelMappingProvider,\n  resampleFilterProvider,\n  weightingFunctionProvider,\n  colorInterpolationProvider,\n  pixelAccessorProvider,\n]);\n","import type { ServiceProvider } from \"./ServiceProvider\";\nimport { BaseServiceContainer } from \"./BaseServiceContainer\";\n\n/**\n * Creates service container.\n *\n * @param providers\n * @internal\n */\nexport function createServiceContainer(\n  providers: ServiceProvider[] = []\n): BaseServiceContainer {\n  const serviceLocator = new BaseServiceContainer();\n  providers.forEach((provider) => provider.register(serviceLocator));\n  return serviceLocator;\n}\n","import { BasePool } from \"../pool\";\nimport type { ServiceContainer, ServiceProvider } from \"../service-container\";\nimport type { ColorStringParsersPool } from \"./ColorStringParsersPool\";\nimport { CompositeColorStringParser } from \"./CompositeColorStringParser\";\nimport { HexColorStringParser } from \"./HexColorStringParser\";\nimport { RgbaColorStringParser } from \"./RgbaColorStringParser\";\nimport { TransparentStringParser } from \"./TransparentStringParser\";\n\n/**\n * Color string parsing service provider.\n * @internal\n */\nexport const colorStringParserProvider: ServiceProvider = {\n  /**\n   * Registers entities, related to color string parsing, in service container.\n   *\n   * @param container\n   */\n  register(container: ServiceContainer) {\n    const pool: ColorStringParsersPool = new BasePool();\n    pool.add(\"transparent\", new TransparentStringParser());\n    pool.add(\"hex\", new HexColorStringParser());\n    pool.add(\"rgba\", new RgbaColorStringParser());\n\n    container.register(\"ColorStringParsersPool\", pool);\n\n    container.register(\n      \"ColorStringParser\",\n      (c) => new CompositeColorStringParser(c.resolve(\"ColorStringParsersPool\"))\n    );\n  },\n};\n","import type { ServiceProvider, ServiceContainer } from \"../service-container\";\nimport { BaseDistortionProcessorFactory } from \"./BaseDistortionProcessorFactory\";\nimport { DistortionController } from \"./DistortionController\";\nimport { DistortionService } from \"./DistortionService\";\n\n/**\n * Distortion processing service provider.\n * @internal\n */\nexport const distortionProcessingProvider: ServiceProvider = {\n  /**\n   * Registers entities, related to distortion processing, in service container.\n   * @param container\n   */\n  register(container: ServiceContainer) {\n    container.register(\n      \"DistortionProcessorFactory\",\n      () => new BaseDistortionProcessorFactory()\n    );\n\n    container.register(\"DistortionController\", (c) => {\n      return new DistortionController(\n        c.resolve(\"OutputViewportResolver\"),\n        c.resolve(\"DistortionProcessorFactory\")\n      );\n    });\n\n    container.register(\"DistortionService\", (c) => {\n      return new DistortionService(\n        c.resolve(\"ReversePixelMapperResolver\"),\n        c.resolve(\"ColorResamplerResolver\"),\n        c.resolve(\"DistortionController\"),\n        c.resolve(\"ImageAdapterResolver\"),\n        c.resolve(\"ColorStringParser\"),\n        c.resolve(\"VirtualPixelDecoratorApplicator\")\n      );\n    });\n  },\n};\n","import type { ServiceProvider, ServiceContainer } from \"../service-container\";\nimport type { ImageAdapterFactoriesPool } from \"./ImageAdapterFactoriesPool\";\nimport { BasePool } from \"../pool\";\nimport { CanvasFactory } from \"./CanvasFactory\";\nimport { BaseImageAdapterResolver } from \"./BaseImageAdapterResolver\";\n\n/**\n * Image adapter service provider.\n * @internal\n */\nexport const imageAdapterProvider: ServiceProvider = {\n  /**\n   * Registers entities, related to image adapter, in service container.\n   *\n   * @param container\n   */\n  register(container: ServiceContainer) {\n    const pool: ImageAdapterFactoriesPool = new BasePool();\n    pool.add(\"BrowserCanvas\", new CanvasFactory());\n    container.register(\"ImageAdapterFactoriesPool\", pool);\n\n    container.register(\"ImageAdapterResolver\", (c) => {\n      return new BaseImageAdapterResolver(\n        c.resolve(\"ImageAdapterFactoriesPool\")\n      );\n    });\n  },\n};\n","import type { ServiceProvider, ServiceContainer } from \"../service-container\";\nimport type { OutputViewportStrategiesPool } from \"./OutputViewportStrategiesPool\";\nimport { BasePool } from \"../pool\";\nimport { UserProvidedViewport } from \"./UserProvidedViewport\";\nimport { BestFitViewport } from \"./BestFitViewport\";\nimport { SourceImageViewport } from \"./SourceImageViewport\";\nimport { BaseOutputViewportResolver } from \"./BaseOutputViewportResolver\";\n\n/**\n * Output viewport resolution service provider.\n * @internal\n */\nexport const outputViewportStrategyProvider: ServiceProvider = {\n  /**\n   * Registers entities, related to output viewport resolution, in service container.\n   *\n   * @param container\n   */\n  register(container: ServiceContainer) {\n    const pool: OutputViewportStrategiesPool = new BasePool();\n    pool.add(\"user-provided\", new UserProvidedViewport());\n    pool.add(\"best-fit\", new BestFitViewport());\n    pool.add(\"source-image\", new SourceImageViewport());\n    container.register(\"OutputViewportStrategiesPool\", pool);\n\n    container.register(\"OutputViewportResolver\", (c) => {\n      return new BaseOutputViewportResolver(\n        c.resolve(\"OutputViewportStrategiesPool\")\n      );\n    });\n  },\n};\n","import { BasePool } from \"../pool\";\nimport type { ServiceContainer, ServiceProvider } from \"../service-container\";\nimport { BaseReversePixelMapperResolver } from \"./BaseReversePixelMapperResolver\";\nimport { Distortion } from \"./Distortion\";\nimport {\n  AffineFactory,\n  AffineProjectionFactory,\n  ArcFactory,\n  PerspectiveFactory,\n  PerspectiveProjectionFactory,\n  PolynomialFactory,\n} from \"./distortions\";\nimport type { ReversePixelMapperFactoriesPool } from \"./ReversePixelMapperFactoriesPool\";\n\n/**\n * Pixel mapping service provider.\n * @internal\n */\nexport const pixelMappingProvider: ServiceProvider = {\n  /**\n   * Registers entities, related to pixel mapping, in service container.\n   *\n   * @param container\n   */\n  register(container: ServiceContainer) {\n    const pool: ReversePixelMapperFactoriesPool = new BasePool();\n    pool.add(Distortion.ARC, new ArcFactory());\n    pool.add(Distortion.AFFINE, new AffineFactory());\n    pool.add(Distortion.AFFINE_PROJECTION, new AffineProjectionFactory());\n    pool.add(Distortion.PERSPECTIVE, new PerspectiveFactory());\n    pool.add(\n      Distortion.PERSPECTIVE_PROJECTION,\n      new PerspectiveProjectionFactory()\n    );\n    pool.add(Distortion.POLYNOMIAL, new PolynomialFactory());\n    container.register(\"ReversePixelMapperFactoriesPool\", pool);\n\n    container.register(\"ReversePixelMapperResolver\", (c) => {\n      return new BaseReversePixelMapperResolver(\n        c.resolve(\"ReversePixelMapperFactoriesPool\")\n      );\n    });\n  },\n};\n","import type { ServiceProvider, ServiceContainer } from \"../service-container\";\nimport type { ResampleFilterPresetsPool } from \"./ResampleFilterPresetsPool\";\nimport { BasePool } from \"../pool\";\nimport { BaseResampleFilterFactory } from \"./BaseResampleFilterFactory\";\nimport { BaseResampleFilterResolver } from \"./BaseResampleFilterResolver\";\n\n/**\n * Resample filter service provider.\n * @internal\n */\nexport const resampleFilterProvider: ServiceProvider = {\n  /**\n   * Registers entities, related to resample filter, in service container.\n   *\n   * @param container\n   */\n  register(container: ServiceContainer) {\n    const pool: ResampleFilterPresetsPool = new BasePool();\n\n    // Register filter presets\n    pool.add(\"Robidoux\", {\n      filterFunctionFactory: \"CubicBC\",\n      // eslint-disable-next-line @typescript-eslint/no-loss-of-precision\n      filterFunctionFactoryArgs: [0.37821575509399867, 0.31089212245300067], // [b, c]\n      windowFunctionFactory: \"Box\",\n      windowFunctionFactoryArgs: [],\n      support: 2,\n      scale: 1.1685777620836932,\n    });\n    pool.add(\"RobidouxSharp\", {\n      filterFunctionFactory: \"CubicBC\",\n      filterFunctionFactoryArgs: [0.2620145123990142, 0.3689927438004929], // [b, c]\n      windowFunctionFactory: \"Box\",\n      windowFunctionFactoryArgs: [],\n      support: 2,\n      scale: 1.105822933719019,\n    });\n    pool.add(\"Box\", {\n      filterFunctionFactory: \"Box\",\n      filterFunctionFactoryArgs: [],\n      windowFunctionFactory: \"Box\",\n      windowFunctionFactoryArgs: [],\n      support: 0.5,\n      scale: 0.5,\n    });\n\n    container.register(\"ResampleFilterPresetsPool\", pool);\n\n    container.register(\"ResampleFilterFactory\", (c) => {\n      return new BaseResampleFilterFactory(\n        c.resolve(\"WeightingFunctionFactoriesPool\")\n      );\n    });\n\n    container.register(\"ResampleFilterResolver\", (c) => {\n      return new BaseResampleFilterResolver(\n        c.resolve(\"ResampleFilterPresetsPool\"),\n        c.resolve(\"ResampleFilterFactory\")\n      );\n    });\n  },\n};\n","import { BasePool } from \"../pool\";\nimport type { ServiceContainer, ServiceProvider } from \"../service-container\";\nimport { BoxFactory } from \"./BoxFactory\";\nimport { CubicBCFactory } from \"./CubicBCFactory\";\nimport type { WeightingFunctionFactoriesPool } from \"./WeightingFunctionFactoriesPool\";\nimport { WeightingFunctionName } from \"./WeightingFunctionName\";\n\n/**\n * Weighting function service provider.\n * @internal\n */\nexport const weightingFunctionProvider: ServiceProvider = {\n  /**\n   * Registers weighting function related entities.\n   *\n   * @param container\n   */\n  register(container: ServiceContainer) {\n    const pool: WeightingFunctionFactoriesPool = new BasePool();\n    pool.add(WeightingFunctionName.BOX, new BoxFactory());\n    pool.add(WeightingFunctionName.CUBIC_BC, new CubicBCFactory());\n    container.register(\"WeightingFunctionFactoriesPool\", pool);\n  },\n};\n","import type { ServiceContainer, ServiceProvider } from \"../service-container\";\nimport { BaseColorInterpolatorFactory } from \"./BaseColorInterpolatorFactory\";\n\n/**\n * Color interpolation service provider.\n * @internal\n */\nexport const colorInterpolationProvider: ServiceProvider = {\n  /**\n   * Registers entities, related to color interpolation in service container.\n   *\n   * @param container\n   */\n  register(container: ServiceContainer) {\n    container.register(\n      \"ColorInterpolatorFactory\",\n      new BaseColorInterpolatorFactory()\n    );\n  },\n};\n","import type { ServiceContainer, ServiceProvider } from \"../service-container\";\nimport { BaseVirtualPixelDecoratorApplicator } from \"./BaseVirtualPixelDecoratorApplicator\";\n\n/**\n * Pixel accessor service provider.\n * @internal\n */\nexport const pixelAccessorProvider: ServiceProvider = {\n  /**\n   * Registers entities, related to pixel accessor, in service container.\n   * @param container\n   */\n  register(container: ServiceContainer) {\n    container.register(\n      \"VirtualPixelDecoratorApplicator\",\n      new BaseVirtualPixelDecoratorApplicator()\n    );\n  },\n};\n","import { LensException } from \"./LensException\";\n\n/**\n * Invalid method call exception.\n */\nexport class InvalidMethodCall extends LensException {\n  /**\n   * @param message Error message.\n   */\n  constructor(message: string) {\n    super(message);\n    this.name = \"InvalidMethodCall\";\n  }\n}\n","/**\n * Library version\n * @public\n */\nexport const VERSION = \"2.0.1\";\n","import type {\n  DistortionResult,\n  DistortionServiceOptions,\n} from \"./distortion-processing\";\nimport { serviceContainer } from \"./serviceContainer\";\nimport type {\n  GetReversePixelMapperFactoryArgs,\n  ReversePixelMapperFactoriesPoolKeyMap,\n  ReversePixelMapper,\n} from \"./pixel-mapper\";\nimport type { ImageAdapter } from \"./image-adapter\";\n\n/**\n * Distorts image using distortion name and distortion arguments.\n *\n * @param image\n * @param distortion\n * @param args\n * @param options\n */\nexport function distort<\n  ResourceType,\n  K extends keyof ReversePixelMapperFactoriesPoolKeyMap\n>(\n  image: ResourceType | ImageAdapter<ResourceType>,\n  distortion: K,\n  args: GetReversePixelMapperFactoryArgs<K>,\n  options?: DistortionServiceOptions\n): Promise<DistortionResult<ResourceType>>;\n\n/**\n * Distorts image using ReversePixelMapper instance.\n *\n * @param image\n * @param reversePixelMapper\n * @param options\n */\nexport function distort<ResourceType>(\n  image: ResourceType | ImageAdapter<ResourceType>,\n  reversePixelMapper: ReversePixelMapper,\n  options?: DistortionServiceOptions\n): Promise<DistortionResult<ResourceType>>;\n\n/**\n * distort() implementation.\n *\n * @param image\n * @param distortionOrMapper\n * @param argsOrOptions\n * @param mayBeOptions\n */\nexport function distort<ResourceType>(\n  image: ResourceType | ImageAdapter<ResourceType>,\n  distortionOrMapper:\n    | keyof ReversePixelMapperFactoriesPoolKeyMap\n    | string\n    | ReversePixelMapper,\n  argsOrOptions: number[] | DistortionServiceOptions | undefined,\n  mayBeOptions?: DistortionServiceOptions\n): Promise<DistortionResult<ResourceType>> {\n  return serviceContainer\n    .resolve(\"DistortionService\")\n    .distort(image, distortionOrMapper, argsOrOptions, mayBeOptions);\n}\n","import type { DistortionServiceOptions } from \"./distortion-processing\";\nimport { serviceContainer } from \"./serviceContainer\";\nimport type {\n  GetReversePixelMapperFactoryArgs,\n  ReversePixelMapperFactoriesPoolKeyMap,\n  ReversePixelMapper,\n} from \"./pixel-mapper\";\nimport type { ImageAdapter } from \"./image-adapter\";\n\n/**\n * Distorts image using distortion name and distortion arguments and returns distorted image resource.\n *\n * @param image\n * @param distortion\n * @param args\n * @param options\n */\nexport function distortUnwrap<\n  ResourceType,\n  K extends keyof ReversePixelMapperFactoriesPoolKeyMap\n>(\n  image: ResourceType | ImageAdapter<ResourceType>,\n  distortion: K,\n  args: GetReversePixelMapperFactoryArgs<K>,\n  options?: DistortionServiceOptions\n): Promise<ResourceType>;\n\n/**\n * Distorts image using ReversePixelMapper instance and returns distorted image resource.\n *\n * @param image\n * @param reversePixelMapper\n * @param options\n */\nexport function distortUnwrap<ResourceType>(\n  image: ResourceType | ImageAdapter<ResourceType>,\n  reversePixelMapper: ReversePixelMapper,\n  options?: DistortionServiceOptions\n): Promise<ResourceType>;\n\n/**\n * distortUnwrap() implementation\n *\n * @param image\n * @param distortionOrMapper\n * @param argsOrOptions\n * @param mayBeOptions\n */\nexport async function distortUnwrap<ResourceType>(\n  image: ResourceType | ImageAdapter<ResourceType>,\n  distortionOrMapper:\n    | keyof ReversePixelMapperFactoriesPoolKeyMap\n    | string\n    | ReversePixelMapper,\n  argsOrOptions: number[] | DistortionServiceOptions | undefined,\n  mayBeOptions?: DistortionServiceOptions\n): Promise<ResourceType> {\n  const result = await serviceContainer\n    .resolve(\"DistortionService\")\n    .distort(image, distortionOrMapper, argsOrOptions, mayBeOptions);\n  return result.image.getResource();\n}\n","import { makeCanvas } from \"./makeCanvas\";\n\n/**\n * Draws offscreen canvas on HTMLCanvasElement and returns it. If instance of HTMLCanvasElement was passed, simple\n * returns it.\n *\n * @param canvas\n */\nexport function toHTMLCanvasElement(\n  canvas: OffscreenCanvas | HTMLCanvasElement\n): HTMLCanvasElement {\n  if (canvas instanceof HTMLCanvasElement) {\n    return canvas;\n  }\n  const canvasElement = makeCanvas(canvas.width, canvas.height, true);\n  const context = canvasElement.getContext(\"2d\");\n  if (!context) {\n    throw new Error(\"Couldn't get canvas context\");\n  }\n  context.drawImage(canvas, 0, 0);\n  return canvasElement;\n}\n"],"names":["AverageInterpolator","neighborsCount","this","includes","RangeError","image","x","y","startX","startY","count","Math","floor","endX","endY","color","v","u","pixelColor","getPixelColor","gamma","round","BackgroundInterpolator","getBackgroundColor","IntegerInterpolator","InterpolationMethod","BaseColorInterpolatorFactory","method","AVERAGE","AVERAGE_9","AVERAGE_16","BACKGROUND","INTEGER","TypeError","BaseColorResamplerResolver","colorResamplerFactoriesPool","resampleFilterResolver","reversePixelMapper","options","preferredResampler","filter","matteColor","interpolationMethod","virtualPixelMethod","factory","getColorResamplerFactory","resampleFilter","supportsEwa","resolve","create","get","requiresResampleFilter","items","find","f","factories","length","Error","isColorResampler","candidate","getResampledColor","setScaling","getScaling","AbstractVirtualPixelDecorator","decorated","width","height","x1","offsetX","y1","offsetY","getViewport","getVirtualPixelColor","setPixelColor","getQuantumRange","getAverageColor","getDecorated","BackgroundVirtualPixel","ConstantVirtualPixel","super","EdgeVirtualPixel","max","min","HorizontalTileEdgeVirtualPixel","rx","ry","HorizontalTileVirtualPixel","MirrorVirtualPixel","doubleWidth","doubleHeight","tx","ty","RandomVirtualPixel","random","TileVirtualPixel","VerticalTileEdgeVirtualPixel","VerticalTileVirtualPixel","VirtualPixelMethod","BaseVirtualPixelDecoratorApplicator","EDGE","MIRROR","RANDOM","TILE","TRANSPARENT","BLACK","GRAY","WHITE","HORIZONTAL_TILE","VERTICAL_TILE","HORIZONTAL_TILE_EDGE","VERTICAL_TILE_EDGE","isHasAverageColor","obj","isHasBackgroundColor","isPixelAccessor","isPixelAccessorWithDimensions","Viewport","x2","y2","getHeight","getArea","getWidth","clone","fixBounds","ceil","scale","scaledWidth","scaledHeight","reset","isViewportLiteral","isVirtualViewportPixelAccessor","isEwaColorResampler","getWeightLookupTable","EPSILON","Number","pow","MAXIMUM_VALUE","MAX_VALUE","M_PI2","PI","M_2PI","blendColors","color1","color2","balance","weight2","result","i","createDeferred","deferred","promise","Promise","reject","degreesToRadians","degrees","perceptibleReciprocal","sign","gaussJordanElimination","coefficients","results","matrix","vectors","rank","forEach","vector","cloneMatrix","numVectors","cols","Array","fill","rows","pivots","col","row","j","k","unsolvable","abs","swap","array","row1","col1","row2","col2","map","slice","LeastSquares","push","terms","makeCanvas","forceOnscreen","canvas","document","createElement","OffscreenCanvas","preloadHtmlImage","src","Image","cleanup","onload","onerror","LensException","message","name","captureStackTrace","constructor","stack","AbortException","InvalidArgument","InvalidArgumentsLength","applyAffineMatrix","invertAffineMatrix","determinant","Affine","isConstantPartialDerivatives","forwardMatrix","fromForwardMatrix","getPartialDerivatives","viewport","u1","v1","u2","v2","forwardMap","bestFit","apex","expand","AffineFactory","controlPoints","leastSquares","addTerms","solve","concat","AffineProjectionFactory","sx","sy","Arc","c0","c1","c2","c3","c4","forceBestFit","angleToWidth","radiusToHeight","viewportWidthX2","getUV","a","ca","cos","sa","sin","vp","atan2","hypot","ArcFactory","args","invertPerspectiveMatrix","applyPerspectiveMatrix","p","q","r","Perspective","reverseMatrix","denominator","absC6","absC7","inverse","scaling","validity","absR","PerspectiveFactory","PerspectiveProjectionFactory","Polynomial","coeffs","n","basis","polyBasisFn","getValidity","dux","duy","dvx","dvy","basisDx","polyBasisDx","basisDy","polyBasisDy","indexX","indexY","PolynomialFactory","termsCount","order","flat","BaseReversePixelMapperResolver","reversePixelMapperFactoriesPool","isReversePixelMapper","reverseMap","isBestFitReversePixelMapper","getBestFitViewport","Distortion","isEwaReversePixelMapper","clampToQuantum","value","quantumRange","EwaResampler","pixelMapper","weightLookupTable","workingSupport","averageInterpolator","defaultInterpolator","imageVirtualPixelMethod","supportSq","weightLookupTableSize","imageViewport","imageArea","imageAverageColor","A","B","C","F","uLimit","vLimit","uWidth","slope","ellipseIsSetUp","limitReached","derivatives","setupEllipse","getWeightedAverage","s","initEllipse","scaleEllipse","major_x","major_y","minor_x","minor_y","major_mag","minor_mag","n11","n12","n21","n22","det","twice_det","frobenius_squared","discriminant","sqrt_discriminant","sqrt","s1s1","s2s2","s1s1minusn11","s1s1minusn22","s1s1minusn11_squared","s1s1minusn22_squared","temp_u11","temp_u21","norm","u11","u21","u0","v0","doesntNeedResampling","interpolate","getImageAverageColor","divisorM","divisorC","red","green","blue","alpha","uw","DDQ","ustart","uend","U","V","Q","DQ","weight","g","b","outOfImageBounds","EwaResamplerFactory","colorInterpolatorFactory","table","rScale","getWorkingSupport","WEIGHT_LOOKUP_TABLE_WIDTH","getWeight","PointResampler","interpolator","PointResamplerFactory","CompositeColorStringParser","parsersPool","colorString","parser","parse","HexColorStringParser","test","split","char","repeat","join","match","parseInt","isColor","isArray","every","channel","isPoint","RgbaColorStringParser","replace","index","num","parseFloat","indexOf","isNaN","TransparentStringParser","ReversePixelMappingProcessor","asyncTimeout","abortSignal","targetImage","resampler","scope","createProcessScope","doProcess","commit","currentX","currentY","aborted","reason","String","startTime","Date","now","setTimeout","bind","SuperSamplingProxy","processor","superSamplingFactor","process","AbstractImageAdapter","backgroundColor","blank","prepareBlank","setViewport","duplicateProps","resized","resize","instance","setBackgroundColor","BaseImageAdapterResolver","factoriesPool","resource","resourceName","Object","prototype","toString","call","getCanvasContext","context","getContext","willReadFrequently","Canvas","imageData","getImageData","data","drawImage","url","createFromImage","blob","bitmap","createImageBitmap","offset","dst","isOffscreen","getResource","putImageData","CanvasFactory","HTMLCanvasElement","isImageAdapter","getBlank","VirtualViewportProxy","adapter","scaled","RepageProxy","repage","fromLiteral","BaseDistortionProcessorFactory","outputScaling","DistortionController","outputViewportResolver","distortionProcessorFactory","distort","createTargetImage","virtualViewportProxy","distortionProcessor","getAdapter","outputViewport","DistortionService","reversePixelMapperResolver","colorResamplerResolver","distortionController","imageAdapterResolver","colorStringParser","virtualPixelDecoratorApplicator","distortionOrMapper","argsOrOptions","mayBeOptions","imageAdapter","clarifyArguments","setImageAdapterOptions","colorResampler","getColorResampler","startTimestamp","distortedImage","endTimestamp","distortion","duration","resolveImageAdapter","realMatteColor","resolveColor","virtualPixelDecoratedImage","decorate","imageBackgroundColor","imageViewportOffset","defaultValue","BaseOutputViewportResolver","outputViewportStrategiesPool","strategies","sort","priority","strategy","getOutputViewport","BestFitViewport","SourceImageViewport","UserProvidedViewport","BasePool","storage","Map","key","has","item","set","delete","from","keys","values","BaseResampleFilter","filterFunction","windowingFunction","support","blur","windowSupport","xBlur","window","BaseResampleFilterFactory","weightingFunctionFactoriesPool","filterFunctionName","filterFunctionFactoryArgs","windowFunctionFactoryName","windowFunctionFactoryArgs","windowFunction","isResampleFilter","isResampleFilterPreset","filterFunctionFactory","windowFunctionFactory","BaseResampleFilterResolver","filterPresetsPool","filterFactory","preset","filterBlur","filterWindowSupport","FilterName","BaseServiceContainer","parent","services","backups","service","backup","restore","pop","clear","createChild","child","BoxFactory","CubicBCFactory","c","p0","p2","p3","q0","q1","q2","q3","WeightingFunctionName","serviceContainer","providers","serviceLocator","provider","register","container","colorResamplerFactoriesPoolRegistered","pool","add","ARC","AFFINE","AFFINE_PROJECTION","PERSPECTIVE","PERSPECTIVE_PROJECTION","POLYNOMIAL","BOX","CUBIC_BC","async","canvasElement"],"mappings":"0NAOO,MAAMA,CAAAA,CAMX,YAAoBC,EACd,CAAA,GAD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