var debug = require('debug')('ylt:contentTypeChecker'); var Q = require('q'); var isJpg = require('is-jpg'); var isPng = require('is-png'); var isSvg = require('is-svg'); var isGif = require('is-gif'); var isWebp = require('is-webp'); var isWoff = require('is-woff'); var isWoff2 = require('is-woff2'); var isOtf = require('is-otf'); var isTtf = require('is-ttf'); var isEot = require('is-eot'); var isJson = require('is-json'); var ContentTypeChecker = function() { function checkContentType(entry) { var deferred = Q.defer(); // Setting isSomething values: switch(entry.type) { case 'html': entry.isHTML = true; break; case 'xml': entry.isXML = true; break; case 'css': entry.isCSS = true; break; case 'js': entry.isJS = true; break; case 'json': entry.isJSON = true; break; case 'image': entry.isImage = true; break; case 'webfont': entry.isWebFont = true; break; case 'video': entry.isVideo = true; break; case 'favicon': entry.isFavicon = true; break; } // Now let's check for mistakes by analysing body content. It happens more often then we think! // Ignore very small files as they are generally tracking pixels if (entry.weightCheck && entry.weightCheck.bodyBuffer && entry.weightCheck.bodySize > 100) { var foundType; try { foundType = findContentType(entry.weightCheck.bodyBuffer); // If it's an image or a font, then rewrite. if (foundType !== null && (foundType.type === 'image' || foundType.type === 'webfont' || foundType.type === 'json')) { if (foundType.type !== entry.type) { debug('Content type %s is wrong for %s. It should be %s.', entry.type, entry.ulr, foundType.type); } rewriteContentType(entry, foundType); } } catch(err) { debug('Error while analyzing the contentType of %s', entry.url); debug(err); } } deferred.resolve(entry); return deferred.promise; } function findContentType(bodyBuffer) { var bodyStr = bodyBuffer.toString(); if (isJpg(bodyBuffer)) { return contentTypes.jpeg; } if (isPng(bodyBuffer)) { return contentTypes.png; } // https://github.com/sindresorhus/is-svg/issues/7 if (/