AuditRules.js 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. /*
  2. * Copyright (C) 2010 Google Inc. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are
  6. * met:
  7. *
  8. * * Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * * Redistributions in binary form must reproduce the above
  11. * copyright notice, this list of conditions and the following disclaimer
  12. * in the documentation and/or other materials provided with the
  13. * distribution.
  14. * * Neither the name of Google Inc. nor the names of its
  15. * contributors may be used to endorse or promote products derived from
  16. * this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. WebInspector.AuditRules.IPAddressRegexp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
  31. WebInspector.AuditRules.CacheableResponseCodes =
  32. {
  33. 200: true,
  34. 203: true,
  35. 206: true,
  36. 300: true,
  37. 301: true,
  38. 410: true,
  39. 304: true // Underlying request is cacheable
  40. }
  41. /**
  42. * @param {!Array.<!WebInspector.NetworkRequest>} requests
  43. * @param {Array.<!WebInspector.resourceTypes>} types
  44. * @param {boolean} needFullResources
  45. * @return {(Object.<string, !Array.<!WebInspector.NetworkRequest>>|Object.<string, !Array.<string>>)}
  46. */
  47. WebInspector.AuditRules.getDomainToResourcesMap = function(requests, types, needFullResources)
  48. {
  49. var domainToResourcesMap = {};
  50. for (var i = 0, size = requests.length; i < size; ++i) {
  51. var request = requests[i];
  52. if (types && types.indexOf(request.type) === -1)
  53. continue;
  54. var parsedURL = request.url.asParsedURL();
  55. if (!parsedURL)
  56. continue;
  57. var domain = parsedURL.host;
  58. var domainResources = domainToResourcesMap[domain];
  59. if (domainResources === undefined) {
  60. domainResources = [];
  61. domainToResourcesMap[domain] = domainResources;
  62. }
  63. domainResources.push(needFullResources ? request : request.url);
  64. }
  65. return domainToResourcesMap;
  66. }
  67. /**
  68. * @constructor
  69. * @extends {WebInspector.AuditRule}
  70. */
  71. WebInspector.AuditRules.GzipRule = function()
  72. {
  73. WebInspector.AuditRule.call(this, "network-gzip", "Enable gzip compression");
  74. }
  75. WebInspector.AuditRules.GzipRule.prototype = {
  76. /**
  77. * @param {!Array.<!WebInspector.NetworkRequest>} requests
  78. * @param {!WebInspector.AuditRuleResult} result
  79. * @param {function(WebInspector.AuditRuleResult)} callback
  80. * @param {!WebInspector.Progress} progress
  81. */
  82. doRun: function(requests, result, callback, progress)
  83. {
  84. var totalSavings = 0;
  85. var compressedSize = 0;
  86. var candidateSize = 0;
  87. var summary = result.addChild("", true);
  88. for (var i = 0, length = requests.length; i < length; ++i) {
  89. var request = requests[i];
  90. if (request.statusCode === 304)
  91. continue; // Do not test 304 Not Modified requests as their contents are always empty.
  92. if (this._shouldCompress(request)) {
  93. var size = request.resourceSize;
  94. candidateSize += size;
  95. if (this._isCompressed(request)) {
  96. compressedSize += size;
  97. continue;
  98. }
  99. var savings = 2 * size / 3;
  100. totalSavings += savings;
  101. summary.addFormatted("%r could save ~%s", request.url, Number.bytesToString(savings));
  102. result.violationCount++;
  103. }
  104. }
  105. if (!totalSavings)
  106. return callback(null);
  107. summary.value = String.sprintf("Compressing the following resources with gzip could reduce their transfer size by about two thirds (~%s):", Number.bytesToString(totalSavings));
  108. callback(result);
  109. },
  110. _isCompressed: function(request)
  111. {
  112. var encodingHeader = request.responseHeaderValue("Content-Encoding");
  113. if (!encodingHeader)
  114. return false;
  115. return /\b(?:gzip|deflate)\b/.test(encodingHeader);
  116. },
  117. _shouldCompress: function(request)
  118. {
  119. return request.type.isTextType() && request.parsedURL.host && request.resourceSize !== undefined && request.resourceSize > 150;
  120. },
  121. __proto__: WebInspector.AuditRule.prototype
  122. }
  123. /**
  124. * @constructor
  125. * @extends {WebInspector.AuditRule}
  126. */
  127. WebInspector.AuditRules.CombineExternalResourcesRule = function(id, name, type, resourceTypeName, allowedPerDomain)
  128. {
  129. WebInspector.AuditRule.call(this, id, name);
  130. this._type = type;
  131. this._resourceTypeName = resourceTypeName;
  132. this._allowedPerDomain = allowedPerDomain;
  133. }
  134. WebInspector.AuditRules.CombineExternalResourcesRule.prototype = {
  135. /**
  136. * @param {!Array.<!WebInspector.NetworkRequest>} requests
  137. * @param {!WebInspector.AuditRuleResult} result
  138. * @param {function(WebInspector.AuditRuleResult)} callback
  139. * @param {!WebInspector.Progress} progress
  140. */
  141. doRun: function(requests, result, callback, progress)
  142. {
  143. var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests, [this._type], false);
  144. var penalizedResourceCount = 0;
  145. // TODO: refactor according to the chosen i18n approach
  146. var summary = result.addChild("", true);
  147. for (var domain in domainToResourcesMap) {
  148. var domainResources = domainToResourcesMap[domain];
  149. var extraResourceCount = domainResources.length - this._allowedPerDomain;
  150. if (extraResourceCount <= 0)
  151. continue;
  152. penalizedResourceCount += extraResourceCount - 1;
  153. summary.addChild(String.sprintf("%d %s resources served from %s.", domainResources.length, this._resourceTypeName, WebInspector.AuditRuleResult.resourceDomain(domain)));
  154. result.violationCount += domainResources.length;
  155. }
  156. if (!penalizedResourceCount)
  157. return callback(null);
  158. summary.value = "There are multiple resources served from same domain. Consider combining them into as few files as possible.";
  159. callback(result);
  160. },
  161. __proto__: WebInspector.AuditRule.prototype
  162. }
  163. /**
  164. * @constructor
  165. * @extends {WebInspector.AuditRules.CombineExternalResourcesRule}
  166. */
  167. WebInspector.AuditRules.CombineJsResourcesRule = function(allowedPerDomain) {
  168. WebInspector.AuditRules.CombineExternalResourcesRule.call(this, "page-externaljs", "Combine external JavaScript", WebInspector.resourceTypes.Script, "JavaScript", allowedPerDomain);
  169. }
  170. WebInspector.AuditRules.CombineJsResourcesRule.prototype = {
  171. __proto__: WebInspector.AuditRules.CombineExternalResourcesRule.prototype
  172. }
  173. /**
  174. * @constructor
  175. * @extends {WebInspector.AuditRules.CombineExternalResourcesRule}
  176. */
  177. WebInspector.AuditRules.CombineCssResourcesRule = function(allowedPerDomain) {
  178. WebInspector.AuditRules.CombineExternalResourcesRule.call(this, "page-externalcss", "Combine external CSS", WebInspector.resourceTypes.Stylesheet, "CSS", allowedPerDomain);
  179. }
  180. WebInspector.AuditRules.CombineCssResourcesRule.prototype = {
  181. __proto__: WebInspector.AuditRules.CombineExternalResourcesRule.prototype
  182. }
  183. /**
  184. * @constructor
  185. * @extends {WebInspector.AuditRule}
  186. */
  187. WebInspector.AuditRules.MinimizeDnsLookupsRule = function(hostCountThreshold) {
  188. WebInspector.AuditRule.call(this, "network-minimizelookups", "Minimize DNS lookups");
  189. this._hostCountThreshold = hostCountThreshold;
  190. }
  191. WebInspector.AuditRules.MinimizeDnsLookupsRule.prototype = {
  192. /**
  193. * @param {!Array.<!WebInspector.NetworkRequest>} requests
  194. * @param {!WebInspector.AuditRuleResult} result
  195. * @param {function(WebInspector.AuditRuleResult)} callback
  196. * @param {!WebInspector.Progress} progress
  197. */
  198. doRun: function(requests, result, callback, progress)
  199. {
  200. var summary = result.addChild("");
  201. var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests, null, false);
  202. for (var domain in domainToResourcesMap) {
  203. if (domainToResourcesMap[domain].length > 1)
  204. continue;
  205. var parsedURL = domain.asParsedURL();
  206. if (!parsedURL)
  207. continue;
  208. if (!parsedURL.host.search(WebInspector.AuditRules.IPAddressRegexp))
  209. continue; // an IP address
  210. summary.addSnippet(domain);
  211. result.violationCount++;
  212. }
  213. if (!summary.children || summary.children.length <= this._hostCountThreshold)
  214. return callback(null);
  215. summary.value = "The following domains only serve one resource each. If possible, avoid the extra DNS lookups by serving these resources from existing domains.";
  216. callback(result);
  217. },
  218. __proto__: WebInspector.AuditRule.prototype
  219. }
  220. /**
  221. * @constructor
  222. * @extends {WebInspector.AuditRule}
  223. */
  224. WebInspector.AuditRules.ParallelizeDownloadRule = function(optimalHostnameCount, minRequestThreshold, minBalanceThreshold)
  225. {
  226. WebInspector.AuditRule.call(this, "network-parallelizehosts", "Parallelize downloads across hostnames");
  227. this._optimalHostnameCount = optimalHostnameCount;
  228. this._minRequestThreshold = minRequestThreshold;
  229. this._minBalanceThreshold = minBalanceThreshold;
  230. }
  231. WebInspector.AuditRules.ParallelizeDownloadRule.prototype = {
  232. /**
  233. * @param {!Array.<!WebInspector.NetworkRequest>} requests
  234. * @param {!WebInspector.AuditRuleResult} result
  235. * @param {function(WebInspector.AuditRuleResult)} callback
  236. * @param {!WebInspector.Progress} progress
  237. */
  238. doRun: function(requests, result, callback, progress)
  239. {
  240. function hostSorter(a, b)
  241. {
  242. var aCount = domainToResourcesMap[a].length;
  243. var bCount = domainToResourcesMap[b].length;
  244. return (aCount < bCount) ? 1 : (aCount == bCount) ? 0 : -1;
  245. }
  246. var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(
  247. requests,
  248. [WebInspector.resourceTypes.Stylesheet, WebInspector.resourceTypes.Image],
  249. true);
  250. var hosts = [];
  251. for (var url in domainToResourcesMap)
  252. hosts.push(url);
  253. if (!hosts.length)
  254. return callback(null); // no hosts (local file or something)
  255. hosts.sort(hostSorter);
  256. var optimalHostnameCount = this._optimalHostnameCount;
  257. if (hosts.length > optimalHostnameCount)
  258. hosts.splice(optimalHostnameCount);
  259. var busiestHostResourceCount = domainToResourcesMap[hosts[0]].length;
  260. var requestCountAboveThreshold = busiestHostResourceCount - this._minRequestThreshold;
  261. if (requestCountAboveThreshold <= 0)
  262. return callback(null);
  263. var avgResourcesPerHost = 0;
  264. for (var i = 0, size = hosts.length; i < size; ++i)
  265. avgResourcesPerHost += domainToResourcesMap[hosts[i]].length;
  266. // Assume optimal parallelization.
  267. avgResourcesPerHost /= optimalHostnameCount;
  268. avgResourcesPerHost = Math.max(avgResourcesPerHost, 1);
  269. var pctAboveAvg = (requestCountAboveThreshold / avgResourcesPerHost) - 1.0;
  270. var minBalanceThreshold = this._minBalanceThreshold;
  271. if (pctAboveAvg < minBalanceThreshold)
  272. return callback(null);
  273. var requestsOnBusiestHost = domainToResourcesMap[hosts[0]];
  274. var entry = result.addChild(String.sprintf("This page makes %d parallelizable requests to %s. Increase download parallelization by distributing the following requests across multiple hostnames.", busiestHostResourceCount, hosts[0]), true);
  275. for (var i = 0; i < requestsOnBusiestHost.length; ++i)
  276. entry.addURL(requestsOnBusiestHost[i].url);
  277. result.violationCount = requestsOnBusiestHost.length;
  278. callback(result);
  279. },
  280. __proto__: WebInspector.AuditRule.prototype
  281. }
  282. /**
  283. * The reported CSS rule size is incorrect (parsed != original in WebKit),
  284. * so use percentages instead, which gives a better approximation.
  285. * @constructor
  286. * @extends {WebInspector.AuditRule}
  287. */
  288. WebInspector.AuditRules.UnusedCssRule = function()
  289. {
  290. WebInspector.AuditRule.call(this, "page-unusedcss", "Remove unused CSS rules");
  291. }
  292. WebInspector.AuditRules.UnusedCssRule.prototype = {
  293. /**
  294. * @param {!Array.<!WebInspector.NetworkRequest>} requests
  295. * @param {!WebInspector.AuditRuleResult} result
  296. * @param {function(WebInspector.AuditRuleResult)} callback
  297. * @param {!WebInspector.Progress} progress
  298. */
  299. doRun: function(requests, result, callback, progress)
  300. {
  301. var self = this;
  302. function evalCallback(styleSheets) {
  303. if (progress.isCanceled())
  304. return;
  305. if (!styleSheets.length)
  306. return callback(null);
  307. var selectors = [];
  308. var testedSelectors = {};
  309. for (var i = 0; i < styleSheets.length; ++i) {
  310. var styleSheet = styleSheets[i];
  311. for (var curRule = 0; curRule < styleSheet.rules.length; ++curRule) {
  312. var selectorText = styleSheet.rules[curRule].selectorText;
  313. if (testedSelectors[selectorText])
  314. continue;
  315. selectors.push(selectorText);
  316. testedSelectors[selectorText] = 1;
  317. }
  318. }
  319. function selectorsCallback(callback, styleSheets, testedSelectors, foundSelectors)
  320. {
  321. if (progress.isCanceled())
  322. return;
  323. var inlineBlockOrdinal = 0;
  324. var totalStylesheetSize = 0;
  325. var totalUnusedStylesheetSize = 0;
  326. var summary;
  327. for (var i = 0; i < styleSheets.length; ++i) {
  328. var styleSheet = styleSheets[i];
  329. var unusedRules = [];
  330. for (var curRule = 0; curRule < styleSheet.rules.length; ++curRule) {
  331. var rule = styleSheet.rules[curRule];
  332. if (!testedSelectors[rule.selectorText] || foundSelectors[rule.selectorText])
  333. continue;
  334. unusedRules.push(rule.selectorText);
  335. }
  336. totalStylesheetSize += styleSheet.rules.length;
  337. totalUnusedStylesheetSize += unusedRules.length;
  338. if (!unusedRules.length)
  339. continue;
  340. var resource = WebInspector.resourceForURL(styleSheet.sourceURL);
  341. var isInlineBlock = resource && resource.request && resource.request.type == WebInspector.resourceTypes.Document;
  342. var url = !isInlineBlock ? WebInspector.AuditRuleResult.linkifyDisplayName(styleSheet.sourceURL) : String.sprintf("Inline block #%d", ++inlineBlockOrdinal);
  343. var pctUnused = Math.round(100 * unusedRules.length / styleSheet.rules.length);
  344. if (!summary)
  345. summary = result.addChild("", true);
  346. var entry = summary.addFormatted("%s: %d% is not used by the current page.", url, pctUnused);
  347. for (var j = 0; j < unusedRules.length; ++j)
  348. entry.addSnippet(unusedRules[j]);
  349. result.violationCount += unusedRules.length;
  350. }
  351. if (!totalUnusedStylesheetSize)
  352. return callback(null);
  353. var totalUnusedPercent = Math.round(100 * totalUnusedStylesheetSize / totalStylesheetSize);
  354. summary.value = String.sprintf("%s rules (%d%) of CSS not used by the current page.", totalUnusedStylesheetSize, totalUnusedPercent);
  355. callback(result);
  356. }
  357. var foundSelectors = {};
  358. function queryCallback(boundSelectorsCallback, selector, styleSheets, testedSelectors, nodeId)
  359. {
  360. if (nodeId)
  361. foundSelectors[selector] = true;
  362. if (boundSelectorsCallback)
  363. boundSelectorsCallback(foundSelectors);
  364. }
  365. function documentLoaded(selectors, document) {
  366. var pseudoSelectorRegexp = /::?(?:[\w-]+)(?:\(.*?\))?/g;
  367. for (var i = 0; i < selectors.length; ++i) {
  368. if (progress.isCanceled())
  369. return;
  370. var effectiveSelector = selectors[i].replace(pseudoSelectorRegexp, "");
  371. WebInspector.domAgent.querySelector(document.id, effectiveSelector, queryCallback.bind(null, i === selectors.length - 1 ? selectorsCallback.bind(null, callback, styleSheets, testedSelectors) : null, selectors[i], styleSheets, testedSelectors));
  372. }
  373. }
  374. WebInspector.domAgent.requestDocument(documentLoaded.bind(null, selectors));
  375. }
  376. function styleSheetCallback(styleSheets, sourceURL, continuation, styleSheet)
  377. {
  378. if (progress.isCanceled())
  379. return;
  380. if (styleSheet) {
  381. styleSheet.sourceURL = sourceURL;
  382. styleSheets.push(styleSheet);
  383. }
  384. if (continuation)
  385. continuation(styleSheets);
  386. }
  387. function allStylesCallback(error, styleSheetInfos)
  388. {
  389. if (progress.isCanceled())
  390. return;
  391. if (error || !styleSheetInfos || !styleSheetInfos.length)
  392. return evalCallback([]);
  393. var styleSheets = [];
  394. for (var i = 0; i < styleSheetInfos.length; ++i) {
  395. var info = styleSheetInfos[i];
  396. WebInspector.CSSStyleSheet.createForId(info.styleSheetId, styleSheetCallback.bind(null, styleSheets, info.sourceURL, i == styleSheetInfos.length - 1 ? evalCallback : null));
  397. }
  398. }
  399. CSSAgent.getAllStyleSheets(allStylesCallback);
  400. },
  401. __proto__: WebInspector.AuditRule.prototype
  402. }
  403. /**
  404. * @constructor
  405. * @extends {WebInspector.AuditRule}
  406. */
  407. WebInspector.AuditRules.CacheControlRule = function(id, name)
  408. {
  409. WebInspector.AuditRule.call(this, id, name);
  410. }
  411. WebInspector.AuditRules.CacheControlRule.MillisPerMonth = 1000 * 60 * 60 * 24 * 30;
  412. WebInspector.AuditRules.CacheControlRule.prototype = {
  413. /**
  414. * @param {!Array.<!WebInspector.NetworkRequest>} requests
  415. * @param {!WebInspector.AuditRuleResult} result
  416. * @param {function(WebInspector.AuditRuleResult)} callback
  417. * @param {!WebInspector.Progress} progress
  418. */
  419. doRun: function(requests, result, callback, progress)
  420. {
  421. var cacheableAndNonCacheableResources = this._cacheableAndNonCacheableResources(requests);
  422. if (cacheableAndNonCacheableResources[0].length)
  423. this.runChecks(cacheableAndNonCacheableResources[0], result);
  424. this.handleNonCacheableResources(cacheableAndNonCacheableResources[1], result);
  425. callback(result);
  426. },
  427. handleNonCacheableResources: function(requests, result)
  428. {
  429. },
  430. _cacheableAndNonCacheableResources: function(requests)
  431. {
  432. var processedResources = [[], []];
  433. for (var i = 0; i < requests.length; ++i) {
  434. var request = requests[i];
  435. if (!this.isCacheableResource(request))
  436. continue;
  437. if (this._isExplicitlyNonCacheable(request))
  438. processedResources[1].push(request);
  439. else
  440. processedResources[0].push(request);
  441. }
  442. return processedResources;
  443. },
  444. execCheck: function(messageText, requestCheckFunction, requests, result)
  445. {
  446. var requestCount = requests.length;
  447. var urls = [];
  448. for (var i = 0; i < requestCount; ++i) {
  449. if (requestCheckFunction.call(this, requests[i]))
  450. urls.push(requests[i].url);
  451. }
  452. if (urls.length) {
  453. var entry = result.addChild(messageText, true);
  454. entry.addURLs(urls);
  455. result.violationCount += urls.length;
  456. }
  457. },
  458. freshnessLifetimeGreaterThan: function(request, timeMs)
  459. {
  460. var dateHeader = this.responseHeader(request, "Date");
  461. if (!dateHeader)
  462. return false;
  463. var dateHeaderMs = Date.parse(dateHeader);
  464. if (isNaN(dateHeaderMs))
  465. return false;
  466. var freshnessLifetimeMs;
  467. var maxAgeMatch = this.responseHeaderMatch(request, "Cache-Control", "max-age=(\\d+)");
  468. if (maxAgeMatch)
  469. freshnessLifetimeMs = (maxAgeMatch[1]) ? 1000 * maxAgeMatch[1] : 0;
  470. else {
  471. var expiresHeader = this.responseHeader(request, "Expires");
  472. if (expiresHeader) {
  473. var expDate = Date.parse(expiresHeader);
  474. if (!isNaN(expDate))
  475. freshnessLifetimeMs = expDate - dateHeaderMs;
  476. }
  477. }
  478. return (isNaN(freshnessLifetimeMs)) ? false : freshnessLifetimeMs > timeMs;
  479. },
  480. responseHeader: function(request, header)
  481. {
  482. return request.responseHeaderValue(header);
  483. },
  484. hasResponseHeader: function(request, header)
  485. {
  486. return request.responseHeaderValue(header) !== undefined;
  487. },
  488. isCompressible: function(request)
  489. {
  490. return request.type.isTextType();
  491. },
  492. isPubliclyCacheable: function(request)
  493. {
  494. if (this._isExplicitlyNonCacheable(request))
  495. return false;
  496. if (this.responseHeaderMatch(request, "Cache-Control", "public"))
  497. return true;
  498. return request.url.indexOf("?") == -1 && !this.responseHeaderMatch(request, "Cache-Control", "private");
  499. },
  500. responseHeaderMatch: function(request, header, regexp)
  501. {
  502. return request.responseHeaderValue(header)
  503. ? request.responseHeaderValue(header).match(new RegExp(regexp, "im"))
  504. : undefined;
  505. },
  506. hasExplicitExpiration: function(request)
  507. {
  508. return this.hasResponseHeader(request, "Date") &&
  509. (this.hasResponseHeader(request, "Expires") || this.responseHeaderMatch(request, "Cache-Control", "max-age"));
  510. },
  511. _isExplicitlyNonCacheable: function(request)
  512. {
  513. var hasExplicitExp = this.hasExplicitExpiration(request);
  514. return this.responseHeaderMatch(request, "Cache-Control", "(no-cache|no-store|must-revalidate)") ||
  515. this.responseHeaderMatch(request, "Pragma", "no-cache") ||
  516. (hasExplicitExp && !this.freshnessLifetimeGreaterThan(request, 0)) ||
  517. (!hasExplicitExp && request.url && request.url.indexOf("?") >= 0) ||
  518. (!hasExplicitExp && !this.isCacheableResource(request));
  519. },
  520. isCacheableResource: function(request)
  521. {
  522. return request.statusCode !== undefined && WebInspector.AuditRules.CacheableResponseCodes[request.statusCode];
  523. },
  524. __proto__: WebInspector.AuditRule.prototype
  525. }
  526. /**
  527. * @constructor
  528. * @extends {WebInspector.AuditRules.CacheControlRule}
  529. */
  530. WebInspector.AuditRules.BrowserCacheControlRule = function()
  531. {
  532. WebInspector.AuditRules.CacheControlRule.call(this, "http-browsercache", "Leverage browser caching");
  533. }
  534. WebInspector.AuditRules.BrowserCacheControlRule.prototype = {
  535. handleNonCacheableResources: function(requests, result)
  536. {
  537. if (requests.length) {
  538. var entry = result.addChild("The following resources are explicitly non-cacheable. Consider making them cacheable if possible:", true);
  539. result.violationCount += requests.length;
  540. for (var i = 0; i < requests.length; ++i)
  541. entry.addURL(requests[i].url);
  542. }
  543. },
  544. runChecks: function(requests, result, callback)
  545. {
  546. this.execCheck("The following resources are missing a cache expiration. Resources that do not specify an expiration may not be cached by browsers:",
  547. this._missingExpirationCheck, requests, result);
  548. this.execCheck("The following resources specify a \"Vary\" header that disables caching in most versions of Internet Explorer:",
  549. this._varyCheck, requests, result);
  550. this.execCheck("The following cacheable resources have a short freshness lifetime:",
  551. this._oneMonthExpirationCheck, requests, result);
  552. // Unable to implement the favicon check due to the WebKit limitations.
  553. this.execCheck("To further improve cache hit rate, specify an expiration one year in the future for the following cacheable resources:",
  554. this._oneYearExpirationCheck, requests, result);
  555. },
  556. _missingExpirationCheck: function(request)
  557. {
  558. return this.isCacheableResource(request) && !this.hasResponseHeader(request, "Set-Cookie") && !this.hasExplicitExpiration(request);
  559. },
  560. _varyCheck: function(request)
  561. {
  562. var varyHeader = this.responseHeader(request, "Vary");
  563. if (varyHeader) {
  564. varyHeader = varyHeader.replace(/User-Agent/gi, "");
  565. varyHeader = varyHeader.replace(/Accept-Encoding/gi, "");
  566. varyHeader = varyHeader.replace(/[, ]*/g, "");
  567. }
  568. return varyHeader && varyHeader.length && this.isCacheableResource(request) && this.freshnessLifetimeGreaterThan(request, 0);
  569. },
  570. _oneMonthExpirationCheck: function(request)
  571. {
  572. return this.isCacheableResource(request) &&
  573. !this.hasResponseHeader(request, "Set-Cookie") &&
  574. !this.freshnessLifetimeGreaterThan(request, WebInspector.AuditRules.CacheControlRule.MillisPerMonth) &&
  575. this.freshnessLifetimeGreaterThan(request, 0);
  576. },
  577. _oneYearExpirationCheck: function(request)
  578. {
  579. return this.isCacheableResource(request) &&
  580. !this.hasResponseHeader(request, "Set-Cookie") &&
  581. !this.freshnessLifetimeGreaterThan(request, 11 * WebInspector.AuditRules.CacheControlRule.MillisPerMonth) &&
  582. this.freshnessLifetimeGreaterThan(request, WebInspector.AuditRules.CacheControlRule.MillisPerMonth);
  583. },
  584. __proto__: WebInspector.AuditRules.CacheControlRule.prototype
  585. }
  586. /**
  587. * @constructor
  588. * @extends {WebInspector.AuditRules.CacheControlRule}
  589. */
  590. WebInspector.AuditRules.ProxyCacheControlRule = function() {
  591. WebInspector.AuditRules.CacheControlRule.call(this, "http-proxycache", "Leverage proxy caching");
  592. }
  593. WebInspector.AuditRules.ProxyCacheControlRule.prototype = {
  594. runChecks: function(requests, result, callback)
  595. {
  596. this.execCheck("Resources with a \"?\" in the URL are not cached by most proxy caching servers:",
  597. this._questionMarkCheck, requests, result);
  598. this.execCheck("Consider adding a \"Cache-Control: public\" header to the following resources:",
  599. this._publicCachingCheck, requests, result);
  600. this.execCheck("The following publicly cacheable resources contain a Set-Cookie header. This security vulnerability can cause cookies to be shared by multiple users.",
  601. this._setCookieCacheableCheck, requests, result);
  602. },
  603. _questionMarkCheck: function(request)
  604. {
  605. return request.url.indexOf("?") >= 0 && !this.hasResponseHeader(request, "Set-Cookie") && this.isPubliclyCacheable(request);
  606. },
  607. _publicCachingCheck: function(request)
  608. {
  609. return this.isCacheableResource(request) &&
  610. !this.isCompressible(request) &&
  611. !this.responseHeaderMatch(request, "Cache-Control", "public") &&
  612. !this.hasResponseHeader(request, "Set-Cookie");
  613. },
  614. _setCookieCacheableCheck: function(request)
  615. {
  616. return this.hasResponseHeader(request, "Set-Cookie") && this.isPubliclyCacheable(request);
  617. },
  618. __proto__: WebInspector.AuditRules.CacheControlRule.prototype
  619. }
  620. /**
  621. * @constructor
  622. * @extends {WebInspector.AuditRule}
  623. */
  624. WebInspector.AuditRules.ImageDimensionsRule = function()
  625. {
  626. WebInspector.AuditRule.call(this, "page-imagedims", "Specify image dimensions");
  627. }
  628. WebInspector.AuditRules.ImageDimensionsRule.prototype = {
  629. /**
  630. * @param {!Array.<!WebInspector.NetworkRequest>} requests
  631. * @param {!WebInspector.AuditRuleResult} result
  632. * @param {function(WebInspector.AuditRuleResult)} callback
  633. * @param {!WebInspector.Progress} progress
  634. */
  635. doRun: function(requests, result, callback, progress)
  636. {
  637. var urlToNoDimensionCount = {};
  638. function doneCallback()
  639. {
  640. for (var url in urlToNoDimensionCount) {
  641. var entry = entry || result.addChild("A width and height should be specified for all images in order to speed up page display. The following image(s) are missing a width and/or height:", true);
  642. var format = "%r";
  643. if (urlToNoDimensionCount[url] > 1)
  644. format += " (%d uses)";
  645. entry.addFormatted(format, url, urlToNoDimensionCount[url]);
  646. result.violationCount++;
  647. }
  648. callback(entry ? result : null);
  649. }
  650. function imageStylesReady(imageId, styles, isLastStyle, computedStyle)
  651. {
  652. if (progress.isCanceled())
  653. return;
  654. const node = WebInspector.domAgent.nodeForId(imageId);
  655. var src = node.getAttribute("src");
  656. if (!src.asParsedURL()) {
  657. for (var frameOwnerCandidate = node; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) {
  658. if (frameOwnerCandidate.baseURL) {
  659. var completeSrc = WebInspector.ParsedURL.completeURL(frameOwnerCandidate.baseURL, src);
  660. break;
  661. }
  662. }
  663. }
  664. if (completeSrc)
  665. src = completeSrc;
  666. if (computedStyle.getPropertyValue("position") === "absolute") {
  667. if (isLastStyle)
  668. doneCallback();
  669. return;
  670. }
  671. if (styles.attributesStyle) {
  672. var widthFound = !!styles.attributesStyle.getLiveProperty("width");
  673. var heightFound = !!styles.attributesStyle.getLiveProperty("height");
  674. }
  675. var inlineStyle = styles.inlineStyle;
  676. if (inlineStyle) {
  677. if (inlineStyle.getPropertyValue("width") !== "")
  678. widthFound = true;
  679. if (inlineStyle.getPropertyValue("height") !== "")
  680. heightFound = true;
  681. }
  682. for (var i = styles.matchedCSSRules.length - 1; i >= 0 && !(widthFound && heightFound); --i) {
  683. var style = styles.matchedCSSRules[i].style;
  684. if (style.getPropertyValue("width") !== "")
  685. widthFound = true;
  686. if (style.getPropertyValue("height") !== "")
  687. heightFound = true;
  688. }
  689. if (!widthFound || !heightFound) {
  690. if (src in urlToNoDimensionCount)
  691. ++urlToNoDimensionCount[src];
  692. else
  693. urlToNoDimensionCount[src] = 1;
  694. }
  695. if (isLastStyle)
  696. doneCallback();
  697. }
  698. function getStyles(nodeIds)
  699. {
  700. if (progress.isCanceled())
  701. return;
  702. var targetResult = {};
  703. function inlineCallback(inlineStyle, attributesStyle)
  704. {
  705. targetResult.inlineStyle = inlineStyle;
  706. targetResult.attributesStyle = attributesStyle;
  707. }
  708. function matchedCallback(result)
  709. {
  710. if (result)
  711. targetResult.matchedCSSRules = result.matchedCSSRules;
  712. }
  713. if (!nodeIds || !nodeIds.length)
  714. doneCallback();
  715. for (var i = 0; nodeIds && i < nodeIds.length; ++i) {
  716. WebInspector.cssModel.getMatchedStylesAsync(nodeIds[i], false, false, matchedCallback);
  717. WebInspector.cssModel.getInlineStylesAsync(nodeIds[i], inlineCallback);
  718. WebInspector.cssModel.getComputedStyleAsync(nodeIds[i], imageStylesReady.bind(null, nodeIds[i], targetResult, i === nodeIds.length - 1));
  719. }
  720. }
  721. function onDocumentAvailable(root)
  722. {
  723. if (progress.isCanceled())
  724. return;
  725. WebInspector.domAgent.querySelectorAll(root.id, "img[src]", getStyles);
  726. }
  727. if (progress.isCanceled())
  728. return;
  729. WebInspector.domAgent.requestDocument(onDocumentAvailable);
  730. },
  731. __proto__: WebInspector.AuditRule.prototype
  732. }
  733. /**
  734. * @constructor
  735. * @extends {WebInspector.AuditRule}
  736. */
  737. WebInspector.AuditRules.CssInHeadRule = function()
  738. {
  739. WebInspector.AuditRule.call(this, "page-cssinhead", "Put CSS in the document head");
  740. }
  741. WebInspector.AuditRules.CssInHeadRule.prototype = {
  742. /**
  743. * @param {!Array.<!WebInspector.NetworkRequest>} requests
  744. * @param {!WebInspector.AuditRuleResult} result
  745. * @param {function(WebInspector.AuditRuleResult)} callback
  746. * @param {!WebInspector.Progress} progress
  747. */
  748. doRun: function(requests, result, callback, progress)
  749. {
  750. function evalCallback(evalResult)
  751. {
  752. if (progress.isCanceled())
  753. return;
  754. if (!evalResult)
  755. return callback(null);
  756. var summary = result.addChild("");
  757. var outputMessages = [];
  758. for (var url in evalResult) {
  759. var urlViolations = evalResult[url];
  760. if (urlViolations[0]) {
  761. result.addFormatted("%s style block(s) in the %r body should be moved to the document head.", urlViolations[0], url);
  762. result.violationCount += urlViolations[0];
  763. }
  764. for (var i = 0; i < urlViolations[1].length; ++i)
  765. result.addFormatted("Link node %r should be moved to the document head in %r", urlViolations[1][i], url);
  766. result.violationCount += urlViolations[1].length;
  767. }
  768. summary.value = String.sprintf("CSS in the document body adversely impacts rendering performance.");
  769. callback(result);
  770. }
  771. function externalStylesheetsReceived(root, inlineStyleNodeIds, nodeIds)
  772. {
  773. if (progress.isCanceled())
  774. return;
  775. if (!nodeIds)
  776. return;
  777. var externalStylesheetNodeIds = nodeIds;
  778. var result = null;
  779. if (inlineStyleNodeIds.length || externalStylesheetNodeIds.length) {
  780. var urlToViolationsArray = {};
  781. var externalStylesheetHrefs = [];
  782. for (var j = 0; j < externalStylesheetNodeIds.length; ++j) {
  783. var linkNode = WebInspector.domAgent.nodeForId(externalStylesheetNodeIds[j]);
  784. var completeHref = WebInspector.ParsedURL.completeURL(linkNode.ownerDocument.baseURL, linkNode.getAttribute("href"));
  785. externalStylesheetHrefs.push(completeHref || "<empty>");
  786. }
  787. urlToViolationsArray[root.documentURL] = [inlineStyleNodeIds.length, externalStylesheetHrefs];
  788. result = urlToViolationsArray;
  789. }
  790. evalCallback(result);
  791. }
  792. function inlineStylesReceived(root, nodeIds)
  793. {
  794. if (progress.isCanceled())
  795. return;
  796. if (!nodeIds)
  797. return;
  798. WebInspector.domAgent.querySelectorAll(root.id, "body link[rel~='stylesheet'][href]", externalStylesheetsReceived.bind(null, root, nodeIds));
  799. }
  800. function onDocumentAvailable(root)
  801. {
  802. if (progress.isCanceled())
  803. return;
  804. WebInspector.domAgent.querySelectorAll(root.id, "body style", inlineStylesReceived.bind(null, root));
  805. }
  806. WebInspector.domAgent.requestDocument(onDocumentAvailable);
  807. },
  808. __proto__: WebInspector.AuditRule.prototype
  809. }
  810. /**
  811. * @constructor
  812. * @extends {WebInspector.AuditRule}
  813. */
  814. WebInspector.AuditRules.StylesScriptsOrderRule = function()
  815. {
  816. WebInspector.AuditRule.call(this, "page-stylescriptorder", "Optimize the order of styles and scripts");
  817. }
  818. WebInspector.AuditRules.StylesScriptsOrderRule.prototype = {
  819. /**
  820. * @param {!Array.<!WebInspector.NetworkRequest>} requests
  821. * @param {!WebInspector.AuditRuleResult} result
  822. * @param {function(WebInspector.AuditRuleResult)} callback
  823. * @param {!WebInspector.Progress} progress
  824. */
  825. doRun: function(requests, result, callback, progress)
  826. {
  827. function evalCallback(resultValue)
  828. {
  829. if (progress.isCanceled())
  830. return;
  831. if (!resultValue)
  832. return callback(null);
  833. var lateCssUrls = resultValue[0];
  834. var cssBeforeInlineCount = resultValue[1];
  835. var entry = result.addChild("The following external CSS files were included after an external JavaScript file in the document head. To ensure CSS files are downloaded in parallel, always include external CSS before external JavaScript.", true);
  836. entry.addURLs(lateCssUrls);
  837. result.violationCount += lateCssUrls.length;
  838. if (cssBeforeInlineCount) {
  839. result.addChild(String.sprintf(" %d inline script block%s found in the head between an external CSS file and another resource. To allow parallel downloading, move the inline script before the external CSS file, or after the next resource.", cssBeforeInlineCount, cssBeforeInlineCount > 1 ? "s were" : " was"));
  840. result.violationCount += cssBeforeInlineCount;
  841. }
  842. callback(result);
  843. }
  844. function cssBeforeInlineReceived(lateStyleIds, nodeIds)
  845. {
  846. if (progress.isCanceled())
  847. return;
  848. if (!nodeIds)
  849. return;
  850. var cssBeforeInlineCount = nodeIds.length;
  851. var result = null;
  852. if (lateStyleIds.length || cssBeforeInlineCount) {
  853. var lateStyleUrls = [];
  854. for (var i = 0; i < lateStyleIds.length; ++i) {
  855. var lateStyleNode = WebInspector.domAgent.nodeForId(lateStyleIds[i]);
  856. var completeHref = WebInspector.ParsedURL.completeURL(lateStyleNode.ownerDocument.baseURL, lateStyleNode.getAttribute("href"));
  857. lateStyleUrls.push(completeHref || "<empty>");
  858. }
  859. result = [ lateStyleUrls, cssBeforeInlineCount ];
  860. }
  861. evalCallback(result);
  862. }
  863. function lateStylesReceived(root, nodeIds)
  864. {
  865. if (progress.isCanceled())
  866. return;
  867. if (!nodeIds)
  868. return;
  869. WebInspector.domAgent.querySelectorAll(root.id, "head link[rel~='stylesheet'][href] ~ script:not([src])", cssBeforeInlineReceived.bind(null, nodeIds));
  870. }
  871. function onDocumentAvailable(root)
  872. {
  873. if (progress.isCanceled())
  874. return;
  875. WebInspector.domAgent.querySelectorAll(root.id, "head script[src] ~ link[rel~='stylesheet'][href]", lateStylesReceived.bind(null, root));
  876. }
  877. WebInspector.domAgent.requestDocument(onDocumentAvailable);
  878. },
  879. __proto__: WebInspector.AuditRule.prototype
  880. }
  881. /**
  882. * @constructor
  883. * @extends {WebInspector.AuditRule}
  884. */
  885. WebInspector.AuditRules.CSSRuleBase = function(id, name)
  886. {
  887. WebInspector.AuditRule.call(this, id, name);
  888. }
  889. WebInspector.AuditRules.CSSRuleBase.prototype = {
  890. /**
  891. * @param {!Array.<!WebInspector.NetworkRequest>} requests
  892. * @param {!WebInspector.AuditRuleResult} result
  893. * @param {function(WebInspector.AuditRuleResult)} callback
  894. * @param {!WebInspector.Progress} progress
  895. */
  896. doRun: function(requests, result, callback, progress)
  897. {
  898. CSSAgent.getAllStyleSheets(sheetsCallback.bind(this));
  899. function sheetsCallback(error, headers)
  900. {
  901. if (error)
  902. return callback(null);
  903. if (!headers.length)
  904. return callback(null);
  905. for (var i = 0; i < headers.length; ++i) {
  906. var header = headers[i];
  907. if (header.disabled)
  908. continue; // Do not check disabled stylesheets.
  909. this._visitStyleSheet(header.styleSheetId, i === headers.length - 1 ? finishedCallback : null, result, progress);
  910. }
  911. }
  912. function finishedCallback()
  913. {
  914. callback(result);
  915. }
  916. },
  917. _visitStyleSheet: function(styleSheetId, callback, result, progress)
  918. {
  919. WebInspector.CSSStyleSheet.createForId(styleSheetId, sheetCallback.bind(this));
  920. function sheetCallback(styleSheet)
  921. {
  922. if (progress.isCanceled())
  923. return;
  924. if (!styleSheet) {
  925. if (callback)
  926. callback();
  927. return;
  928. }
  929. this.visitStyleSheet(styleSheet, result);
  930. for (var i = 0; i < styleSheet.rules.length; ++i)
  931. this._visitRule(styleSheet, styleSheet.rules[i], result);
  932. this.didVisitStyleSheet(styleSheet, result);
  933. if (callback)
  934. callback();
  935. }
  936. },
  937. _visitRule: function(styleSheet, rule, result)
  938. {
  939. this.visitRule(styleSheet, rule, result);
  940. var allProperties = rule.style.allProperties;
  941. for (var i = 0; i < allProperties.length; ++i)
  942. this.visitProperty(styleSheet, allProperties[i], result);
  943. this.didVisitRule(styleSheet, rule, result);
  944. },
  945. visitStyleSheet: function(styleSheet, result)
  946. {
  947. // Subclasses can implement.
  948. },
  949. didVisitStyleSheet: function(styleSheet, result)
  950. {
  951. // Subclasses can implement.
  952. },
  953. visitRule: function(styleSheet, rule, result)
  954. {
  955. // Subclasses can implement.
  956. },
  957. didVisitRule: function(styleSheet, rule, result)
  958. {
  959. // Subclasses can implement.
  960. },
  961. visitProperty: function(styleSheet, property, result)
  962. {
  963. // Subclasses can implement.
  964. },
  965. __proto__: WebInspector.AuditRule.prototype
  966. }
  967. /**
  968. * @constructor
  969. * @extends {WebInspector.AuditRules.CSSRuleBase}
  970. */
  971. WebInspector.AuditRules.VendorPrefixedCSSProperties = function()
  972. {
  973. WebInspector.AuditRules.CSSRuleBase.call(this, "page-vendorprefixedcss", "Use normal CSS property names instead of vendor-prefixed ones");
  974. this._webkitPrefix = "-webkit-";
  975. }
  976. WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedProperties = [
  977. "background-clip", "background-origin", "background-size",
  978. "border-radius", "border-bottom-left-radius", "border-bottom-right-radius", "border-top-left-radius", "border-top-right-radius",
  979. "box-shadow", "box-sizing", "opacity", "text-shadow"
  980. ].keySet();
  981. WebInspector.AuditRules.VendorPrefixedCSSProperties.prototype = {
  982. didVisitStyleSheet: function(styleSheet)
  983. {
  984. delete this._styleSheetResult;
  985. },
  986. visitRule: function(rule)
  987. {
  988. this._mentionedProperties = {};
  989. },
  990. didVisitRule: function()
  991. {
  992. delete this._ruleResult;
  993. delete this._mentionedProperties;
  994. },
  995. visitProperty: function(styleSheet, property, result)
  996. {
  997. if (!property.name.startsWith(this._webkitPrefix))
  998. return;
  999. var normalPropertyName = property.name.substring(this._webkitPrefix.length).toLowerCase(); // Start just after the "-webkit-" prefix.
  1000. if (WebInspector.AuditRules.VendorPrefixedCSSProperties.supportedProperties[normalPropertyName] && !this._mentionedProperties[normalPropertyName]) {
  1001. var style = property.ownerStyle;
  1002. var liveProperty = style.getLiveProperty(normalPropertyName);
  1003. if (liveProperty && !liveProperty.styleBased)
  1004. return; // WebCore can provide normal versions of prefixed properties automatically, so be careful to skip only normal source-based properties.
  1005. var rule = style.parentRule;
  1006. this._mentionedProperties[normalPropertyName] = true;
  1007. if (!this._styleSheetResult)
  1008. this._styleSheetResult = result.addChild(rule.sourceURL ? WebInspector.linkifyResourceAsNode(rule.sourceURL) : "<unknown>");
  1009. if (!this._ruleResult) {
  1010. var anchor = WebInspector.linkifyURLAsNode(rule.sourceURL, rule.selectorText);
  1011. anchor.preferredPanel = "resources";
  1012. anchor.lineNumber = rule.lineNumberInSource();
  1013. this._ruleResult = this._styleSheetResult.addChild(anchor);
  1014. }
  1015. ++result.violationCount;
  1016. this._ruleResult.addSnippet(String.sprintf("\"" + this._webkitPrefix + "%s\" is used, but \"%s\" is supported.", normalPropertyName, normalPropertyName));
  1017. }
  1018. },
  1019. __proto__: WebInspector.AuditRules.CSSRuleBase.prototype
  1020. }
  1021. /**
  1022. * @constructor
  1023. * @extends {WebInspector.AuditRule}
  1024. */
  1025. WebInspector.AuditRules.CookieRuleBase = function(id, name)
  1026. {
  1027. WebInspector.AuditRule.call(this, id, name);
  1028. }
  1029. WebInspector.AuditRules.CookieRuleBase.prototype = {
  1030. /**
  1031. * @param {!Array.<!WebInspector.NetworkRequest>} requests
  1032. * @param {!WebInspector.AuditRuleResult} result
  1033. * @param {function(WebInspector.AuditRuleResult)} callback
  1034. * @param {!WebInspector.Progress} progress
  1035. */
  1036. doRun: function(requests, result, callback, progress)
  1037. {
  1038. var self = this;
  1039. function resultCallback(receivedCookies) {
  1040. if (progress.isCanceled())
  1041. return;
  1042. self.processCookies(receivedCookies, requests, result);
  1043. callback(result);
  1044. }
  1045. WebInspector.Cookies.getCookiesAsync(resultCallback);
  1046. },
  1047. mapResourceCookies: function(requestsByDomain, allCookies, callback)
  1048. {
  1049. for (var i = 0; i < allCookies.length; ++i) {
  1050. for (var requestDomain in requestsByDomain) {
  1051. if (WebInspector.Cookies.cookieDomainMatchesResourceDomain(allCookies[i].domain(), requestDomain))
  1052. this._callbackForResourceCookiePairs(requestsByDomain[requestDomain], allCookies[i], callback);
  1053. }
  1054. }
  1055. },
  1056. _callbackForResourceCookiePairs: function(requests, cookie, callback)
  1057. {
  1058. if (!requests)
  1059. return;
  1060. for (var i = 0; i < requests.length; ++i) {
  1061. if (WebInspector.Cookies.cookieMatchesResourceURL(cookie, requests[i].url))
  1062. callback(requests[i], cookie);
  1063. }
  1064. },
  1065. __proto__: WebInspector.AuditRule.prototype
  1066. }
  1067. /**
  1068. * @constructor
  1069. * @extends {WebInspector.AuditRules.CookieRuleBase}
  1070. */
  1071. WebInspector.AuditRules.CookieSizeRule = function(avgBytesThreshold)
  1072. {
  1073. WebInspector.AuditRules.CookieRuleBase.call(this, "http-cookiesize", "Minimize cookie size");
  1074. this._avgBytesThreshold = avgBytesThreshold;
  1075. this._maxBytesThreshold = 1000;
  1076. }
  1077. WebInspector.AuditRules.CookieSizeRule.prototype = {
  1078. _average: function(cookieArray)
  1079. {
  1080. var total = 0;
  1081. for (var i = 0; i < cookieArray.length; ++i)
  1082. total += cookieArray[i].size();
  1083. return cookieArray.length ? Math.round(total / cookieArray.length) : 0;
  1084. },
  1085. _max: function(cookieArray)
  1086. {
  1087. var result = 0;
  1088. for (var i = 0; i < cookieArray.length; ++i)
  1089. result = Math.max(cookieArray[i].size(), result);
  1090. return result;
  1091. },
  1092. processCookies: function(allCookies, requests, result)
  1093. {
  1094. function maxSizeSorter(a, b)
  1095. {
  1096. return b.maxCookieSize - a.maxCookieSize;
  1097. }
  1098. function avgSizeSorter(a, b)
  1099. {
  1100. return b.avgCookieSize - a.avgCookieSize;
  1101. }
  1102. var cookiesPerResourceDomain = {};
  1103. function collectorCallback(request, cookie)
  1104. {
  1105. var cookies = cookiesPerResourceDomain[request.parsedURL.host];
  1106. if (!cookies) {
  1107. cookies = [];
  1108. cookiesPerResourceDomain[request.parsedURL.host] = cookies;
  1109. }
  1110. cookies.push(cookie);
  1111. }
  1112. if (!allCookies.length)
  1113. return;
  1114. var sortedCookieSizes = [];
  1115. var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests,
  1116. null,
  1117. true);
  1118. var matchingResourceData = {};
  1119. this.mapResourceCookies(domainToResourcesMap, allCookies, collectorCallback.bind(this));
  1120. for (var requestDomain in cookiesPerResourceDomain) {
  1121. var cookies = cookiesPerResourceDomain[requestDomain];
  1122. sortedCookieSizes.push({
  1123. domain: requestDomain,
  1124. avgCookieSize: this._average(cookies),
  1125. maxCookieSize: this._max(cookies)
  1126. });
  1127. }
  1128. var avgAllCookiesSize = this._average(allCookies);
  1129. var hugeCookieDomains = [];
  1130. sortedCookieSizes.sort(maxSizeSorter);
  1131. for (var i = 0, len = sortedCookieSizes.length; i < len; ++i) {
  1132. var maxCookieSize = sortedCookieSizes[i].maxCookieSize;
  1133. if (maxCookieSize > this._maxBytesThreshold)
  1134. hugeCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(sortedCookieSizes[i].domain) + ": " + Number.bytesToString(maxCookieSize));
  1135. }
  1136. var bigAvgCookieDomains = [];
  1137. sortedCookieSizes.sort(avgSizeSorter);
  1138. for (var i = 0, len = sortedCookieSizes.length; i < len; ++i) {
  1139. var domain = sortedCookieSizes[i].domain;
  1140. var avgCookieSize = sortedCookieSizes[i].avgCookieSize;
  1141. if (avgCookieSize > this._avgBytesThreshold && avgCookieSize < this._maxBytesThreshold)
  1142. bigAvgCookieDomains.push(WebInspector.AuditRuleResult.resourceDomain(domain) + ": " + Number.bytesToString(avgCookieSize));
  1143. }
  1144. result.addChild(String.sprintf("The average cookie size for all requests on this page is %s", Number.bytesToString(avgAllCookiesSize)));
  1145. var message;
  1146. if (hugeCookieDomains.length) {
  1147. var entry = result.addChild("The following domains have a cookie size in excess of 1KB. This is harmful because requests with cookies larger than 1KB typically cannot fit into a single network packet.", true);
  1148. entry.addURLs(hugeCookieDomains);
  1149. result.violationCount += hugeCookieDomains.length;
  1150. }
  1151. if (bigAvgCookieDomains.length) {
  1152. var entry = result.addChild(String.sprintf("The following domains have an average cookie size in excess of %d bytes. Reducing the size of cookies for these domains can reduce the time it takes to send requests.", this._avgBytesThreshold), true);
  1153. entry.addURLs(bigAvgCookieDomains);
  1154. result.violationCount += bigAvgCookieDomains.length;
  1155. }
  1156. },
  1157. __proto__: WebInspector.AuditRules.CookieRuleBase.prototype
  1158. }
  1159. /**
  1160. * @constructor
  1161. * @extends {WebInspector.AuditRules.CookieRuleBase}
  1162. */
  1163. WebInspector.AuditRules.StaticCookielessRule = function(minResources)
  1164. {
  1165. WebInspector.AuditRules.CookieRuleBase.call(this, "http-staticcookieless", "Serve static content from a cookieless domain");
  1166. this._minResources = minResources;
  1167. }
  1168. WebInspector.AuditRules.StaticCookielessRule.prototype = {
  1169. processCookies: function(allCookies, requests, result)
  1170. {
  1171. var domainToResourcesMap = WebInspector.AuditRules.getDomainToResourcesMap(requests,
  1172. [WebInspector.resourceTypes.Stylesheet,
  1173. WebInspector.resourceTypes.Image],
  1174. true);
  1175. var totalStaticResources = 0;
  1176. for (var domain in domainToResourcesMap)
  1177. totalStaticResources += domainToResourcesMap[domain].length;
  1178. if (totalStaticResources < this._minResources)
  1179. return;
  1180. var matchingResourceData = {};
  1181. this.mapResourceCookies(domainToResourcesMap, allCookies, this._collectorCallback.bind(this, matchingResourceData));
  1182. var badUrls = [];
  1183. var cookieBytes = 0;
  1184. for (var url in matchingResourceData) {
  1185. badUrls.push(url);
  1186. cookieBytes += matchingResourceData[url]
  1187. }
  1188. if (badUrls.length < this._minResources)
  1189. return;
  1190. var entry = result.addChild(String.sprintf("%s of cookies were sent with the following static resources. Serve these static resources from a domain that does not set cookies:", Number.bytesToString(cookieBytes)), true);
  1191. entry.addURLs(badUrls);
  1192. result.violationCount = badUrls.length;
  1193. },
  1194. _collectorCallback: function(matchingResourceData, request, cookie)
  1195. {
  1196. matchingResourceData[request.url] = (matchingResourceData[request.url] || 0) + cookie.size();
  1197. },
  1198. __proto__: WebInspector.AuditRules.CookieRuleBase.prototype
  1199. }