├── .eslintignore ├── .travis.yml ├── .gitignore ├── example ├── images │ ├── cat.gif │ ├── pigrock.jpg │ ├── find-peace.png │ ├── wil_wheaton_fes.jpg │ └── logo.svg ├── package.json └── server.js ├── .editorconfig ├── .eslintrc ├── .snyk ├── LICENSE.txt ├── lib ├── image-cache.js ├── image-optimizer.js └── index.js ├── package.json ├── README.md └── test ├── index.js ├── image-optimizer.js └── image-cache.js /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/** 2 | example/node_modules/** 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | node_js: 4 | - 9 5 | - 8 6 | - 6 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | example/node_modules/** 2 | node_modules/** 3 | coverage.html 4 | npm-debug.log 5 | -------------------------------------------------------------------------------- /example/images/cat.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fhemberger/hapi-imagemin-proxy/HEAD/example/images/cat.gif -------------------------------------------------------------------------------- /example/images/pigrock.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fhemberger/hapi-imagemin-proxy/HEAD/example/images/pigrock.jpg -------------------------------------------------------------------------------- /example/images/find-peace.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fhemberger/hapi-imagemin-proxy/HEAD/example/images/find-peace.png -------------------------------------------------------------------------------- /example/images/wil_wheaton_fes.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fhemberger/hapi-imagemin-proxy/HEAD/example/images/wil_wheaton_fes.jpg -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | end_of_line = lf 9 | insert_final_newline = true 10 | trim_trailing_whitespace = true 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | 15 | [{package.json,.eslintrc}] 16 | indent_style = space 17 | indent_size = 2 18 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "name": "hapi-imageoptimizer-example", 4 | "scripts": { 5 | "start": "node server.js 2>&1", 6 | "postinstall": "cd ..; npm install; cd -" 7 | }, 8 | "dependencies": { 9 | "good": "^7.0.1", 10 | "good-console": "^6.1.2", 11 | "good-squeeze": "^3.0.1", 12 | "hapi": "^13.5.0", 13 | "promise.pipe": "^3.0.0" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": ["hapi"], 3 | "extends": "hapi", 4 | "env": { 5 | "node": true, 6 | "es6": true 7 | }, 8 | "rules": { 9 | "complexity": [1, 8], 10 | "consistent-return": 0, 11 | "eol-last": 1, 12 | "hapi/hapi-capitalize-modules": 0, 13 | "key-spacing": 0, 14 | "max-depth": [1, 2], 15 | "max-nested-callbacks": [2, 4], 16 | "max-params": [1, 4], 17 | "no-confusing-arrow": 0, 18 | "no-console": 1, 19 | "no-multi-spaces": 0, 20 | "no-shadow": 0, 21 | "no-trailing-spaces": 1, 22 | "no-underscore-dangle": 0, 23 | "no-unused-vars": 1, 24 | "quotes": [1, "single"], 25 | "space-before-function-paren": [1, "always"] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /.snyk: -------------------------------------------------------------------------------- 1 | # Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities. 2 | version: v1.12.0 3 | ignore: {} 4 | # patches apply the minimum changes required to fix a vulnerability 5 | patch: 6 | 'npm:ms:20170412': 7 | - imagemin-gm > gm > debug > ms: 8 | patched: '2017-05-26T08:21:08.238Z' 9 | 'npm:tunnel-agent:20170305': 10 | - imagemin-gifsicle > gifsicle > bin-build > download > caw > tunnel-agent: 11 | patched: '2018-06-29T00:35:31.105Z' 12 | - imagemin-gifsicle > gifsicle > bin-wrapper > download > caw > tunnel-agent: 13 | patched: '2018-06-29T00:35:31.105Z' 14 | - imagemin-jpegoptim > jpegoptim-bin > bin-wrapper > download > caw > tunnel-agent: 15 | patched: '2018-06-29T00:35:31.105Z' 16 | - imagemin-jpegoptim > jpegoptim-bin > bin-build > download > caw > tunnel-agent: 17 | patched: '2018-06-29T00:35:31.105Z' 18 | - imagemin-pngquant > pngquant-bin > bin-wrapper > download > caw > tunnel-agent: 19 | patched: '2018-06-29T00:35:31.105Z' 20 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Frederic Hemberger 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /example/server.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Path = require('path'); 4 | const Hapi = require('hapi'); 5 | const server = new Hapi.Server(); 6 | 7 | const internals = {}; 8 | internals.plugins = [ 9 | { 10 | register: require('good'), 11 | options: { 12 | reporters: { 13 | console: [ 14 | { 15 | module: 'good-squeeze', 16 | name: 'Squeeze', 17 | args: [{ log: '*', request: '*' }] 18 | }, 19 | { 20 | module: 'good-console', 21 | args: [{ format: 'YYYY-MM-DDTHH:mm:ss.SSS[Z]' }] 22 | }, 23 | 'stdout' 24 | ] 25 | } 26 | } 27 | }, 28 | { 29 | register: require('../lib/index.js'), 30 | options: { 31 | source: Path.join(process.cwd(), 'images') 32 | } 33 | } 34 | ]; 35 | 36 | server.connection({ 37 | port: Number(process.env.PORT) || 5678 38 | }); 39 | 40 | server.register(internals.plugins, (err) => { 41 | 42 | if (err) { 43 | throw err; 44 | } 45 | 46 | // We don't serve their kind here 47 | server.route({ 48 | method: 'GET', 49 | path: '/favicon.ico', 50 | handler: (request, reply) => reply().code(404) 51 | }); 52 | 53 | server.start(() => server.log('info', `Server running at: ${server.info.uri}`)); 54 | }); 55 | -------------------------------------------------------------------------------- /lib/image-cache.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const ms = require('ms'); 4 | const Catbox = require('catbox'); 5 | const Package = require('../package.json'); 6 | 7 | const internals = {}; 8 | 9 | 10 | internals.getKey = (filename) => ({ 11 | id : filename, 12 | segment : Package.name 13 | }); 14 | 15 | 16 | const ImageCache = module.exports = function (engine, options) { 17 | 18 | if (!engine) { 19 | engine = require('catbox-memory'); 20 | options = Object.assign(options || {}, { allowMixedContent: true }); 21 | } 22 | 23 | this._ttl = options.expiresIn || ms('1h'); 24 | this._cache = new Catbox.Client(engine, options); 25 | }; 26 | 27 | 28 | ImageCache.prototype.get = function (filename) { 29 | 30 | const key = internals.getKey(filename); 31 | return new Promise((resolve, reject) => { 32 | 33 | this._cache.get(key, (err, cached) => { 34 | 35 | if (err) { 36 | return reject(err); 37 | } 38 | 39 | return resolve(cached && cached.item ? cached.item : null); 40 | }); 41 | }); 42 | }; 43 | 44 | 45 | ImageCache.prototype.set = function (filename, data) { 46 | 47 | const key = internals.getKey(filename); 48 | return new Promise((resolve, reject) => { 49 | 50 | this._cache.set(key, data, this._ttl, (err) => err ? reject(err) : resolve(data)); 51 | }); 52 | }; 53 | 54 | 55 | ImageCache.prototype.start = function () { 56 | 57 | return new Promise((resolve, reject) => { 58 | 59 | this._cache.start((err) => err ? reject(err) : resolve()); 60 | }); 61 | }; 62 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hapi-imagemin-proxy", 3 | "version": "2.0.1", 4 | "description": "Hapi proxy for serving optimized images", 5 | "author": "Frederic Hemberger (https://frederic-hemberger.de/)", 6 | "repository": "https://github.com/fhemberger/hapi-imagemin-proxy.git", 7 | "license": "MIT", 8 | "main": "lib/index.js", 9 | "scripts": { 10 | "lab": "NODE_ENV=test lab -L --lint-warnings-threshold 99999 --globals __RESOLVED_TMP_DIR__,Atomics,BigInt,BigInt64Array,BigUint64Array,SharedArrayBuffer,URL,URLSearchParams,WebAssembly", 11 | "test": "npm run lab -- test/*.js", 12 | "coverage": "npm run lab -- -c", 13 | "coverage:html": "npm run coverage -- -r html -o coverage.html", 14 | "snyk-protect": "snyk protect", 15 | "prepublish": "npm run snyk-protect", 16 | "prepare": "npm run snyk-protect" 17 | }, 18 | "engines": { 19 | "node": ">= 6.0.0" 20 | }, 21 | "files": [ 22 | "lib" 23 | ], 24 | "keywords": [ 25 | "hapi", 26 | "image", 27 | "images", 28 | "optimize", 29 | "imageoptim", 30 | "imagemin", 31 | "imagemagick", 32 | "graphicsmagick", 33 | "jpg", 34 | "jpeg", 35 | "png", 36 | "gif", 37 | "svg", 38 | "proxy" 39 | ], 40 | "dependencies": { 41 | "boom": "^6.0.0", 42 | "catbox": "^9.0.0", 43 | "catbox-memory": "^3.1.2", 44 | "generaterr": "^1.5.0", 45 | "hoek": "^5.0.4", 46 | "imagemin-gifsicle": "^5.2.0", 47 | "imagemin-gm": "^2.0.0", 48 | "imagemin-jpegoptim": "^5.2.0", 49 | "imagemin-pngquant": "^5.1.0", 50 | "imagemin-svgo": "^6.0.0", 51 | "joi": "^13.7.0", 52 | "ms": "^2.1.1", 53 | "promise.pipe": "^3.0.0", 54 | "snyk": "^1.103.4", 55 | "wreck": "12.x.x", 56 | "xregexp": "^4.2.0" 57 | }, 58 | "devDependencies": { 59 | "code": "4.x.x", 60 | "eslint-config-hapi": "10.0.0", 61 | "eslint-plugin-hapi": "4.x.x", 62 | "hapi": "16.x.x", 63 | "lab": "12.x.x", 64 | "pre-commit": "^1.2.2", 65 | "proxyquire": "^1.8.0", 66 | "sinon": "^4.3.0" 67 | }, 68 | "snyk": true 69 | } 70 | -------------------------------------------------------------------------------- /lib/image-optimizer.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Fs = require('fs'); 4 | const Url = require('url'); 5 | const Path = require('path'); 6 | const Boom = require('boom'); 7 | const Wreck = require('wreck'); 8 | const Hoek = require('hoek'); 9 | const promisePipe = require('promise.pipe'); 10 | 11 | 12 | // Default optimization plugins 13 | const imageminGm = require('imagemin-gm'); 14 | const imageminJpegoptim = require('imagemin-jpegoptim'); 15 | const imageminPngquant = require('imagemin-pngquant'); 16 | const imageminGifsicle = require('imagemin-gifsicle'); 17 | const imageminSvgo = require('imagemin-svgo'); 18 | 19 | 20 | const internals = { 21 | defaults: { 22 | plugins: [ 23 | imageminJpegoptim({ progressive: true, max: 75 }), 24 | imageminPngquant(), 25 | imageminGifsicle({ optimizationLevel: 3 }), 26 | imageminSvgo() 27 | ] 28 | } 29 | }; 30 | 31 | internals.isLocal = (path) => !/^https?:\/\//.test(path); 32 | 33 | 34 | exports.fullPath = (basePath, filename) => { 35 | 36 | if (internals.isLocal(basePath) ) { 37 | return Path.join(basePath, filename); 38 | } 39 | 40 | const parsed = Url.parse(basePath); 41 | const path = Path.join(parsed.path, filename); 42 | const auth = parsed.auth ? `${parsed.auth}@` : ''; 43 | 44 | return `${parsed.protocol}//${auth}${parsed.host}${path}`; 45 | }; 46 | 47 | 48 | /* eslint-disable hapi/hapi-scope-start */ 49 | exports.get = (image, wreckOptions) => (new Promise((resolve, reject) => { 50 | 51 | if (internals.isLocal(image)) { 52 | return Fs.readFile(image, (err, payload) => { 53 | 54 | return err ? 55 | reject(Boom.wrap(err, err.code === 'ENOENT' ? 404 : 500)) : 56 | resolve(payload); 57 | }); 58 | } 59 | 60 | Wreck.get(image, wreckOptions, (err, res, payload) => { 61 | 62 | if (!err && res.statusCode !== 200) { 63 | err = Boom.create(res.statusCode, image); 64 | } 65 | 66 | return err ? reject(err) : resolve(payload); 67 | }); 68 | })); 69 | /* eslint-enable hapi/hapi-scope-start */ 70 | 71 | 72 | exports.optimize = (input, options) => { 73 | 74 | const opts = Hoek.applyToDefaults(internals.defaults, options); 75 | 76 | if (opts.format) { 77 | opts.plugins.unshift(imageminGm.convert(opts.format)); 78 | } 79 | 80 | if (opts.width || opts.height) { 81 | opts.plugins.unshift(imageminGm.resize({ 82 | width : opts.width, 83 | height : opts.height, 84 | gravity : 'Center' 85 | })); 86 | } 87 | 88 | return opts.plugins.length > 0 ? promisePipe(opts.plugins)(input) : Promise.resolve(input); 89 | }; 90 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Path = require('path'); 4 | const Hoek = require('hoek'); 5 | const Boom = require('boom'); 6 | const XRegExp = require('xregexp'); 7 | const ImageCache = require('./image-cache.js'); 8 | const ImageOptimizer = require('./image-optimizer.js'); 9 | 10 | const internals = {}; 11 | 12 | internals.pathPattern = XRegExp( 13 | `^ 14 | (?.+?(?:jpe?g|gif|png|svg)) # File name 15 | (?:,w(?\\d{1,4})(?=,|$))? # Width 16 | (?:,h(?\\d{1,4})(?=,|$))? # Height 17 | (?:,(?jpe?g|gif|png|svg))? # Output format 18 | $`, 'x'); 19 | 20 | 21 | exports.register = function (server, options, next) { 22 | 23 | const mime = server.mime._byExtension; 24 | 25 | Hoek.assert(options.source, 'Missing image source directory: `options.source`'); 26 | 27 | const config = options.imagecache || {}; 28 | const imageCache = new ImageCache(config.engine, config.options); 29 | 30 | server.route({ 31 | method: 'GET', 32 | path: '/{param*}', 33 | config: { 34 | cache: options.cache 35 | }, 36 | handler: function (request, reply) { 37 | 38 | const parsedPath = XRegExp.exec(request.path, internals.pathPattern); 39 | 40 | if (!parsedPath) { 41 | return reply(Boom.notFound()); 42 | } 43 | 44 | const originalFormat = Path.extname(parsedPath.filename).slice(1); 45 | const imageOptions = { 46 | width : parsedPath.width, 47 | height : parsedPath.height, 48 | format : parsedPath.format 49 | }; 50 | 51 | imageCache.get(request.path) 52 | .then((imageData) => { 53 | 54 | if (imageData) { 55 | return imageData; 56 | } 57 | 58 | server.log(['debug'], `cache miss: ${request.path}`); 59 | return ImageOptimizer.get(ImageOptimizer.fullPath(options.source, parsedPath.filename), options.wreck) 60 | .then((imageData) => ImageOptimizer.optimize(imageData, imageOptions)) 61 | .then((imageData) => imageCache.set(request.path, imageData)); 62 | }) 63 | .then((imageData) => { 64 | 65 | server.log(['debug'], `cache hit: ${request.path}`); 66 | 67 | const type = mime[imageOptions.format || originalFormat].type; 68 | return reply(imageData).type(type); 69 | }) 70 | .catch((err) => { 71 | 72 | server.log(['error'], err); 73 | 74 | // Reply with matching error code but don't leak details 75 | return reply(Boom.create(err.output.statusCode)); 76 | }); 77 | } 78 | }); 79 | 80 | 81 | imageCache.start() 82 | .then(() => next()); 83 | }; 84 | 85 | 86 | exports.register.attributes = { 87 | pkg: require('../package.json') 88 | }; 89 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hapi-imagemin-proxy 2 | 3 | Image optimization proxy written in Node.js using [hapi](http://hapijs.com/). 4 | 5 | [![Build Status](https://travis-ci.org/fhemberger/hapi-imagemin-proxy.svg?branch=master)](http://travis-ci.org/fhemberger/hapi-imagemin-proxy) ![Current Version](https://img.shields.io/npm/v/hapi-imagemin-proxy.svg) 6 | 7 | Allows you to resize an image and change image formats. Output is always optimized for the smallest file size. 8 | 9 | - `http://localhost:5678/cat.gif,w100` - Resize to a width of 100px 10 | - `http://localhost:5678/cat.gif,w100,h50` - Fit into 100px × 50px (keeping aspect ratio) 11 | - `http://localhost:5678/find-peace.png,jpg` - Convert PNG to JPG 12 | - `http://localhost:5678/find-peace.png,w100,h50,jpg` - All combined 13 | 14 | 15 | ## Usage 16 | 17 | Requires [GraphicsMagick](http://www.graphicsmagick.org) to be installed (e.g. on Mac OS X via [Homebrew](http://brew.sh): `brew install graphicsmagick`). 18 | 19 | ``` 20 | npm install hapi-imagemin-proxy 21 | ``` 22 | 23 | Afterwards, include `hapi-imagemin-proxy` as plug-in into your existing Hapi project (a demo server can be found in `/example`): 24 | 25 | ```javascript 26 | const Hapi = require('hapi'); 27 | const server = new Hapi.Server(); 28 | 29 | server.register({ 30 | plugin: require('hapi-imagemin-proxy'), 31 | options: { 32 | source: '/path/to/images', 33 | cache: {}, 34 | imageCache: { 35 | engine: require('catbox-memory'), 36 | options: { 37 | expiresIn: 3600000 38 | } 39 | }, 40 | plugins: [ 41 | imageminGm.resize(), 42 | imageminGm.convert(), 43 | imageminJpegoptim({ progressive: true, max: 75 }), 44 | imageminPngquant(), 45 | imageminGifsicle({ optimizationLevel: 3 }), 46 | imageminSvgo() 47 | ] 48 | // ... 49 | } 50 | }, function (err) { 51 | 52 | if (err) { 53 | return { 54 | console.error(err); 55 | } 56 | } 57 | }); 58 | ``` 59 | 60 | 61 | ## Options 62 | 63 | - `source`: Location of the images to be served. Can be either a local path or a URL (required). 64 | - `wreck`: When `source` is an URL, these request options are passed to [Wreck](https://github.com/hapijs/wreck#requestmethod-uri-options-callback). 65 | - `cache`: Sets Hapi's [route.cache](http://hapijs.com/api#route-options) options 66 | - `imagecache`: 67 | - `engine`: Catbox caching engine. **Must** support binary data, e.g. [`catbox-s3`](https://github.com/fhemberger/catbox-s3). Default: `require('catbox-memory')` 68 | - `options`: Engine specific options (optional) 69 | - `maxByteSize`: only for `catbox-memory`, default: `104857600` (100MB) 70 | - `expiresIn`: Cache time-to-live in milliseconds, default: `3600000` (one hour) 71 | - `plugins`: Array of imagemin optimization plug-ins, defaults: 72 | 73 | ``` 74 | imageminJpegoptim({ progressive: true, max: 75 }), 75 | imageminPngquant(), 76 | imageminGifsicle({ optimizationLevel: 3 }), 77 | imageminSvgo() 78 | ``` 79 | 80 | 81 | ## TODO 82 | 83 | - Use [cjpeg-dssim](https://github.com/technopagan/cjpeg-dssim) for JPG optimization 84 | - Rewrite using async/await to support hapi@v17.x.x 85 | 86 | 87 | ## License 88 | 89 | [MIT](LICENSE.txt) 90 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Hapi = require('hapi'); 4 | const Code = require('code'); 5 | const Lab = require('lab'); 6 | const Boom = require('boom'); 7 | const Sinon = require('sinon'); 8 | const proxyquire = require('proxyquire').noCallThru(); 9 | 10 | 11 | // Test shortcuts 12 | const lab = exports.lab = Lab.script(); 13 | const expect = Code.expect; 14 | const before = lab.before; 15 | const after = lab.after; 16 | const describe = lab.describe; 17 | const it = lab.it; 18 | 19 | 20 | // Test stubs 21 | const jpeg = Buffer.from(new Uint8Array([0xFF, 0xD8])); 22 | const imageOptimizer = { 23 | get : Sinon.stub(), 24 | fullPath : Sinon.stub(), 25 | optimize : Sinon.stub() 26 | }; 27 | const imageCache = { 28 | get : Sinon.stub(), 29 | set : Sinon.stub(), 30 | start : Sinon.stub() 31 | }; 32 | const ImageCache = function () {}; 33 | ImageCache.prototype = imageCache; 34 | 35 | const plugin = proxyquire('../lib/index.js', { 36 | './image-optimizer.js' : imageOptimizer, 37 | './image-cache.js' : ImageCache 38 | }); 39 | 40 | 41 | describe('hapi-imagemin-proxy', () => { 42 | 43 | const server = new Hapi.Server({ debug: false }); 44 | 45 | before((done) => { 46 | 47 | imageCache.start.returns(Promise.resolve()); 48 | server.connection({ port: 5678 }); 49 | server.register( 50 | { register: plugin, options: { source: __dirname } }, 51 | (err) => err ? done(err) : server.start(done)); 52 | }); 53 | 54 | 55 | after((done) => { 56 | 57 | server.stop({ timeout: 0 }, (err) => done(err)); 58 | }); 59 | 60 | 61 | it('is running', (done) => { 62 | 63 | expect(new Date(server.info.started)).to.be.a.date(); 64 | done(); 65 | }); 66 | 67 | 68 | it('should respond with HTTP 404 if no matching file name was provided in URL', (done) => { 69 | 70 | server.inject('/', (res) => { 71 | 72 | expect( res.statusCode ).to.equal( 404 ); 73 | done(); 74 | }); 75 | }); 76 | 77 | 78 | it('should respond with cached image data on cache hit', (done) => { 79 | 80 | imageCache.get.returns(Promise.resolve(jpeg)); 81 | 82 | server.inject('/imagename.jpg', (res) => { 83 | 84 | expect( res.rawPayload ).to.only.include( jpeg ); 85 | expect( res.statusCode ).to.equal( 200 ); 86 | done(); 87 | }); 88 | }); 89 | 90 | 91 | it('should load the image file on cache miss', (done) => { 92 | 93 | imageCache.get.returns(Promise.resolve()); 94 | imageCache.set.returns(Promise.resolve(jpeg)); 95 | imageOptimizer.get.returns(Promise.resolve()); 96 | 97 | server.inject('/imagename.jpg', (res) => { 98 | 99 | expect( res.rawPayload ).to.only.include( jpeg ); 100 | expect( res.statusCode ).to.equal( 200 ); 101 | done(); 102 | }); 103 | }); 104 | 105 | 106 | it('should return HTTP 404 if image file could not be loaded', (done) => { 107 | 108 | const err = Boom.wrap(new Error('ENOENT: no such file or directory'), 404); 109 | imageCache.get.returns(Promise.reject(err)); 110 | 111 | server.inject('/imagename.jpg', (res) => { 112 | 113 | expect( res.statusCode ).to.equal( 404 ); 114 | expect( JSON.parse(res.payload).message ).to.equal('Not Found'); 115 | done(); 116 | }); 117 | }); 118 | 119 | 120 | it('should return HTTP 500 on error', (done) => { 121 | 122 | const err = Boom.wrap(new Error(), 500); 123 | imageCache.get.returns(Promise.reject(err)); 124 | 125 | server.inject('/imagename.jpg', (res) => { 126 | 127 | expect( res.statusCode ).to.equal( 500 ); 128 | expect( JSON.parse(res.payload).message ).to.equal('An internal server error occurred'); 129 | done(); 130 | }); 131 | }); 132 | 133 | }); 134 | -------------------------------------------------------------------------------- /test/image-optimizer.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Path = require('path'); 4 | const Code = require('code'); 5 | const Lab = require('lab'); 6 | const Sinon = require('sinon'); 7 | const proxyquire = require('proxyquire').noCallThru(); 8 | 9 | 10 | // Test shortcuts 11 | const lab = exports.lab = Lab.script(); 12 | const expect = Code.expect; 13 | const describe = lab.describe; 14 | const it = lab.it; 15 | 16 | 17 | // Test stubs 18 | /* eslint-disable brace-style, hapi/hapi-scope-start */ 19 | const jpeg = Buffer.from(new Uint8Array([0xFF, 0xD8])); 20 | const imageminGmStub = { 21 | convert : Sinon.stub().returns(() => { Promise.resolve(jpeg); }), 22 | resize : Sinon.stub().returns(() => { Promise.resolve(jpeg); }) 23 | }; 24 | const imageOptimizer = proxyquire('../lib/image-optimizer.js', { 'imagemin-gm': imageminGmStub }); 25 | /* eslint-enable brace-style, hapi/hapi-scope-start */ 26 | 27 | 28 | describe('Image Optimizer', () => { 29 | 30 | describe('fullPath', () => { 31 | 32 | it('should return a valid path for local files', (done) => { 33 | 34 | expect( imageOptimizer.fullPath('/foo/bar', '/baz.jpg') ).to.equal('/foo/bar/baz.jpg'); 35 | expect( imageOptimizer.fullPath('/foo/bar/', '/baz.jpg') ).to.equal('/foo/bar/baz.jpg'); 36 | done(); 37 | }); 38 | 39 | 40 | it('should return a valid URL for remote files', (done) => { 41 | 42 | expect( imageOptimizer.fullPath('http://foo.bar', '/baz.jpg') ).to.equal('http://foo.bar/baz.jpg'); 43 | expect( imageOptimizer.fullPath('http://foo.bar/baz', 'zing/zang.jpg') ).to.equal('http://foo.bar/baz/zing/zang.jpg'); 44 | expect( imageOptimizer.fullPath('http://basic:auth@foo.bar/', '/baz.jpg') ).to.equal('http://basic:auth@foo.bar/baz.jpg'); 45 | done(); 46 | }); 47 | }); 48 | 49 | 50 | describe('get', () => { 51 | 52 | it('should load a local file and return its content', (done) => { 53 | 54 | imageOptimizer.get(Path.join(process.cwd(), '.gitignore')) 55 | .then(( content ) => { 56 | 57 | expect(content).to.exist(); 58 | done(); 59 | }) 60 | .catch((err) => done(err)); 61 | }); 62 | 63 | 64 | it('should reject if the local file could not be loaded', (done) => { 65 | 66 | imageOptimizer.get('nonexistantfile') 67 | .catch((err) => { 68 | 69 | expect( err ).to.be.an.error(); 70 | done(); 71 | }); 72 | }); 73 | 74 | 75 | it('should GET a remote file and return its content', (done) => { 76 | 77 | imageOptimizer.get('http://example.com/') 78 | .then((content) => { 79 | 80 | expect( content ).to.exist(); 81 | done(); 82 | }) 83 | .catch((err) => done(err)); 84 | }); 85 | 86 | 87 | it('should reject if the remote file could not be loaded', (done) => { 88 | 89 | imageOptimizer.get('http://nonexistantdomainna.me') 90 | .catch((err) => { 91 | 92 | expect( err ).to.be.an.error(); 93 | done(); 94 | }); 95 | }); 96 | }); 97 | 98 | 99 | describe('optimize', () => { 100 | 101 | /* eslint-disable brace-style, hapi/hapi-scope-start */ 102 | it('should convert image formats', (done) => { 103 | 104 | imageOptimizer.optimize(jpeg, { format: 'png', plugins: [] }); 105 | expect( imageminGmStub.convert.calledOnce ).to.be.true(); 106 | done(); 107 | }); 108 | 109 | it('should resize the image', (done) => { 110 | 111 | imageOptimizer.optimize(jpeg, { width: 100, plugins: [] }); 112 | expect( imageminGmStub.resize.calledOnce ).to.be.true(); 113 | done(); 114 | }); 115 | 116 | it('should pass the original buffer if no plugins were given', (done) => { 117 | 118 | const result = imageOptimizer.optimize(jpeg, { plugins: [] }); 119 | expect( result ).to.equal( Promise.resolve(jpeg) ); 120 | done(); 121 | }); 122 | }); 123 | 124 | }); 125 | -------------------------------------------------------------------------------- /example/images/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 12 | 17 | 22 | 25 | 31 | 36 | 39 | 40 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /test/image-cache.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Code = require('code'); 4 | const Lab = require('lab'); 5 | const Sinon = require('sinon'); 6 | const proxyquire = require('proxyquire').noCallThru(); 7 | 8 | 9 | // Test shortcuts 10 | const lab = exports.lab = Lab.script(); 11 | const expect = Code.expect; 12 | const describe = lab.describe; 13 | const it = lab.it; 14 | 15 | 16 | // Test stubs 17 | /* eslint-disable hapi/hapi-scope-start, brace-style */ 18 | const Catbox = { Client: function (engine) { this.engine = engine; } }; 19 | Catbox.Client.prototype = { 20 | get : Sinon.stub(), 21 | set : Sinon.stub(), 22 | start : Sinon.stub() 23 | }; 24 | /* eslint-enable hapi/hapi-scope-start, brace-style */ 25 | 26 | 27 | const ImageCache = proxyquire('../lib/image-cache.js', { 28 | 'catbox' : Catbox, 29 | 'catbox-memory' : 'catbox-memory' 30 | }); 31 | 32 | 33 | describe('Image Cache', () => { 34 | 35 | describe('constructor', () => { 36 | 37 | it('should use "catbox-memory" if no engine is specified', (done) => { 38 | 39 | const imageCache = new ImageCache(); 40 | expect( imageCache._cache.engine ).to.equal( 'catbox-memory' ); 41 | done(); 42 | }); 43 | 44 | 45 | it('should have a ttl of one hour if `options.expiresIn` is not given', (done) => { 46 | 47 | const imageCache = new ImageCache(); 48 | expect( imageCache._ttl ).to.equal( 3600000 ); 49 | done(); 50 | }); 51 | 52 | 53 | it('should set a ttl based on `options.expiresIn`', (done) => { 54 | 55 | const imageCache = new ImageCache(null, { expiresIn: 60000 }); 56 | expect( imageCache._ttl ).to.equal( 60000 ); 57 | done(); 58 | }); 59 | }); 60 | 61 | 62 | describe('get', () => { 63 | 64 | it('should resolve on success', (done) => { 65 | 66 | const imageCache = new ImageCache(); 67 | imageCache._cache.get.yields(null, { item: 'data' }); 68 | imageCache.get('filename') 69 | .then((data) => { 70 | 71 | expect( data ).to.equal( 'data' ); 72 | done(); 73 | }) 74 | .catch((err) => done(err)); 75 | }); 76 | 77 | 78 | it('should reject on error', (done) => { 79 | 80 | const imageCache = new ImageCache(); 81 | imageCache._cache.get.yields(new Error('get')); 82 | imageCache.get('filename') 83 | .catch((err) => { 84 | 85 | expect( err ).to.be.an.error(Error, 'get'); 86 | done(); 87 | }); 88 | }); 89 | }); 90 | 91 | 92 | describe('set', () => { 93 | 94 | it('should resolve on success', (done) => { 95 | 96 | const imageCache = new ImageCache(); 97 | imageCache._cache.set.yields(null); 98 | imageCache.set('filename', 'data') 99 | .then((data) => { 100 | 101 | expect( data ).to.equal( 'data' ); 102 | done(); 103 | }) 104 | .catch((err) => done(err)); 105 | }); 106 | 107 | 108 | it('should reject on error', (done) => { 109 | 110 | const imageCache = new ImageCache(); 111 | imageCache._cache.set.yields(new Error('set')); 112 | imageCache.set() 113 | .catch((err) => { 114 | 115 | expect( err ).to.be.an.error(Error, 'set'); 116 | done(); 117 | }); 118 | }); 119 | }); 120 | 121 | 122 | describe('start', () => { 123 | 124 | it('should start the caching engine', (done) => { 125 | 126 | const imageCache = new ImageCache(); 127 | imageCache._cache.start.yields(null); 128 | imageCache.start() 129 | .then(() => { 130 | 131 | expect( true ).to.be.true(); 132 | done(); 133 | }) 134 | .catch((err) => done(err)); 135 | }); 136 | 137 | it('should reject on error', (done) => { 138 | 139 | const imageCache = new ImageCache(); 140 | imageCache._cache.start.yields(new Error('start')); 141 | imageCache.start() 142 | .catch((err) => { 143 | 144 | expect( err ).to.be.an.error(Error, 'start'); 145 | done(); 146 | }); 147 | }); 148 | }); 149 | 150 | }); 151 | --------------------------------------------------------------------------------