All files / node-iiif/lib transform.js

99.13% Statements 114/115
94.52% Branches 69/73
100% Functions 21/21
99.07% Lines 107/108

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 2133x 3x     3x   3x   3x                 201x 201x 166x   201x       201x 8x   193x       39x 11x 5x 1x   4x         39x 39x       43x   42x   19x 3x 16x 3x   13x     74x 37x 37x 37x       47x   43x   22x 11x   11x   38x       35x   34x 23x     11x 2x   11x 11x     11x 11x       36x 35x   4x 2x 2x 2x   35x       40x 39x     38x   38x   2x 2x   4x 4x 1x 1x   4x   32x   38x 38x 4x   38x       31x 31x       3x 3x 3x 3x 3x 2x 2x   1x 1x   3x           3x 12x   6x 6x 3x       16x 52x   16x 16x 5x   11x       11x 11x 2x   9x 9x       20x 20x 20x 2x   20x     40x   20x 20x 3x   17x       3x            
const Sharp = require('sharp');
const IIIFError = require('./error');
 
// Integer RegEx
const IR = '\\d+';
// Float RegEx
const FR = '\\d+(?:\.\\d+)?'; // eslint-disable-line no-useless-escape
 
const Validators = {
  quality: ['color', 'gray', 'bitonal', 'default'],
  format: ['jpg', 'jpeg', 'tif', 'tiff', 'png', 'webp'],
  region: ['full', 'square', `pct:${FR},${FR},${FR},${FR}`, `${IR},${IR},${IR},${IR}`],
  size: ['full', 'max', `pct:${FR}`, `${IR},`, `,${IR}`, `\\!?${IR},${IR}`],
  rotation: `\\!?${FR}`
};
 
function validator (type) {
  let result = Validators[type];
  if (result instanceof Array) {
    result = result.join('|');
  }
  return new RegExp('^(' + result + ')$');
}
 
function validate (type, v) {
  if (!validator(type).test(v)) {
    throw new IIIFError(`Invalid ${type}: ${v}`);
  }
  return true;
}
 
function validateDensity (v) {
  if (v === null) return true;
  if (v === undefined) return true;
  if (typeof v !== 'number' || v < 0) {
    throw new IIIFError(`Invalid density value: ${v}`);
  }
  return true;
};
 
class Operations {
  constructor (dims) {
    this.dims = dims;
    this.pipeline = Sharp({ limitInputPixels: false });
  }
 
  region (v) {
    validate('region', v);
 
    if (v === 'full') {
      // do nothing
    } else if (v === 'square') {
      this._regionSquare(this.dims);
    } else if (v.match(/^pct:([\d.,]+)/)) {
      this._regionPct(RegExp.$1, this.dims);
    } else {
      this._regionXYWH(v);
    }
 
    const ifPositive = (a, b) => (a > 0 ? a : b);
    this.dims.width = ifPositive(this.pipeline.options.widthPre, this.dims.width);
    this.dims.height = ifPositive(this.pipeline.options.heightPre, this.dims.height);
    return this;
  }
 
  size (v) {
    validate('size', v);
 
    if (v === 'full' || v === 'max') {
      // do nothing
    } else if (v.match(/^pct:([\d]+)/)) {
      this._sizePct(RegExp.$1, this.dims);
    } else {
      this._sizeWH(v);
    }
    return this;
  }
 
  rotation (v) {
    validate('rotation', v);
 
    if (v === '0') {
      return this;
    }
 
    if (v[0] === '!') {
      this.pipeline = this.pipeline.flop();
    }
    const value = Number(v.replace(/^!/, ''));
    Iif (isNaN(value)) {
      throw new IIIFError(`Invalid rotation value: ${v}`);
    }
    this.pipeline = this.pipeline.rotate(value);
    return this;
  }
 
  quality (v) {
    validate('quality', v);
    if (v === 'color' || v === 'default') {
      // do nothing
    } else if (v === 'gray') {
      this.pipeline = this.pipeline.grayscale();
    } else if (v === 'bitonal') {
      this.pipeline = this.pipeline.threshold();
    }
    return this;
  }
 
  format (v, density) {
    validate('format', v);
    validateDensity(density);
 
    let pipelineFormat;
    const pipelineOptions = {};
 
    switch (v) {
      case 'jpeg':
        pipelineFormat = 'jpg';
        break;
      case 'tif':
        pipelineFormat = 'tiff';
        if (density) {
          pipelineOptions.xres = density / 25.4;
          pipelineOptions.yres = density / 25.4;
        }
        break;
      default:
        pipelineFormat = v;
    }
    this.pipeline = this.pipeline.toFormat(pipelineFormat, pipelineOptions);
    if (density) {
      this.pipeline = this.pipeline.withMetadata({ density: density });
    }
    return this;
  }
 
  withMetadata (v) {
    if (v) this.pipeline = this.pipeline.withMetadata();
    return this;
  }
 
  _regionSquare (dims) {
    if (dims.width !== dims.height) {
      const side = Math.min(dims.width, dims.height);
      const params = { width: side, height: side };
      const offset = Math.abs(Math.floor((dims.width - dims.height) / 2));
      if (dims.width > dims.height) {
        params.left = offset;
        params.top = 0;
      } else {
        params.left = 0;
        params.top = offset;
      }
      this.pipeline = this.pipeline.extract(params);
    }
  }
 
  _regionPct (v, dims) {
    let x, y, w, h;
    [x, y, w, h] = v.split(/\s*,\s*/).map((pct) => {
      return Number(pct) / 100.0;
    });
    [x, w] = [x, w].map((val) => Math.round(dims.width * val));
    [y, h] = [y, h].map((val) => Math.round(dims.height * val));
    this._regionXYWH([x, y, w, h]);
  }
 
  _regionXYWH (v) {
    if (typeof v === 'string') {
      v = v.split(/\s*,\s*/).map((val) => Number(val));
    }
    const params = { left: v[0], top: v[1], width: v[2], height: v[3] };
    if (params.width === 0 || params.height === 0) {
      throw new IIIFError('Region width and height must both be > 0');
    }
    this.pipeline = this.pipeline.extract(params);
  }
 
  _sizePct (v, dims) {
    const pct = Number(v);
    if (isNaN(pct) || pct <= 0) {
      throw new IIIFError(`Invalid resize %: ${v}`);
    }
    const width = Math.round(dims.width * (pct / 100.0));
    this._sizeWH(`${width},`);
  }
 
  _sizeWH (v) {
    const params = { fit: 'cover' };
    if (typeof v === 'string') {
      if (v[0] === '!') {
        params.fit = 'inside';
      }
      v = v
        .replace(/^!/, '')
        .split(/\s*,\s*/)
        .map((val) => (val === '' ? null : Number(val)));
    }
    [params.width, params.height] = v;
    if (params.width === 0 || params.height === 0) {
      throw new IIIFError('Resize width and height must both be > 0');
    }
    this.pipeline = this.pipeline.resize(params);
  }
}
 
module.exports = {
  Qualities: Validators.quality,
  Formats: Validators.format,
  Operations,
  IIIFError
};