Skip to content
Myr

utils.js

This file

Path

lib/utils.js

472 lines · 9.4 KiB · JavaScript

Last changed by

improve etag control for res.sendDouglas Christopher Wilsonbefore adoptionc21226a

History of this file

Take it

12/**3 * Module dependencies.4 */56var mime = require('connect').mime7  , deprecate = require('util').deprecate8  , proxyaddr = require('proxy-addr')9  , crc32 = require('buffer-crc32')10  , crypto = require('crypto');1112/**13 * toString ref.14 */1516var toString = {}.toString;1718/**19 * Simple detection of charset parameter in content-type20 */21var charsetRegExp = /;\s*charset\s*=/;2223/**24 * Deprecate function, like core `util.deprecate`,25 * but with NODE_ENV and color support.26 *27 * @param {Function} fn28 * @param {String} msg29 * @return {Function}30 * @api private31 */3233exports.deprecate = function(fn, msg){34  if (process.env.NODE_ENV === 'test') return fn;3536  // prepend module name37  msg = 'express: ' + msg;3839  if (process.stderr.isTTY) {40    // colorize41    msg = '\x1b[31;1m' + msg + '\x1b[0m';42  }4344  return deprecate(fn, msg);45};4647/**48 * Return strong ETag for `body`.49 *50 * @param {String|Buffer} body51 * @param {String} [encoding]52 * @return {String}53 * @api private54 */5556exports.etag = function etag(body, encoding){57  if (body.length === 0) {58    // fast-path empty body59    return '"1B2M2Y8AsgTpgAmY7PhCfg=="'60  }6162  var hash = crypto63    .createHash('md5')64    .update(body, encoding)65    .digest('base64')66  return '"' + hash + '"'67};6869/**70 * Return weak ETag for `body`.71 *72 * @param {String|Buffer} body73 * @param {String} [encoding]74 * @return {String}75 * @api private76 */7778exports.wetag = function wetag(body, encoding){79  if (body.length === 0) {80    // fast-path empty body81    return 'W/"0-0"'82  }8384  var buf = Buffer.isBuffer(body)85    ? body86    : new Buffer(body, encoding)87  var len = buf.length88  return 'W/"' + len.toString(16) + '-' + crc32.unsigned(buf) + '"'89};9091/**92 * Make `locals()` bound to the given `obj`.93 *94 * This is used for `app.locals` and `res.locals`.95 *96 * @param {Object} obj97 * @return {Function}98 * @api private99 */100101exports.locals = function(){102  function locals(obj){103    for (var key in obj) locals[key] = obj[key];104    return obj;105  };106107  return locals;108};109110/**111 * Check if `path` looks absolute.112 *113 * @param {String} path114 * @return {Boolean}115 * @api private116 */117118exports.isAbsolute = function(path){119  if ('/' == path[0]) return true;120  if (':' == path[1] && '\\' == path[2]) return true;121  if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path122};123124/**125 * Flatten the given `arr`.126 *127 * @param {Array} arr128 * @return {Array}129 * @api private130 */131132exports.flatten = function(arr, ret){133  var ret = ret || []134    , len = arr.length;135  for (var i = 0; i < len; ++i) {136    if (Array.isArray(arr[i])) {137      exports.flatten(arr[i], ret);138    } else {139      ret.push(arr[i]);140    }141  }142  return ret;143};144145/**146 * Normalize the given `type`, for example "html" becomes "text/html".147 *148 * @param {String} type149 * @return {Object}150 * @api private151 */152153exports.normalizeType = function(type){154  return ~type.indexOf('/')155    ? acceptParams(type)156    : { value: mime.lookup(type), params: {} };157};158159/**160 * Normalize `types`, for example "html" becomes "text/html".161 *162 * @param {Array} types163 * @return {Array}164 * @api private165 */166167exports.normalizeTypes = function(types){168  var ret = [];169170  for (var i = 0; i < types.length; ++i) {171    ret.push(exports.normalizeType(types[i]));172  }173174  return ret;175};176177/**178 * Return the acceptable type in `types`, if any.179 *180 * @param {Array} types181 * @param {String} str182 * @return {String}183 * @api private184 */185186exports.acceptsArray = function(types, str){187  // accept anything when Accept is not present188  if (!str) return types[0];189190  // parse191  var accepted = exports.parseAccept(str)192    , normalized = exports.normalizeTypes(types)193    , len = accepted.length;194195  for (var i = 0; i < len; ++i) {196    for (var j = 0, jlen = types.length; j < jlen; ++j) {197      if (exports.accept(normalized[j], accepted[i])) {198        return types[j];199      }200    }201  }202};203204/**205 * Check if `type(s)` are acceptable based on206 * the given `str`.207 *208 * @param {String|Array} type(s)209 * @param {String} str210 * @return {Boolean|String}211 * @api private212 */213214exports.accepts = function(type, str){215  if ('string' == typeof type) type = type.split(/ *, */);216  return exports.acceptsArray(type, str);217};218219/**220 * Check if `type` array is acceptable for `other`.221 *222 * @param {Object} type223 * @param {Object} other224 * @return {Boolean}225 * @api private226 */227228exports.accept = function(type, other){229  var t = type.value.split('/');230  return (t[0] == other.type || '*' == other.type)231    && (t[1] == other.subtype || '*' == other.subtype)232    && paramsEqual(type.params, other.params);233};234235/**236 * Check if accept params are equal.237 *238 * @param {Object} a239 * @param {Object} b240 * @return {Boolean}241 * @api private242 */243244function paramsEqual(a, b){245  return !Object.keys(a).some(function(k) {246    return a[k] != b[k];247  });248}249250/**251 * Parse accept `str`, returning252 * an array objects containing253 * `.type` and `.subtype` along254 * with the values provided by255 * `parseQuality()`.256 *257 * @param {Type} name258 * @return {Type}259 * @api private260 */261262exports.parseAccept = function(str){263  return exports264    .parseParams(str)265    .map(function(obj){266      var parts = obj.value.split('/');267      obj.type = parts[0];268      obj.subtype = parts[1];269      return obj;270    });271};272273/**274 * Parse quality `str`, returning an275 * array of objects with `.value`,276 * `.quality` and optional `.params`277 *278 * @param {String} str279 * @return {Array}280 * @api private281 */282283exports.parseParams = function(str){284  return str285    .split(/ *, */)286    .map(acceptParams)287    .filter(function(obj){288      return obj.quality;289    })290    .sort(function(a, b){291      if (a.quality === b.quality) {292        return a.originalIndex - b.originalIndex;293      } else {294        return b.quality - a.quality;295      }296    });297};298299/**300 * Parse accept params `str` returning an301 * object with `.value`, `.quality` and `.params`.302 * also includes `.originalIndex` for stable sorting303 *304 * @param {String} str305 * @return {Object}306 * @api private307 */308309function acceptParams(str, index) {310  var parts = str.split(/ *; */);311  var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };312313  for (var i = 1; i < parts.length; ++i) {314    var pms = parts[i].split(/ *= */);315    if ('q' == pms[0]) {316      ret.quality = parseFloat(pms[1]);317    } else {318      ret.params[pms[0]] = pms[1];319    }320  }321322  return ret;323}324325/**326 * Escape special characters in the given string of html.327 *328 * @param  {String} html329 * @return {String}330 * @api private331 */332333exports.escape = function(html) {334  return String(html)335    .replace(/&/g, '&amp;')336    .replace(/"/g, '&quot;')337    .replace(/</g, '&lt;')338    .replace(/>/g, '&gt;');339};340341/**342 * Normalize the given path string,343 * returning a regular expression.344 *345 * An empty array should be passed,346 * which will contain the placeholder347 * key names. For example "/user/:id" will348 * then contain ["id"].349 *350 * @param  {String|RegExp|Array} path351 * @param  {Array} keys352 * @param  {Boolean} sensitive353 * @param  {Boolean} strict354 * @return {RegExp}355 * @api private356 */357358exports.pathRegexp = function(path, keys, sensitive, strict) {359  if (toString.call(path) == '[object RegExp]') return path;360  if (Array.isArray(path)) path = '(' + path.join('|') + ')';361  path = path362    .concat(strict ? '' : '/?')363    .replace(/\/\(/g, '(?:/')364    .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){365      keys.push({ name: key, optional: !! optional });366      slash = slash || '';367      return ''368        + (optional ? '' : slash)369        + '(?:'370        + (optional ? slash : '')371        + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'372        + (optional || '')373        + (star ? '(/*)?' : '');374    })375    .replace(/([\/.])/g, '\\$1')376    .replace(/\*/g, '(.*)');377  return new RegExp('^' + path + '$', sensitive ? '' : 'i');378}379380/**381 * Compile "etag" value to function.382 *383 * @param  {Boolean|String|Function} val384 * @return {Function}385 * @api private386 */387388exports.compileETag = function(val) {389  var fn;390391  if (typeof val === 'function') {392    return val;393  }394395  switch (val) {396    case true:397      fn = exports.wetag;398      break;399    case false:400      break;401    case 'strong':402      fn = exports.etag;403      break;404    case 'weak':405      fn = exports.wetag;406      break;407    default:408      throw new TypeError('unknown value for etag function: ' + val);409  }410411  return fn;412}413414/**415 * Compile "proxy trust" value to function.416 *417 * @param  {Boolean|String|Number|Array|Function} val418 * @return {Function}419 * @api private420 */421422exports.compileTrust = function(val) {423  if (typeof val === 'function') return val;424425  if (val === true) {426    // Support plain true/false427    return function(){ return true };428  }429430  if (typeof val === 'number') {431    // Support trusting hop count432    return function(a, i){ return i < val };433  }434435  if (typeof val === 'string') {436    // Support comma-separated values437    val = val.split(/ *, */);438  }439440  return proxyaddr.compile(val || []);441}442443/**444 * Set the charset in a given Content-Type string.445 *446 * @param {String} type447 * @param {String} charset448 * @return {String}449 * @api private450 */451452exports.setCharset = function(type, charset){453  if (!type || !charset) return type;454455  var exists = charsetRegExp.test(type);456457  // removing existing charset458  if (exists) {459    var parts = type.split(';');460461    for (var i = 1; i < parts.length; i++) {462      if (charsetRegExp.test(';' + parts[i])) {463        parts.splice(i, 1);464        break;465      }466    }467468    type = parts.join(';');469  }470471  return type + '; charset=' + charset;472};