utils.js
This file
Path
lib/utils.js
410 lines · 8.3 KiB · JavaScript
Last changed by
mark res.send ETag as weak and reduce collisionsDouglas Christopher Wilsonbefore adoption8ab96ab
History of this fileTake it
The walk stopped after 200 commits: lines older than d876778 point at it.
Merge pull request #1597 from Cauldrath/cookie_versionTJ Holowaychukbefore adoptiond876778
lines 1–6why, one step back12/**3 * Module dependencies.4 */56var mime = require('connect').mimeAdd standard deprecation utilityDouglas Christopher Wilsonbefore adoption8dc4ff2
line 7why, one step back7 , deprecate = require('util').deprecateimprove proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
line 8why, one step back8 , proxyaddr = require('proxy-addr')Merge pull request #1597 from Cauldrath/cookie_versionTJ Holowaychukbefore adoptiond876778
lines 9–15why, one step back9 , crc32 = require('buffer-crc32');1011/**12 * toString ref.13 */1415var toString = {}.toString;Add standard deprecation utilityDouglas Christopher Wilsonbefore adoption8dc4ff2
lines 16–17why, one step back1617/**set proper charset in content-type for res.sendDouglas Christopher Wilsonbefore adoptionf14e39d
lines 18–22why, one step back18 * Simple detection of charset parameter in content-type19 */20var charsetRegExp = /;\s*charset\s*=/;2122/**deprecation messages are bright red on TTYsDouglas Christopher Wilsonbefore adoptiond98e2e7
lines 23–24why, one step back23 * Deprecate function, like core `util.deprecate`,24 * but with NODE_ENV and color support.Add standard deprecation utilityDouglas Christopher Wilsonbefore adoption8dc4ff2
lines 25–32why, one step back25 *26 * @param {Function} fn27 * @param {String} msg28 * @return {Function}29 * @api private30 */3132exports.deprecate = function(fn, msg){deprecation messages are bright red on TTYsDouglas Christopher Wilsonbefore adoptiond98e2e7
lines 33–43why, one step back33 if (process.env.NODE_ENV === 'test') return fn;3435 // prepend module name36 msg = 'express: ' + msg;3738 if (process.stderr.isTTY) {39 // colorize40 msg = '\x1b[31;1m' + msg + '\x1b[0m';41 }4243 return deprecate(fn, msg);Add standard deprecation utilityDouglas Christopher Wilsonbefore adoption8dc4ff2
line 44why, one step back44};Merge pull request #1597 from Cauldrath/cookie_versionTJ Holowaychukbefore adoptiond876778
lines 45–49why, one step back4546/**47 * Return ETag for `body`.48 *49 * @param {String|Buffer} bodymark res.send ETag as weak and reduce collisionsDouglas Christopher Wilsonbefore adoption8ab96ab
line 50why, one step back50 * @param {String} [encoding]Merge pull request #1597 from Cauldrath/cookie_versionTJ Holowaychukbefore adoptiond876778
lines 51–54why, one step back51 * @return {String}52 * @api private53 */54mark res.send ETag as weak and reduce collisionsDouglas Christopher Wilsonbefore adoption8ab96ab
lines 55–60why, one step back55exports.etag = function(body, encoding){56 var buf = Buffer.isBuffer(body)57 ? body58 : new Buffer(body, encoding)59 var len = buf.length60 return 'W/"' + len.toString(16) + '-' + crc32.unsigned(buf) + '"'Merge pull request #1597 from Cauldrath/cookie_versionTJ Holowaychukbefore adoptiond876778
lines 61–72why, one step back61};6263/**64 * Make `locals()` bound to the given `obj`.65 *66 * This is used for `app.locals` and `res.locals`.67 *68 * @param {Object} obj69 * @return {Function}70 * @api private71 */72lint: remove unused stuffJonathan Ongbefore adoption9bed2b8
line 73why, one step back73exports.locals = function(){Merge pull request #1597 from Cauldrath/cookie_versionTJ Holowaychukbefore adoptiond876778
lines 74–92why, one step back74 function locals(obj){75 for (var key in obj) locals[key] = obj[key];76 return obj;77 };7879 return locals;80};8182/**83 * Check if `path` looks absolute.84 *85 * @param {String} path86 * @return {Boolean}87 * @api private88 */8990exports.isAbsolute = function(path){91 if ('/' == path[0]) return true;92 if (':' == path[1] && '\\' == path[2]) return true;Merge pull request #1740 from superic/masterTJ Holowaychukbefore adoptione43ff07
line 93why, one step back93 if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute pathMerge pull request #1597 from Cauldrath/cookie_versionTJ Holowaychukbefore adoptiond876778
lines 94–349why, one step back94};9596/**97 * Flatten the given `arr`.98 *99 * @param {Array} arr100 * @return {Array}101 * @api private102 */103104exports.flatten = function(arr, ret){105 var ret = ret || []106 , len = arr.length;107 for (var i = 0; i < len; ++i) {108 if (Array.isArray(arr[i])) {109 exports.flatten(arr[i], ret);110 } else {111 ret.push(arr[i]);112 }113 }114 return ret;115};116117/**118 * Normalize the given `type`, for example "html" becomes "text/html".119 *120 * @param {String} type121 * @return {Object}122 * @api private123 */124125exports.normalizeType = function(type){126 return ~type.indexOf('/')127 ? acceptParams(type)128 : { value: mime.lookup(type), params: {} };129};130131/**132 * Normalize `types`, for example "html" becomes "text/html".133 *134 * @param {Array} types135 * @return {Array}136 * @api private137 */138139exports.normalizeTypes = function(types){140 var ret = [];141142 for (var i = 0; i < types.length; ++i) {143 ret.push(exports.normalizeType(types[i]));144 }145146 return ret;147};148149/**150 * Return the acceptable type in `types`, if any.151 *152 * @param {Array} types153 * @param {String} str154 * @return {String}155 * @api private156 */157158exports.acceptsArray = function(types, str){159 // accept anything when Accept is not present160 if (!str) return types[0];161162 // parse163 var accepted = exports.parseAccept(str)164 , normalized = exports.normalizeTypes(types)165 , len = accepted.length;166167 for (var i = 0; i < len; ++i) {168 for (var j = 0, jlen = types.length; j < jlen; ++j) {169 if (exports.accept(normalized[j], accepted[i])) {170 return types[j];171 }172 }173 }174};175176/**177 * Check if `type(s)` are acceptable based on178 * the given `str`.179 *180 * @param {String|Array} type(s)181 * @param {String} str182 * @return {Boolean|String}183 * @api private184 */185186exports.accepts = function(type, str){187 if ('string' == typeof type) type = type.split(/ *, */);188 return exports.acceptsArray(type, str);189};190191/**192 * Check if `type` array is acceptable for `other`.193 *194 * @param {Object} type195 * @param {Object} other196 * @return {Boolean}197 * @api private198 */199200exports.accept = function(type, other){201 var t = type.value.split('/');202 return (t[0] == other.type || '*' == other.type)203 && (t[1] == other.subtype || '*' == other.subtype)204 && paramsEqual(type.params, other.params);205};206207/**208 * Check if accept params are equal.209 *210 * @param {Object} a211 * @param {Object} b212 * @return {Boolean}213 * @api private214 */215216function paramsEqual(a, b){217 return !Object.keys(a).some(function(k) {218 return a[k] != b[k];219 });220}221222/**223 * Parse accept `str`, returning224 * an array objects containing225 * `.type` and `.subtype` along226 * with the values provided by227 * `parseQuality()`.228 *229 * @param {Type} name230 * @return {Type}231 * @api private232 */233234exports.parseAccept = function(str){235 return exports236 .parseParams(str)237 .map(function(obj){238 var parts = obj.value.split('/');239 obj.type = parts[0];240 obj.subtype = parts[1];241 return obj;242 });243};244245/**246 * Parse quality `str`, returning an247 * array of objects with `.value`,248 * `.quality` and optional `.params`249 *250 * @param {String} str251 * @return {Array}252 * @api private253 */254255exports.parseParams = function(str){256 return str257 .split(/ *, */)258 .map(acceptParams)259 .filter(function(obj){260 return obj.quality;261 })262 .sort(function(a, b){263 if (a.quality === b.quality) {264 return a.originalIndex - b.originalIndex;265 } else {266 return b.quality - a.quality;267 }268 });269};270271/**272 * Parse accept params `str` returning an273 * object with `.value`, `.quality` and `.params`.274 * also includes `.originalIndex` for stable sorting275 *276 * @param {String} str277 * @return {Object}278 * @api private279 */280281function acceptParams(str, index) {282 var parts = str.split(/ *; */);283 var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };284285 for (var i = 1; i < parts.length; ++i) {286 var pms = parts[i].split(/ *= */);287 if ('q' == pms[0]) {288 ret.quality = parseFloat(pms[1]);289 } else {290 ret.params[pms[0]] = pms[1];291 }292 }293294 return ret;295}296297/**298 * Escape special characters in the given string of html.299 *300 * @param {String} html301 * @return {String}302 * @api private303 */304305exports.escape = function(html) {306 return String(html)307 .replace(/&/g, '&')308 .replace(/"/g, '"')309 .replace(/</g, '<')310 .replace(/>/g, '>');311};312313/**314 * Normalize the given path string,315 * returning a regular expression.316 *317 * An empty array should be passed,318 * which will contain the placeholder319 * key names. For example "/user/:id" will320 * then contain ["id"].321 *322 * @param {String|RegExp|Array} path323 * @param {Array} keys324 * @param {Boolean} sensitive325 * @param {Boolean} strict326 * @return {RegExp}327 * @api private328 */329330exports.pathRegexp = function(path, keys, sensitive, strict) {331 if (toString.call(path) == '[object RegExp]') return path;332 if (Array.isArray(path)) path = '(' + path.join('|') + ')';333 path = path334 .concat(strict ? '' : '/?')335 .replace(/\/\(/g, '(?:/')336 .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){337 keys.push({ name: key, optional: !! optional });338 slash = slash || '';339 return ''340 + (optional ? '' : slash)341 + '(?:'342 + (optional ? slash : '')343 + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'344 + (optional || '')345 + (star ? '(/*)?' : '');346 })347 .replace(/([\/.])/g, '\\$1')348 .replace(/\*/g, '(.*)');349 return new RegExp('^' + path + '$', sensitive ? '' : 'i');improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 350–378why, one step back350}351352/**353 * Compile "proxy trust" value to function.354 *355 * @param {Boolean|String|Number|Array|Function} val356 * @return {Function}357 * @api private358 */359360exports.compileTrust = function(val) {361 if (typeof val === 'function') return val;362363 if (val === true) {364 // Support plain true/false365 return function(){ return true };366 }367368 if (typeof val === 'number') {369 // Support trusting hop count370 return function(a, i){ return i < val };371 }372373 if (typeof val === 'string') {374 // Support comma-separated values375 val = val.split(/ *, */);376 }377378 return proxyaddr.compile(val || []);Merge pull request #1597 from Cauldrath/cookie_versionTJ Holowaychukbefore adoptiond876778
line 379why, one step back379}set proper charset in content-type for res.sendDouglas Christopher Wilsonbefore adoptionf14e39d
lines 380–410why, one step back380381/**382 * Set the charset in a given Content-Type string.383 *384 * @param {String} type385 * @param {String} charset386 * @return {String}387 * @api private388 */389390exports.setCharset = function(type, charset){391 if (!type || !charset) return type;392393 var exists = charsetRegExp.test(type);394395 // removing existing charset396 if (exists) {397 var parts = type.split(';');398399 for (var i = 1; i < parts.length; i++) {400 if (charsetRegExp.test(';' + parts[i])) {401 parts.splice(i, 1);402 break;403 }404 }405406 type = parts.join(';');407 }408409 return type + '; charset=' + charset;410};