Skip to content
Myr

utils.js

This file

Path

lib/utils.js

416 lines · 8.3 KiB · JavaScript

Last changed by

Use content-type to parse Content-Type headersDouglas Christopher Wilsonbefore adoptionf22937f

History of this file

Take it

1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2014-2015 Douglas Christopher Wilson5 * MIT Licensed6 */78/**9 * Module dependencies.10 * @api private11 */1213var contentType = require('content-type');14var etag = require('etag');15var mime = require('connect').mime;16var proxyaddr = require('proxy-addr');1718/**19 * toString ref.20 */2122var toString = {}.toString;2324/**25 * Return strong ETag for `body`.26 *27 * @param {String|Buffer} body28 * @param {String} [encoding]29 * @return {String}30 * @api private31 */3233exports.etag = function (body, encoding) {34  var buf = !Buffer.isBuffer(body)35    ? new Buffer(body, encoding)36    : body;3738  return etag(buf, {weak: false});39};4041/**42 * Return weak ETag for `body`.43 *44 * @param {String|Buffer} body45 * @param {String} [encoding]46 * @return {String}47 * @api private48 */4950exports.wetag = function wetag(body, encoding){51  var buf = !Buffer.isBuffer(body)52    ? new Buffer(body, encoding)53    : body;5455  return etag(buf, {weak: true});56};5758/**59 * Make `locals()` bound to the given `obj`.60 *61 * This is used for `app.locals` and `res.locals`.62 *63 * @param {Object} obj64 * @return {Function}65 * @api private66 */6768exports.locals = function(){69  function locals(obj){70    for (var key in obj) locals[key] = obj[key];71    return obj;72  };7374  return locals;75};7677/**78 * Check if `path` looks absolute.79 *80 * @param {String} path81 * @return {Boolean}82 * @api private83 */8485exports.isAbsolute = function(path){86  if ('/' == path[0]) return true;87  if (':' == path[1] && '\\' == path[2]) return true;88  if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path89};9091/**92 * Flatten the given `arr`.93 *94 * @param {Array} arr95 * @return {Array}96 * @api private97 */9899exports.flatten = function(arr, ret){100  var ret = ret || []101    , len = arr.length;102  for (var i = 0; i < len; ++i) {103    if (Array.isArray(arr[i])) {104      exports.flatten(arr[i], ret);105    } else {106      ret.push(arr[i]);107    }108  }109  return ret;110};111112/**113 * Normalize the given `type`, for example "html" becomes "text/html".114 *115 * @param {String} type116 * @return {Object}117 * @api private118 */119120exports.normalizeType = function(type){121  return ~type.indexOf('/')122    ? acceptParams(type)123    : { value: mime.lookup(type), params: {} };124};125126/**127 * Normalize `types`, for example "html" becomes "text/html".128 *129 * @param {Array} types130 * @return {Array}131 * @api private132 */133134exports.normalizeTypes = function(types){135  var ret = [];136137  for (var i = 0; i < types.length; ++i) {138    ret.push(exports.normalizeType(types[i]));139  }140141  return ret;142};143144/**145 * Return the acceptable type in `types`, if any.146 *147 * @param {Array} types148 * @param {String} str149 * @return {String}150 * @api private151 */152153exports.acceptsArray = function(types, str){154  // accept anything when Accept is not present155  if (!str) return types[0];156157  // parse158  var accepted = exports.parseAccept(str)159    , normalized = exports.normalizeTypes(types)160    , len = accepted.length;161162  for (var i = 0; i < len; ++i) {163    for (var j = 0, jlen = types.length; j < jlen; ++j) {164      if (exports.accept(normalized[j], accepted[i])) {165        return types[j];166      }167    }168  }169};170171/**172 * Check if `type(s)` are acceptable based on173 * the given `str`.174 *175 * @param {String|Array} type(s)176 * @param {String} str177 * @return {Boolean|String}178 * @api private179 */180181exports.accepts = function(type, str){182  if ('string' == typeof type) type = type.split(/ *, */);183  return exports.acceptsArray(type, str);184};185186/**187 * Check if `type` array is acceptable for `other`.188 *189 * @param {Object} type190 * @param {Object} other191 * @return {Boolean}192 * @api private193 */194195exports.accept = function(type, other){196  var t = type.value.split('/');197  return (t[0] == other.type || '*' == other.type)198    && (t[1] == other.subtype || '*' == other.subtype)199    && paramsEqual(type.params, other.params);200};201202/**203 * Check if accept params are equal.204 *205 * @param {Object} a206 * @param {Object} b207 * @return {Boolean}208 * @api private209 */210211function paramsEqual(a, b){212  return !Object.keys(a).some(function(k) {213    return a[k] != b[k];214  });215}216217/**218 * Parse accept `str`, returning219 * an array objects containing220 * `.type` and `.subtype` along221 * with the values provided by222 * `parseQuality()`.223 *224 * @param {Type} name225 * @return {Type}226 * @api private227 */228229exports.parseAccept = function(str){230  return exports231    .parseParams(str)232    .map(function(obj){233      var parts = obj.value.split('/');234      obj.type = parts[0];235      obj.subtype = parts[1];236      return obj;237    });238};239240/**241 * Parse quality `str`, returning an242 * array of objects with `.value`,243 * `.quality` and optional `.params`244 *245 * @param {String} str246 * @return {Array}247 * @api private248 */249250exports.parseParams = function(str){251  return str252    .split(/ *, */)253    .map(acceptParams)254    .filter(function(obj){255      return obj.quality;256    })257    .sort(function(a, b){258      if (a.quality === b.quality) {259        return a.originalIndex - b.originalIndex;260      } else {261        return b.quality - a.quality;262      }263    });264};265266/**267 * Parse accept params `str` returning an268 * object with `.value`, `.quality` and `.params`.269 * also includes `.originalIndex` for stable sorting270 *271 * @param {String} str272 * @return {Object}273 * @api private274 */275276function acceptParams(str, index) {277  var parts = str.split(/ *; */);278  var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };279280  for (var i = 1; i < parts.length; ++i) {281    var pms = parts[i].split(/ *= */);282    if ('q' == pms[0]) {283      ret.quality = parseFloat(pms[1]);284    } else {285      ret.params[pms[0]] = pms[1];286    }287  }288289  return ret;290}291292/**293 * Normalize the given path string,294 * returning a regular expression.295 *296 * An empty array should be passed,297 * which will contain the placeholder298 * key names. For example "/user/:id" will299 * then contain ["id"].300 *301 * @param  {String|RegExp|Array} path302 * @param  {Array} keys303 * @param  {Boolean} sensitive304 * @param  {Boolean} strict305 * @return {RegExp}306 * @api private307 */308309exports.pathRegexp = function(path, keys, sensitive, strict) {310  if (toString.call(path) == '[object RegExp]') return path;311  if (Array.isArray(path)) path = '(' + path.join('|') + ')';312  path = path313    .concat(strict ? '' : '/?')314    .replace(/\/\(/g, '(?:/')315    .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){316      keys.push({ name: key, optional: !! optional });317      slash = slash || '';318      return ''319        + (optional ? '' : slash)320        + '(?:'321        + (optional ? slash : '')322        + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'323        + (optional || '')324        + (star ? '(/*)?' : '');325    })326    .replace(/([\/.])/g, '\\$1')327    .replace(/\*/g, '(.*)');328  return new RegExp('^' + path + '$', sensitive ? '' : 'i');329}330331/**332 * Compile "etag" value to function.333 *334 * @param  {Boolean|String|Function} val335 * @return {Function}336 * @api private337 */338339exports.compileETag = function(val) {340  var fn;341342  if (typeof val === 'function') {343    return val;344  }345346  switch (val) {347    case true:348      fn = exports.wetag;349      break;350    case false:351      break;352    case 'strong':353      fn = exports.etag;354      break;355    case 'weak':356      fn = exports.wetag;357      break;358    default:359      throw new TypeError('unknown value for etag function: ' + val);360  }361362  return fn;363}364365/**366 * Compile "proxy trust" value to function.367 *368 * @param  {Boolean|String|Number|Array|Function} val369 * @return {Function}370 * @api private371 */372373exports.compileTrust = function(val) {374  if (typeof val === 'function') return val;375376  if (val === true) {377    // Support plain true/false378    return function(){ return true };379  }380381  if (typeof val === 'number') {382    // Support trusting hop count383    return function(a, i){ return i < val };384  }385386  if (typeof val === 'string') {387    // Support comma-separated values388    val = val.split(/ *, */);389  }390391  return proxyaddr.compile(val || []);392}393394/**395 * Set the charset in a given Content-Type string.396 *397 * @param {String} type398 * @param {String} charset399 * @return {String}400 * @api private401 */402403exports.setCharset = function setCharset(type, charset) {404  if (!type || !charset) {405    return type;406  }407408  // parse type409  var parsed = contentType.parse(type);410411  // set charset412  parsed.parameters.charset = charset;413414  // format type415  return contentType.format(parsed);416};