utils.js
This file
Path
lib/utils.js
369 lines · 7.5 KiB · JavaScript
Last changed by
improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
History of this fileTake it
The walk stopped after 200 commits: lines older than ed27344 point at it.
fix res.cookie() testsTJ Holowaychukbefore adoptioned27344
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')fix res.cookie() testsTJ Holowaychukbefore adoptioned27344
lines 9–11why, one step back9 , crc32 = require('buffer-crc32');1011/**refactorTJ Holowaychukbefore adoptionf8a33d1
lines 12–15why, one step back12 * toString ref.13 */1415var toString = {}.toString;Add standard deprecation utilityDouglas Christopher Wilsonbefore adoption8dc4ff2
lines 16–17why, one step back1617/**deprecation messages are bright red on TTYsDouglas Christopher Wilsonbefore adoptiond98e2e7
lines 18–19why, one step back18 * Deprecate function, like core `util.deprecate`,19 * but with NODE_ENV and color support.Add standard deprecation utilityDouglas Christopher Wilsonbefore adoption8dc4ff2
lines 20–27why, one step back20 *21 * @param {Function} fn22 * @param {String} msg23 * @return {Function}24 * @api private25 */2627exports.deprecate = function(fn, msg){deprecation messages are bright red on TTYsDouglas Christopher Wilsonbefore adoptiond98e2e7
lines 28–38why, one step back28 if (process.env.NODE_ENV === 'test') return fn;2930 // prepend module name31 msg = 'express: ' + msg;3233 if (process.stderr.isTTY) {34 // colorize35 msg = '\x1b[31;1m' + msg + '\x1b[0m';36 }3738 return deprecate(fn, msg);Add standard deprecation utilityDouglas Christopher Wilsonbefore adoption8dc4ff2
line 39why, one step back39};refactorTJ Holowaychukbefore adoptionf8a33d1
lines 40–41why, one step back4041/**fix res.cookie() testsTJ Holowaychukbefore adoptioned27344
lines 42–62why, one step back42 * Return ETag for `body`.43 *44 * @param {String|Buffer} body45 * @return {String}46 * @api private47 */4849exports.etag = function(body){50 return '"' + crc32.signed(body) + '"';51};5253/**54 * Make `locals()` bound to the given `obj`.55 *56 * This is used for `app.locals` and `res.locals`.57 *58 * @param {Object} obj59 * @return {Function}60 * @api private61 */62lint: remove unused stuffJonathan Ongbefore adoption9bed2b8
line 63why, one step back63exports.locals = function(){fix res.cookie() testsTJ Holowaychukbefore adoptioned27344
lines 64–82why, one step back64 function locals(obj){65 for (var key in obj) locals[key] = obj[key];66 return obj;67 };6869 return locals;70};7172/**73 * Check if `path` looks absolute.74 *75 * @param {String} path76 * @return {Boolean}77 * @api private78 */7980exports.isAbsolute = function(path){81 if ('/' == path[0]) return true;82 if (':' == path[1] && '\\' == path[2]) return true;Merge pull request #1740 from superic/masterTJ Holowaychukbefore adoptione43ff07
line 83why, one step back83 if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute pathfix res.cookie() testsTJ Holowaychukbefore adoptioned27344
lines 84–252why, one step back84};8586/**87 * Flatten the given `arr`.88 *89 * @param {Array} arr90 * @return {Array}91 * @api private92 */9394exports.flatten = function(arr, ret){95 var ret = ret || []96 , len = arr.length;97 for (var i = 0; i < len; ++i) {98 if (Array.isArray(arr[i])) {99 exports.flatten(arr[i], ret);100 } else {101 ret.push(arr[i]);102 }103 }104 return ret;105};106107/**108 * Normalize the given `type`, for example "html" becomes "text/html".109 *110 * @param {String} type111 * @return {Object}112 * @api private113 */114115exports.normalizeType = function(type){116 return ~type.indexOf('/')117 ? acceptParams(type)118 : { value: mime.lookup(type), params: {} };119};120121/**122 * Normalize `types`, for example "html" becomes "text/html".123 *124 * @param {Array} types125 * @return {Array}126 * @api private127 */128129exports.normalizeTypes = function(types){130 var ret = [];131132 for (var i = 0; i < types.length; ++i) {133 ret.push(exports.normalizeType(types[i]));134 }135136 return ret;137};138139/**140 * Return the acceptable type in `types`, if any.141 *142 * @param {Array} types143 * @param {String} str144 * @return {String}145 * @api private146 */147148exports.acceptsArray = function(types, str){149 // accept anything when Accept is not present150 if (!str) return types[0];151152 // parse153 var accepted = exports.parseAccept(str)154 , normalized = exports.normalizeTypes(types)155 , len = accepted.length;156157 for (var i = 0; i < len; ++i) {158 for (var j = 0, jlen = types.length; j < jlen; ++j) {159 if (exports.accept(normalized[j], accepted[i])) {160 return types[j];161 }162 }163 }164};165166/**167 * Check if `type(s)` are acceptable based on168 * the given `str`.169 *170 * @param {String|Array} type(s)171 * @param {String} str172 * @return {Boolean|String}173 * @api private174 */175176exports.accepts = function(type, str){177 if ('string' == typeof type) type = type.split(/ *, */);178 return exports.acceptsArray(type, str);179};180181/**182 * Check if `type` array is acceptable for `other`.183 *184 * @param {Object} type185 * @param {Object} other186 * @return {Boolean}187 * @api private188 */189190exports.accept = function(type, other){191 var t = type.value.split('/');192 return (t[0] == other.type || '*' == other.type)193 && (t[1] == other.subtype || '*' == other.subtype)194 && paramsEqual(type.params, other.params);195};196197/**198 * Check if accept params are equal.199 *200 * @param {Object} a201 * @param {Object} b202 * @return {Boolean}203 * @api private204 */205206function paramsEqual(a, b){207 return !Object.keys(a).some(function(k) {208 return a[k] != b[k];209 });210}211212/**213 * Parse accept `str`, returning214 * an array objects containing215 * `.type` and `.subtype` along216 * with the values provided by217 * `parseQuality()`.218 *219 * @param {Type} name220 * @return {Type}221 * @api private222 */223224exports.parseAccept = function(str){225 return exports226 .parseParams(str)227 .map(function(obj){228 var parts = obj.value.split('/');229 obj.type = parts[0];230 obj.subtype = parts[1];231 return obj;232 });233};234235/**236 * Parse quality `str`, returning an237 * array of objects with `.value`,238 * `.quality` and optional `.params`239 *240 * @param {String} str241 * @return {Array}242 * @api private243 */244245exports.parseParams = function(str){246 return str247 .split(/ *, */)248 .map(acceptParams)249 .filter(function(obj){250 return obj.quality;251 })252 .sort(function(a, b){Merge pull request #1578 from Notificare/masterTJ Holowaychukbefore adoption5ba6c30
lines 253–257why, one step back253 if (a.quality === b.quality) {254 return a.originalIndex - b.originalIndex;255 } else {256 return b.quality - a.quality;257 }fix res.cookie() testsTJ Holowaychukbefore adoptioned27344
lines 258–263why, one step back258 });259};260261/**262 * Parse accept params `str` returning an263 * object with `.value`, `.quality` and `.params`.Merge pull request #1578 from Notificare/masterTJ Holowaychukbefore adoption5ba6c30
line 264why, one step back264 * also includes `.originalIndex` for stable sortingfix res.cookie() testsTJ Holowaychukbefore adoptioned27344
lines 265–270why, one step back265 *266 * @param {String} str267 * @return {Object}268 * @api private269 */270Merge pull request #1578 from Notificare/masterTJ Holowaychukbefore adoption5ba6c30
line 271why, one step back271function acceptParams(str, index) {fix res.cookie() testsTJ Holowaychukbefore adoptioned27344
line 272why, one step back272 var parts = str.split(/ *; */);Merge pull request #1578 from Notificare/masterTJ Holowaychukbefore adoption5ba6c30
line 273why, one step back273 var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };fix res.cookie() testsTJ Holowaychukbefore adoptioned27344
lines 274–320why, one step back274275 for (var i = 1; i < parts.length; ++i) {276 var pms = parts[i].split(/ *= */);277 if ('q' == pms[0]) {278 ret.quality = parseFloat(pms[1]);279 } else {280 ret.params[pms[0]] = pms[1];281 }282 }283284 return ret;285}286287/**288 * Escape special characters in the given string of html.289 *290 * @param {String} html291 * @return {String}292 * @api private293 */294295exports.escape = function(html) {296 return String(html)297 .replace(/&/g, '&')298 .replace(/"/g, '"')299 .replace(/</g, '<')300 .replace(/>/g, '>');301};302303/**304 * Normalize the given path string,305 * returning a regular expression.306 *307 * An empty array should be passed,308 * which will contain the placeholder309 * key names. For example "/user/:id" will310 * then contain ["id"].311 *312 * @param {String|RegExp|Array} path313 * @param {Array} keys314 * @param {Boolean} sensitive315 * @param {Boolean} strict316 * @return {RegExp}317 * @api private318 */319320exports.pathRegexp = function(path, keys, sensitive, strict) {refactorTJ Holowaychukbefore adoptionf8a33d1
line 321why, one step back321 if (toString.call(path) == '[object RegExp]') return path;fix res.cookie() testsTJ Holowaychukbefore adoptioned27344
lines 322–339why, one step back322 if (Array.isArray(path)) path = '(' + path.join('|') + ')';323 path = path324 .concat(strict ? '' : '/?')325 .replace(/\/\(/g, '(?:/')326 .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){327 keys.push({ name: key, optional: !! optional });328 slash = slash || '';329 return ''330 + (optional ? '' : slash)331 + '(?:'332 + (optional ? slash : '')333 + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'334 + (optional || '')335 + (star ? '(/*)?' : '');336 })337 .replace(/([\/.])/g, '\\$1')338 .replace(/\*/g, '(.*)');339 return new RegExp('^' + path + '$', sensitive ? '' : 'i');improve proxy trust with ip address listDouglas Christopher Wilsonbefore adoption566720b
lines 340–368why, one step back340}341342/**343 * Compile "proxy trust" value to function.344 *345 * @param {Boolean|String|Number|Array|Function} val346 * @return {Function}347 * @api private348 */349350exports.compileTrust = function(val) {351 if (typeof val === 'function') return val;352353 if (val === true) {354 // Support plain true/false355 return function(){ return true };356 }357358 if (typeof val === 'number') {359 // Support trusting hop count360 return function(a, i){ return i < val };361 }362363 if (typeof val === 'string') {364 // Support comma-separated values365 val = val.split(/ *, */);366 }367368 return proxyaddr.compile(val || []);fix res.cookie() testsTJ Holowaychukbefore adoptioned27344
line 369why, one step back369}