Skip to content
Myr

utils.js

This file

Path

lib/utils.js

431 lines · 8.6 KiB · JavaScript

Last changed by

deprecate things with depd moduleDouglas Christopher Wilsonbefore adoption9c731f1

History of this file

Take it

12/**3 * Module dependencies.4 */56var mime = require('connect').mime7  , proxyaddr = require('proxy-addr')8  , crc32 = require('buffer-crc32')9  , crypto = require('crypto');1011/**12 * toString ref.13 */1415var toString = {}.toString;1617/**18 * Simple detection of charset parameter in content-type19 */20var charsetRegExp = /;\s*charset\s*=/;2122/**23 * Return strong ETag for `body`.24 *25 * @param {String|Buffer} body26 * @param {String} [encoding]27 * @return {String}28 * @api private29 */3031exports.etag = function etag(body, encoding){32  if (body.length === 0) {33    // fast-path empty body34    return '"1B2M2Y8AsgTpgAmY7PhCfg=="'35  }3637  var hash = crypto38    .createHash('md5')39    .update(body, encoding)40    .digest('base64')41  return '"' + hash + '"'42};4344/**45 * Return weak ETag for `body`.46 *47 * @param {String|Buffer} body48 * @param {String} [encoding]49 * @return {String}50 * @api private51 */5253exports.wetag = function wetag(body, encoding){54  if (body.length === 0) {55    // fast-path empty body56    return 'W/"0-0"'57  }5859  var buf = Buffer.isBuffer(body)60    ? body61    : new Buffer(body, encoding)62  var len = buf.length63  return 'W/"' + len.toString(16) + '-' + crc32.unsigned(buf) + '"'64};6566/**67 * Make `locals()` bound to the given `obj`.68 *69 * This is used for `app.locals` and `res.locals`.70 *71 * @param {Object} obj72 * @return {Function}73 * @api private74 */7576exports.locals = function(){77  function locals(obj){78    for (var key in obj) locals[key] = obj[key];79    return obj;80  };8182  return locals;83};8485/**86 * Check if `path` looks absolute.87 *88 * @param {String} path89 * @return {Boolean}90 * @api private91 */9293exports.isAbsolute = function(path){94  if ('/' == path[0]) return true;95  if (':' == path[1] && '\\' == path[2]) return true;96  if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path97};9899/**100 * Flatten the given `arr`.101 *102 * @param {Array} arr103 * @return {Array}104 * @api private105 */106107exports.flatten = function(arr, ret){108  var ret = ret || []109    , len = arr.length;110  for (var i = 0; i < len; ++i) {111    if (Array.isArray(arr[i])) {112      exports.flatten(arr[i], ret);113    } else {114      ret.push(arr[i]);115    }116  }117  return ret;118};119120/**121 * Normalize the given `type`, for example "html" becomes "text/html".122 *123 * @param {String} type124 * @return {Object}125 * @api private126 */127128exports.normalizeType = function(type){129  return ~type.indexOf('/')130    ? acceptParams(type)131    : { value: mime.lookup(type), params: {} };132};133134/**135 * Normalize `types`, for example "html" becomes "text/html".136 *137 * @param {Array} types138 * @return {Array}139 * @api private140 */141142exports.normalizeTypes = function(types){143  var ret = [];144145  for (var i = 0; i < types.length; ++i) {146    ret.push(exports.normalizeType(types[i]));147  }148149  return ret;150};151152/**153 * Return the acceptable type in `types`, if any.154 *155 * @param {Array} types156 * @param {String} str157 * @return {String}158 * @api private159 */160161exports.acceptsArray = function(types, str){162  // accept anything when Accept is not present163  if (!str) return types[0];164165  // parse166  var accepted = exports.parseAccept(str)167    , normalized = exports.normalizeTypes(types)168    , len = accepted.length;169170  for (var i = 0; i < len; ++i) {171    for (var j = 0, jlen = types.length; j < jlen; ++j) {172      if (exports.accept(normalized[j], accepted[i])) {173        return types[j];174      }175    }176  }177};178179/**180 * Check if `type(s)` are acceptable based on181 * the given `str`.182 *183 * @param {String|Array} type(s)184 * @param {String} str185 * @return {Boolean|String}186 * @api private187 */188189exports.accepts = function(type, str){190  if ('string' == typeof type) type = type.split(/ *, */);191  return exports.acceptsArray(type, str);192};193194/**195 * Check if `type` array is acceptable for `other`.196 *197 * @param {Object} type198 * @param {Object} other199 * @return {Boolean}200 * @api private201 */202203exports.accept = function(type, other){204  var t = type.value.split('/');205  return (t[0] == other.type || '*' == other.type)206    && (t[1] == other.subtype || '*' == other.subtype)207    && paramsEqual(type.params, other.params);208};209210/**211 * Check if accept params are equal.212 *213 * @param {Object} a214 * @param {Object} b215 * @return {Boolean}216 * @api private217 */218219function paramsEqual(a, b){220  return !Object.keys(a).some(function(k) {221    return a[k] != b[k];222  });223}224225/**226 * Parse accept `str`, returning227 * an array objects containing228 * `.type` and `.subtype` along229 * with the values provided by230 * `parseQuality()`.231 *232 * @param {Type} name233 * @return {Type}234 * @api private235 */236237exports.parseAccept = function(str){238  return exports239    .parseParams(str)240    .map(function(obj){241      var parts = obj.value.split('/');242      obj.type = parts[0];243      obj.subtype = parts[1];244      return obj;245    });246};247248/**249 * Parse quality `str`, returning an250 * array of objects with `.value`,251 * `.quality` and optional `.params`252 *253 * @param {String} str254 * @return {Array}255 * @api private256 */257258exports.parseParams = function(str){259  return str260    .split(/ *, */)261    .map(acceptParams)262    .filter(function(obj){263      return obj.quality;264    })265    .sort(function(a, b){266      if (a.quality === b.quality) {267        return a.originalIndex - b.originalIndex;268      } else {269        return b.quality - a.quality;270      }271    });272};273274/**275 * Parse accept params `str` returning an276 * object with `.value`, `.quality` and `.params`.277 * also includes `.originalIndex` for stable sorting278 *279 * @param {String} str280 * @return {Object}281 * @api private282 */283284function acceptParams(str, index) {285  var parts = str.split(/ *; */);286  var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };287288  for (var i = 1; i < parts.length; ++i) {289    var pms = parts[i].split(/ *= */);290    if ('q' == pms[0]) {291      ret.quality = parseFloat(pms[1]);292    } else {293      ret.params[pms[0]] = pms[1];294    }295  }296297  return ret;298}299300/**301 * Normalize the given path string,302 * returning a regular expression.303 *304 * An empty array should be passed,305 * which will contain the placeholder306 * key names. For example "/user/:id" will307 * then contain ["id"].308 *309 * @param  {String|RegExp|Array} path310 * @param  {Array} keys311 * @param  {Boolean} sensitive312 * @param  {Boolean} strict313 * @return {RegExp}314 * @api private315 */316317exports.pathRegexp = function(path, keys, sensitive, strict) {318  if (toString.call(path) == '[object RegExp]') return path;319  if (Array.isArray(path)) path = '(' + path.join('|') + ')';320  path = path321    .concat(strict ? '' : '/?')322    .replace(/\/\(/g, '(?:/')323    .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){324      keys.push({ name: key, optional: !! optional });325      slash = slash || '';326      return ''327        + (optional ? '' : slash)328        + '(?:'329        + (optional ? slash : '')330        + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'331        + (optional || '')332        + (star ? '(/*)?' : '');333    })334    .replace(/([\/.])/g, '\\$1')335    .replace(/\*/g, '(.*)');336  return new RegExp('^' + path + '$', sensitive ? '' : 'i');337}338339/**340 * Compile "etag" value to function.341 *342 * @param  {Boolean|String|Function} val343 * @return {Function}344 * @api private345 */346347exports.compileETag = function(val) {348  var fn;349350  if (typeof val === 'function') {351    return val;352  }353354  switch (val) {355    case true:356      fn = exports.wetag;357      break;358    case false:359      break;360    case 'strong':361      fn = exports.etag;362      break;363    case 'weak':364      fn = exports.wetag;365      break;366    default:367      throw new TypeError('unknown value for etag function: ' + val);368  }369370  return fn;371}372373/**374 * Compile "proxy trust" value to function.375 *376 * @param  {Boolean|String|Number|Array|Function} val377 * @return {Function}378 * @api private379 */380381exports.compileTrust = function(val) {382  if (typeof val === 'function') return val;383384  if (val === true) {385    // Support plain true/false386    return function(){ return true };387  }388389  if (typeof val === 'number') {390    // Support trusting hop count391    return function(a, i){ return i < val };392  }393394  if (typeof val === 'string') {395    // Support comma-separated values396    val = val.split(/ *, */);397  }398399  return proxyaddr.compile(val || []);400}401402/**403 * Set the charset in a given Content-Type string.404 *405 * @param {String} type406 * @param {String} charset407 * @return {String}408 * @api private409 */410411exports.setCharset = function(type, charset){412  if (!type || !charset) return type;413414  var exists = charsetRegExp.test(type);415416  // removing existing charset417  if (exists) {418    var parts = type.split(';');419420    for (var i = 1; i < parts.length; i++) {421      if (charsetRegExp.test(';' + parts[i])) {422        parts.splice(i, 1);423        break;424      }425    }426427    type = parts.join(';');428  }429430  return type + '; charset=' + charset;431};