utils.js
This file
Path
lib/utils.js
280 lines · 5.6 KiB · JavaScript
Last changed by
Merge pull request #1533 from shesek/old-viewcallbacksTJ Holowaychukbefore adoption9df93d6
History of this fileTake it
The walk stopped after 200 commits: lines older than 2b90cd7 point at it.
Added `req.host`TJ Holowaychukbefore adoption2b90cd7
lines 1–5why, one step back12/**3 * Module dependencies.4 */5add etag utilTJ Holowaychukbefore adoptionf2f0976
line 6why, one step back6var mime = require('connect').mimemergeTJ Holowaychukbefore adoptione2ad0d3
line 7why, one step back7 , crc32 = require('buffer-crc32');add etag utilTJ Holowaychukbefore adoptionf2f0976
lines 8–17why, one step back89/**10 * Return ETag for `body`.11 *12 * @param {String|Buffer} body13 * @return {String}14 * @api private15 */1617exports.etag = function(body){mergeTJ Holowaychukbefore adoptione2ad0d3
line 18why, one step back18 return '"' + crc32.signed(body) + '"';add etag utilTJ Holowaychukbefore adoptionf2f0976
line 19why, one step back19};Added `req.host`TJ Holowaychukbefore adoption2b90cd7
lines 20–265why, one step back2021/**22 * Make `locals()` bound to the given `obj`.23 * 24 * This is used for `app.locals` and `res.locals`. 25 *26 * @param {Object} obj27 * @return {Function}28 * @api private29 */3031exports.locals = function(obj){32 function locals(obj){33 for (var key in obj) locals[key] = obj[key];34 return obj;35 };3637 return locals;38};3940/**41 * Check if `path` looks absolute.42 *43 * @param {String} path44 * @return {Boolean}45 * @api private46 */4748exports.isAbsolute = function(path){49 if ('/' == path[0]) return true;50 if (':' == path[1] && '\\' == path[2]) return true;51};5253/**54 * Flatten the given `arr`.55 *56 * @param {Array} arr57 * @return {Array}58 * @api private59 */6061exports.flatten = function(arr, ret){62 var ret = ret || []63 , len = arr.length;64 for (var i = 0; i < len; ++i) {65 if (Array.isArray(arr[i])) {66 exports.flatten(arr[i], ret);67 } else {68 ret.push(arr[i]);69 }70 }71 return ret;72};7374/**75 * Normalize the given `type`, for example "html" becomes "text/html".76 *77 * @param {String} type78 * @return {String}79 * @api private80 */8182exports.normalizeType = function(type){83 return ~type.indexOf('/') ? type : mime.lookup(type);84};8586/**87 * Normalize `types`, for example "html" becomes "text/html".88 *89 * @param {Array} types90 * @return {Array}91 * @api private92 */9394exports.normalizeTypes = function(types){95 var ret = [];9697 for (var i = 0; i < types.length; ++i) {98 ret.push(~types[i].indexOf('/')99 ? types[i]100 : mime.lookup(types[i]));101 }102103 return ret;104};105106/**107 * Return the acceptable type in `types`, if any.108 *109 * @param {Array} types110 * @param {String} str111 * @return {String}112 * @api private113 */114115exports.acceptsArray = function(types, str){116 // accept anything when Accept is not present117 if (!str) return types[0];118119 // parse120 var accepted = exports.parseAccept(str)121 , normalized = exports.normalizeTypes(types)122 , len = accepted.length;123124 for (var i = 0; i < len; ++i) {125 for (var j = 0, jlen = types.length; j < jlen; ++j) {126 if (exports.accept(normalized[j].split('/'), accepted[i])) {127 return types[j];128 }129 }130 }131};132133/**134 * Check if `type(s)` are acceptable based on135 * the given `str`.136 *137 * @param {String|Array} type(s)138 * @param {String} str139 * @return {Boolean|String}140 * @api private141 */142143exports.accepts = function(type, str){144 if ('string' == typeof type) type = type.split(/ *, */);145 return exports.acceptsArray(type, str);146};147148/**149 * Check if `type` array is acceptable for `other`.150 *151 * @param {Array} type152 * @param {Object} other153 * @return {Boolean}154 * @api private155 */156157exports.accept = function(type, other){158 return (type[0] == other.type || '*' == other.type)159 && (type[1] == other.subtype || '*' == other.subtype);160};161162/**163 * Parse accept `str`, returning164 * an array objects containing165 * `.type` and `.subtype` along166 * with the values provided by167 * `parseQuality()`.168 *169 * @param {Type} name170 * @return {Type}171 * @api private172 */173174exports.parseAccept = function(str){175 return exports176 .parseQuality(str)177 .map(function(obj){178 var parts = obj.value.split('/');179 obj.type = parts[0];180 obj.subtype = parts[1];181 return obj;182 });183};184185/**186 * Parse quality `str`, returning an187 * array of objects with `.value` and188 * `.quality`.189 *190 * @param {Type} name191 * @return {Type}192 * @api private193 */194195exports.parseQuality = function(str){196 return str197 .split(/ *, */)198 .map(quality)199 .filter(function(obj){200 return obj.quality;201 })202 .sort(function(a, b){203 return b.quality - a.quality;204 });205};206207/**208 * Parse quality `str` returning an209 * object with `.value` and `.quality`.210 *211 * @param {String} str212 * @return {Object}213 * @api private214 */215216function quality(str) {217 var parts = str.split(/ *; */)218 , val = parts[0];219220 var q = parts[1]221 ? parseFloat(parts[1].split(/ *= */)[1])222 : 1;223224 return { value: val, quality: q };225}226227/**228 * Escape special characters in the given string of html.229 *230 * @param {String} html231 * @return {String}232 * @api private233 */234235exports.escape = function(html) {236 return String(html)237 .replace(/&/g, '&')238 .replace(/"/g, '"')239 .replace(/</g, '<')240 .replace(/>/g, '>');241};242243/**244 * Normalize the given path string,245 * returning a regular expression.246 *247 * An empty array should be passed,248 * which will contain the placeholder249 * key names. For example "/user/:id" will250 * then contain ["id"].251 *252 * @param {String|RegExp|Array} path253 * @param {Array} keys254 * @param {Boolean} sensitive255 * @param {Boolean} strict256 * @return {RegExp}257 * @api private258 */259260exports.pathRegexp = function(path, keys, sensitive, strict) {261 if (path instanceof RegExp) return path;262 if (Array.isArray(path)) path = '(' + path.join('|') + ')';263 path = path264 .concat(strict ? '' : '/?')265 .replace(/\/\(/g, '(?:/')* immediately after :param would become not greedyriadhbefore adoption73bed61
line 266why, one step back266 .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){Added `req.host`TJ Holowaychukbefore adoption2b90cd7
lines 267–273why, one step back267 keys.push({ name: key, optional: !! optional });268 slash = slash || '';269 return ''270 + (optional ? '' : slash)271 + '(?:'272 + (optional ? slash : '')273 + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'* immediately after :param would become not greedyriadhbefore adoption73bed61
line 274why, one step back274 + (optional || '')tests for issues 1115 fix for utilsriadhbefore adoption3827f5e
line 275why, one step back275 + (star ? '(/*)?' : '');Added `req.host`TJ Holowaychukbefore adoption2b90cd7
lines 276–280why, one step back276 })277 .replace(/([\/.])/g, '\\$1')278 .replace(/\*/g, '(.*)');279 return new RegExp('^' + path + '$', sensitive ? '' : 'i');280}